tripal.entities.api.inc 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025
  1. <?php
  2. /**
  3. * A replacement for the entity_load function of Drupal.
  4. *
  5. * This function should be used for loading of Tripal Entities. It provides
  6. * greater control to limit which fields are loaded with the entity. The
  7. * entity_load() function of Drupal will automatically attach all fields at
  8. * once but this may not be desired as some fields can be comples and large and
  9. * the site developer may desire loading of fields via AJAX or the user of
  10. * web services may wish to specify the fields they want to include.
  11. *
  12. * @param $entity_type:
  13. * The entity type to load, e.g. node or user.
  14. * @param $ids
  15. * An array of entity IDs, or FALSE to load all entities.
  16. * @param $reset: Whether to reset the internal cache for the requested entity
  17. * type. Unlike the entity_load() function this defaults to TRUE.
  18. * @param $field_ids
  19. * A list of numeric feild IDs that should be loaded. The
  20. * TripalField named 'content_type' is always automatically added.
  21. *
  22. * @return
  23. * An array of entity objects indexed by their ids. When no results are
  24. * found, an empty array is returned.
  25. */
  26. function tripal_load_entity($entity_type, $ids = FALSE, $reset = TRUE,
  27. $field_ids = array()) {
  28. // The $conditions is deprecated in the funtion arguments of entity_load
  29. // so it was removed from the parameters of this function as well. But
  30. // the load() function of the entity controller still expects it so set it
  31. // to an empty array.
  32. $conditions = array();
  33. // If this isn't a TripalEntity then just load it the old fashioned way
  34. // although caching will not be used if it not specifically set to FALSE.
  35. if ($entity_type != 'TripalEntity') {
  36. return entity_load($entity_type, $ids, $conditions, $reset);
  37. }
  38. // Get the entity controller and clear the cache if requested (default).
  39. $ec = entity_get_controller($entity_type);
  40. if ($reset) {
  41. $ec->resetCache();
  42. }
  43. return $ec->load($ids, $conditions, $field_ids);
  44. }
  45. /**
  46. * Retrieves a TripalTerm entity that matches the given arguments.
  47. *
  48. * @param $values
  49. * An associative array used to match a term. Valid keys may be 'vocabulary',
  50. * 'accession, or 'term_id'. The keys 'vocabulary' and 'accession' must
  51. * always be used together to uniquely identify a term. The key 'term_id'
  52. * can be used alone to uniquely identify a term.
  53. *
  54. * @return
  55. * A TripalTerm entity object or NULL if not found.
  56. */
  57. function tripal_load_term_entity($values) {
  58. $vocabulary = array_key_exists('vocabulary', $values) ? $values['vocabulary'] : '';
  59. $accession = array_key_exists('accession', $values) ? $values['accession'] : '';
  60. $term_id = array_key_exists('term_id', $values) ? $values['term_id'] : '';
  61. $term = NULL;
  62. if ($vocabulary and $accession) {
  63. $query = db_select('tripal_term', 'tt');
  64. $query->join('tripal_vocab', 'tv', 'tv.id = tt.vocab_id');
  65. $query->fields('tt', array('id'))
  66. ->fields('tv', array('vocabulary'))
  67. ->condition('tv.vocabulary', $vocabulary)
  68. ->condition('tt.accession', $accession);
  69. $term = $query->execute()->fetchObject();
  70. }
  71. else if ($term_id) {
  72. $query = db_select('tripal_term', 'tt');
  73. $query->fields('tt', array('id'))
  74. ->condition('tt.id', $term_id);
  75. $term = $query->execute()->fetchObject();
  76. }
  77. if ($term) {
  78. $entity = entity_load('TripalTerm', array($term->id));
  79. return reset($entity);
  80. }
  81. return NULL;
  82. }
  83. /**
  84. * Retrieves a TripalVocab entity that maches the given arguments.
  85. *
  86. * @param $values
  87. * An associative array used to match a vocabulary. The valid keys are
  88. * 'vocab_id' and 'vocabulary'.
  89. *
  90. * @return
  91. * A TripalVocab entity object or NULL if not found.
  92. */
  93. function tripal_load_vocab_entity($values) {
  94. $vocabulary = array_key_exists('vocabulary', $values) ? $values['vocabulary'] : '';
  95. $vocab_id = array_key_exists('vocab_id', $values) ? $values['vocab_id'] : '';
  96. $vocab = NULL;
  97. $query= db_select('tripal_vocab', 'tv')
  98. ->fields('tv');
  99. if ($vocabulary) {
  100. $query->condition('tv.vocabulary', $vocabulary);
  101. }
  102. if ($vocab_id) {
  103. $query->condition('tv.id', $vocab_id);
  104. }
  105. $vocab = $query->execute()->fetchObject();
  106. if ($vocab) {
  107. $entity = entity_load('TripalVocab', array($vocab->id));
  108. return reset($entity);
  109. }
  110. return NULL;
  111. }
  112. /**
  113. * Retrieves a TripalBundle entity that matches the given arguments.
  114. *
  115. * @param $values
  116. * An associative array used to match a bundle. Valid keys may:
  117. * - id: the numeric id of the bundle.
  118. * - name: the bundle name (e.g. 'bio_data_234')
  119. * - label: the bundle label (e.g. 'Organism')
  120. * - term_id: the term ID to which the bundle belongs
  121. *
  122. * @return
  123. * A TripalBundle entity object or NULL if not found.
  124. */
  125. function tripal_load_bundle_entity($values) {
  126. $query = db_select('tripal_bundle', 'tb');
  127. $query->fields('tb');
  128. if (array_key_exists('id', $values)) {
  129. $query->condition('tb.id', $values['id']);
  130. }
  131. if (array_key_exists('name', $values)) {
  132. $query->condition('tb.name', $values['name']);
  133. }
  134. if (array_key_exists('label', $values)) {
  135. $query->condition('tb.label', $values['label']);
  136. }
  137. if (array_key_exists('term_id', $values)) {
  138. $query->condition('tb.term_id', $values['term_id']);
  139. }
  140. $bundle = $query->execute()->fetchObject();
  141. if ($bundle) {
  142. $entity = entity_load('TripalBundle', array($bundle->id));
  143. return reset($entity);
  144. }
  145. return NULL;
  146. }
  147. /**
  148. * Allows a module to perform tasks after a TripalBundle object is created.
  149. *
  150. * @param $bundle
  151. * The newly created TripalBundle object.
  152. */
  153. function hook_bundle_create(&$bundle) {
  154. }
  155. /**
  156. * Creates a new Tripal Entity type (i.e. bundle).
  157. *
  158. * @param $vocabulary
  159. * The abbreviated vocabulary for the vocabulary (e.g. RO, SO, PATO).
  160. * @param $accession
  161. * The unique term ID in the vocabulary $vocabulary (i.e. an accession).
  162. * @param $term_name
  163. * A human-readable name for this term. This will became the name that
  164. * appears for the content type. In practice, this should be the name
  165. * of the term. (E.g. the name for SO:0000704 is gene).
  166. * @param $error
  167. * A string, passed by reference, that is filled with the error message
  168. * if the function fails.
  169. *
  170. * @return
  171. * TRUE if the entity type (bundle) was succesfully created. FALSE otherwise.
  172. */
  173. function tripal_create_bundle($vocabulary, $accession, $term_name, &$error = '') {
  174. $transaction = db_transaction();
  175. try {
  176. // First create the TripalVocab if it doesn't already exist.
  177. $vocab = tripal_load_vocab_entity(array('vocabulary' => $vocabulary));
  178. if (!$vocab) {
  179. $vocab = entity_get_controller('TripalVocab')->create(array('vocabulary' => $vocabulary));
  180. $vocab->save();
  181. }
  182. // Next create the TripalTerm if it doesn't already exist.
  183. $term = tripal_load_term_entity(array(
  184. 'vocabulary' => $vocabulary,
  185. 'accession' => $accession
  186. ));
  187. if (!$term) {
  188. $args = array('vocab_id' => $vocab->id, 'accession' => $accession, 'name' => $term_name);
  189. $term = entity_get_controller('TripalTerm')->create($args);
  190. $term = $term->save();
  191. }
  192. // If the bundle doesn't already exist, then add it.
  193. $bundle_name = 'bio_data_' . $term->id;
  194. $einfo = entity_get_info('TripalEntity');
  195. if (!in_array($bundle_name, array_keys($einfo['bundles']))) {
  196. // Insert the bundle.
  197. db_insert('tripal_bundle')
  198. ->fields(array(
  199. 'label' => $term_name,
  200. 'type' => 'TripalEntity',
  201. 'name' => $bundle_name,
  202. 'term_id' => $term->id,
  203. ))
  204. ->execute();
  205. }
  206. // Allow modules to make additions to the entity when it's created.
  207. $bundle = tripal_load_bundle_entity(array('name' => $bundle_name));
  208. $modules = module_implements('bundle_create');
  209. foreach ($modules as $module) {
  210. $function = $module . '_bundle_create';
  211. $function($bundle);
  212. }
  213. // Clear the entity cache so that Drupal will read our
  214. // hook_entity_info() implementation.
  215. global $language;
  216. $langcode = $language->language;
  217. cache_clear_all("entity_info:$langcode", 'cache');
  218. variable_set('menu_rebuild_needed', TRUE);
  219. // Get the bundle object.
  220. $bundle = tripal_load_bundle_entity(array('name' => $bundle_name));
  221. // Get the list of fields to create.
  222. foreach (module_implements('field_create_info') as $module) {
  223. $function = $module . '_field_create_info';
  224. if (function_exists($function)) {
  225. $fields = $function('TripalEntity', $bundle);
  226. if (!$fields){
  227. continue;
  228. }
  229. foreach ($fields as $field_name => $info) {
  230. // If the field already exists then skip it.
  231. $field = field_info_field($info['field_name']);
  232. if ($field) {
  233. continue;
  234. }
  235. $field = field_create_field($info);
  236. if (!$field) {
  237. tripal_set_message(t("Could not create new field: %field.",
  238. array('%field' => $info['field_name'])), TRIPAL_ERROR);
  239. }
  240. }
  241. }
  242. }
  243. // Now get the list of field instances to add to the bundle.
  244. foreach (module_implements('field_create_instance_info') as $module) {
  245. $function = $module . '_field_create_instance_info';
  246. if (function_exists($function)) {
  247. $fields = $function('TripalEntity', $bundle);
  248. if (!$fields){
  249. continue;
  250. }
  251. foreach ($fields as $field_name => $info) {
  252. // If the field is already attached to this bundle then skip it.
  253. $field = field_info_field($info['field_name']);
  254. if ($field and array_key_exists('bundles', $field) and
  255. array_key_exists('TripalEntity', $field['bundles']) and
  256. in_array($bundle_name, $field['bundles']['TripalEntity'])) {
  257. continue;
  258. }
  259. $instance = field_create_instance($info);
  260. }
  261. }
  262. }
  263. }
  264. catch (Exception $e) {
  265. $transaction->rollback();
  266. $error = _drupal_decode_exception($e);
  267. drupal_set_message(t("Failed to create content type': %message",
  268. array('%message' => $error['!message'])), 'error');
  269. return FALSE;
  270. }
  271. return TRUE;
  272. }
  273. /**
  274. * Refreshes the bundle such that new fields added by modules will be found.
  275. *
  276. * @param $bundle_name
  277. * The name of the bundle to refresh (e.g. bio_data_4).
  278. */
  279. function tripal_refresh_bundle_fields($bundle_name) {
  280. // Get the bundle object.
  281. $bundle = tripal_load_bundle_entity(array('name' => $bundle_name));
  282. if (!$bundle) {
  283. tripal_report_error('tripal', TRIPAL_ERROR, "Unrecognized bundle name '%bundle'.",
  284. array('%bundle' => $bundle_name));
  285. return FALSE;
  286. }
  287. $term = tripal_load_term_entity(array('term_id' => $bundle->term_id));
  288. // Allow modules now add fields to the bundle
  289. module_invoke_all('add_bundle_fields', 'TripalEntity', $bundle, $term);
  290. // Allow modules to update existing fields
  291. module_invoke_all('update_bundle_fields', 'TripalEntity', $bundle, $term);
  292. }
  293. /**
  294. * Updates an existing field and its attached instance to a bundle.
  295. *
  296. *
  297. * @param $field_name
  298. * The name of the field.
  299. * @param $field_info
  300. * An associative array containing the field information. The following
  301. * key/value pairs are supported:
  302. * 'field_type' : a valid field type. May be any of the Drupal default
  303. * fields, one created by the tripal_chado module or another custom module.
  304. * 'widget_type' : a valid widget type. May be any of the Drupal default
  305. * fields, one created by the tripal_chado module or another custom module.
  306. * 'field_settings' : an array of settings that are appropriate for the
  307. * selected field type.
  308. * 'widget_settings' : an array of settings that are appropriate for the
  309. * selected widget type.
  310. * 'description' : a default description for this field.
  311. * 'label' : a label used as a header for this field.
  312. * 'is_required' : indicates if the field is required in the edit form.
  313. * 'cardinality' : indicates the number of values this field can support.
  314. * the default is 1 (meaning only one value). Use a value of
  315. * FIELD_CARDINALITY_UNLIMITED for unlimited number of values.
  316. * 'default_value' : A default value for the field.
  317. * 'format' : A string indicating the format for the field. Must be
  318. * specific to the field.
  319. * @param $entity_type_name
  320. * The entity type name.
  321. * @param $bundle_name
  322. * The bundle name.
  323. *
  324. * @return
  325. * FALSE if the field could not be updated
  326. *
  327. * TODO: this function really shouldn't try to create an instance and
  328. * attach to a bundle at the same time.
  329. *
  330. */
  331. function tripal_update_bundle_field($field_name, $field_info, $entity_type_name, $bundle_name) {
  332. $field = field_info_field($field_name);
  333. // If the field doesn't exists or is not attached to this bundle then
  334. // just return, there is nothing left to do.
  335. if (!$field or !array_key_exists('bundles', $field) or
  336. !array_key_exists($entity_type_name, $field['bundles']) or
  337. !in_array($bundle_name, $field['bundles'][$entity_type_name])) {
  338. return FALSE;
  339. }
  340. $field['field_name'] = $field_name;
  341. if (array_key_exists('field_type', $field_info)) {
  342. $field['cardinality'] = $field_info['cardinality'];
  343. }
  344. if (array_key_exists('locked', $field_info)) {
  345. $field['locked'] = $field_info['locked'];
  346. }
  347. if (array_key_exists('storage', $field_info)) {
  348. $field['storage']['type'] = $field_info['storage'];
  349. }
  350. if (array_key_exists('field_settings', $field_info)) {
  351. $field['settings'] = $field_info['field_settings'];
  352. }
  353. field_update_field($field);
  354. $field_instance['field_name'] = $field_name;
  355. $field_instance['entity_type'] = $entity_type_name;
  356. $field_instance['bundle'] = $bundle_name;
  357. if (array_key_exists('label', $field_info)) {
  358. $field['label'] = $field_info['label'];
  359. }
  360. if (array_key_exists('description', $field_info)) {
  361. $field['description'] = $field_info['description'];
  362. }
  363. if (array_key_exists('widget', $field_info)) {
  364. if (array_key_exists('widget_type', $field_info['widget'])) {
  365. $field['widget']['type'] = $field_info['widget_type'];
  366. }
  367. if (array_key_exists('widget_settings', $field_info['widget'])) {
  368. $field['widget']['settings'] = $field_info['widget_settings'];
  369. }
  370. }
  371. if (array_key_exists('required', $field_info)) {
  372. $field['required'] = $field_info['is_required'];
  373. }
  374. if (array_key_exists('settings', $field_info)) {
  375. $field['settings'] = $field_info['field_settings'];
  376. }
  377. if (array_key_exists('default_value', $field_info)) {
  378. $field['default_value'] = $field_info['default_value'];
  379. }
  380. if (array_key_exists('format', $field_info)) {
  381. $field['format'] = $field_info['format'];
  382. }
  383. field_update_instance($field_instance);
  384. }
  385. /**
  386. * Allows a module to make changes to an entity object after creation.
  387. *
  388. * This function is added by Tripal to allow datastore backends to add
  389. * addition properties to the entity that they themselves will use later.
  390. *
  391. * @param $entity
  392. * @param $entity_type
  393. */
  394. function hook_entity_create(&$entity, $entity_type) {
  395. }
  396. /**
  397. * @section
  398. * Bundle Variables.
  399. */
  400. /**
  401. * Fetch the value for a given tripal variable.
  402. *
  403. * @param string $variable_name
  404. * The name of the variable as in tripal_variables.name.
  405. * @param int $bundle_id
  406. * The unique identfier for the bundle you want the value for.
  407. * @return text
  408. * The value of the specified variable for the specified bundle.
  409. */
  410. function tripal_get_bundle_variable($variable_name, $bundle_id, $default = FALSE) {
  411. $variable = tripal_get_variable($variable_name);
  412. // Warn if we can't find the tripal_variable.
  413. if (!$variable) {
  414. return $default;
  415. }
  416. // Select the value for this variable.
  417. $value = db_select('tripal_bundle_variables', 'var')
  418. ->fields('var', array('value'))
  419. ->condition('var.bundle_id', $bundle_id)
  420. ->condition('var.variable_id', $variable->variable_id)
  421. ->execute()
  422. ->fetchField();
  423. // Warn if the value appears to be empty.
  424. if (!$value) {
  425. return $default;
  426. }
  427. return $value;
  428. }
  429. /**
  430. * Save the value of a tripal variable for a given bundle.
  431. *
  432. * @param string $variable_name
  433. * The name of the variable as in tripal_variables.name.
  434. * @param int $bundle_id
  435. * The unique identfier for the bundle you want the value for.
  436. * @param $text $value
  437. * The value of the variable for the given bundle.
  438. */
  439. function tripal_set_bundle_variable($variable_name, $bundle_id, $value) {
  440. $variable = tripal_get_variable($variable_name);
  441. if (!$variable) {
  442. return FALSE;
  443. }
  444. // And then we need to write the new format to the tripal_bundle_variables table.
  445. $record = array(
  446. 'bundle_id' => $bundle_id,
  447. 'variable_id' => $variable->variable_id,
  448. 'value' => $value,
  449. );
  450. // Check whether there is already a format saved.
  451. $bundle_variable_id = db_select('tripal_bundle_variables', 'var')
  452. ->fields('var', array('bundle_variable_id'))
  453. ->condition('var.bundle_id', $record['bundle_id'])
  454. ->condition('var.variable_id', $record['variable_id'])
  455. ->execute()
  456. ->fetchField();
  457. if ($bundle_variable_id) {
  458. $record['bundle_variable_id'] = $bundle_variable_id;
  459. return drupal_write_record('tripal_bundle_variables', $record, 'bundle_variable_id');
  460. }
  461. else {
  462. return drupal_write_record('tripal_bundle_variables', $record);
  463. }
  464. }
  465. /**
  466. * @section
  467. * Title & URL Formats.
  468. */
  469. /**
  470. * Get Page Title Format for a given Tripal Entity Type.
  471. *
  472. * @param TripalBundle $entity
  473. * The Entity object for the Tripal Bundle the title format is for.
  474. */
  475. function tripal_get_title_format($entity) {
  476. // Get the existing title format if it exists.
  477. $title_format = tripal_get_bundle_variable('title_format', $entity->id);
  478. // If there isn't yet a title format for this bundle/type then we should
  479. // determine the default.
  480. if (!$title_format) {
  481. $title_format = tripal_get_default_title_format($entity);
  482. tripal_save_title_format($entity, $title_format);
  483. }
  484. return $title_format;
  485. }
  486. /**
  487. * Save Page Title Format for a given Tripal Entity Type.
  488. *
  489. * @param TripalBundle $entity
  490. * The Entity object for the Tripal Bundle the title format is for.
  491. * @param string $format
  492. * The pattern to be used when generating entity titles for the above type.
  493. */
  494. function tripal_save_title_format($entity, $format) {
  495. return tripal_set_bundle_variable('title_format', $entity->id, $format);
  496. }
  497. /**
  498. * Determine the default title format to use for an entity.
  499. *
  500. * @param TripalBundle $entity
  501. * The Entity object for the Tripal Bundle that the title format is for.
  502. *
  503. * @return string
  504. * A default title format.
  505. */
  506. function tripal_get_default_title_format($entity) {
  507. $format = NULL;
  508. // Retrieve all available tokens.
  509. $tokens = tripal_get_entity_tokens($entity);
  510. // A) Check to see if more informed modules have suggested a title for this type.
  511. // Invoke hook_tripal_default_title_format() to get all suggestions from other modules.
  512. $suggestions = module_invoke_all('tripal_default_title_format', $entity, $tokens);
  513. if ($suggestions) {
  514. // Use the suggestion with the lightest weight.
  515. $lightest_key = NULL;
  516. foreach ($suggestions as $k => $s) {
  517. if ($lightest_key === NULL) $lightest_key = $k;
  518. if ($s['weight'] < $lightest_key) $lightest_key = $k;
  519. }
  520. $format = $suggestions[$lightest_key]['format'];
  521. }
  522. // B) Check to see if any fields contain "name" in the machine name and if so, use them.
  523. $name_fields = preg_grep('/name/', array_keys($tokens));
  524. if ($name_fields AND !$format) {
  525. $format = implode(', ', $name_fields);
  526. }
  527. // C) Generate our own ugly title by simply comma-separating all the required fields.
  528. if (!$format) {
  529. $tmp = array();
  530. // Check which tokens are required fields and join them into a default format.
  531. foreach($tokens as $token) {
  532. if ($token['required']) {
  533. $tmp[] = $token['token'];
  534. }
  535. }
  536. $format = implode(', ', $tmp);
  537. }
  538. return $format;
  539. }
  540. /**
  541. * Implement this hook to define default formats for Tripal Content Types.
  542. *
  543. * @param TripalBundle $entity
  544. * A tripal content type entity with information to be used for determining the default title format.
  545. * @param array $available_tokens
  546. * An array of available tokens for this particular tripal content type.
  547. *
  548. * @return array
  549. * An array of potential formats. The lightest weighted format suggested by all modules will be chosen.
  550. * Each array item should consist of a 'weight' and 'format'. See the hook implementation below
  551. * for examples.
  552. * - weight: an integer used to determine priority of suggestions.
  553. * The smaller/lighter the number the higher the priority.
  554. * Best practice is to use a weight less than 0 for extension modules.
  555. * specifically, -2 is a good weight for calculated formats and -5 is a
  556. * good weight for hard-coded formats specific to a given type.
  557. * - format: a string including approved tokens used to determine the title
  558. * on Tripal content pages.
  559. */
  560. function hook_tripal_default_title_format($entity, $available_tokens) {
  561. $format = array();
  562. // If you want to suggest a default format for a particular vocabulary term:
  563. //---------------------------------------------------------------------------
  564. // Load the term associated with this Tripal Content type.
  565. $term = entity_load('TripalTerm', array('id' => $entity->term_id));
  566. $term = reset($term);
  567. // If it's the term you are interested in then suggest a format.
  568. if ($term->name == 'organism') {
  569. // To suggest a format, add an element to the array with a format & weight key.
  570. $format[] = array(
  571. // This is the format/pattern you suggest be used to determine the title of organism pages.
  572. 'format' => '[organism__genus] [organism__species]',
  573. // The weight/priority of your suggestion.
  574. 'weight' => -5
  575. );
  576. }
  577. // Say you know that in your particular site, all 'names' are required
  578. // and you want to only use the human-readable name:
  579. //---------------------------------------------------------------------------
  580. $name_field = preg_grep('/__name]$/', array_keys($available_tokens));
  581. $name_field = reset($name_field);
  582. if (is_string($name_field)) {
  583. $format[] = array(
  584. 'format' => $name_field,
  585. 'weight' => -2,
  586. );
  587. }
  588. return $format;
  589. }
  590. /**
  591. * Returns an array of tokens based on Tripal Entity Fields.
  592. *
  593. * @param TripalBundle $entity
  594. * The bundle entity for which you want tokens.
  595. * @return
  596. * An array of tokens where the key is the machine_name of the token.
  597. */
  598. function tripal_get_entity_tokens($entity, $options = array()) {
  599. $tokens = array();
  600. // Set default options.
  601. $options['required only'] = (isset($options['required only'])) ? $options['required only'] : FALSE;
  602. $options['include id'] = (isset($options['include id'])) ? $options['include id'] : TRUE;
  603. if ($options['include id']) {
  604. $token = '[TripalBundle__bundle_id]';
  605. $tokens[$token] = array(
  606. 'label' => 'Bundle ID',
  607. 'description' => 'The unique identifier for this Tripal Content Type.',
  608. 'token' => $token,
  609. 'field_name' => NULL,
  610. 'required' => TRUE
  611. );
  612. $token = '[TripalEntity__entity_id]';
  613. $tokens[$token] = array(
  614. 'label' => 'Content/Entity ID',
  615. 'description' => 'The unique identifier for an individual piece of Tripal Content.',
  616. 'token' => $token,
  617. 'field_name' => NULL,
  618. 'required' => TRUE
  619. );
  620. }
  621. $fields = field_info_instances('TripalEntity', $entity->name);
  622. foreach ($fields as $f) {
  623. // Build the token from the field information.
  624. $token = '[' . $f['field_name'] . ']';
  625. $current_token = array(
  626. 'label' => $f['label'],
  627. 'description' => $f['description'],
  628. 'token' => $token,
  629. 'field_name' => $f['field_name'],
  630. 'required' => $f['required']
  631. );
  632. // If the required only option is set then we only want to add
  633. // required fields to the token list.
  634. if ($options['required only'] AND $current_token['required']) {
  635. $tokens[$token] = $current_token;
  636. }
  637. // If the required only option is not set then add everything.
  638. elseif (!$options['required only']) {
  639. $tokens[$token] = $current_token;
  640. }
  641. }
  642. return $tokens;
  643. }
  644. /**
  645. * Replace all Tripal Tokens in a given string.
  646. *
  647. * NOTE: If there is no value for a token then the token is removed.
  648. *
  649. * @param string $string
  650. * The string containing tokens.
  651. * @param TripalEntity $entity
  652. * The entity with field values used to find values of tokens.
  653. * @param TripalBundle $bundle_entity
  654. * The bundle enitity containing special values sometimes needed for token replacement.
  655. *
  656. * @return
  657. * The string will all tokens replaced with values.
  658. */
  659. function tripal_replace_entity_tokens($string, &$entity, $bundle_entity = NULL) {
  660. // Determine which tokens were used in the format string
  661. $used_tokens = array();
  662. if (preg_match_all('/\[\w+\]/', $string, $matches)) {
  663. $used_tokens = $matches[0];
  664. }
  665. // If there are no tokens then just return the string.
  666. if (count($used_tokens) == 0) {
  667. return $string;
  668. }
  669. // If the field are not loaded for the entity then we want to load them
  670. // but we won't do a field_attach_load() as that will load all of the
  671. // fields. For syncing (publishing) of content loading all fields for
  672. // all synced entities causes extreme slowness, so we'll only attach
  673. // the necessary fields for replacing tokens.
  674. $attach_fields = array();
  675. foreach($used_tokens as $token) {
  676. $field_name = str_replace(array('.','[',']'), array('__','',''), $token);
  677. if (!property_exists($entity, $field_name)) {
  678. $field = field_info_field($field_name);
  679. $storage = $field['storage'];
  680. $attach_fields[$storage['type']]['storage'] = $storage;
  681. $attach_fields[$storage['type']]['fields'][] = $field;
  682. }
  683. }
  684. // If we have any fields that need attaching, then do so now.
  685. if (count(array_keys($attach_fields)) > 0) {
  686. foreach ($attach_fields as $storage_type => $details) {
  687. $storage = $details['storage'];
  688. $fields = $details['fields'];
  689. $field_ids = array();
  690. foreach ($fields as $field) {
  691. $field_ids[$field['id']] = array($entity->id);
  692. }
  693. $entities = array($entity->id => $entity);
  694. module_invoke($storage['module'], 'field_storage_load', 'TripalEntity',
  695. $entities, FIELD_LOAD_CURRENT, $field_ids, array());
  696. }
  697. }
  698. // Now that all necessary fields are attached process the tokens.
  699. foreach($used_tokens as $token) {
  700. $value = '';
  701. if (isset($entity->{$field_name})) {
  702. // Render the value from the field.
  703. // First get the items to be rendered.
  704. $field_value = field_get_items('TripalEntity', $entity, $field_name);
  705. if (isset($field_value[0])) {
  706. // Then get a render array for just the value of the first item (no markup).
  707. $field_render_arr = field_view_value('TripalEntity', $entity, $field_name, $field_value[0]);
  708. // Finally render the value from the render array.
  709. $value = render($field_render_arr);
  710. }
  711. }
  712. // The TripalBundle__bundle_id is a special token for substituting the
  713. // bundle id.
  714. elseif ($field_name === 'TripalBundle__bundle_id') {
  715. // Load the bundle entity if we weren't given it.
  716. if (!$bundle_entity) {
  717. $bundle_entity = tripal_load_bundle_entity(array('name' => $entity->bundle));
  718. }
  719. // This token should be the id of the TripalBundle.
  720. $value = $bundle_entity->id;
  721. }
  722. // The TripalBundle__bundle_id is a special token for substituting the
  723. // entty id.
  724. elseif ($field_name === 'TripalEntity__entity_id') {
  725. // This token should be the id of the TripalEntity.
  726. $value = $entity->id;
  727. }
  728. // Perform the replacement of the token with the value.
  729. $string = str_replace($token, $value, $string);
  730. }
  731. return $string;
  732. }
  733. /**
  734. * Formats the tokens for display.
  735. *
  736. * @param array $tokens
  737. * A list of tokens generated via tripal_get_entity_tokens().
  738. * @return
  739. * Rendered output describing the available tokens.
  740. */
  741. function theme_token_list($tokens) {
  742. $header = array('Token', 'Name', 'Description');
  743. $rows = array();
  744. foreach ($tokens as $details) {
  745. $rows[] = array(
  746. $details['token'],
  747. $details['label'],
  748. $details['description'],
  749. );
  750. }
  751. return theme('table', array('header' => $header, 'rows' => $rows));
  752. }
  753. /**
  754. * @section
  755. * Vocabulary Hooks.
  756. */
  757. /**
  758. * A hook for specifying information about the data store for vocabularies.
  759. *
  760. * The storage backend for controlled vocabularies has traditionally been
  761. * the Chado CV term tables. However, Tripal v3.0 introduces APIs for supporting
  762. * other backends. Therefore, this function indicates to Tripal which
  763. * data stores are capable of providing support for terms.
  764. *
  765. * @return
  766. * An array describing the storage backends implemented by the module. The
  767. * keys are storage backend names. To avoid name clashes, storage
  768. * backend names should be prefixed with the name of the module that
  769. * exposes them. The values are arrays describing the storage backend,
  770. * with the following key/value pairs:
  771. *
  772. * label: The human-readable name of the storage backend.
  773. * module: The name of the module providing the support for this backend.
  774. * description: A short description for the storage backend.
  775. * settings: An array whose keys are the names of the settings available for
  776. * the storage backend, and whose values are the default values for
  777. * those settings.
  778. */
  779. function hook_vocab_storage_info() {
  780. return array(
  781. 'term_chado_storage' => array(
  782. 'label' => t('Chado storage'),
  783. 'description' => t('Integrates terms stored in the local Chado database with Tripal entities.'),
  784. 'settings' => array(),
  785. ),
  786. );
  787. }
  788. /**
  789. * Creates a form for specifying a term for TripalEntity creation.
  790. *
  791. * This hook allows the module that implements a vocabulary storage backend
  792. * to provide the form necessary to select a term that will then be used for
  793. * creating a new TripalEntity type. Tripal will expect that a 'vocabulary' and
  794. * 'accession' are in the $form_state['storage'] array. The 'vocabulary' and
  795. * must be the abbreviated uppercase vocabulary for the vocabulary (e.g. 'RO',
  796. * 'SO', 'PATO', etc.). The 'accession' must be the unique term ID (or
  797. * accession) for the term in the vocabulary.
  798. *
  799. * @param $form
  800. * @param $form_state
  801. *
  802. * @return
  803. * A form object.
  804. */
  805. function hook_vocab_select_term_form(&$form, &$form_state) {
  806. return $form;
  807. }
  808. /**
  809. * Validates the hook_vocab_select_term_form().
  810. *
  811. * @param $name
  812. */
  813. function hook_vocab_select_term_form_validate($form, &$form_state) {
  814. }
  815. /**
  816. * Provides a form for importing vocabularies and their terms.
  817. *
  818. * Tripal allows for vocabularies to be stored separately from the biological
  819. * data. This hook allows the default term storage backend to provide an
  820. * approprite form for importing ontologies (either in OBO or OWL format).
  821. *
  822. * @param $form
  823. * @param $form_state
  824. *
  825. */
  826. function hook_vocab_import_form($form, &$form_state) {
  827. return $form;
  828. }
  829. function hook_vocab_import_form_validate($form, &$form_state) {
  830. }
  831. function hook_vocab_import_form_submit($form, &$form_state) {
  832. }
  833. /**
  834. * Hook used by the default term storage backend to provide details for a term.
  835. *
  836. * This hook is called by the tripal_entity module to retrieve information
  837. * about the term from the storage backend. It must return an array with
  838. * a set of keys.
  839. *
  840. * @param $vocabulary
  841. * The vocabulary of the vocabulary in which the term is found.
  842. * @param $accession
  843. * The unique identifier (accession) for this term.
  844. *
  845. * @return
  846. * An array with at least the following keys:
  847. * -vocabulary : An associative array with the following keys
  848. * -name: The short name for the vocabulary (e.g. SO, PATO, etc).
  849. * -description: The description of this vocabulary.
  850. * -url: The URL for the vocabulary.
  851. * -accession : The name unique ID of the term.
  852. * -url : The URL for the term.
  853. * -name : The name of the term.
  854. * -definition : The term's description.
  855. * any other keys may be added as desired. Returns NULL if the term
  856. * cannot be found.
  857. */
  858. function hook_vocab_get_term($vocabulary, $accession) {
  859. // See the tripal_chado_vocab_get_term() function for an example.
  860. }
  861. /**
  862. * Hook used by the default term storage backend to add new terms.
  863. *
  864. * @param $values
  865. * An associative array of key/value pairs used to add a new term. The
  866. * keys are:
  867. * vocabulary : The vocabulary of the vocabulary.
  868. * accession : The name unique ID of the term.
  869. * url : The URL for the term.
  870. * name : The name of the term.
  871. * definition : The term's description.
  872. * @return
  873. * TRUE if the term was added, FALSE otherwise. If the term already exists
  874. * it will be updated and the return value will be TRUE,
  875. */
  876. function hook_vocab_set_term($values) {
  877. // See the tripal_chado_vocab_set_term() function for an example.
  878. }
  879. /**
  880. * Retrieves full information about a vocabulary term.
  881. *
  882. * Vocabularies are stored in a database backend. Tripal has no requirements
  883. * for how terms are stored. By default, the tripal_chado modules provides
  884. * storage for vocabularies and terms. This function will call the
  885. * hook_vocab_get_term() function for the database backend that is housing the
  886. * vocabularies and allow it to return the details about the term.
  887. *
  888. * @param $vocabulary
  889. * The vocabulary of the vocabulary in which the term is found.
  890. * @param $accession
  891. * The unique identifier (accession) for this term.
  892. *
  893. * @return
  894. * An array with at least the following keys:
  895. * vocabulary : The short name of the vocabulary (e.g. SO, PATO, foaf).
  896. * accession : The name unique ID of the term.
  897. * url : The URL for the term.
  898. * name : The name of the term.
  899. * definition : The term's description.
  900. * any other keys may be added as desired. Returns NULL if the term
  901. * cannot be found.
  902. */
  903. function tripal_get_term_details($vocabulary, $accession) {
  904. // TODO: we need some sort of administrative interface that lets the user
  905. // switch to the desired vocabulary type. For now, we'll just use the
  906. // first one in the list.
  907. $stores = module_invoke_all('vocab_storage_info');
  908. if (is_array($stores) and count($stores) > 0) {
  909. $keys = array_keys($stores);
  910. $module = $stores[$keys[0]]['module'];
  911. $function = $module . '_vocab_get_term';
  912. if (function_exists($function)) {
  913. return $function($vocabulary, $accession);
  914. }
  915. }
  916. }