tripal_chado.variables.api.inc 47 KB

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