tripal_chado.variables.api.inc 43 KB

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