tripal_entities.api.inc 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637
  1. <?php
  2. /**
  3. * Retrieves a TripalTerm entity that matches the given arguments.
  4. *
  5. * @param $namespace
  6. * The namespace for the vocabulary
  7. * @param $accession
  8. * The ID (accession) of the term in the vocabulary.
  9. *
  10. * @return
  11. * A TripalTerm entity object or NULL if not found.
  12. */
  13. function tripal_load_term_entity($namespace, $accession) {
  14. $query = db_select('tripal_term', 'tt');
  15. $query->join('tripal_vocab' ,'tv', 'tv.id = tt.vocab_id');
  16. $query->fields('tt', array('id', 'accession'))
  17. ->fields('tv', array('namespace'))
  18. ->condition('tv.namespace', $namespace)
  19. ->condition('tt.accession', $accession);
  20. $term = $query->execute()->fetchObject();
  21. if ($term) {
  22. $entity = entity_load('TripalTerm', array($term->id));
  23. return reset($entity);
  24. }
  25. return NULL;
  26. }
  27. /**
  28. * Retrieves a TripalVocab entity that maches the given arguments.
  29. *
  30. * @param $namespace
  31. *
  32. * @return
  33. * A TripalVocab entity object or NULL if not found.
  34. */
  35. function tripal_load_vocab_entity($namespace) {
  36. $vocab = db_select('tripal_vocab', 'tv')
  37. ->fields('tv')
  38. ->condition('tv.namespace', $namespace)
  39. ->execute()
  40. ->fetchObject();
  41. if ($vocab) {
  42. $entity = entity_load('TripalVocab', array($vocab->id));
  43. return reset($entity);
  44. }
  45. return NULL;
  46. }
  47. /**
  48. * Retrieves a TripalBundle entity that matches the given arguments.
  49. *
  50. * @param $values
  51. * An associative array used to match a bundle. Valid keys may be 'name' or
  52. * 'label' (e.g. array('name' => 'bio-data_234').
  53. *
  54. * @return
  55. * A TripalBundle entity object or NULL if not found.
  56. */
  57. function tripal_load_bundle_entity($values) {
  58. $query = db_select('tripal_bundle', 'tb');
  59. $query->fields('tb');
  60. if (array_key_exists('name', $values)) {
  61. $query->condition('tb.name', $values['name']);
  62. }
  63. if (array_key_exists('label', $values)) {
  64. $query->condition('tb.label', $values['label']);
  65. }
  66. $bundle = $query->execute()->fetchObject();
  67. if ($bundle) {
  68. $entity = entity_load('TripalBundle', array($bundle->id));
  69. return reset($entity);
  70. }
  71. return NULL;
  72. }
  73. /**
  74. * Creates a new Tripal Entity type (i.e. bundle).
  75. *
  76. * @param $namespace
  77. * The abbreviated namespace for the vocabulary (e.g. RO, SO, PATO).
  78. * @param $accession
  79. * The unique term ID in the vocabulary $namespace (i.e. an accession).
  80. * @param $term_name
  81. * A human-readable name for this term. This will became the name that
  82. * appears for the content type. In practice, this should be the name
  83. * of the term. (E.g. the name for SO:0000704 is gene).
  84. * @param $error
  85. * A string, passed by reference, that is filled with the error message
  86. * if the function fails.
  87. *
  88. * @return
  89. * TRUE if the entity type (bundle) was succesfully created. FALSE otherwise.
  90. */
  91. function tripal_create_bundle($namespace, $accession, $term_name, &$error = '') {
  92. // First create the TripalVocab if it doesn't already exist.
  93. $vocab = tripal_load_vocab_entity($namespace);
  94. if (!$vocab) {
  95. $vocab = entity_get_controller('TripalVocab')->create(array('namespace' => $namespace));
  96. $vocab->save();
  97. }
  98. // Next create the TripalTerm if it doesn't already exist.
  99. $term = tripal_load_term_entity($namespace, $accession);
  100. if (!$term) {
  101. $args = array('vocab_id' => $vocab->id, 'accession' => $accession, 'name' => $term_name);
  102. $term = entity_get_controller('TripalTerm')->create($args);
  103. $term = $term->save();
  104. }
  105. // If the bundle doesn't already exist, then add it.
  106. $bundle_name = 'bio-data_' . $term->id;
  107. $einfo = entity_get_info('TripalEntity');
  108. if (!in_array($bundle_name, array_keys($einfo['bundles']))) {
  109. // Insert the bundle.
  110. db_insert('tripal_bundle')
  111. ->fields(array(
  112. 'label' => $term_name,
  113. 'type' => 'TripalEntity',
  114. 'name' => $bundle_name,
  115. 'term_id' => $term->id,
  116. ))
  117. ->execute();
  118. }
  119. // Clear the entity cache so that Drupal will read our
  120. // hook_entity_info() implementation.
  121. global $language;
  122. $langcode = $language->language;
  123. cache_clear_all("entity_info:$langcode", 'cache');
  124. variable_set('menu_rebuild_needed', TRUE);
  125. // Get the bundle object.
  126. $bundle = tripal_load_bundle_entity(array('name' => $bundle_name));
  127. // Allow modules to now add fields to the bundle
  128. module_invoke_all('add_bundle_fields', 'TripalEntity', $bundle, $term);
  129. return TRUE;
  130. }
  131. /**
  132. * Allows a module to make changes to an entity object after creation.
  133. *
  134. * This function is added by Tripal to allow datastore backends to add
  135. * addition properties to the entity that they themselves will use later.
  136. *
  137. * @param $entity
  138. * @param $entity_type
  139. */
  140. function hook_entity_create(&$entity, $entity_type) {
  141. }
  142. /**
  143. * Allows a module to add fields to a bundle.
  144. *
  145. * This function is called after the bundle is created and allows any module
  146. * to add fields to it.
  147. *
  148. * @param $entity_type
  149. * The entity type (e.g. TripalEntity).
  150. * @param $bundle
  151. * A TripalBundle object.
  152. * @param $term
  153. * An instance of a TripalTerm object.
  154. *
  155. * @return
  156. * TRUE on success, FALSE on failure.
  157. */
  158. function hook_add_bundle_fields($entity_type, $bundle, $term) {
  159. }
  160. /**
  161. * @section
  162. * Bundle Variables.
  163. */
  164. /**
  165. * Fetch the value for a given tripal variable.
  166. *
  167. * @param string $variable_name
  168. * The name of the variable as in tripal_variables.name.
  169. * @param int $bundle_id
  170. * The unique identfier for the bundle you want the value for.
  171. * @return text
  172. * The value of the specified variable for the specified bundle.
  173. */
  174. function tripal_get_bundle_variable($variable_name, $bundle_id, $default = FALSE) {
  175. $variable = tripal_get_variable($variable_name);
  176. // Warn if we can't find the tripal_variable.
  177. if (!$variable) {
  178. return $default;
  179. }
  180. // Select the value for this variable.
  181. $value = db_select('tripal_bundle_variables', 'var')
  182. ->fields('var', array('value'))
  183. ->condition('var.bundle_id', $bundle_id)
  184. ->condition('var.variable_id', $variable->variable_id)
  185. ->execute()
  186. ->fetchField();
  187. // Warn if the value appears to be empty.
  188. if (!$value) {
  189. return $default;
  190. }
  191. return $value;
  192. }
  193. /**
  194. * Save the value of a tripal variable for a given bundle.
  195. *
  196. * @param string $variable_name
  197. * The name of the variable as in tripal_variables.name.
  198. * @param int $bundle_id
  199. * The unique identfier for the bundle you want the value for.
  200. * @param $text $value
  201. * The value of the variable for the given bundle.
  202. */
  203. function tripal_set_bundle_variable($variable_name, $bundle_id, $value) {
  204. $variable = tripal_get_variable($variable_name);
  205. // And then we need to write the new format to the tripal_bundle_variables table.
  206. $record = array(
  207. 'bundle_id' => $bundle_id,
  208. 'variable_id' => $variable->variable_id,
  209. 'value' => $value,
  210. );
  211. // Check whether there is already a format saved.
  212. $bundle_variable_id = db_select('tripal_bundle_variables', 'var')
  213. ->fields('var', array('bundle_variable_id'))
  214. ->condition('var.bundle_id', $record['bundle_id'])
  215. ->condition('var.variable_id', $record['variable_id'])
  216. ->execute()
  217. ->fetchField();
  218. if ($bundle_variable_id) {
  219. $record['bundle_variable_id'] = $bundle_variable_id;
  220. return drupal_write_record('tripal_bundle_variables', $record, 'bundle_variable_id');
  221. }
  222. else {
  223. return drupal_write_record('tripal_bundle_variables', $record);
  224. }
  225. }
  226. /**
  227. * @section
  228. * Title & URL Formats.
  229. */
  230. /**
  231. * Get Page Title Format for a given Tripal Entity Type.
  232. *
  233. * @param TripalBundle $entity
  234. * The Entity object for the Tripal Bundle the title format is for.
  235. */
  236. function tripal_get_title_format($entity) {
  237. // Get the existing title format if it exists.
  238. $title_format = tripal_get_bundle_variable('title_format', $entity->id);
  239. // If there isn't yet a title format for this bundle/type then we should
  240. // determine the default.
  241. if (!$title_format) {
  242. $title_format = tripal_get_default_title_format($entity);
  243. tripal_save_title_format($entity, $title_format);
  244. }
  245. return $title_format;
  246. }
  247. /**
  248. * Save Page Title Format for a given Tripal Entity Type.
  249. *
  250. * @param TripalBundle $entity
  251. * The Entity object for the Tripal Bundle the title format is for.
  252. * @param string $format
  253. * The pattern to be used when generating entity titles for the above type.
  254. */
  255. function tripal_save_title_format($entity, $format) {
  256. return tripal_set_bundle_variable('title_format', $entity->id, $format);
  257. }
  258. /**
  259. * Determine the default pattern/format to use for an entity type.
  260. *
  261. * @param TripalBundle $entity
  262. * The Entity object for the Tripal Bundle the title format is for.
  263. * @return string
  264. * A default title format.
  265. */
  266. function tripal_get_default_title_format($entity) {
  267. $format = NULL;
  268. // Retrieve all available tokens.
  269. $tokens = tripal_get_tokens($entity);
  270. // A) Check to see if more informed modules have suggested a title for this type.
  271. // Invoke hook_tripal_default_title_format() to get all suggestions from other modules.
  272. $suggestions = module_invoke_all('tripal_default_title_format', $entity, $tokens);
  273. if ($suggestions) {
  274. // Use the suggestion with the lightest weight.
  275. $lightest_key = NULL;
  276. foreach ($suggestions as $k => $s) {
  277. if ($lightest_key === NULL) $lightest_key = $k;
  278. if ($s['weight'] < $lightest_key) $lightest_key = $k;
  279. }
  280. $format = $suggestions[$lightest_key]['format'];
  281. }
  282. // B) Check to see if any fields contain "name" in the machine name and if so, use them.
  283. $name_fields = preg_grep('/name/', array_keys($tokens));
  284. if ($name_fields AND !$format) {
  285. $format = implode(', ', $name_fields);
  286. }
  287. // C) Generate our own ugly title by simply comma-separating all the required fields.
  288. if (!$format) {
  289. $tmp = array();
  290. // Check which tokens are required fields and join them into a default format.
  291. foreach($tokens as $token) {
  292. if ($token['required']) {
  293. $tmp[] = $token['token'];
  294. }
  295. }
  296. $format = implode(', ', $tmp);
  297. }
  298. return $format;
  299. }
  300. /**
  301. * Implement this hook to define default formats for Tripal Content Types.
  302. *
  303. * @param TripalBundle $entity
  304. * A tripal content type entity with information to be used for determining the default title format.
  305. * @param array $available_tokens
  306. * An array of available tokens for this particular tripal content type.
  307. *
  308. * @return array
  309. * An array of potential formats. The lightest weighted format suggested by all modules will be chosen.
  310. * Each array item should consist of a 'weight' and 'format'. See the hook implementation below
  311. * for examples.
  312. * - weight: an integer used to determine priority of suggestions.
  313. * The smaller/lighter the number the higher the priority.
  314. * Best practice is to use a weight less than 0 for extension modules.
  315. * specifically, -2 is a good weight for calculated formats and -5 is a
  316. * good weight for hard-coded formats specific to a given type.
  317. * - format: a string including approved tokens used to determine the title
  318. * on Tripal content pages.
  319. */
  320. function hook_tripal_default_title_format($entity, $available_tokens) {
  321. $format = array();
  322. // If you want to suggest a default format for a particular vocabulary term:
  323. //---------------------------------------------------------------------------
  324. // Load the term associated with this Tripal Content type.
  325. $term = entity_load('TripalTerm', array('id' => $entity->term_id));
  326. $term = reset($term);
  327. // If it's the term you are interested in then suggest a format.
  328. if ($term->name == 'organism') {
  329. // To suggest a format, add an element to the array with a format & weight key.
  330. $format[] = array(
  331. // This is the format/pattern you suggest be used to determine the title of organism pages.
  332. 'format' => '[organism__genus] [organism__species]',
  333. // The weight/priority of your suggestion.
  334. 'weight' => -5
  335. );
  336. }
  337. // Say you know that in your particular site, all 'names' are required
  338. // and you want to only use the human-readable name:
  339. //---------------------------------------------------------------------------
  340. $name_field = preg_grep('/__name]$/', array_keys($available_tokens));
  341. $name_field = reset($name_field);
  342. if (is_string($name_field)) {
  343. $format[] = array(
  344. 'format' => $name_field,
  345. 'weight' => -2,
  346. );
  347. }
  348. return $format;
  349. }
  350. /**
  351. * Returns an array of tokens based on Tripal Entity Fields.
  352. *
  353. * @param TripalBundle $entity
  354. * The bundle entity for which you want tokens.
  355. * @return
  356. * An array of tokens where the key is the machine_name of the token.
  357. */
  358. function tripal_get_tokens($entity, $options = array()) {
  359. $tokens = array();
  360. // Set default options.
  361. $options['required only'] = (isset($options['required only'])) ? $options['required only'] : FALSE;
  362. $options['include id'] = (isset($options['include id'])) ? $options['include id'] : TRUE;
  363. if ($options['include id']) {
  364. $token = '[TripalBundle__bundle_id]';
  365. $tokens[$token] = array(
  366. 'label' => 'Bundle ID',
  367. 'description' => 'The unique identifier for this Tripal Content Type.',
  368. 'token' => $token,
  369. 'field_name' => NULL,
  370. 'required' => TRUE
  371. );
  372. $token = '[TripalEntity__entity_id]';
  373. $tokens[$token] = array(
  374. 'label' => 'Content/Entity ID',
  375. 'description' => 'The unique identifier for an individual piece of Tripal Content.',
  376. 'token' => $token,
  377. 'field_name' => NULL,
  378. 'required' => TRUE
  379. );
  380. }
  381. $fields = field_info_instances('TripalEntity', $entity->name);
  382. foreach ($fields as $f) {
  383. // Build the token from the field information.
  384. $token = '[' . $f['field_name'] . ']';
  385. $current_token = array(
  386. 'label' => $f['label'],
  387. 'description' => $f['description'],
  388. 'token' => $token,
  389. 'field_name' => $f['field_name'],
  390. 'required' => $f['required']
  391. );
  392. // If the required only option is set then we only want to add
  393. // required fields to the token list.
  394. if ($options['required only'] AND $current_token['required']) {
  395. $tokens[$token] = $current_token;
  396. }
  397. // If the required only option is not set then add everything.
  398. elseif (!$options['required only']) {
  399. $tokens[$token] = $current_token;
  400. }
  401. }
  402. return $tokens;
  403. }
  404. /**
  405. * Replace all Tripal Tokens in a given string.
  406. *
  407. * NOTE: If there is no value for a token then the token is removed.
  408. *
  409. * @param string $string
  410. * The string containing tokens.
  411. * @param TripalEntity $entity
  412. * The entity with field values used to find values of tokens.
  413. * @param TripalBundle $bundle_entity
  414. * The bundle enitity containing special values sometimes needed for token replacement.
  415. *
  416. * @return
  417. * The string will all tokens replaced with values.
  418. */
  419. function tripal_replace_tokens($string, $entity, $bundle_entity = NULL) {
  420. // Determine which tokens were used in the format string
  421. if (preg_match_all('/\[\w+\]/', $string, $matches)) {
  422. $used_tokens = $matches[0];
  423. foreach($used_tokens as $token) {
  424. $field = str_replace(array('.','[',']'),array('__','',''),$token);
  425. $value = '';
  426. if (isset($entity->{$field})) {
  427. // Render the value from the field.
  428. // First get the items to be rendered.
  429. $field_value = field_get_items('TripalEntity', $entity, $field);
  430. if (isset($field_value[0])) {
  431. // Then get a render array for just the value of the first item (no markup).
  432. $field_render_arr = field_view_value('TripalEntity', $entity, $field, $field_value[0]);
  433. // Finally render the value from the render array.
  434. $value = render($field_render_arr);
  435. }
  436. }
  437. elseif ($field === 'TripalBundle__bundle_id') {
  438. // Load the bundle entity if we weren't given it.
  439. if (!$bundle_entity) {
  440. $bundle_entity = tripal_load_bundle_entity(array('name' => $entity->bundle));
  441. }
  442. // This token should be the id of the TripalBundle.
  443. $value = $bundle_entity->id;
  444. }
  445. elseif ($field === 'TripalEntity__entity_id') {
  446. // This token should be the id of the TripalEntity.
  447. $value = $entity->id;
  448. }
  449. $string = str_replace($token, $value, $string);
  450. }
  451. }
  452. return $string;
  453. }
  454. /**
  455. * Formats the tokens for display.
  456. *
  457. * @param array $tokens
  458. * A list of tokens generated via tripal_get_tokens().
  459. * @return
  460. * Rendered output describing the available tokens.
  461. */
  462. function theme_token_list($tokens) {
  463. $header = array('Token', 'Name', 'Description');
  464. $rows = array();
  465. foreach ($tokens as $details) {
  466. $rows[] = array(
  467. $details['token'],
  468. $details['label'],
  469. $details['description'],
  470. );
  471. }
  472. return theme('table', array('header' => $header, 'rows' => $rows));
  473. }
  474. /**
  475. * @section
  476. * Vocabulary Hooks.
  477. */
  478. /**
  479. * A hook for specifying information about the data store for vocabularies.
  480. *
  481. * The storage backend for controlled vocabularies has traditionally been
  482. * the Chado CV term tables. However, Tripal v3.0 introduces APIs for supporting
  483. * other backends. Therefore, this function indicates to Tripal which
  484. * data stores are capable of providing support for terms.
  485. *
  486. * @return
  487. * An array describing the storage backends implemented by the module. The
  488. * keys are storage backend names. To avoid name clashes, storage
  489. * backend names should be prefixed with the name of the module that
  490. * exposes them. The values are arrays describing the storage backend,
  491. * with the following key/value pairs:
  492. *
  493. * label: The human-readable name of the storage backend.
  494. * module: The name of the module providing the support for this backend.
  495. * description: A short description for the storage backend.
  496. * settings: An array whose keys are the names of the settings available for
  497. * the storage backend, and whose values are the default values for
  498. * those settings.
  499. */
  500. function hook_vocab_storage_info() {
  501. return array(
  502. 'term_chado_storage' => array(
  503. 'label' => t('Chado storage'),
  504. 'description' => t('Integrates terms stored in the local Chado database with Tripal entities.'),
  505. 'settings' => array(),
  506. ),
  507. );
  508. }
  509. /**
  510. * Creates a form for specifying a term for TripalEntity creation.
  511. *
  512. * This hook allows the module that implements a vocabulary storage backend
  513. * to provide the form necessary to select a term that will then be used for
  514. * creating a new TripalEntity type. Tripal will expect that a 'namespace' and
  515. * 'accession' are in the $form_state['storage'] array. The 'namespace' and
  516. * must be the abbreviated uppercase namespace for the vocabulary (e.g. 'RO',
  517. * 'SO', 'PATO', etc.). The 'accession' must be the unique term ID (or
  518. * accession) for the term in the vocabulary.
  519. *
  520. * @param $form
  521. * @param $form_state
  522. *
  523. * @return
  524. * A form object.
  525. */
  526. function hook_vocab_select_term_form(&$form, &$form_state) {
  527. return $form;
  528. }
  529. /**
  530. * Validates the hook_vocab_select_term_form().
  531. *
  532. * @param $name
  533. */
  534. function hook_vocab_select_term_form_validate($form, &$form_state) {
  535. }
  536. /**
  537. * Hook used by the default term storage backend to provide details for a term.
  538. *
  539. * This hook is called by the tripal_entity module to retrieve information
  540. * about the term from the storage backend. It must return an array with
  541. * a set of keys.
  542. *
  543. * @param $namespace
  544. * The namespace of the vocabulary in which the term is found.
  545. * @param $accession
  546. * The unique identifier (accession) for this term.
  547. *
  548. * @return
  549. * An array with at least the following keys:
  550. * namespace : The namespace of the vocabulary.
  551. * accession : The name unique ID of the term.
  552. * url_prefix : The URL by which terms (accessions) can be appended.
  553. * name : The name of the term.
  554. * definition : The term's description.
  555. * any other keys may be added as desired. Returns NULL if the term
  556. * cannot be found.
  557. */
  558. function hook_vocab_get_term($namespace, $accession) {
  559. // See the tripal_chado_vocab_get_term() function for an example.
  560. }