tripal.entities.api.inc 37 KB

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