tripal_chado.variables.api.inc 44 KB

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