tripal_core.chado_variables.api.inc

This API generates objects containing the full details of a record(s) in chado.

File

tripal_core/api/tripal_core.chado_variables.api.inc
View source
  1. <?php
  2. /**
  3. * @file
  4. * This API generates objects containing the full details of a record(s) in chado.
  5. */
  6. /**
  7. * Generates an object containing the full details of a record(s) in Chado.
  8. *
  9. * The object returned contains key/value pairs where the keys are the fields
  10. * in the Chado table.
  11. *
  12. * The returned object differs from the array returned by chado_select_record()
  13. * as all foreign key relationships in the Chado table have been followed and
  14. * those data are also included. This function automatically excludes some
  15. * fields and tables. Fields that are extremely long, such as text fields are
  16. * automatically excluded to prevent long page loads. Linking tables that have
  17. * a many-to-one relationship with the record are also excluded. Use the
  18. * chado_expand_var() to manually add in excluded fields and data from linker
  19. * tables.
  20. *
  21. * Example Usage:
  22. * @code
  23. * $values = array(
  24. * 'name' => 'Medtr4g030710'
  25. * );
  26. * $feature = chado_generate_var('feature', $values);
  27. * @endcode
  28. *
  29. * The $values array passed to this fucntion can be of the same format used
  30. * by the chado_select_record() function.
  31. *
  32. * If a field is a foreign key then its value is an object that contains
  33. * key/value pairs for that record. The following code provides examples
  34. * for retrieving values associated with the record, either as columns in the
  35. * original Chado table or as columns in linked records through foreign keys:
  36. * @code
  37. * // Get the feature name.
  38. * $name = $feature->name;
  39. * // Get the feature unique name.
  40. * $uniquename = $feature->uniquename;
  41. * // Get the feature type. Because the type name is obtained via
  42. * // a foreign key with the cvterm table, the objects are nested
  43. * // and we can follow the foreign key fields to retrieve those values
  44. * $type = $feature->type_id->name;
  45. * // Get the name of the vocabulary.
  46. * $cv = $feature->type_id->cv_id->name;
  47. * // Get the vocabulary id.
  48. * $cv_id = $feature->type_id->cv_id->cv_id;
  49. * @endcode
  50. *
  51. *
  52. * This will return an object if there is only one feature with the name
  53. * Medtr4g030710 or it will return an array of feature objects if more than one
  54. * feature has that name.
  55. *
  56. * Note to Module Designers: Fields can be excluded by default from these
  57. * objects by implementing one of the following hooks:
  58. * - hook_exclude_field_from_tablename_by_default (where tablename is the
  59. * name of the table): This hook allows you to add fields to be excluded
  60. * on a per table basis. Simply implement this hook to return an array of
  61. * fields to be excluded. The following example will ensure that
  62. * feature.residues is excluded from a feature object by default:
  63. * @code
  64. * mymodule_exclude_field_from_feature_by_default() {
  65. * return array('residues' => TRUE);
  66. * }
  67. * @endcode
  68. * - hook_exclude_type_by_default:
  69. * This hook allows you to exclude fields using conditional. This
  70. * function should return an array of postgresql types mapped to criteria.
  71. * If the field types of any table match the criteria then the field
  72. * is excluded. Tokens available in criteria are &gt;field_value&lt;
  73. * and &gt;field_name&lt;. The following example will exclude all text
  74. * fields with a length > 50. Thus if $feature.residues is longer than
  75. * 50 it will be excluded, otherwise it will be added.
  76. * @code
  77. * mymodule_exclude_type_by_default() {
  78. * return array('text' => 'length(&gt;field_value&lt; ) > 50');
  79. * }
  80. * @endcode
  81. *
  82. *
  83. * @param $table
  84. * The name of the base table to generate a variable for
  85. * @param $values
  86. * A select values array that selects the records you want from the base table
  87. * (this has the same form as chado_select_record)
  88. * @param $base_options
  89. * An array containing options for the base table. For example, an
  90. * option of 'order_by' may be used to sort results in the base table
  91. * if more than one are returned. The options must be compatible with
  92. * the options accepted by the chado_select_record() function.
  93. * Additionally, These options are available for this function:
  94. * -return_array:
  95. * can be provided to force the function to always return an array. Default
  96. * behavior is to return a single record if only one record exists or to
  97. * return an array if multiple records exist.
  98. * - include_fk:
  99. * an array of FK relationships to follow. By default, the
  100. * chado_select_record function will follow all FK relationships but this
  101. * may generate more queries then is desired slowing down this function
  102. * call when there are lots of FK relationships to follow. Provide an
  103. * array specifying the fields to include. For example, if expanding a
  104. * property table (e.g. featureprop) and you want the CV and accession
  105. * but do not want the DB the following array would work:
  106. *
  107. * $table_options = array(
  108. * 'include_fk' => array(
  109. * 'type_id' => array(
  110. * 'cv_id' => 1,
  111. * 'dbxref_id' => 1,
  112. * )
  113. * )
  114. * );
  115. *
  116. * The above array will expand the 'type_id' of the property table but only
  117. * further expand the cv_id and the dbxref_id and will go no further.
  118. * - pager:
  119. * Use this option if it is desired to return only a subset of results
  120. * so that they may be shown within a Drupal-style pager. This should be
  121. * an array with two keys: 'limit' and 'element'. The value of 'limit'
  122. * should specify the number of records to return and 'element' is a
  123. * unique integer to differentiate between pagers when more than one
  124. * appear on a page. The 'element' should start with zero and increment by
  125. * one for each pager.
  126. * @return
  127. * Either an object (if only one record was selected from the base table)
  128. * or an array of objects (if more than one record was selected from the
  129. * base table). If the option 'return_array' is provided the function
  130. * always returns an array.
  131. *
  132. * @ingroup tripal_chado_query_api
  133. */
  134. function chado_generate_var($table, $values, $base_options = array()) {
  135. $all = new stdClass();
  136. $return_array = 0;
  137. if (array_key_exists('return_array', $base_options)) {
  138. $return_array = 1;
  139. }
  140. $include_fk = FALSE;
  141. if (array_key_exists('include_fk', $base_options)) {
  142. $include_fk = $base_options['include_fk'];
  143. }
  144. $pager = array();
  145. if (array_key_exists('pager', $base_options)) {
  146. $pager = $base_options['pager'];
  147. }
  148. // get description for the current table----------------------------------------------------------
  149. $table_desc = chado_get_schema($table);
  150. if (!$table_desc or count($table_desc) == 0) {
  151. tripal_report_error('tripal_core', TRIPAL_ERROR,
  152. "chado_generate_var: The table '%table' has not been defined. " .
  153. "and cannot be expanded. If this is a custom table, please add it using the Tripal " .
  154. "custom table interface.", array('%table' => $table));
  155. if ($return_array) {
  156. return array();
  157. }
  158. return FALSE;
  159. }
  160. $table_primary_key = $table_desc['primary key'][0];
  161. $table_columns = array_keys($table_desc['fields']);
  162. // Expandable fields without value needed for criteria--------------------------------------------
  163. // Add in the default expandable arrays
  164. // These are used for later expanding fields, tables, foreign keys and nodes
  165. $all->expandable_fields = array();
  166. $all->expandable_foreign_keys = array();
  167. if (array_key_exists('referring_tables', $table_desc) and $table_desc['referring_tables']) {
  168. $all->expandable_tables = $table_desc['referring_tables'];
  169. }
  170. else {
  171. $all->expandable_tables = array();
  172. }
  173. $all->expandable_nodes = array();
  174. // Get fields to be removed by name.................................
  175. // This gets all implementations of hook_exclude_field_from_<table>_by_default()
  176. // where <table> is the current table a variable is being created for.
  177. // This allows modules to specify that some fields should be excluded by default
  178. // For example, tripal core provides a tripal_core_exclude_field_from_feature_by_default()
  179. // which says that we usually don't want to include the residues field by default since
  180. // it can be very large and cause performance issues.
  181. // If a field is excluded by default it can always be expanded at a later point by calling
  182. // chado_expand_var($chado_var, 'field', <field name as shown in expandable_fields array>);
  183. // First get an array of all the fields to be removed for the current table
  184. // module_invoke_all() is drupal's way of invoking all implementations of the specified
  185. // hook and merging all of the results.
  186. // $fields_to_remove should be an array with the keys matching field names
  187. // and the values being strings to be executed using php_eval() to determine whether
  188. // to exclude the field (evaluates to TRUE) or not (evaluates to FALSE)
  189. $fields_to_remove = module_invoke_all('exclude_field_from_' . $table . '_by_default');
  190. // Now, for each field to be removed
  191. foreach ($fields_to_remove as $field_name => $criteria) {
  192. //replace <field_name> with the current field name
  193. $criteria = preg_replace('/<field_name> /', addslashes($field_name), $criteria);
  194. // if field_value needed we can't deal with this field yet
  195. if (preg_match('/<field_value> /', $criteria)) {
  196. break;
  197. }
  198. //if criteria then remove from query
  199. // @coder-ignore: only module designers can populate $criteria -not a security risk
  200. $success = php_eval('<?php return ' . $criteria . '; ?>');
  201. if ($success) {
  202. unset($table_columns[array_search($field_name, $table_columns)]);
  203. unset($fields_to_remove[$field_name]);
  204. $all->expandable_fields[] = $table . '.' . $field_name;
  205. }
  206. }
  207. // Get fields to be removed by type................................
  208. // This gets all implementations of hook_exclude_type_by_default().
  209. // This allows modules to specify that some types of fields should be excluded by default
  210. // For example, tripal core provides a tripal_core_exclude_type_by_default() which says
  211. // that text fields are often very large and if they are longer than 250 characters then
  212. // we want to exclude them by default
  213. // If a field is excluded by default it can always be expanded at a later point by calling
  214. // chado_expand_var($chado_var, 'field', <field name as shown in expandable_fields array>);
  215. // First get an array of all the types of fields to be removed for the current table
  216. // module_invoke_all() is drupal's way of invoking all implementations of the specified
  217. // hook and merging all of the results.
  218. // $types_to_remove should be an array with the keys matching field names
  219. // and the values being strings to be executed using php_eval() to determine whether
  220. // to exclude the field (evaluates to TRUE) or not (evaluates to FALSE)
  221. // (ie: array('text' => 'strlen("<field_value> ") > 100');
  222. $types_to_remove = module_invoke_all('exclude_type_by_default');
  223. // Get a list of all the types of fields
  224. // the key is the type of field and the value is an array of fields of this type
  225. $field_types = array();
  226. foreach ($table_desc['fields'] as $field_name => $field_array) {
  227. $field_types[$field_array['type']][] = $field_name;
  228. }
  229. // We want to use the types to remove in conjunction with our table field descriptions
  230. // to determine which fields might need to be removed
  231. foreach ($types_to_remove as $field_type => $criteria) {
  232. // if there are fields of that type to remove
  233. if (isset($field_types[$field_type])) {
  234. // Do any processing needed on the php criteria
  235. //replace <field_name> with the current field name
  236. $criteria = preg_replace('/<field_name> /', addslashes($field_name), $criteria);
  237. foreach ($field_types[$field_type] as $field_name) {
  238. // if field_value needed we can't deal with this field yet
  239. if (preg_match('/<field_value>/', $criteria)) {
  240. $fields_to_remove[$field_name] = $criteria;
  241. continue;
  242. }
  243. // if criteria then remove from query
  244. // (as long as <field_value> is not needed for the criteria to be evaluated)
  245. // @coder-ignore: only module designers can populate $criteria -not a security risk
  246. $success = php_eval('<?php return ' . $criteria . '; ?>');
  247. if ($success) {
  248. unset($table_columns[array_search($field_name, $table_columns)]);
  249. $all->expandable_fields[] = $table . '.' . $field_name;
  250. }
  251. } //end of foreach field of that type
  252. }
  253. } //end of foreach type to be removed
  254. // get the values for the record in the current table---------------------------------------------
  255. $results = chado_select_record($table, $table_columns, $values, $base_options);
  256. if ($results) {
  257. foreach ($results as $key => $object) {
  258. // Add empty expandable_x arrays
  259. $object->expandable_fields = $all->expandable_fields;
  260. $object->expandable_foreign_keys = $all->expandable_foreign_keys;
  261. $object->expandable_tables = $all->expandable_tables;
  262. $object->expandable_nodes = $all->expandable_nodes;
  263. // add curent table
  264. $object->tablename = $table;
  265. // check if the current table maps to a node type-----------------------------------------------
  266. // if this table is connected to a node there will be a chado_tablename table in drupal
  267. if (db_table_exists('chado_' . $table)) {
  268. // that has a foreign key to this one ($table_desc['primary key'][0]
  269. // and to the node table (nid)
  270. $sql = "
  271. SELECT $table_primary_key, nid
  272. FROM {chado_$table}
  273. WHERE $table_primary_key = :$table_primary_key
  274. ";
  275. $mapping = db_query($sql, array(":$table_primary_key" => $object->{$table_primary_key}))->fetchObject();
  276. if ($mapping and $mapping->$table_primary_key) {
  277. $object->nid = $mapping->nid;
  278. $object->expandable_nodes[] = $table;
  279. }
  280. }
  281. // remove any fields where criteria needs to be evalulated---------------------------------------
  282. // The fields to be removed can be populated by implementing either
  283. // hook_exclude_field_from_<table>_by_default() where <table> is the current table
  284. // OR hook_exclude_type_by_default() where there are fields of the specified type in the current table
  285. // It only reaches this point if the criteria specified for whether or not to
  286. // exclude the field includes <field_value> which means it has to be evaluated after
  287. // the query has been executed
  288. foreach ($fields_to_remove as $field_name => $criteria) {
  289. // If the field is an object then we don't support exclusion of it
  290. // For example, if the field is a foreign key
  291. if (!isset($object->{$field_name})) {
  292. break;
  293. }
  294. // replace <field_value> with the actual value of the field from the query
  295. $criteria = preg_replace('/<field_value>/', addslashes($object->{$field_name}), $criteria);
  296. // evaluate the criteria, if TRUE is returned then exclude the field
  297. // excluded fields can be expanded later by calling
  298. // chado_expand_var($var, 'field', <field name as shown in expandable_fields array>);
  299. $success = php_eval('<?php return ' . $criteria . '; ?>');
  300. if ($success) {
  301. unset($object->{$field_name});
  302. $object->expandable_fields[] = $table . '.' . $field_name;
  303. }
  304. }
  305. // recursively follow foreign key relationships nesting objects as we go------------------------
  306. if (array_key_exists('foreign keys', $table_desc) and $table_desc['foreign keys']) {
  307. foreach ($table_desc['foreign keys'] as $foreign_key_array) {
  308. $foreign_table = $foreign_key_array['table'];
  309. foreach ($foreign_key_array['columns'] as $foreign_key => $primary_key) {
  310. // Note: Foreign key is the field in the current table whereas primary_key is the field in
  311. // the table referenced by the foreign key
  312. //Dont do anything if the foreign key is empty
  313. if (empty($object->{$foreign_key})) {
  314. continue;
  315. }
  316. if (is_array($include_fk)) {
  317. // don't recurse if the callee has supplied an $fk_include list and this
  318. // FK table is not in the list.
  319. if (is_array($include_fk) and !array_key_exists($foreign_key, $include_fk)) {
  320. $object->expandable_foreign_keys[] = $table . '.' . $foreign_key . ' => ' . $foreign_table;
  321. continue;
  322. }
  323. }
  324. // if we have the option but it is not an array then we don't recurse any furutehr
  325. if ($include_fk === TRUE) {
  326. $object->expandable_foreign_keys[] = $table . '.' . $foreign_key . ' => ' . $foreign_table;
  327. continue;
  328. }
  329. // get the record from the foreign table
  330. $foreign_values = array($primary_key => $object->{$foreign_key});
  331. $options = array();
  332. if (is_array($include_fk)) {
  333. $options['include_fk'] = $include_fk[$foreign_key];
  334. }
  335. $foreign_object = chado_generate_var($foreign_table, $foreign_values, $options);
  336. // add the foreign record to the current object in a nested manner
  337. $object->{$foreign_key} = $foreign_object;
  338. // Flatten expandable_x arrays so only in the bottom object
  339. if (property_exists($object->{$foreign_key}, 'expandable_fields') and
  340. is_array($object->{$foreign_key}->expandable_fields)) {
  341. $object->expandable_fields = array_merge(
  342. $object->expandable_fields,
  343. $object->{$foreign_key}->expandable_fields
  344. );
  345. unset($object->{$foreign_key}->expandable_fields);
  346. }
  347. if (property_exists($object->{$foreign_key}, 'expandable_foreign_keys') and
  348. is_array($object->{$foreign_key}->expandable_foreign_keys)) {
  349. $object->expandable_foreign_keys = array_merge(
  350. $object->expandable_foreign_keys,
  351. $object->{$foreign_key}->expandable_foreign_keys
  352. );
  353. unset($object->{$foreign_key}->expandable_foreign_keys);
  354. }
  355. if (property_exists($object->{$foreign_key}, 'expandable_tables') and
  356. is_array($object->{$foreign_key}->expandable_tables)) {
  357. $object->expandable_tables = array_merge(
  358. $object->expandable_tables,
  359. $object->{$foreign_key}->expandable_tables
  360. );
  361. unset($object->{$foreign_key}->expandable_tables);
  362. }
  363. if (property_exists($object->{$foreign_key}, 'expandable_nodes') and
  364. is_array($object->{$foreign_key}->expandable_nodes)) {
  365. $object->expandable_nodes = array_merge(
  366. $object->expandable_nodes,
  367. $object->{$foreign_key}->expandable_nodes
  368. );
  369. unset($object->{$foreign_key}->expandable_nodes);
  370. }
  371. }
  372. }
  373. $results[$key] = $object;
  374. }
  375. }
  376. }
  377. // convert the results into an array
  378. $results_arr = array();
  379. foreach ($results as $record) {
  380. $results_arr[] = $record;
  381. }
  382. // check only one result returned
  383. if (!$return_array) {
  384. if (sizeof($results_arr) == 1) {
  385. // add results to object
  386. return $results_arr[0];
  387. }
  388. elseif (!empty($results_arr)) {
  389. return $results_arr;
  390. }
  391. else {
  392. // no results returned
  393. }
  394. }
  395. // the caller has requested results are always returned as
  396. // an array
  397. else {
  398. if (!$results_arr) {
  399. return array();
  400. }
  401. else {
  402. return $results_arr;
  403. }
  404. }
  405. }
  406. /**
  407. * Retrieves fields, or tables that were excluded by default from a variable.
  408. *
  409. * The chado_generate_var() function automatically excldue some
  410. * fields and tables from the default form of a variable. Fields that are
  411. * extremely long, such as text fields are automatically excluded to prevent
  412. * long page loads. Linking tables that have a many-to-one relationship with
  413. * the record are also excluded. This function allows for custom expansion
  414. * of the record created by chado_generate_var() by specifyin the field and
  415. * tables that should be added.
  416. *
  417. * Example Usage:
  418. * @code
  419. * // Get a chado object to be expanded
  420. * $values = array(
  421. * 'name' => 'Medtr4g030710'
  422. * );
  423. * $features = chado_generate_var('feature', $values);
  424. * // Expand the feature.residues field
  425. * $feature = chado_expand_var($feature, 'field', 'feature.residues');
  426. * // Expand the feature properties (featureprop table)
  427. * $feature = chado_expand_var($feature, 'table', 'featureprop');
  428. * @endcode
  429. *
  430. * If a field is requested, it's value is added where it normally is expected
  431. * in the record. If a table is requested then a new key/value element is
  432. * added to the record. The key is the table's name and the value is an
  433. * array of records (of the same type created by chado_generate_var()). For
  434. * example, expanding a 'feature' record to include a 'pub' record via the
  435. * 'feature_pub' table. The following provides a simple example for how
  436. * the 'feature_pub' table is added.
  437. *
  438. * @code
  439. * array(
  440. * 'feature_id' => 1
  441. * 'name' => 'blah',
  442. * 'uniquename' => 'blah',
  443. * ....
  444. * 'feature_pub => array(
  445. * [pub object],
  446. * [pub object],
  447. * [pub object],
  448. * [pub object],
  449. * )
  450. * )
  451. * @endcode
  452. *
  453. * where [pub object] is a record of a publication as created by
  454. * chado_generate_var().
  455. *
  456. * If the requested table has multiple foreign keys, such as the 'featureloc'
  457. * or 'feature_genotype' tables, then an additional level is added to the
  458. * array where the foreign key column names are added. An example feature
  459. * record with an expanded featureloc table is shown below:
  460. *
  461. * @code
  462. * array(
  463. * 'feature_id' => 1
  464. * 'name' => 'blah',
  465. * 'uniquename' => 'blah',
  466. * ....
  467. * 'featureloc => array(
  468. * 'srcfeature_id' => array(
  469. * [feature object],
  470. * ...
  471. * )
  472. * 'feature_id' => array(
  473. * [feature object],
  474. * ...
  475. * )
  476. * )
  477. * )
  478. * @endcode
  479. *
  480. * @param $object
  481. * This must be an object generated using chado_generate_var()
  482. * @param $type
  483. * Indicates what is being expanded. Must be one of 'field', 'foreign_key',
  484. * 'table', 'node'. While field and node are self-explanitory, it might help
  485. * to note that 'table' refers to tables that have a foreign key pointing to
  486. * the current table (ie: featureprop is a table that can be expanded for
  487. * features) and 'foreign_key' expands a foreign key in the current table
  488. * that might have been excluded (ie: feature.type_id for features).
  489. * @param $to_expand
  490. * The name of the field/foreign_key/table/node to be expanded
  491. * @param $table_options
  492. * - order_by:
  493. * An array containing options for the base table. For example, an
  494. * option of 'order_by' may be used to sort results in the base table
  495. * if more than one are returned. The options must be compatible with
  496. * the options accepted by the chado_select_record() function.
  497. * - return_array:
  498. * Additionally, The option 'return_array' can be provided to force
  499. * the function to expand tables as an array. Default behavior is to expand
  500. * a table as single record if only one record exists or to expand as an
  501. * array if multiple records exist.
  502. * - include_fk:
  503. * an array of FK relationships to follow. By default, the
  504. * chado_expand_var function will follow all FK relationships but this
  505. * may generate more queries then is desired slowing down this function call
  506. * when there are lots of FK relationships to follow. Provide an array
  507. * specifying the fields to include. For example, if expanding a property
  508. * table (e.g. featureprop) and you want the CV and accession but do not
  509. * want the DB the following array would work:
  510. * $table_options = array(
  511. * 'include_fk' => array(
  512. * 'type_id' => array(
  513. * 'cv_id' => 1,
  514. * 'dbxref_id' => 1,
  515. * )
  516. * )
  517. * );
  518. * The above array will expand the 'type_id' of the property table but only
  519. * further expand the cv_id and the dbxref_id and will go no further.
  520. * - pager:
  521. * Use this option if it is desired to return only a subset of results
  522. * so that they may be shown within a Drupal-style pager. This should be
  523. * an array with two keys: 'limit' and 'element'. The value of 'limit'
  524. * should specify the number of records to return and 'element' is a
  525. * unique integer to differentiate between pagers when more than one
  526. * appear on a page. The 'element' should start with zero and increment by
  527. * one for each pager. This only works when type is a 'table'.
  528. * - filter:
  529. * This options is only used where type=table and allows you to
  530. * expand only a subset of results based on the given criteria. Criteria
  531. * should provided as an array of [field name] => [value] similar to the
  532. * values array provided to chado_generate_var(). For example, when expanding
  533. * the featureprop table for a feature, you will already get only properties
  534. * for that feature, this option allows you to further get only properties
  535. * of a given type by passing in array('type_id' => array('name' => [name of type]))
  536. * @return
  537. * A chado object supplemented with the field/table/node requested to be expanded.
  538. * If the type is a table and it has already been expanded no changes is made to the
  539. * returned object
  540. *
  541. *
  542. * @ingroup tripal_chado_query_api
  543. */
  544. function chado_expand_var($object, $type, $to_expand, $table_options = array()) {
  545. // make sure we have a value
  546. if (!$object) {
  547. tripal_report_error('tripal_core', TRIPAL_ERROR,
  548. 'Cannot pass non array as argument, $object, to chado_expand_var function.', array());
  549. return $object;
  550. }
  551. // check to see if we are expanding an array of objects
  552. if (is_array($object)) {
  553. foreach ($object as $index => $o) {
  554. $object[$index] = chado_expand_var($o, $type, $to_expand);
  555. }
  556. return $object;
  557. }
  558. // get the base table name
  559. $base_table = $object->tablename;
  560. switch ($type) {
  561. case "field": //--------------------------------------------------------------------------------
  562. if (preg_match('/(\w+)\.(\w+)/', $to_expand, $matches)) {
  563. $tablename = $matches[1];
  564. $fieldname = $matches[2];
  565. $table_desc = chado_get_schema($tablename);
  566. // BASE CASE: the field is from the current table
  567. if ($base_table == $tablename) {
  568. // Use the table description to fully describe the current object
  569. // in a $values array to be used to select the field from chado
  570. $values = array();
  571. foreach ($table_desc['primary key'] as $key) {
  572. if(property_exists($object, $key)) {
  573. $values[$key] = $object->{$key};
  574. }
  575. }
  576. // Retrieve the field from Chado
  577. $results = chado_select_record($tablename, array($fieldname), $values);
  578. // Check that the field was retrieved correctly
  579. if (isset($results[0])) {
  580. $object->{$fieldname} = $results[0]->{$fieldname};
  581. $object->expanded = $to_expand;
  582. }
  583. // If it wasn't retrieved correctly, we need to warn the administrator
  584. }
  585. // RECURSIVE CASE: the field is in a nested object
  586. else {
  587. // We want to look at each field and if it's an object then we want to
  588. // attempt to expand the field in it via recursion
  589. foreach ((array) $object as $field_name => $field_value) {
  590. if (is_object($field_value)) {
  591. $object->{$field_name} = chado_expand_var(
  592. $field_value,
  593. 'field',
  594. $to_expand
  595. );
  596. }
  597. } //end of for each field in the current object
  598. }
  599. }
  600. // Otherwise we weren't able to extract the parts of the field to expand
  601. // Thus we will warn the administrator
  602. else {
  603. tripal_report_error('tripal_core', TRIPAL_ERROR,
  604. 'chado_expand_var: Field (%field) not in the right format. " .
  605. "It should be <tablename>.<fieldname>', array('%field' => $to_expand));
  606. }
  607. break;
  608. case "foreign_key": //--------------------------------------------------------------------------
  609. if (preg_match('/(\w+)\.(\w+) => (\w+)/', $to_expand, $matches)) {
  610. $table_name = $matches[1];
  611. $field_name = $matches[2];
  612. $foreign_table = $matches[3];
  613. $table_desc = chado_get_schema($table_name);
  614. // BASE CASE: The foreign key is from the current table
  615. if ($base_table == $table_name) {
  616. // Get the value of the foreign key from the object
  617. $field_value = $object->{$field_name};
  618. // Get the name of the field in the foreign table using the table description
  619. // For example, with the feature.type_id => cvterm.cvterm_id we need cvterm_id
  620. $foreign_field_name = FALSE;
  621. foreach ($table_desc['foreign keys'][$foreign_table]['columns'] as $left => $right) {
  622. if ($right == $field_name) {
  623. $foreign_field_name = $left;
  624. }
  625. }
  626. // Check that we were able to determine the field name in the foreign table
  627. if ($foreign_field_name) {
  628. // Generate a chado variable of the foreign key
  629. // For example, if the foreign key to expand is feature.type_id
  630. // then we want to generate a chado cvterm variable that matches the feature.type_id
  631. $foreign_var = chado_generate_var(
  632. $foreign_table, // thus in the example above, generate a cvterm var
  633. array($foreign_field_name => $field_value), // where the cvterm.cvterm_id = feature.type_id value
  634. $table_options //pass in the same options given to this function
  635. );
  636. // Check that the foreign object was returned
  637. if ($foreign_var) {
  638. // It was so now we can add this chado variable to our current object
  639. // in place of the key value
  640. $object->{$field_name} = $foreign_var;
  641. $object->expanded = $to_expand;
  642. }
  643. // Otherwise we weren't able to expand the foreign key
  644. else {
  645. tripal_report_error('tripal_core', TRIPAL_ERROR,
  646. 'chado_expand_var: unable to retrieve the object desribed by the foreign key
  647. while trying to expand %fk.',
  648. array('%fk' => $to_expand));
  649. }
  650. }
  651. // Else we were unable to determine the field name in the foreign table
  652. else {
  653. tripal_report_error('tripal_core', TRIPAL_ERROR,
  654. 'chado_expand_var: unable to determine the field name in the table the foreign
  655. key points to while trying to expand %fk.',
  656. array('%fk' => $to_expand));
  657. }
  658. }
  659. // RECURSIVE CASE: Check any nested objects
  660. else {
  661. foreach ((array) $object as $field_name => $field_value) {
  662. if (is_object($field_value)) {
  663. $object->{$field_name} = chado_expand_var(
  664. $field_value,
  665. 'foreign_key',
  666. $to_expand
  667. );
  668. }
  669. } //end of for each field in the current object
  670. }
  671. }
  672. // Otherwise we weren't able to extract the parts of the foreign key to expand
  673. // Thus we will warn the administrator
  674. else {
  675. tripal_report_error('tripal_core', TRIPAL_ERROR,
  676. 'chado_expand_var: foreign_key (%fk) not in the right format. " .
  677. "It should be <tablename>.<fieldname>', array('%fk' => $to_expand));
  678. }
  679. break;
  680. case "table": //--------------------------------------------------------------------------------
  681. $foreign_table = $to_expand;
  682. // BASE CASE: don't expand the table it already is expanded
  683. if (array_key_exists($foreign_table, $object)) {
  684. return $object;
  685. }
  686. $foreign_table_desc = chado_get_schema($foreign_table);
  687. // TODO: if we don't get a foreign_table (which could happen of a custom table
  688. // is not correctly defined or the table name is mispelled then we should return
  689. // gracefully.
  690. // BASE CASE: If it's connected to the base table via a FK constraint
  691. // then we have all the information needed to expand it now
  692. if (array_key_exists($base_table, $foreign_table_desc['foreign keys'])) {
  693. foreach ($foreign_table_desc['foreign keys'][$base_table]['columns'] as $left => $right) {
  694. // if the FK value in the base table is not there then we can't expand it, so just skip it.
  695. if (!$object->{$right}) {
  696. continue;
  697. }
  698. // If the user wants to limit the results they expand, make sure
  699. // those criteria are taken into account.
  700. if (isset($table_options['filter'])) {
  701. if (is_array($table_options['filter'])) {
  702. $filter_criteria = $table_options['filter'];
  703. $filter_criteria[$left] = $object->{$right};
  704. }
  705. else {
  706. // If they supplied criteria but it's not in the correct format
  707. // then warn them but proceed as though criteria was not supplied.
  708. $filter_criteria = array($left => $object->{$right});
  709. tripal_report_error('tripal_core', TRIPAL_WARNING,
  710. 'chado_expand_var: unable to apply supplied filter criteria
  711. since it should be an array. You supplied %criteria',
  712. array('%criteria' => print_r($table_options['filter'], TRUE))
  713. );
  714. }
  715. }
  716. else {
  717. $filter_criteria = array($left => $object->{$right});
  718. }
  719. // generate a new object for this table using the FK values in the base table.
  720. $new_options = $table_options;
  721. $foreign_object = chado_generate_var($foreign_table, $filter_criteria, $new_options);
  722. // if the generation of the object was successful, update the base object to include it.
  723. if ($foreign_object) {
  724. // in the case where the foreign key relationship exists more
  725. // than once with the same table we want to alter the array structure to
  726. // include the field name.
  727. if (count($foreign_table_desc['foreign keys'][$base_table]['columns']) > 1) {
  728. if (!property_exists($object, $foreign_table)) {
  729. $object->{$foreign_table} = new stdClass();
  730. }
  731. $object->{$foreign_table}->{$left} = $foreign_object;
  732. $object->expanded = $to_expand;
  733. }
  734. else {
  735. if (!property_exists($object, $foreign_table)) {
  736. $object->{$foreign_table} = new stdClass();
  737. }
  738. $object->{$foreign_table} = $foreign_object;
  739. $object->expanded = $to_expand;
  740. }
  741. }
  742. // if the object returned is NULL then handle that
  743. else {
  744. // in the case where the foreign key relationship exists more
  745. // than once with the same table we want to alter the array structure to
  746. // include the field name.
  747. if (count($foreign_table_desc['foreign keys'][$base_table]['columns']) > 1) {
  748. if (!property_exists($object, $foreign_table)) {
  749. $object->{$foreign_table} = new stdClass();
  750. }
  751. $object->{$foreign_table}->{$left} = NULL;
  752. }
  753. else {
  754. $object->{$foreign_table} = NULL;
  755. }
  756. }
  757. }
  758. }
  759. // RECURSIVE CASE: if the table is not connected directly to the current base table
  760. // through a foreign key relationship, then maybe it has a relationship to
  761. // one of the nested objects.
  762. else {
  763. // We need to recurse -the table has a relationship to one of the nested objects
  764. // We assume it's a nested object if the value of the field is an object
  765. $did_expansion = 0;
  766. foreach ((array) $object as $field_name => $field_value) {
  767. // CASE #1: This field is an already expanded foreign key and the table to be
  768. // expanded is in the table referenced by the foreign key
  769. // First of all it can only be expanded if it's an object
  770. // And if it's a foreign key it should have a tablename property
  771. if (is_object($field_value) AND property_exists($field_value, 'tablename')) {
  772. $object->{$field_name} = chado_expand_var($field_value, 'table', $foreign_table);
  773. }
  774. // CASE #2: This field is an already expanded object (ie: the field is actually
  775. // the expanded table name) and the table to be expanded si related to it
  776. // check to see if the $field_name is a valid chado table, we don't need
  777. // to call chado_expand_var on fields that aren't tables
  778. $check = chado_get_schema($field_name);
  779. if ($check) {
  780. $did_expansion = 1;
  781. $object->{$field_name} = chado_expand_var($field_value, 'table', $foreign_table);
  782. }
  783. }
  784. // if we did not expand this table we should return a message that the foreign table
  785. // could not be expanded
  786. if (!$did_expansion) {
  787. tripal_report_error('tripal_core', TRIPAL_ERROR, 'chado_expand_var: Could not expand %table. ' .
  788. 'The table is either not related to the base object through a foreign key relationships or ' .
  789. 'it is already expanded. First check the object to ensure it doesn’t already contain the ' .
  790. 'data needed and otherwise check the table definition using chado_get_schema() to ensure ' .
  791. 'a proper foreign key relationship is present.',
  792. array('%table' => $foreign_table));
  793. }
  794. }
  795. break;
  796. case "node": //---------------------------------------------------------------------------------
  797. // BASE CASE: if the node to be expanded is for our base table, then just expand it
  798. if ($object->tablename == $to_expand) {
  799. // Load the node based on the current objects nid (node primary key)
  800. $node = NULL;
  801. if (property_exists($object, 'nid')) {
  802. $node = node_load($object->nid);
  803. }
  804. // Try to get the nid based on the tablename
  805. else {
  806. // Invoke all hook_node_info to avoid hard-coding the chado_$table assumption
  807. foreach (module_invoke_all('node_info') as $node_info) {
  808. if (array_key_exists('chado_node_api', $node_info)) {
  809. if ($node_info['chado_node_api']['base_table'] == $object->tablename) {
  810. $key_name = $node_info['chado_node_api']['base_table'] . '_id';
  811. $nid = chado_get_nid_from_id(
  812. $node_info['chado_node_api']['base_table'],
  813. $object->{$key_name},
  814. $node_info['base']);
  815. if ($nid > 0) {
  816. $object->nid = $nid;
  817. $node = node_load($nid);
  818. break;
  819. }
  820. }
  821. }
  822. }
  823. }
  824. // If we have successfully loaded the node...
  825. if ($node) {
  826. // Move expandable arrays from the object into the node
  827. $object->expanded = $to_expand;
  828. $node->expandable_fields = $object->expandable_fields;
  829. unset($object->expandable_fields);
  830. $node->expandable_tables = $object->expandable_tables;
  831. unset($object->expandable_tables);
  832. $node->expandable_nodes = $object->expandable_nodes;
  833. unset($object->expandable_nodes);
  834. // The node becomes the base object with the obejct added to it.
  835. // For example, we may start with a feature object with a name, uniquename , type, etc.
  836. // After expanding we will return the node and at $node->feature you will find the original object
  837. $node->{$base_table} = $object;
  838. $object = $node;
  839. }
  840. // Else we were unable to load the node
  841. else {
  842. // Warn the administrator
  843. if (isset($object->nid)) {
  844. tripal_report_error('tripal_core', TRIPAL_ERROR, 'chado_expand_var: No node matches the nid (%nid) supplied.',
  845. array('%nid' => $object->nid));
  846. }
  847. else {
  848. tripal_report_error('tripal_core', TRIPAL_NOTICE, 'chado_expand_var: There is no node for the current object: <pre>%object</pre>', array('%object' => print_r($object,TRUE)));
  849. }
  850. } //end of if node
  851. }
  852. // RECURSIVE CASE: check to see if the node to be expanded associates with a
  853. // chado table within one of the nested objects.
  854. else {
  855. // We need to recurse -the node to expand is one of the nested objects
  856. // We assume it's a nested object if the field value is an object
  857. foreach ((array) $object as $field_name => $field_value) {
  858. if (is_object($field_value)) {
  859. $object->{$field_name} = chado_expand_var(
  860. $field_value,
  861. 'node',
  862. $to_expand
  863. );
  864. }
  865. } //end of for each field in the current object
  866. }
  867. break;
  868. // The $type to be expanded is not yet supported
  869. default:
  870. tripal_report_error('tripal_core', TRIPAL_ERROR, 'chado_expand_var: Unrecognized type (%type). Should be one of "field", "table", "node".',
  871. array('%type' => $type));
  872. return FALSE;
  873. }
  874. // Move expandable arrays downwards -------------------------------
  875. // If the type was either table or foreign key then a new chado variable was generated
  876. // this variable will have it's own expandable array's which need to be moved down
  877. // and merged with the base objects expandable arrays
  878. // Thus, check all nested objects for expandable arrays
  879. // and if they have them, move them downwards
  880. foreach ( (array)$object as $field_name => $field_value) {
  881. if (is_object($field_value)) {
  882. // The current nested object has expandable arrays
  883. if (isset($field_value->expandable_fields)) {
  884. // Move expandable fields downwards
  885. if (isset($field_value->expandable_fields) and is_array($field_value->expandable_fields)) {
  886. // If the current object has it's own expandable fields then merge them
  887. if (isset($object->expandable_fields)) {
  888. $object->expandable_fields = array_merge(
  889. $object->expandable_fields,
  890. $object->{$field_name}->expandable_fields
  891. );
  892. unset($object->{$field_name}->expandable_fields);
  893. }
  894. // Otherwise, just move the expandable fields downwards
  895. else {
  896. $object->expandable_fields = $object->{$field_name}->expandable_fields;
  897. unset($object->{$field_name}->expandable_fields);
  898. }
  899. }
  900. // Move expandable foreign keys downwards
  901. if (isset($field_value->expandable_foreign_keys) and is_array($field_value->expandable_foreign_keys)) {
  902. // If the current object has it's own expandable foreign keys then merge them
  903. if (isset($object->expandable_foreign_keys)) {
  904. $object->expandable_foreign_keys = array_merge(
  905. $object->expandable_foreign_keys,
  906. $object->{$field_name}->expandable_foreign_keys
  907. );
  908. unset($object->{$field_name}->expandable_foreign_keys);
  909. }
  910. // Otherwise, just move the expandable foreign keys downwards
  911. else {
  912. $object->expandable_foreign_keys = $object->{$field_name}->expandable_foreign_keys;
  913. unset($object->{$field_name}->expandable_foreign_keys);
  914. }
  915. }
  916. // Move expandable tables downwards
  917. if (isset($field_value->expandable_tables) and is_array($field_value->expandable_tables)) {
  918. // If the current object has it's own expandable tables then merge them
  919. if (isset($object->expandable_tables)) {
  920. $object->expandable_tables = array_merge(
  921. $object->expandable_tables,
  922. $object->{$field_name}->expandable_tables
  923. );
  924. unset($object->{$field_name}->expandable_tables);
  925. }
  926. // Otherwise, just move the expandable tables downwards
  927. else {
  928. $object->expandable_tables = $object->{$field_name}->expandable_tables;
  929. unset($object->{$field_name}->expandable_tables);
  930. }
  931. }
  932. // Move expandable nodes downwards
  933. if (isset($field_value->expandable_nodes) and is_array($field_value->expandable_nodes)) {
  934. // If the current object has it's own expandable tables then merge them
  935. if (isset($object->expandable_nodes)) {
  936. $object->expandable_nodes = array_merge(
  937. $object->expandable_nodes,
  938. $object->{$field_name}->expandable_nodes
  939. );
  940. unset($object->{$field_name}->expandable_nodes);
  941. }
  942. // Otherwise, just move the expandable tables downwards
  943. else {
  944. $object->expandable_nodes = $object->{$field_name}->expandable_nodes;
  945. unset($object->{$field_name}->expandable_nodes);
  946. }
  947. }
  948. }
  949. }
  950. }
  951. // Move extended array downwards ----------------------------------
  952. // This tells us what we have expanded (ie: that we succeeded)
  953. // and is needed to remove the entry from the expandable array
  954. // If there is no expanded field in the current object then check any of the nested objects
  955. // and move it down
  956. if (!property_exists($object, 'expanded')) {
  957. // It's a nested object if the value is an object
  958. foreach ( (array)$object as $field_name => $field_value) {
  959. if (is_object($field_value)) {
  960. // Check if the current nested object has an expanded array
  961. if (isset($field_value->expanded)) {
  962. // If so, then move it downwards
  963. $object->expanded = $field_value->expanded;
  964. unset($field_value->expanded);
  965. }
  966. }
  967. }
  968. }
  969. // Check again if there is an expanded field in the current object
  970. // We check again because it might have been moved downwards above
  971. if (property_exists($object, 'expanded')) {
  972. // If so, then remove the expanded identifier from the correct expandable array
  973. $expandable_name = 'expandable_' . $type . 's';
  974. if (property_exists($object, $expandable_name) and $object->{$expandable_name}) {
  975. $key_to_remove = array_search($object->expanded, $object->{$expandable_name});
  976. unset($object->{$expandable_name}[$key_to_remove]);
  977. unset($object->expanded);
  978. }
  979. }
  980. // Finally, Return the object!
  981. return $object;
  982. }