tripal.entities.api.inc 36 KB

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