tripal_chado.variables.api.inc 47 KB

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