tripal_chado.variables.api.inc 47 KB

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