tripal.entities.api.inc 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142
  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. * Implements hook_cron().
  408. */
  409. function tripal_cron() {
  410. if (variable_get('tripal_admin_notification_creation_during_cron', TRUE)) {
  411. $modules = module_implements('tripal_cron_notification');
  412. foreach ($modules as $module) {
  413. $function = $module . '_tripal_cron_notification';
  414. $function();
  415. }
  416. watchdog('tripal_cron', 'tripal_cron ran');
  417. }
  418. }
  419. /**
  420. * Refreshes the bundle such that new fields added by modules will be found during cron.
  421. *
  422. * @param $bundle_name
  423. * The name of the bundle to refresh (e.g. bio_data_4).
  424. */
  425. function tripal_tripal_cron_notification() {
  426. $num_created = 0;
  427. // Get all bundle names to cycle through.
  428. $all_bundles = db_select('tripal_bundle', 'tb')
  429. ->fields('tb', array('name'))
  430. ->execute()->fetchAll();
  431. foreach ($all_bundles as $bundle_name){
  432. // Get the bundle object.
  433. $bundle = tripal_load_bundle_entity(array('name' => $bundle_name->name));
  434. if (!$bundle) {
  435. tripal_report_error('tripal', TRIPAL_ERROR, "Unrecognized bundle name '%bundle'.",
  436. array('%bundle' => $bundle_name));
  437. return FALSE;
  438. }
  439. // Allow modules to add fields to the new bundle.
  440. $modules = module_implements('bundle_fields_info');
  441. foreach ($modules as $module) {
  442. $function = $module . '_bundle_fields_info';
  443. $info = $function('TripalEntity', $bundle);
  444. foreach ($info as $field_name => $details) {
  445. // If the field already exists then skip it.
  446. $field = field_info_field($details['field_name']);
  447. if ($field) {
  448. continue;
  449. }
  450. // Create notification that new fields exist.
  451. $detail_info = ' Tripal has detected a new field ' . $details['field_name'] .' for ' . $bundle->label. ' content type is available for import.';
  452. $title = 'New field available for import';
  453. $actions['Import'] = 'admin/import/field/' . $details['field_name'] . '/' . $bundle_name->name . '/' . $module . '/field';
  454. $type = 'Field';
  455. $submitter_id = $details['field_name'] . '-' . $bundle_name->name . '-' . $module;
  456. tripal_add_notifcation($title, $detail_info, $type, $actions, $submitter_id);
  457. $num_created++;
  458. }
  459. }
  460. // Allow modules to add instances to the new bundle.
  461. $modules = module_implements('bundle_instances_info');
  462. foreach ($modules as $module) {
  463. $function = $module . '_bundle_instances_info';
  464. $info = $function('TripalEntity', $bundle);
  465. foreach ($info as $field_name => $details) {
  466. // If the field is already attached to this bundle then skip it.
  467. $field = field_info_field($details['field_name']);
  468. if ($field and array_key_exists('bundles', $field) and
  469. array_key_exists('TripalEntity', $field['bundles']) and
  470. in_array($bundle->name, $field['bundles']['TripalEntity'])) {
  471. continue;
  472. }
  473. // Create notification that new fields exist.
  474. $detail_info = ' Tripal has detected a new field ' . $details['field_name'] .' for ' . $bundle->label. ' content type is available for import.';
  475. $title = 'New field available for import';
  476. $actions['Import'] = 'admin/import/field/' . $details['field_name'] . '/' . $bundle->name . '/' . $module . '/instance';
  477. $type = 'Field';
  478. $submitter_id = $details['field_name'] . '-' . $bundle_name->name . '-' . $module;
  479. tripal_add_notifcation($title, $detail_info, $type, $actions, $submitter_id);
  480. $num_created++;
  481. }
  482. }
  483. if ($num_created == 0) {
  484. watchdog('tripal_cron', '<pre>No new fields for '. print_r($bundle_name->name, TRUE) .'</pre>');
  485. }
  486. }
  487. }
  488. /**
  489. * Retrieves information about a given content type.
  490. *
  491. * @param $bundle_name
  492. * The name of a bundle.
  493. *
  494. * @return
  495. * An object containing information about the bundle.
  496. */
  497. function tripal_get_content_type($bundle_name) {
  498. return db_select('tripal_bundle', 'tb')
  499. ->fields('tb')
  500. ->condition('tb.name', $bundle_name)
  501. ->execute()
  502. ->fetchAll();
  503. }
  504. /**
  505. * Refreshes the bundle such that new fields added by modules will be found.
  506. *
  507. * @param $bundle_name
  508. * The name of the bundle to refresh (e.g. bio_data_4).
  509. */
  510. function tripal_refresh_bundle_fields($bundle_name) {
  511. $num_created = 0;
  512. // Get the bundle object.
  513. $bundle = tripal_load_bundle_entity(array('name' => $bundle_name));
  514. if (!$bundle) {
  515. tripal_report_error('tripal', TRIPAL_ERROR, "Unrecognized bundle name '%bundle'.",
  516. array('%bundle' => $bundle_name));
  517. return FALSE;
  518. }
  519. // Allow modules to add fields to the new bundle.
  520. $modules = module_implements('bundle_fields_info');
  521. foreach ($modules as $module) {
  522. $function = $module . '_bundle_fields_info';
  523. $info = $function('TripalEntity', $bundle);
  524. foreach ($info as $field_name => $details) {
  525. $field_type = $details['type'];
  526. // If the field already exists then skip it.
  527. $field = field_info_field($details['field_name']);
  528. if ($field) {
  529. continue;
  530. }
  531. // Create the field.
  532. $field = field_create_field($details);
  533. if (!$field) {
  534. tripal_set_message(t("Could not create new field: %field.",
  535. array('%field' => $details['field_name'])), TRIPAL_ERROR);
  536. }
  537. }
  538. }
  539. // Allow modules to add instances to the new bundle.
  540. $modules = module_implements('bundle_instances_info');
  541. foreach ($modules as $module) {
  542. $function = $module . '_bundle_instances_info';
  543. $info = $function('TripalEntity', $bundle);
  544. foreach ($info as $field_name => $details) {
  545. // If the field is already attached to this bundle then skip it.
  546. $field = field_info_field($details['field_name']);
  547. if ($field and array_key_exists('bundles', $field) and
  548. array_key_exists('TripalEntity', $field['bundles']) and
  549. in_array($bundle->name, $field['bundles']['TripalEntity'])) {
  550. continue;
  551. }
  552. // Create the field instance.
  553. $instance = field_create_instance($details);
  554. $num_created++;
  555. drupal_set_message(t("Created field: %field", array('%field' => $info[$field_name]['label'])));
  556. }
  557. }
  558. if ($num_created == 0) {
  559. drupal_set_message(t("No new fields were added."));
  560. }
  561. }
  562. /**
  563. * Updates an existing field and its attached instance to a bundle.
  564. *
  565. *
  566. * @param $field_name
  567. * The name of the field.
  568. * @param $field_info
  569. * An associative array containing the field information. The following
  570. * key/value pairs are supported:
  571. * 'field_type' : a valid field type. May be any of the Drupal default
  572. * fields, one created by the tripal_chado module or another custom module.
  573. * 'widget_type' : a valid widget type. May be any of the Drupal default
  574. * fields, one created by the tripal_chado module or another custom module.
  575. * 'field_settings' : an array of settings that are appropriate for the
  576. * selected field type.
  577. * 'widget_settings' : an array of settings that are appropriate for the
  578. * selected widget type.
  579. * 'description' : a default description for this field.
  580. * 'label' : a label used as a header for this field.
  581. * 'is_required' : indicates if the field is required in the edit form.
  582. * 'cardinality' : indicates the number of values this field can support.
  583. * the default is 1 (meaning only one value). Use a value of
  584. * FIELD_CARDINALITY_UNLIMITED for unlimited number of values.
  585. * 'default_value' : A default value for the field.
  586. * 'format' : A string indicating the format for the field. Must be
  587. * specific to the field.
  588. * @param $entity_type_name
  589. * The entity type name.
  590. * @param $bundle_name
  591. * The bundle name.
  592. *
  593. * @return
  594. * FALSE if the field could not be updated
  595. *
  596. * TODO: this function really shouldn't try to create an instance and
  597. * attach to a bundle at the same time.
  598. *
  599. */
  600. function tripal_update_bundle_field($field_name, $field_info, $entity_type_name, $bundle_name) {
  601. $field = field_info_field($field_name);
  602. // If the field doesn't exists or is not attached to this bundle then
  603. // just return, there is nothing left to do.
  604. if (!$field or !array_key_exists('bundles', $field) or
  605. !array_key_exists($entity_type_name, $field['bundles']) or
  606. !in_array($bundle_name, $field['bundles'][$entity_type_name])) {
  607. return FALSE;
  608. }
  609. $field['field_name'] = $field_name;
  610. if (array_key_exists('field_type', $field_info)) {
  611. $field['cardinality'] = $field_info['cardinality'];
  612. }
  613. if (array_key_exists('locked', $field_info)) {
  614. $field['locked'] = $field_info['locked'];
  615. }
  616. if (array_key_exists('storage', $field_info)) {
  617. $field['storage']['type'] = $field_info['storage'];
  618. }
  619. if (array_key_exists('field_settings', $field_info)) {
  620. $field['settings'] = $field_info['field_settings'];
  621. }
  622. field_update_field($field);
  623. $field_instance['field_name'] = $field_name;
  624. $field_instance['entity_type'] = $entity_type_name;
  625. $field_instance['bundle'] = $bundle_name;
  626. if (array_key_exists('label', $field_info)) {
  627. $field['label'] = $field_info['label'];
  628. }
  629. if (array_key_exists('description', $field_info)) {
  630. $field['description'] = $field_info['description'];
  631. }
  632. if (array_key_exists('widget', $field_info)) {
  633. if (array_key_exists('widget_type', $field_info['widget'])) {
  634. $field['widget']['type'] = $field_info['widget_type'];
  635. }
  636. if (array_key_exists('widget_settings', $field_info['widget'])) {
  637. $field['widget']['settings'] = $field_info['widget_settings'];
  638. }
  639. }
  640. if (array_key_exists('required', $field_info)) {
  641. $field['required'] = $field_info['is_required'];
  642. }
  643. if (array_key_exists('settings', $field_info)) {
  644. $field['settings'] = $field_info['field_settings'];
  645. }
  646. if (array_key_exists('default_value', $field_info)) {
  647. $field['default_value'] = $field_info['default_value'];
  648. }
  649. if (array_key_exists('format', $field_info)) {
  650. $field['format'] = $field_info['format'];
  651. }
  652. field_update_instance($field_instance);
  653. }
  654. /**
  655. * Allows a module to make changes to an entity object after creation.
  656. *
  657. * This function is added by Tripal to allow datastore backends to add
  658. * addition properties to the entity that they themselves will use later.
  659. *
  660. * @param $entity
  661. * @param $entity_type
  662. */
  663. function hook_entity_create(&$entity, $entity_type) {
  664. }
  665. /**
  666. * @section
  667. * Bundle Variables.
  668. */
  669. /**
  670. * Fetch the value for a given tripal variable.
  671. *
  672. * @param string $variable_name
  673. * The name of the variable as in tripal_variables.name.
  674. * @param int $bundle_id
  675. * The unique identfier for the bundle you want the value for.
  676. * @return text
  677. * The value of the specified variable for the specified bundle.
  678. */
  679. function tripal_get_bundle_variable($variable_name, $bundle_id, $default = FALSE) {
  680. $variable = tripal_get_variable($variable_name);
  681. // Warn if we can't find the tripal_variable.
  682. if (!$variable) {
  683. return $default;
  684. }
  685. // Select the value for this variable.
  686. $value = db_select('tripal_bundle_variables', 'var')
  687. ->fields('var', array('value'))
  688. ->condition('var.bundle_id', $bundle_id)
  689. ->condition('var.variable_id', $variable->variable_id)
  690. ->execute()
  691. ->fetchField();
  692. // Warn if the value appears to be empty.
  693. if (!$value) {
  694. return $default;
  695. }
  696. return $value;
  697. }
  698. /**
  699. * Save the value of a tripal variable for a given bundle.
  700. *
  701. * @param string $variable_name
  702. * The name of the variable as in tripal_variables.name.
  703. * @param int $bundle_id
  704. * The unique identfier for the bundle you want the value for.
  705. * @param $text $value
  706. * The value of the variable for the given bundle.
  707. */
  708. function tripal_set_bundle_variable($variable_name, $bundle_id, $value) {
  709. $variable = tripal_get_variable($variable_name);
  710. if (!$variable) {
  711. return FALSE;
  712. }
  713. // And then we need to write the new format to the tripal_bundle_variables table.
  714. $record = array(
  715. 'bundle_id' => $bundle_id,
  716. 'variable_id' => $variable->variable_id,
  717. 'value' => $value,
  718. );
  719. // Check whether there is already a format saved.
  720. $bundle_variable_id = db_select('tripal_bundle_variables', 'var')
  721. ->fields('var', array('bundle_variable_id'))
  722. ->condition('var.bundle_id', $record['bundle_id'])
  723. ->condition('var.variable_id', $record['variable_id'])
  724. ->execute()
  725. ->fetchField();
  726. if ($bundle_variable_id) {
  727. $record['bundle_variable_id'] = $bundle_variable_id;
  728. return drupal_write_record('tripal_bundle_variables', $record, 'bundle_variable_id');
  729. }
  730. else {
  731. return drupal_write_record('tripal_bundle_variables', $record);
  732. }
  733. }
  734. /**
  735. * @section
  736. * Title & URL Formats.
  737. */
  738. /**
  739. * Get Page Title Format for a given Tripal Entity Type.
  740. *
  741. * @param TripalBundle $bundle
  742. * The Entity object for the Tripal Bundle the title format is for.
  743. */
  744. function tripal_get_title_format($bundle) {
  745. // Get the existing title format if it exists.
  746. $title_format = tripal_get_bundle_variable('title_format', $bundle->id);
  747. // If there isn't yet a title format for this bundle/type then we should
  748. // determine the default.
  749. if (!$title_format) {
  750. $title_format = tripal_get_default_title_format($bundle);
  751. tripal_save_title_format($bundle, $title_format);
  752. }
  753. return $title_format;
  754. }
  755. /**
  756. * Save Page Title Format for a given Tripal Entity Type.
  757. *
  758. * @param TripalBundle $entity
  759. * The Entity object for the Tripal Bundle the title format is for.
  760. * @param string $format
  761. * The pattern to be used when generating entity titles for the above type.
  762. */
  763. function tripal_save_title_format($entity, $format) {
  764. return tripal_set_bundle_variable('title_format', $entity->id, $format);
  765. }
  766. /**
  767. * Determine the default title format to use for an entity.
  768. *
  769. * @param TripalBundle $bundle
  770. * The Entity object for the Tripal Bundle that the title format is for.
  771. *
  772. * @return string
  773. * A default title format.
  774. */
  775. function tripal_get_default_title_format($bundle) {
  776. $format = '';
  777. // Retrieve all available tokens.
  778. $tokens = tripal_get_entity_tokens($bundle);
  779. // A) Check to see if more informed modules have suggested a title for this
  780. // type. Invoke hook_tripal_default_title_format() to get all suggestions
  781. // from other modules.
  782. $suggestions = module_invoke_all('tripal_default_title_format', $bundle, $tokens);
  783. if ($suggestions) {
  784. // Use the suggestion with the lightest weight.
  785. $lightest_key = NULL;
  786. foreach ($suggestions as $k => $s) {
  787. if ($lightest_key === NULL) $lightest_key = $k;
  788. if ($s['weight'] < $lightest_key) $lightest_key = $k;
  789. }
  790. $format = $suggestions[$lightest_key]['format'];
  791. return $format;
  792. }
  793. // B) Generate our own ugly title by simply comma-separating all the
  794. // required fields.
  795. if (!$format) {
  796. $tmp = array();
  797. // Check which tokens are required fields and join them into a default format.
  798. foreach($tokens as $token) {
  799. if ($token['required']) {
  800. $tmp[] = $token['token'];
  801. }
  802. }
  803. $format = implode(', ', $tmp);
  804. return $format;
  805. }
  806. return $format;
  807. }
  808. /**
  809. * Implement this hook to define default formats for Tripal Content Types.
  810. *
  811. * @param TripalBundle $bundle
  812. * A tripal content type entity with information to be used for determining the default title format.
  813. * @param array $available_tokens
  814. * An array of available tokens for this particular tripal content type.
  815. *
  816. * @return array
  817. * An array of potential formats. The lightest weighted format suggested by all modules will be chosen.
  818. * Each array item should consist of a 'weight' and 'format'. See the hook implementation below
  819. * for examples.
  820. * - weight: an integer used to determine priority of suggestions.
  821. * The smaller/lighter the number the higher the priority.
  822. * Best practice is to use a weight less than 0 for extension modules.
  823. * specifically, -2 is a good weight for calculated formats and -5 is a
  824. * good weight for hard-coded formats specific to a given type.
  825. * - format: a string including approved tokens used to determine the title
  826. * on Tripal content pages.
  827. */
  828. function hook_tripal_default_title_format($bundle, $available_tokens) {
  829. $format = array();
  830. // If you want to suggest a default format for a particular vocabulary term:
  831. //---------------------------------------------------------------------------
  832. // Load the term associated with this Tripal Content type.
  833. $term = entity_load('TripalTerm', array('id' => $bundle->term_id));
  834. $term = reset($term);
  835. // If it's the term you are interested in then suggest a format.
  836. if ($term->name == 'organism') {
  837. // To suggest a format, add an element to the array with a format & weight key.
  838. $format[] = array(
  839. // This is the format/pattern you suggest be used to determine the title of organism pages.
  840. 'format' => '[organism__genus] [organism__species]',
  841. // The weight/priority of your suggestion.
  842. 'weight' => -5
  843. );
  844. }
  845. // Say you know that in your particular site, all 'names' are required
  846. // and you want to only use the human-readable name:
  847. //---------------------------------------------------------------------------
  848. $name_field = preg_grep('/__name]$/', array_keys($available_tokens));
  849. $name_field = reset($name_field);
  850. if (is_string($name_field)) {
  851. $format[] = array(
  852. 'format' => $name_field,
  853. 'weight' => -2,
  854. );
  855. }
  856. return $format;
  857. }
  858. /**
  859. * Returns an array of tokens based on Tripal Entity Fields.
  860. *
  861. * @param TripalBundle $entity
  862. * The bundle entity for which you want tokens.
  863. * @return
  864. * An array of tokens where the key is the machine_name of the token.
  865. */
  866. function tripal_get_entity_tokens($entity, $options = array()) {
  867. $tokens = array();
  868. // Set default options.
  869. $options['required only'] = (isset($options['required only'])) ? $options['required only'] : FALSE;
  870. $options['include id'] = (isset($options['include id'])) ? $options['include id'] : TRUE;
  871. if ($options['include id']) {
  872. $token = '[TripalBundle__bundle_id]';
  873. $tokens[$token] = array(
  874. 'label' => 'Bundle ID',
  875. 'description' => 'The unique identifier for this Tripal Content Type.',
  876. 'token' => $token,
  877. 'field_name' => NULL,
  878. 'required' => TRUE
  879. );
  880. $token = '[TripalEntity__entity_id]';
  881. $tokens[$token] = array(
  882. 'label' => 'Content/Entity ID',
  883. 'description' => 'The unique identifier for an individual piece of Tripal Content.',
  884. 'token' => $token,
  885. 'field_name' => NULL,
  886. 'required' => TRUE
  887. );
  888. }
  889. $fields = field_info_instances('TripalEntity', $entity->name);
  890. foreach ($fields as $f) {
  891. // Build the token from the field information.
  892. $token = '[' . $f['field_name'] . ']';
  893. $current_token = array(
  894. 'label' => $f['label'],
  895. 'description' => $f['description'],
  896. 'token' => $token,
  897. 'field_name' => $f['field_name'],
  898. 'required' => $f['required']
  899. );
  900. // If the required only option is set then we only want to add
  901. // required fields to the token list.
  902. if ($options['required only'] AND $current_token['required']) {
  903. $tokens[$token] = $current_token;
  904. }
  905. // If the required only option is not set then add everything.
  906. elseif (!$options['required only']) {
  907. $tokens[$token] = $current_token;
  908. }
  909. }
  910. return $tokens;
  911. }
  912. /**
  913. * Replace all Tripal Tokens in a given string.
  914. *
  915. * NOTE: If there is no value for a token then the token is removed.
  916. *
  917. * @param string $string
  918. * The string containing tokens.
  919. * @param TripalEntity $entity
  920. * The entity with field values used to find values of tokens.
  921. * @param TripalBundle $bundle_entity
  922. * The bundle enitity containing special values sometimes needed for token replacement.
  923. *
  924. * @return
  925. * The string will all tokens replaced with values.
  926. */
  927. function tripal_replace_entity_tokens($string, &$entity, $bundle_entity = NULL) {
  928. // Determine which tokens were used in the format string
  929. $used_tokens = array();
  930. if (preg_match_all('/\[\w+\]/', $string, $matches)) {
  931. $used_tokens = $matches[0];
  932. }
  933. // If there are no tokens then just return the string.
  934. if (count($used_tokens) == 0) {
  935. return $string;
  936. }
  937. // If the field are not loaded for the entity then we want to load them
  938. // but we won't do a field_attach_load() as that will load all of the
  939. // fields. For syncing (publishing) of content loading all fields for
  940. // all synced entities causes extreme slowness, so we'll only attach
  941. // the necessary fields for replacing tokens.
  942. $attach_fields = array();
  943. foreach($used_tokens as $token) {
  944. $field_name = str_replace(array('.','[',']'), array('__','',''), $token);
  945. if (!property_exists($entity, $field_name)) {
  946. $field = field_info_field($field_name);
  947. $storage = $field['storage'];
  948. $attach_fields[$storage['type']]['storage'] = $storage;
  949. $attach_fields[$storage['type']]['fields'][] = $field;
  950. }
  951. }
  952. // If we have any fields that need attaching, then do so now.
  953. if (count(array_keys($attach_fields)) > 0) {
  954. foreach ($attach_fields as $storage_type => $details) {
  955. $storage = $details['storage'];
  956. $fields = $details['fields'];
  957. $field_ids = array();
  958. foreach ($fields as $field) {
  959. $field_ids[$field['id']] = array($entity->id);
  960. }
  961. $entities = array($entity->id => $entity);
  962. }
  963. module_invoke($storage['module'], 'field_storage_load', 'TripalEntity',
  964. $entities, FIELD_LOAD_CURRENT, $field_ids, array());
  965. }
  966. // Now that all necessary fields are attached process the tokens.
  967. foreach($used_tokens as $token) {
  968. $field_name = str_replace(array('.','[',']'), array('__','',''), $token);
  969. $value = '';
  970. if (property_exists($entity, $field_name)) {
  971. // Note: there is a memory leak in field_get_items() so we can't use it
  972. // here or bulk publising will slowly erode memory.
  973. //$field_value = field_get_items('TripalEntity', $entity, $field_name);
  974. $value = $entity->{$field_name}['und'][0]['value'];
  975. // TODO: deal with the value when it is not a scalar.
  976. }
  977. // The TripalBundle__bundle_id is a special token for substituting the
  978. // bundle id.
  979. elseif ($field_name === 'TripalBundle__bundle_id') {
  980. // Load the bundle entity if we weren't given it.
  981. if (!$bundle_entity) {
  982. $bundle_entity = tripal_load_bundle_entity(array('name' => $entity->bundle));
  983. }
  984. // This token should be the id of the TripalBundle.
  985. $value = $bundle_entity->id;
  986. }
  987. // The TripalBundle__bundle_id is a special token for substituting the
  988. // entty id.
  989. elseif ($field_name === 'TripalEntity__entity_id') {
  990. // This token should be the id of the TripalEntity.
  991. $value = $entity->id;
  992. }
  993. // Perform the replacement of the token with the value.
  994. $string = str_replace($token, $value, $string);
  995. }
  996. return $string;
  997. }
  998. /**
  999. * Formats the tokens for display.
  1000. *
  1001. * @param array $tokens
  1002. * A list of tokens generated via tripal_get_entity_tokens().
  1003. * @return
  1004. * Rendered output describing the available tokens.
  1005. */
  1006. function theme_token_list($tokens) {
  1007. $header = array('Token', 'Name', 'Description');
  1008. $rows = array();
  1009. foreach ($tokens as $details) {
  1010. $rows[] = array(
  1011. $details['token'],
  1012. $details['label'],
  1013. $details['description'],
  1014. );
  1015. }
  1016. return theme('table', array('header' => $header, 'rows' => $rows));
  1017. }