tripal.entities.api.inc 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965
  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. Defaults to FALSE.
  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 = FALSE,
  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_unchanged('TripalBundle', $bundle->id);
  143. return $entity;
  144. }
  145. return NULL;
  146. }
  147. /**
  148. * Allows a module to perform tasks before a TripalBundle object is deleted.
  149. *
  150. * @param $bundle
  151. * The newly created TripalBundle object.
  152. */
  153. function hook_bundle_delete($bundle) {
  154. }
  155. /**
  156. * Allows a module to perform tasks after a TripalBundle object is created.
  157. *
  158. * @param $bundle
  159. * The newly created TripalBundle object.
  160. * @param $storage_args
  161. * Arguments passed to the storage backend for this bundle. These arguments
  162. * typically provide details for how to associate this bundle with records
  163. * in the storage system. Each storage system will have its own set of
  164. * arguments that it will expect.
  165. */
  166. function hook_bundle_create(&$bundle, $storage_args) {
  167. }
  168. /**
  169. * Allows a module to perform tasks after fields are added to a TripalBundle.
  170. *
  171. * @param $bundle
  172. * The newly created TripalBundle object.
  173. */
  174. function hook_bundle_postcreate(&$bundle) {
  175. }
  176. /**
  177. * Creates a new Tripal Entity type (i.e. bundle).
  178. *
  179. * @param $args
  180. * An array of arguments that must include the following keys:
  181. * - vocabulary: The abbreviated vocabulary for the vocabulary
  182. * (e.g. RO, SO, PATO).
  183. * - accession: The unique term ID in the vocabulary $vocabulary
  184. * (i.e. an accession).
  185. * - term_name: A human-readable name for this term. This will became
  186. * the name that appears for the content type. In practice, this
  187. * should be the name of the term. (E.g. the name for SO:0000704 is gene).
  188. * @param $error
  189. * A string, passed by reference, that is filled with the error message
  190. * if the function fails.
  191. * @return
  192. * The bundle object or FALSE if failure.
  193. */
  194. function tripal_create_bundle($args, &$error = '') {
  195. $vocabulary = $args['vocabulary'];
  196. $accession = $args['accession'];
  197. $term_name = $args['term_name'];
  198. $storage_args = $args['storage_args'];
  199. $transaction = db_transaction();
  200. try {
  201. // First create the TripalVocab if it doesn't already exist.
  202. $vocab = tripal_load_vocab_entity(array('vocabulary' => $vocabulary));
  203. if (!$vocab) {
  204. $vocab = entity_get_controller('TripalVocab')->create(array('vocabulary' => $vocabulary));
  205. $vocab->save();
  206. }
  207. // Next create the TripalTerm if it doesn't already exist.
  208. $term = tripal_load_term_entity(array(
  209. 'vocabulary' => $vocabulary,
  210. 'accession' => $accession
  211. ));
  212. if (!$term) {
  213. $targs = array('vocab_id' => $vocab->id, 'accession' => $accession, 'name' => $term_name);
  214. $term = entity_get_controller('TripalTerm')->create($targs);
  215. $term = $term->save();
  216. }
  217. // If the bundle doesn't already exist, then add it.
  218. $bundle_name = 'bio_data_' . $term->id;
  219. $einfo = entity_get_info('TripalEntity');
  220. if (!in_array($bundle_name, array_keys($einfo['bundles']))) {
  221. // Make the label for the content type have capitalized words. The
  222. // exception is 'mRNA' which we know should not be uppercased.
  223. $label = ucwords(preg_replace('/_/', ' ', $term_name));
  224. if ($term_name == 'mRNA') {
  225. $label = $term_name;
  226. }
  227. // Insert the bundle.
  228. db_insert('tripal_bundle')
  229. ->fields(array(
  230. 'label' => $label,
  231. 'type' => 'TripalEntity',
  232. 'name' => $bundle_name,
  233. 'term_id' => $term->id,
  234. ))
  235. ->execute();
  236. }
  237. // Allow modules to make additions to the entity when it's created.
  238. $bundle = tripal_load_bundle_entity(array('name' => $bundle_name));
  239. $modules = module_implements('bundle_create');
  240. foreach ($modules as $module) {
  241. $function = $module . '_bundle_create';
  242. $function($bundle, $storage_args);
  243. }
  244. // Clear the entity cache so that Drupal will read our
  245. // hook_entity_info() implementation.
  246. global $language;
  247. $langcode = $language->language;
  248. cache_clear_all("entity_info:$langcode", 'cache');
  249. variable_set('menu_rebuild_needed', TRUE);
  250. // Get the bundle object.
  251. $bundle = tripal_load_bundle_entity(array('name' => $bundle_name));
  252. // Allow modules to add fields to the new bundle.
  253. $modules = module_implements('bundle_create_fields');
  254. foreach ($modules as $module) {
  255. $function = $module . '_bundle_create_fields';
  256. $info = $function('TripalEntity', $bundle);
  257. foreach ($info as $field_name => $details) {
  258. $field_type = $details['type'];
  259. // TODO: make sure the field term exits. If not then
  260. // skip it.
  261. // If the field already exists then skip it.
  262. $field = field_info_field($details['field_name']);
  263. if ($field) {
  264. continue;
  265. }
  266. // Create the field.
  267. $field = field_create_field($details);
  268. if (!$field) {
  269. tripal_set_message(t("Could not create new field: %field.",
  270. array('%field' => $details['field_name'])), TRIPAL_ERROR);
  271. }
  272. }
  273. }
  274. // Allow modules to add instances to the new bundle.
  275. $modules = module_implements('bundle_create_instances');
  276. foreach ($modules as $module) {
  277. $function = $module . '_bundle_create_instances';
  278. $info = $function('TripalEntity', $bundle);
  279. foreach ($info as $field_name => $details) {
  280. // If the field is already attached to this bundle then skip it.
  281. $field = field_info_field($details['field_name']);
  282. if ($field and array_key_exists('bundles', $field) and
  283. array_key_exists('TripalEntity', $field['bundles']) and
  284. in_array($bundle->name, $field['bundles']['TripalEntity'])) {
  285. continue;
  286. }
  287. // Create the field instance.
  288. $instance = field_create_instance($details);
  289. }
  290. }
  291. $modules = module_implements('bundle_postcreate');
  292. foreach ($modules as $module) {
  293. $function = $module . '_bundle_postcreate';
  294. $function($bundle);
  295. }
  296. // Finally set admin perimssions for the content type:
  297. // $roles = user_roles();
  298. // $admin_rid = variable_get('user_admin_role');
  299. // $perms = user_role_permissions(array($admin_rid));
  300. // dpm($perms);
  301. // foreach ($perms[$admin_rid] as $perm => $value) {
  302. // $perms[$admin_rid][$perm] = TRUE;
  303. // }
  304. // user_role_change_permissions($admin_rid, $perms[$admin_rid]);
  305. }
  306. catch (Exception $e) {
  307. $transaction->rollback();
  308. $error = _drupal_decode_exception($e);
  309. drupal_set_message(t("Failed to create content type: %message.",
  310. array('%message' => $error['!message'])), 'error');
  311. return FALSE;
  312. }
  313. return $bundle;
  314. }
  315. /**
  316. * Retrieves a list of the content types.
  317. *
  318. * @return
  319. * An array of bundles. Each bundle is an object containing information
  320. * about that bundle.
  321. */
  322. function tripal_get_content_types() {
  323. return db_select('tripal_bundle', 'tb')
  324. ->fields('tb')
  325. ->execute()
  326. ->fetchAll();
  327. }
  328. /**
  329. * Retrieves information about a given content type.
  330. *
  331. * @param $bundle_name
  332. * The name of a bundle.
  333. *
  334. * @return
  335. * An object containing information about the bundle.
  336. */
  337. function tripal_get_content_type($bundle_name) {
  338. return db_select('tripal_bundle', 'tb')
  339. ->fields('tb')
  340. ->condition('tb.name', $bundle_name)
  341. ->execute()
  342. ->fetchAll();
  343. }
  344. /**
  345. * Refreshes the bundle such that new fields added by modules will be found.
  346. *
  347. * @param $bundle_name
  348. * The name of the bundle to refresh (e.g. bio_data_4).
  349. */
  350. function tripal_refresh_bundle_fields($bundle_name) {
  351. $num_created = 0;
  352. // Get the bundle object.
  353. $bundle = tripal_load_bundle_entity(array('name' => $bundle_name));
  354. if (!$bundle) {
  355. tripal_report_error('tripal', TRIPAL_ERROR, "Unrecognized bundle name '%bundle'.",
  356. array('%bundle' => $bundle_name));
  357. return FALSE;
  358. }
  359. // Allow modules to add fields to the new bundle.
  360. $modules = module_implements('bundle_create_fields');
  361. foreach ($modules as $module) {
  362. $function = $module . '_bundle_create_fields';
  363. $info = $function('TripalEntity', $bundle);
  364. foreach ($info as $field_name => $details) {
  365. $field_type = $details['type'];
  366. // If the field already exists then skip it.
  367. $field = field_info_field($details['field_name']);
  368. if ($field) {
  369. continue;
  370. }
  371. // Create the field.
  372. $field = field_create_field($details);
  373. if (!$field) {
  374. tripal_set_message(t("Could not create new field: %field.",
  375. array('%field' => $details['field_name'])), TRIPAL_ERROR);
  376. }
  377. }
  378. }
  379. // Allow modules to add instances to the new bundle.
  380. $modules = module_implements('bundle_create_instances');
  381. foreach ($modules as $module) {
  382. $function = $module . '_bundle_create_instances';
  383. $info = $function('TripalEntity', $bundle);
  384. foreach ($info as $field_name => $details) {
  385. // If the field is already attached to this bundle then skip it.
  386. $field = field_info_field($details['field_name']);
  387. if ($field and array_key_exists('bundles', $field) and
  388. array_key_exists('TripalEntity', $field['bundles']) and
  389. in_array($bundle->name, $field['bundles']['TripalEntity'])) {
  390. continue;
  391. }
  392. // Create the field instance.
  393. $instance = field_create_instance($details);
  394. $num_created++;
  395. drupal_set_message(t("Created field: %field", array('%field' => $info[$field_name]['label'])));
  396. }
  397. }
  398. if ($num_created == 0) {
  399. drupal_set_message(t("No new fields were added."));
  400. }
  401. }
  402. /**
  403. * Updates an existing field and its attached instance to a bundle.
  404. *
  405. *
  406. * @param $field_name
  407. * The name of the field.
  408. * @param $field_info
  409. * An associative array containing the field information. The following
  410. * key/value pairs are supported:
  411. * 'field_type' : a valid field type. May be any of the Drupal default
  412. * fields, one created by the tripal_chado module or another custom module.
  413. * 'widget_type' : a valid widget type. May be any of the Drupal default
  414. * fields, one created by the tripal_chado module or another custom module.
  415. * 'field_settings' : an array of settings that are appropriate for the
  416. * selected field type.
  417. * 'widget_settings' : an array of settings that are appropriate for the
  418. * selected widget type.
  419. * 'description' : a default description for this field.
  420. * 'label' : a label used as a header for this field.
  421. * 'is_required' : indicates if the field is required in the edit form.
  422. * 'cardinality' : indicates the number of values this field can support.
  423. * the default is 1 (meaning only one value). Use a value of
  424. * FIELD_CARDINALITY_UNLIMITED for unlimited number of values.
  425. * 'default_value' : A default value for the field.
  426. * 'format' : A string indicating the format for the field. Must be
  427. * specific to the field.
  428. * @param $entity_type_name
  429. * The entity type name.
  430. * @param $bundle_name
  431. * The bundle name.
  432. *
  433. * @return
  434. * FALSE if the field could not be updated
  435. *
  436. * TODO: this function really shouldn't try to create an instance and
  437. * attach to a bundle at the same time.
  438. *
  439. */
  440. function tripal_update_bundle_field($field_name, $field_info, $entity_type_name, $bundle_name) {
  441. $field = field_info_field($field_name);
  442. // If the field doesn't exists or is not attached to this bundle then
  443. // just return, there is nothing left to do.
  444. if (!$field or !array_key_exists('bundles', $field) or
  445. !array_key_exists($entity_type_name, $field['bundles']) or
  446. !in_array($bundle_name, $field['bundles'][$entity_type_name])) {
  447. return FALSE;
  448. }
  449. $field['field_name'] = $field_name;
  450. if (array_key_exists('field_type', $field_info)) {
  451. $field['cardinality'] = $field_info['cardinality'];
  452. }
  453. if (array_key_exists('locked', $field_info)) {
  454. $field['locked'] = $field_info['locked'];
  455. }
  456. if (array_key_exists('storage', $field_info)) {
  457. $field['storage']['type'] = $field_info['storage'];
  458. }
  459. if (array_key_exists('field_settings', $field_info)) {
  460. $field['settings'] = $field_info['field_settings'];
  461. }
  462. field_update_field($field);
  463. $field_instance['field_name'] = $field_name;
  464. $field_instance['entity_type'] = $entity_type_name;
  465. $field_instance['bundle'] = $bundle_name;
  466. if (array_key_exists('label', $field_info)) {
  467. $field['label'] = $field_info['label'];
  468. }
  469. if (array_key_exists('description', $field_info)) {
  470. $field['description'] = $field_info['description'];
  471. }
  472. if (array_key_exists('widget', $field_info)) {
  473. if (array_key_exists('widget_type', $field_info['widget'])) {
  474. $field['widget']['type'] = $field_info['widget_type'];
  475. }
  476. if (array_key_exists('widget_settings', $field_info['widget'])) {
  477. $field['widget']['settings'] = $field_info['widget_settings'];
  478. }
  479. }
  480. if (array_key_exists('required', $field_info)) {
  481. $field['required'] = $field_info['is_required'];
  482. }
  483. if (array_key_exists('settings', $field_info)) {
  484. $field['settings'] = $field_info['field_settings'];
  485. }
  486. if (array_key_exists('default_value', $field_info)) {
  487. $field['default_value'] = $field_info['default_value'];
  488. }
  489. if (array_key_exists('format', $field_info)) {
  490. $field['format'] = $field_info['format'];
  491. }
  492. field_update_instance($field_instance);
  493. }
  494. /**
  495. * Allows a module to make changes to an entity object after creation.
  496. *
  497. * This function is added by Tripal to allow datastore backends to add
  498. * addition properties to the entity that they themselves will use later.
  499. *
  500. * @param $entity
  501. * @param $entity_type
  502. */
  503. function hook_entity_create(&$entity, $entity_type) {
  504. }
  505. /**
  506. * @section
  507. * Bundle Variables.
  508. */
  509. /**
  510. * Fetch the value for a given tripal variable.
  511. *
  512. * @param string $variable_name
  513. * The name of the variable as in tripal_variables.name.
  514. * @param int $bundle_id
  515. * The unique identfier for the bundle you want the value for.
  516. * @return text
  517. * The value of the specified variable for the specified bundle.
  518. */
  519. function tripal_get_bundle_variable($variable_name, $bundle_id, $default = FALSE) {
  520. $variable = tripal_get_variable($variable_name);
  521. // Warn if we can't find the tripal_variable.
  522. if (!$variable) {
  523. return $default;
  524. }
  525. // Select the value for this variable.
  526. $value = db_select('tripal_bundle_variables', 'var')
  527. ->fields('var', array('value'))
  528. ->condition('var.bundle_id', $bundle_id)
  529. ->condition('var.variable_id', $variable->variable_id)
  530. ->execute()
  531. ->fetchField();
  532. // Warn if the value appears to be empty.
  533. if (!$value) {
  534. return $default;
  535. }
  536. return $value;
  537. }
  538. /**
  539. * Save the value of a tripal variable for a given bundle.
  540. *
  541. * @param string $variable_name
  542. * The name of the variable as in tripal_variables.name.
  543. * @param int $bundle_id
  544. * The unique identfier for the bundle you want the value for.
  545. * @param $text $value
  546. * The value of the variable for the given bundle.
  547. */
  548. function tripal_set_bundle_variable($variable_name, $bundle_id, $value) {
  549. $variable = tripal_get_variable($variable_name);
  550. if (!$variable) {
  551. return FALSE;
  552. }
  553. // And then we need to write the new format to the tripal_bundle_variables table.
  554. $record = array(
  555. 'bundle_id' => $bundle_id,
  556. 'variable_id' => $variable->variable_id,
  557. 'value' => $value,
  558. );
  559. // Check whether there is already a format saved.
  560. $bundle_variable_id = db_select('tripal_bundle_variables', 'var')
  561. ->fields('var', array('bundle_variable_id'))
  562. ->condition('var.bundle_id', $record['bundle_id'])
  563. ->condition('var.variable_id', $record['variable_id'])
  564. ->execute()
  565. ->fetchField();
  566. if ($bundle_variable_id) {
  567. $record['bundle_variable_id'] = $bundle_variable_id;
  568. return drupal_write_record('tripal_bundle_variables', $record, 'bundle_variable_id');
  569. }
  570. else {
  571. return drupal_write_record('tripal_bundle_variables', $record);
  572. }
  573. }
  574. /**
  575. * @section
  576. * Title & URL Formats.
  577. */
  578. /**
  579. * Get Page Title Format for a given Tripal Entity Type.
  580. *
  581. * @param TripalBundle $bundle
  582. * The Entity object for the Tripal Bundle the title format is for.
  583. */
  584. function tripal_get_title_format($bundle) {
  585. // Get the existing title format if it exists.
  586. $title_format = tripal_get_bundle_variable('title_format', $bundle->id);
  587. // If there isn't yet a title format for this bundle/type then we should
  588. // determine the default.
  589. if (!$title_format) {
  590. $title_format = tripal_get_default_title_format($bundle);
  591. tripal_save_title_format($bundle, $title_format);
  592. }
  593. return $title_format;
  594. }
  595. /**
  596. * Save Page Title Format for a given Tripal Entity Type.
  597. *
  598. * @param TripalBundle $entity
  599. * The Entity object for the Tripal Bundle the title format is for.
  600. * @param string $format
  601. * The pattern to be used when generating entity titles for the above type.
  602. */
  603. function tripal_save_title_format($entity, $format) {
  604. return tripal_set_bundle_variable('title_format', $entity->id, $format);
  605. }
  606. /**
  607. * Determine the default title format to use for an entity.
  608. *
  609. * @param TripalBundle $bundle
  610. * The Entity object for the Tripal Bundle that the title format is for.
  611. *
  612. * @return string
  613. * A default title format.
  614. */
  615. function tripal_get_default_title_format($bundle) {
  616. $format = '';
  617. // Retrieve all available tokens.
  618. $tokens = tripal_get_entity_tokens($bundle);
  619. // A) Check to see if more informed modules have suggested a title for this
  620. // type. Invoke hook_tripal_default_title_format() to get all suggestions
  621. // from other modules.
  622. $suggestions = module_invoke_all('tripal_default_title_format', $bundle, $tokens);
  623. if ($suggestions) {
  624. // Use the suggestion with the lightest weight.
  625. $lightest_key = NULL;
  626. foreach ($suggestions as $k => $s) {
  627. if ($lightest_key === NULL) $lightest_key = $k;
  628. if ($s['weight'] < $lightest_key) $lightest_key = $k;
  629. }
  630. $format = $suggestions[$lightest_key]['format'];
  631. return $format;
  632. }
  633. // B) Generate our own ugly title by simply comma-separating all the
  634. // required fields.
  635. if (!$format) {
  636. $tmp = array();
  637. // Check which tokens are required fields and join them into a default format.
  638. foreach($tokens as $token) {
  639. if ($token['required']) {
  640. $tmp[] = $token['token'];
  641. }
  642. }
  643. $format = implode(', ', $tmp);
  644. return $format;
  645. }
  646. return $format;
  647. }
  648. /**
  649. * Implement this hook to define default formats for Tripal Content Types.
  650. *
  651. * @param TripalBundle $bundle
  652. * A tripal content type entity with information to be used for determining the default title format.
  653. * @param array $available_tokens
  654. * An array of available tokens for this particular tripal content type.
  655. *
  656. * @return array
  657. * An array of potential formats. The lightest weighted format suggested by all modules will be chosen.
  658. * Each array item should consist of a 'weight' and 'format'. See the hook implementation below
  659. * for examples.
  660. * - weight: an integer used to determine priority of suggestions.
  661. * The smaller/lighter the number the higher the priority.
  662. * Best practice is to use a weight less than 0 for extension modules.
  663. * specifically, -2 is a good weight for calculated formats and -5 is a
  664. * good weight for hard-coded formats specific to a given type.
  665. * - format: a string including approved tokens used to determine the title
  666. * on Tripal content pages.
  667. */
  668. function hook_tripal_default_title_format($bundle, $available_tokens) {
  669. $format = array();
  670. // If you want to suggest a default format for a particular vocabulary term:
  671. //---------------------------------------------------------------------------
  672. // Load the term associated with this Tripal Content type.
  673. $term = entity_load('TripalTerm', array('id' => $bundle->term_id));
  674. $term = reset($term);
  675. // If it's the term you are interested in then suggest a format.
  676. if ($term->name == 'organism') {
  677. // To suggest a format, add an element to the array with a format & weight key.
  678. $format[] = array(
  679. // This is the format/pattern you suggest be used to determine the title of organism pages.
  680. 'format' => '[organism__genus] [organism__species]',
  681. // The weight/priority of your suggestion.
  682. 'weight' => -5
  683. );
  684. }
  685. // Say you know that in your particular site, all 'names' are required
  686. // and you want to only use the human-readable name:
  687. //---------------------------------------------------------------------------
  688. $name_field = preg_grep('/__name]$/', array_keys($available_tokens));
  689. $name_field = reset($name_field);
  690. if (is_string($name_field)) {
  691. $format[] = array(
  692. 'format' => $name_field,
  693. 'weight' => -2,
  694. );
  695. }
  696. return $format;
  697. }
  698. /**
  699. * Returns an array of tokens based on Tripal Entity Fields.
  700. *
  701. * @param TripalBundle $entity
  702. * The bundle entity for which you want tokens.
  703. * @return
  704. * An array of tokens where the key is the machine_name of the token.
  705. */
  706. function tripal_get_entity_tokens($entity, $options = array()) {
  707. $tokens = array();
  708. // Set default options.
  709. $options['required only'] = (isset($options['required only'])) ? $options['required only'] : FALSE;
  710. $options['include id'] = (isset($options['include id'])) ? $options['include id'] : TRUE;
  711. if ($options['include id']) {
  712. $token = '[TripalBundle__bundle_id]';
  713. $tokens[$token] = array(
  714. 'label' => 'Bundle ID',
  715. 'description' => 'The unique identifier for this Tripal Content Type.',
  716. 'token' => $token,
  717. 'field_name' => NULL,
  718. 'required' => TRUE
  719. );
  720. $token = '[TripalEntity__entity_id]';
  721. $tokens[$token] = array(
  722. 'label' => 'Content/Entity ID',
  723. 'description' => 'The unique identifier for an individual piece of Tripal Content.',
  724. 'token' => $token,
  725. 'field_name' => NULL,
  726. 'required' => TRUE
  727. );
  728. }
  729. $fields = field_info_instances('TripalEntity', $entity->name);
  730. foreach ($fields as $f) {
  731. // Build the token from the field information.
  732. $token = '[' . $f['field_name'] . ']';
  733. $current_token = array(
  734. 'label' => $f['label'],
  735. 'description' => $f['description'],
  736. 'token' => $token,
  737. 'field_name' => $f['field_name'],
  738. 'required' => $f['required']
  739. );
  740. // If the required only option is set then we only want to add
  741. // required fields to the token list.
  742. if ($options['required only'] AND $current_token['required']) {
  743. $tokens[$token] = $current_token;
  744. }
  745. // If the required only option is not set then add everything.
  746. elseif (!$options['required only']) {
  747. $tokens[$token] = $current_token;
  748. }
  749. }
  750. return $tokens;
  751. }
  752. /**
  753. * Replace all Tripal Tokens in a given string.
  754. *
  755. * NOTE: If there is no value for a token then the token is removed.
  756. *
  757. * @param string $string
  758. * The string containing tokens.
  759. * @param TripalEntity $entity
  760. * The entity with field values used to find values of tokens.
  761. * @param TripalBundle $bundle_entity
  762. * The bundle enitity containing special values sometimes needed for token replacement.
  763. *
  764. * @return
  765. * The string will all tokens replaced with values.
  766. */
  767. function tripal_replace_entity_tokens($string, &$entity, $bundle_entity = NULL) {
  768. // Determine which tokens were used in the format string
  769. $used_tokens = array();
  770. if (preg_match_all('/\[\w+\]/', $string, $matches)) {
  771. $used_tokens = $matches[0];
  772. }
  773. // If there are no tokens then just return the string.
  774. if (count($used_tokens) == 0) {
  775. return $string;
  776. }
  777. // If the field are not loaded for the entity then we want to load them
  778. // but we won't do a field_attach_load() as that will load all of the
  779. // fields. For syncing (publishing) of content loading all fields for
  780. // all synced entities causes extreme slowness, so we'll only attach
  781. // the necessary fields for replacing tokens.
  782. $attach_fields = array();
  783. foreach($used_tokens as $token) {
  784. $field_name = str_replace(array('.','[',']'), array('__','',''), $token);
  785. if (!property_exists($entity, $field_name)) {
  786. $field = field_info_field($field_name);
  787. $storage = $field['storage'];
  788. $attach_fields[$storage['type']]['storage'] = $storage;
  789. $attach_fields[$storage['type']]['fields'][] = $field;
  790. }
  791. }
  792. // If we have any fields that need attaching, then do so now.
  793. if (count(array_keys($attach_fields)) > 0) {
  794. foreach ($attach_fields as $storage_type => $details) {
  795. $storage = $details['storage'];
  796. $fields = $details['fields'];
  797. $field_ids = array();
  798. foreach ($fields as $field) {
  799. $field_ids[$field['id']] = array($entity->id);
  800. }
  801. $entities = array($entity->id => $entity);
  802. }
  803. module_invoke($storage['module'], 'field_storage_load', 'TripalEntity',
  804. $entities, FIELD_LOAD_CURRENT, $field_ids, array());
  805. }
  806. // Now that all necessary fields are attached process the tokens.
  807. foreach($used_tokens as $token) {
  808. $field_name = str_replace(array('.','[',']'), array('__','',''), $token);
  809. $value = '';
  810. if (property_exists($entity, $field_name)) {
  811. // Note: there is a memory leak in field_get_items() so we can't use it
  812. // here or bulk publising will slowly erode memory.
  813. //$field_value = field_get_items('TripalEntity', $entity, $field_name);
  814. $value = $entity->{$field_name}['und'][0]['value'];
  815. // TODO: deal with the value when it is not a scalar.
  816. }
  817. // The TripalBundle__bundle_id is a special token for substituting the
  818. // bundle id.
  819. elseif ($field_name === 'TripalBundle__bundle_id') {
  820. // Load the bundle entity if we weren't given it.
  821. if (!$bundle_entity) {
  822. $bundle_entity = tripal_load_bundle_entity(array('name' => $entity->bundle));
  823. }
  824. // This token should be the id of the TripalBundle.
  825. $value = $bundle_entity->id;
  826. }
  827. // The TripalBundle__bundle_id is a special token for substituting the
  828. // entty id.
  829. elseif ($field_name === 'TripalEntity__entity_id') {
  830. // This token should be the id of the TripalEntity.
  831. $value = $entity->id;
  832. }
  833. // Perform the replacement of the token with the value.
  834. $string = str_replace($token, $value, $string);
  835. }
  836. return $string;
  837. }
  838. /**
  839. * Formats the tokens for display.
  840. *
  841. * @param array $tokens
  842. * A list of tokens generated via tripal_get_entity_tokens().
  843. * @return
  844. * Rendered output describing the available tokens.
  845. */
  846. function theme_token_list($tokens) {
  847. $header = array('Token', 'Name', 'Description');
  848. $rows = array();
  849. foreach ($tokens as $details) {
  850. $rows[] = array(
  851. $details['token'],
  852. $details['label'],
  853. $details['description'],
  854. );
  855. }
  856. return theme('table', array('header' => $header, 'rows' => $rows));
  857. }