tripal_chado.variables.api.inc 47 KB

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