tripal_chado.variables.api.inc 47 KB

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