tripal_chado.variables.api.inc 47 KB

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