tripal_entities.api.inc 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649
  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. // tripal_report_error(
  179. // 'trpbundle_var',
  180. // TRIPAL_WARNING,
  181. // 'Unable to fetch tripal bundle variable value due to missing tripal variable (%var).',
  182. // array('%var' => $variable_name)
  183. // );
  184. // return FALSE;
  185. return $default;
  186. }
  187. // Select the value for this variable.
  188. $value = db_select('tripal_bundle_variables', 'var')
  189. ->fields('var', array('value'))
  190. ->condition('var.bundle_id', $bundle_id)
  191. ->condition('var.variable_id', $variable->variable_id)
  192. ->execute()
  193. ->fetchField();
  194. // Warn if the value appears to be empty.
  195. if (!$value) {
  196. // tripal_report_error(
  197. // 'trpbundle_var',
  198. // TRIPAL_WARNING,
  199. // 'Unable to fetch tripal bundle variable (%var) value.',
  200. // array('%var' => $variable_name)
  201. // );
  202. return $default;
  203. }
  204. return $value;
  205. }
  206. /**
  207. * Save the value of a tripal variable for a given bundle.
  208. *
  209. * @param string $variable_name
  210. * The name of the variable as in tripal_variables.name.
  211. * @param int $bundle_id
  212. * The unique identfier for the bundle you want the value for.
  213. * @param $text $value
  214. * The value of the variable for the given bundle.
  215. */
  216. function tripal_set_bundle_variable($variable_name, $bundle_id, $value) {
  217. $variable = tripal_get_variable($variable_name);
  218. // And then we need to write the new format to the tripal_bundle_variables table.
  219. $record = array(
  220. 'bundle_id' => $bundle_id,
  221. 'variable_id' => $variable->variable_id,
  222. 'value' => $value,
  223. );
  224. // Check whether there is already a format saved.
  225. $bundle_variable_id = db_select('tripal_bundle_variables', 'var')
  226. ->fields('var', array('bundle_variable_id'))
  227. ->condition('var.bundle_id', $record['bundle_id'])
  228. ->condition('var.variable_id', $record['variable_id'])
  229. ->execute()
  230. ->fetchField();
  231. if ($bundle_variable_id) {
  232. $record['bundle_variable_id'] = $bundle_variable_id;
  233. return drupal_write_record('tripal_bundle_variables', $record, 'bundle_variable_id');
  234. }
  235. else {
  236. return drupal_write_record('tripal_bundle_variables', $record);
  237. }
  238. }
  239. /**
  240. * @section
  241. * Title & URL Formats.
  242. */
  243. /**
  244. * Get Page Title Format for a given Tripal Entity Type.
  245. *
  246. * @param TripalBundle $entity
  247. * The Entity object for the Tripal Bundle the title format is for.
  248. */
  249. function tripal_get_title_format($entity) {
  250. // Get the existing title format if it exists.
  251. $title_format = tripal_get_bundle_variable('title_format', $entity->id);
  252. // If there isn't yet a title format for this bundle/type then we should
  253. // determine the default.
  254. if (!$title_format) {
  255. $title_format = tripal_get_default_title_format($entity);
  256. tripal_save_title_format($entity, $title_format);
  257. }
  258. return $title_format;
  259. }
  260. /**
  261. * Save Page Title Format for a given Tripal Entity Type.
  262. *
  263. * @param TripalBundle $entity
  264. * The Entity object for the Tripal Bundle the title format is for.
  265. * @param string $format
  266. * The pattern to be used when generating entity titles for the above type.
  267. */
  268. function tripal_save_title_format($entity, $format) {
  269. return tripal_set_bundle_variable('title_format', $entity->id, $format);
  270. }
  271. /**
  272. * Determine the default pattern/format to use for an entity type.
  273. *
  274. * @param TripalBundle $entity
  275. * The Entity object for the Tripal Bundle the title format is for.
  276. * @return string
  277. * A default title format.
  278. */
  279. function tripal_get_default_title_format($entity) {
  280. $format = NULL;
  281. // Retrieve all available tokens.
  282. $tokens = tripal_get_tokens($entity);
  283. // A) Check to see if more informed modules have suggested a title for this type.
  284. // Invoke hook_tripal_default_title_format() to get all suggestions from other modules.
  285. $suggestions = module_invoke_all('tripal_default_title_format', $entity, $tokens);
  286. if ($suggestions) {
  287. // Use the suggestion with the lightest weight.
  288. $lightest_key = NULL;
  289. foreach ($suggestions as $k => $s) {
  290. if ($lightest_key === NULL) $lightest_key = $k;
  291. if ($s['weight'] < $lightest_key) $lightest_key = $k;
  292. }
  293. $format = $suggestions[$lightest_key]['format'];
  294. }
  295. // B) Check to see if any fields contain "name" in the machine name and if so, use them.
  296. $name_fields = preg_grep('/name/', array_keys($tokens));
  297. if ($name_fields AND !$format) {
  298. $format = implode(', ', $name_fields);
  299. }
  300. // C) Generate our own ugly title by simply comma-separating all the required fields.
  301. if (!$format) {
  302. $tmp = array();
  303. // Check which tokens are required fields and join them into a default format.
  304. foreach($tokens as $token) {
  305. if ($token['required']) {
  306. $tmp[] = $token['token'];
  307. }
  308. }
  309. $format = implode(', ', $tmp);
  310. }
  311. return $format;
  312. }
  313. /**
  314. * Implement this hook to define default formats for Tripal Content Types.
  315. *
  316. * @param TripalBundle $entity
  317. * A tripal content type entity with information to be used for determining the default title format.
  318. * @param array $available_tokens
  319. * An array of available tokens for this particular tripal content type.
  320. *
  321. * @return array
  322. * An array of potential formats. The lightest weighted format suggested by all modules will be chosen.
  323. * Each array item should consist of a 'weight' and 'format'. See the hook implementation below
  324. * for examples.
  325. * - weight: an integer used to determine priority of suggestions.
  326. * The smaller/lighter the number the higher the priority.
  327. * Best practice is to use a weight less than 0 for extension modules.
  328. * specifically, -2 is a good weight for calculated formats and -5 is a
  329. * good weight for hard-coded formats specific to a given type.
  330. * - format: a string including approved tokens used to determine the title
  331. * on Tripal content pages.
  332. */
  333. function hook_tripal_default_title_format($entity, $available_tokens) {
  334. $format = array();
  335. // If you want to suggest a default format for a particular vocabulary term:
  336. //---------------------------------------------------------------------------
  337. // Load the term associated with this Tripal Content type.
  338. $term = entity_load('TripalTerm', array('id' => $entity->term_id));
  339. $term = reset($term);
  340. // If it's the term you are interested in then suggest a format.
  341. if ($term->name == 'organism') {
  342. // To suggest a format, add an element to the array with a format & weight key.
  343. $format[] = array(
  344. // This is the format/pattern you suggest be used to determine the title of organism pages.
  345. 'format' => '[organism__genus] [organism__species]',
  346. // The weight/priority of your suggestion.
  347. 'weight' => -5
  348. );
  349. }
  350. // Say you know that in your particular site, all 'names' are required
  351. // and you want to only use the human-readable name:
  352. //---------------------------------------------------------------------------
  353. $name_field = preg_grep('/__name]$/', array_keys($available_tokens));
  354. $name_field = reset($name_field);
  355. if (is_string($name_field)) {
  356. $format[] = array(
  357. 'format' => $name_field,
  358. 'weight' => -2,
  359. );
  360. }
  361. return $format;
  362. }
  363. /**
  364. * Returns an array of tokens based on Tripal Entity Fields.
  365. *
  366. * @param TripalBundle $entity
  367. * The bundle entity for which you want tokens.
  368. * @return
  369. * An array of tokens where the key is the machine_name of the token.
  370. */
  371. function tripal_get_tokens($entity, $options = array()) {
  372. $tokens = array();
  373. // Set default options.
  374. $options['required only'] = (isset($options['required only'])) ? $options['required only'] : FALSE;
  375. $options['include id'] = (isset($options['include id'])) ? $options['include id'] : TRUE;
  376. if ($options['include id']) {
  377. $token = '[TripalBundle__bundle_id]';
  378. $tokens[$token] = array(
  379. 'label' => 'Bundle ID',
  380. 'description' => 'The unique identifier for this Tripal Content Type.',
  381. 'token' => $token,
  382. 'field_name' => NULL,
  383. 'required' => TRUE
  384. );
  385. $token = '[TripalEntity__entity_id]';
  386. $tokens[$token] = array(
  387. 'label' => 'Content/Entity ID',
  388. 'description' => 'The unique identifier for an individual piece of Tripal Content.',
  389. 'token' => $token,
  390. 'field_name' => NULL,
  391. 'required' => TRUE
  392. );
  393. }
  394. $fields = field_info_instances('TripalEntity', $entity->name);
  395. foreach ($fields as $f) {
  396. // Build the token from the field information.
  397. $token = '[' . $f['field_name'] . ']';
  398. $current_token = array(
  399. 'label' => $f['label'],
  400. 'description' => $f['description'],
  401. 'token' => $token,
  402. 'field_name' => $f['field_name'],
  403. 'required' => $f['required']
  404. );
  405. // If the required only option is set then we only want to add
  406. // required fields to the token list.
  407. if ($options['required only'] AND $current_token['required']) {
  408. $tokens[$token] = $current_token;
  409. }
  410. // If the required only option is not set then add everything.
  411. elseif (!$options['required only']) {
  412. $tokens[$token] = $current_token;
  413. }
  414. }
  415. return $tokens;
  416. }
  417. /**
  418. * Replace all Tripal Tokens in a given string.
  419. *
  420. * NOTE: If there is no value for a token then the token is removed.
  421. *
  422. * @param string $string
  423. * The string containing tokens.
  424. * @param TripalEntity $entity
  425. * The entity with field values used to find values of tokens.
  426. * @param TripalBundle $bundle_entity
  427. * The bundle enitity containing special values sometimes needed for token replacement.
  428. *
  429. * @return
  430. * The string will all tokens replaced with values.
  431. */
  432. function tripal_replace_tokens($string, $entity, $bundle_entity = NULL) {
  433. // Determine which tokens were used in the format string
  434. if (preg_match_all('/\[\w+\]/', $string, $matches)) {
  435. $used_tokens = $matches[0];
  436. foreach($used_tokens as $token) {
  437. $field = str_replace(array('.','[',']'),array('__','',''),$token);
  438. $value = '';
  439. if (isset($entity->{$field})) {
  440. // Render the value from the field.
  441. // First get the items to be rendered.
  442. $field_value = field_get_items('TripalEntity', $entity, $field);
  443. if (isset($field_value[0])) {
  444. // Then get a render array for just the value of the first item (no markup).
  445. $field_render_arr = field_view_value('TripalEntity', $entity, $field, $field_value[0]);
  446. // Finally render the value from the render array.
  447. $value = render($field_render_arr);
  448. }
  449. }
  450. elseif ($field === 'TripalBundle__bundle_id') {
  451. // Load the bundle entity if we weren't given it.
  452. if (!$bundle_entity) {
  453. $bundle_entity = tripal_load_bundle_entity(array('name' => $entity->bundle));
  454. }
  455. // This token should be the id of the TripalBundle.
  456. $value = $bundle_entity->id;
  457. }
  458. elseif ($field === 'TripalEntity__entity_id') {
  459. // This token should be the id of the TripalEntity.
  460. $value = $entity->id;
  461. }
  462. $string = str_replace($token, $value, $string);
  463. }
  464. }
  465. return $string;
  466. }
  467. /**
  468. * Formats the tokens for display.
  469. *
  470. * @param array $tokens
  471. * A list of tokens generated via tripal_get_tokens().
  472. * @return
  473. * Rendered output describing the available tokens.
  474. */
  475. function theme_token_list($tokens) {
  476. $header = array('Token', 'Name', 'Description');
  477. $rows = array();
  478. foreach ($tokens as $details) {
  479. $rows[] = array(
  480. $details['token'],
  481. $details['label'],
  482. $details['description'],
  483. );
  484. }
  485. return theme('table', array('header' => $header, 'rows' => $rows));
  486. }
  487. /**
  488. * @section
  489. * Vocabulary Hooks.
  490. */
  491. /**
  492. * A hook for specifying information about the data store for vocabularies.
  493. *
  494. * The storage backend for controlled vocabularies has traditionally been
  495. * the Chado CV term tables. However, Tripal v3.0 introduces APIs for supporting
  496. * other backends. Therefore, this function indicates to Tripal which
  497. * data stores are capable of providing support for terms.
  498. *
  499. * @return
  500. * An array describing the storage backends implemented by the module. The
  501. * keys are storage backend names. To avoid name clashes, storage
  502. * backend names should be prefixed with the name of the module that
  503. * exposes them. The values are arrays describing the storage backend,
  504. * with the following key/value pairs:
  505. *
  506. * label: The human-readable name of the storage backend.
  507. * module: The name of the module providing the support for this backend.
  508. * description: A short description for the storage backend.
  509. * settings: An array whose keys are the names of the settings available for
  510. * the storage backend, and whose values are the default values for
  511. * those settings.
  512. */
  513. function hook_vocab_storage_info() {
  514. return array(
  515. 'term_chado_storage' => array(
  516. 'label' => t('Chado storage'),
  517. 'description' => t('Integrates terms stored in the local Chado database with Tripal entities.'),
  518. 'settings' => array(),
  519. ),
  520. );
  521. }
  522. /**
  523. * Creates a form for specifying a term for TripalEntity creation.
  524. *
  525. * This hook allows the module that implements a vocabulary storage backend
  526. * to provide the form necessary to select a term that will then be used for
  527. * creating a new TripalEntity type. Tripal will expect that a 'namespace' and
  528. * 'accession' are in the $form_state['storage'] array. The 'namespace' and
  529. * must be the abbreviated uppercase namespace for the vocabulary (e.g. 'RO',
  530. * 'SO', 'PATO', etc.). The 'accession' must be the unique term ID (or
  531. * accession) for the term in the vocabulary.
  532. *
  533. * @param $form
  534. * @param $form_state
  535. *
  536. * @return
  537. * A form object.
  538. */
  539. function hook_vocab_select_term_form(&$form, &$form_state) {
  540. return $form;
  541. }
  542. /**
  543. * Validates the hook_vocab_select_term_form().
  544. *
  545. * @param $name
  546. */
  547. function hook_vocab_select_term_form_validate($form, &$form_state) {
  548. }
  549. /**
  550. * Hook used by the default term storage backend to provide details for a term.
  551. *
  552. * This hook is called by the tripal_entity module to retrieve information
  553. * about the term from the storage backend. It must return an array with
  554. * a set of keys.
  555. *
  556. * @param $namespace
  557. * The namespace of the vocabulary in which the term is found.
  558. * @param $accession
  559. * The unique identifier (accession) for this term.
  560. *
  561. * @return
  562. * An array with at least the following keys:
  563. * namespace : The namespace of the vocabulary.
  564. * accession : The name unique ID of the term.
  565. * url_prefix : The URL by which terms (accessions) can be appended.
  566. * name : The name of the term.
  567. * definition : The term's description.
  568. * any other keys may be added as desired. Returns NULL if the term
  569. * cannot be found.
  570. */
  571. function hook_vocab_get_term($namespace, $accession) {
  572. }