tripal_chado.variables.api.inc 47 KB

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