tripal_core.chado_variables.api.inc 42 KB

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