tripal.entities.api.inc 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591
  1. <?php
  2. /**
  3. * @file
  4. * Provides an application programming interface (API) for working with
  5. * TripalEntity content types (bundles) and their entities.
  6. *
  7. */
  8. /**
  9. * @defgroup tripal_entities_api Tripal Entities
  10. * @ingroup tripal_api
  11. * @{
  12. * Provides an application programming interface (API) for working with
  13. * TripalEntity content types (bundles) and their entities.
  14. *
  15. * Bundles (Content Types): Bundles are types of content in a Drupal site.
  16. * By default, Drupal provides the Basic Page and Article content types,
  17. * and Drupal allows a site developer to create new content types on-the-fly
  18. * using the administrative interface--no programming required. Tripal also
  19. * provides several Content Type by default. During installation of Tripal the
  20. * Organism, Gene, Project, Analysis and other content types are created
  21. * automatically. The site developer can then create new content types for
  22. * different biological data--again, without any programming required.
  23. *
  24. * In order to to assist with data exchange and use of common data formats,
  25. * Tripal Bundles are defined using a controlled vocabulary term (cvterm).
  26. * For example, a "Gene" Bundle is defined using the Sequence Ontology term for
  27. * gene whose term accession is: SO:0000704. This mapping allows Tripal to
  28. * compare content across Tripal sites, and expose data to computational tools
  29. * that understand these vocabularies. By default, Tripal uses Chado as its
  30. * primary data storage back-end.
  31. *
  32. * Entity: An entity is a discrete data record. Entities are most commonly
  33. * seen as "pages" on a Drupal web site and are instances of a Bundle
  34. * (i.e content type). When data is published on a Tripal site such as
  35. * organisms, genes, germplasm, maps, etc., each record is represented by a
  36. * single entity with an entity ID as its only attribute. All other
  37. * information that the entity provides is made available via Fields.
  38. *
  39. * For more information please see:
  40. * http://tripal.info/tutorials/v3.x/developers-handbook/structure
  41. * @}
  42. *
  43. */
  44. /**
  45. * @section
  46. * Hooks.
  47. */
  48. /**
  49. * Allows a module to make changes to an entity object after creation.
  50. *
  51. * This function is added by Tripal to allow datastore backends to add
  52. * addition properties to the entity that they themselves will use later.
  53. *
  54. * @param $entity
  55. * @param $entity_type
  56. *
  57. * @ingroup tripal_entities_api
  58. */
  59. function hook_entity_create(&$entity, $entity_type) {
  60. }
  61. /**
  62. * Allows a module to perform tasks after a TripalBundle object is created.
  63. *
  64. * @param $bundle
  65. * The newly created TripalBundle object.
  66. * @param $storage_args
  67. * Arguments passed to the storage backend for this bundle. These arguments
  68. * typically provide details for how to associate this bundle with records
  69. * in the storage system. Each storage system will have its own set of
  70. * arguments that it will expect.
  71. *
  72. * @ingroup tripal_entities_api
  73. */
  74. function hook_bundle_create(&$bundle, $storage_args) {
  75. }
  76. /**
  77. * Allows a module to perform tasks after fields are added to a TripalBundle.
  78. *
  79. * @param $bundle
  80. * The newly created TripalBundle object.
  81. *
  82. * @ingroup tripal_entities_api
  83. */
  84. function hook_bundle_postcreate(&$bundle) {
  85. }
  86. /**
  87. * Allows a module to add admin notifications to the associated tripal table
  88. * during the cron run.
  89. *
  90. * @ingroup tripal_entities_api
  91. */
  92. function hook_tripal_cron_notification() {
  93. }
  94. /**
  95. * Allows a module to perform tasks before a TripalBundle object is deleted.
  96. *
  97. * @param $bundle
  98. * The newly created TripalBundle object.
  99. *
  100. * @ingroup tripal_entities_api
  101. */
  102. function hook_bundle_delete($bundle) {
  103. }
  104. /**
  105. * Implement this hook to define default formats for Tripal Content Types.
  106. *
  107. * @param TripalBundle $bundle
  108. * A tripal content type entity with information to be used for determining
  109. * the default title format.
  110. * @param array $available_tokens
  111. * An array of available tokens for this particular tripal content type.
  112. *
  113. * @return array
  114. * An array of potential formats. The lightest weighted format suggested by
  115. * all modules will be chosen.
  116. * Each array item should consist of a 'weight' and 'format'. See the hook
  117. * implementation below for examples.
  118. * - weight: an integer used to determine priority of suggestions.
  119. * The smaller/lighter the number the higher the priority.
  120. * Best practice is to use a weight less than 0 for extension modules.
  121. * specifically, -2 is a good weight for calculated formats and -5 is a
  122. * good weight for hard-coded formats specific to a given type.
  123. * - format: a string including approved tokens used to determine the title
  124. * on Tripal content pages.
  125. *
  126. * @ingroup tripal_entities_api
  127. */
  128. function hook_tripal_default_title_format($bundle, $available_tokens) {
  129. $format = array();
  130. // If you want to suggest a default format for a particular vocabulary term:
  131. //---------------------------------------------------------------------------
  132. // Load the term associated with this Tripal Content type.
  133. $term = entity_load('TripalTerm', array('id' => $bundle->term_id));
  134. $term = reset($term);
  135. // If it's the term you are interested in then suggest a format.
  136. if ($term->name == 'organism') {
  137. // To suggest a format, add an element to the array with a format & weight
  138. // key.
  139. $format[] = array(
  140. // This is the format/pattern you suggest be used to determine the title
  141. // of organism pages.
  142. 'format' => '[organism__genus] [organism__species]',
  143. // The weight/priority of your suggestion.
  144. 'weight' => -5
  145. );
  146. }
  147. // Say you know that in your particular site, all 'names' are required
  148. // and you want to only use the human-readable name:
  149. //---------------------------------------------------------------------------
  150. $name_field = preg_grep('/__name]$/', array_keys($available_tokens));
  151. $name_field = reset($name_field);
  152. if (is_string($name_field)) {
  153. $format[] = array(
  154. 'format' => $name_field,
  155. 'weight' => -2,
  156. );
  157. }
  158. return $format;
  159. }
  160. /**
  161. * @section
  162. * Entity.
  163. */
  164. /**
  165. * A replacement for the entity_load function of Drupal.
  166. *
  167. * This function should be used for loading of Tripal Entities. It provides
  168. * greater control to limit which fields are loaded with the entity. The
  169. * entity_load() function of Drupal will automatically attach all fields at
  170. * once but this may not be desired as some fields can be complex and large, and
  171. * the site developer may desire loading of fields via AJAX or the user of
  172. * web services may wish to specify the fields they want to include.
  173. *
  174. * @param $entity_type:
  175. * The entity type to load, e.g. node or user.
  176. * @param $ids
  177. * An array of entity IDs, or FALSE to load all entities.
  178. * @param $reset: Whether to reset the internal cache for the requested entity
  179. * type. Defaults to FALSE.
  180. * @param $field_ids
  181. * A list of numeric field IDs that should be loaded. The
  182. * TripalField named 'content_type' is always automatically added.
  183. * @param $cache
  184. * When loading of entities they can be cached with Drupal for later
  185. * faster loading. However, this can cause memory issues when running
  186. * Tripal jobs that load lots of entities. Caching of entities can
  187. * be disabled to improve memory performance by setting this to FALSE.
  188. * @return
  189. * An array of entity objects indexed by their ids. When no results are
  190. * found, an empty array is returned.
  191. *
  192. * @ingroup tripal_entities_api
  193. */
  194. function tripal_load_entity($entity_type, $ids = FALSE, $reset = FALSE,
  195. $field_ids = array(), $cache = TRUE) {
  196. // The $conditions is deprecated in the funtion arguments of entity_load
  197. // so it was removed from the parameters of this function as well. But
  198. // the load() function of the entity controller still expects it so set it
  199. // to an empty array.
  200. $conditions = array();
  201. // If this isn't a TripalEntity then just load it the old fashioned way
  202. // although caching will not be used if it not specifically set to FALSE.
  203. if ($entity_type != 'TripalEntity') {
  204. return entity_load($entity_type, $ids, $conditions, $reset);
  205. }
  206. // Get the entity controller and clear the cache if requested (default).
  207. $ec = entity_get_controller($entity_type);
  208. if ($reset) {
  209. $ec->resetCache();
  210. }
  211. return $ec->load($ids, $conditions, $field_ids, $cache);
  212. }
  213. /**
  214. * Retrieves a TripalTerm entity that matches the given arguments.
  215. *
  216. * @param $values
  217. * An associative array used to match a term.
  218. * Valid keys may be:
  219. * - vocabulary: Must always be used with accession to uniquely
  220. * identify a term.
  221. * - accession: Must always be used with vocabulary to uniquely
  222. * identify a term.
  223. * - term_id: Can be used alone to uniquely identify a term.
  224. *
  225. * @return
  226. * A TripalTerm entity object or NULL if not found.
  227. *
  228. * @ingroup tripal_entities_api
  229. */
  230. function tripal_load_term_entity($values) {
  231. $vocabulary = array_key_exists('vocabulary', $values) ? $values['vocabulary'] : '';
  232. $accession = array_key_exists('accession', $values) ? $values['accession'] : '';
  233. $term_id = array_key_exists('term_id', $values) ? $values['term_id'] : '';
  234. $term = NULL;
  235. if ($vocabulary and $accession) {
  236. $query = db_select('tripal_term', 'tt');
  237. $query->join('tripal_vocab', 'tv', 'tv.id = tt.vocab_id');
  238. $query->fields('tt', array('id'))
  239. ->fields('tv', array('vocabulary'))
  240. ->condition('tv.vocabulary', $vocabulary)
  241. ->condition('tt.accession', $accession);
  242. $term = $query->execute()->fetchObject();
  243. }
  244. else if ($term_id) {
  245. $query = db_select('tripal_term', 'tt');
  246. $query->fields('tt', array('id'))
  247. ->condition('tt.id', $term_id);
  248. $term = $query->execute()->fetchObject();
  249. }
  250. if ($term) {
  251. $entity = entity_load('TripalTerm', array($term->id));
  252. return reset($entity);
  253. }
  254. return NULL;
  255. }
  256. /**
  257. * Retrieves a TripalVocab entity that maches the given arguments.
  258. *
  259. * @param $values
  260. * An associative array used to match a vocabulary.
  261. * The valid keys are:
  262. * - vocab_id: integer id of the vocabulary.
  263. * - vocabulary: string name of vocabulary.
  264. *
  265. * @return
  266. * A TripalVocab entity object or NULL if not found.
  267. *
  268. * @ingroup tripal_entities_api
  269. */
  270. function tripal_load_vocab_entity($values) {
  271. $vocabulary = array_key_exists('vocabulary', $values) ? $values['vocabulary'] : '';
  272. $vocab_id = array_key_exists('vocab_id', $values) ? $values['vocab_id'] : '';
  273. $vocab = NULL;
  274. $query= db_select('tripal_vocab', 'tv')
  275. ->fields('tv');
  276. if ($vocabulary) {
  277. $query->condition('tv.vocabulary', $vocabulary);
  278. }
  279. if ($vocab_id) {
  280. $query->condition('tv.id', $vocab_id);
  281. }
  282. $vocab = $query->execute()->fetchObject();
  283. if ($vocab) {
  284. $entity = entity_load('TripalVocab', array($vocab->id));
  285. return reset($entity);
  286. }
  287. return NULL;
  288. }
  289. /**
  290. * Retrieves a TripalBundle entity that matches the given arguments.
  291. *
  292. * @param $values
  293. * An associative array used to match a bundle. Valid keys may:
  294. * - id: the numeric id of the bundle.
  295. * - name: the bundle name (e.g. 'bio_data_234')
  296. * - label: the bundle label (e.g. 'Organism')
  297. * - term_id: the term ID to which the bundle belongs
  298. *
  299. * @return
  300. * A TripalBundle entity object or NULL if not found.
  301. *
  302. * @ingroup tripal_entities_api
  303. */
  304. function tripal_load_bundle_entity($values) {
  305. $query = db_select('tripal_bundle', 'tb');
  306. $query->fields('tb');
  307. if (array_key_exists('id', $values)) {
  308. $query->condition('tb.id', $values['id']);
  309. }
  310. if (array_key_exists('name', $values)) {
  311. $query->condition('tb.name', $values['name']);
  312. }
  313. if (array_key_exists('label', $values)) {
  314. $query->condition('tb.label', $values['label']);
  315. }
  316. if (array_key_exists('term_id', $values)) {
  317. $query->condition('tb.term_id', $values['term_id']);
  318. }
  319. $bundle = $query->execute()->fetchObject();
  320. if ($bundle) {
  321. $entity = entity_load_unchanged('TripalBundle', $bundle->id);
  322. return $entity;
  323. }
  324. return NULL;
  325. }
  326. /**
  327. * Allows a module to write to the admin notification table.
  328. *
  329. * @param $title
  330. * A generic phrase indicating what the notification is for.
  331. * @param $details
  332. * A human-readable sentence or two describing the issue.
  333. * @param $type
  334. * A one word type indicating the type of notification. Tripal types include:
  335. * Jobs, Fields.
  336. * If no type is required please pass NULL.
  337. * @param $actions
  338. * A serialized PHP associative array containing the link and URL for each
  339. * action.
  340. * If not type is required please pass NULL.
  341. * @param $submitter_id
  342. * A unique ID provided by the submitter for checking to make sure that the
  343. * notification is not added more than once.
  344. *
  345. * @ingroup tripal_entities_api
  346. */
  347. function tripal_add_notification($title, $details, $type, $actions, $submitter_id) {
  348. $transaction = db_transaction();
  349. // Check the notification isn't already in the admin notification table.
  350. $dedup = db_select('tripal_admin_notfications', 'tan')
  351. ->fields('tan')
  352. ->condition('submitter_id', $submitter_id, '=')
  353. ->execute()->fetchAll();
  354. if (empty($dedup)) {
  355. try {
  356. $record = new stdClass;
  357. $record->details = $details;
  358. $record->title = $title;
  359. $record->submitter_id = $submitter_id;
  360. $record->actions = serialize($actions);
  361. $record->enabled = 1;
  362. $record->type = $type;
  363. $success = drupal_write_record('tripal_admin_notfications', $record);
  364. }
  365. catch (Exception $e) {
  366. $transaction->rollback();
  367. watchdog('tripal_cron', 'Could not write notification to database.');
  368. }
  369. }
  370. }
  371. /**
  372. * Creates a new Tripal Entity type (i.e. bundle).
  373. *
  374. * @param $args
  375. * An array of arguments that must include the following keys:
  376. * - vocabulary: The abbreviated vocabulary for the vocabulary
  377. * (e.g. RO, SO, PATO).
  378. * - accession: The unique term ID in the vocabulary $vocabulary
  379. * (i.e. an accession).
  380. * - term_name: A human-readable name for this term. This will became
  381. * the name that appears for the content type. In practice, this
  382. * should be the name of the term. (E.g. the name for SO:0000704 is gene).
  383. * @param $error
  384. * A string, passed by reference, that is filled with the error message
  385. * if the function fails.
  386. *
  387. * @return
  388. * The bundle object or FALSE if failure.
  389. *
  390. * @ingroup tripal_entities_api
  391. */
  392. function tripal_create_bundle($args, &$error = '') {
  393. $vocabulary = $args['vocabulary'];
  394. $accession = $args['accession'];
  395. $term_name = $args['term_name'];
  396. $storage_args = $args['storage_args'];
  397. $transaction = db_transaction();
  398. try {
  399. // First create the TripalVocab if it doesn't already exist.
  400. $vocab = tripal_load_vocab_entity(array('vocabulary' => $vocabulary));
  401. if (!$vocab) {
  402. $vocab = entity_get_controller('TripalVocab')->create(array('vocabulary' => $vocabulary));
  403. $vocab->save();
  404. }
  405. // Next create the TripalTerm if it doesn't already exist.
  406. $term = tripal_load_term_entity(array(
  407. 'vocabulary' => $vocabulary,
  408. 'accession' => $accession
  409. ));
  410. if (!$term) {
  411. $targs = array('vocab_id' => $vocab->id, 'accession' => $accession, 'name' => $term_name);
  412. $term = entity_get_controller('TripalTerm')->create($targs);
  413. $term = $term->save();
  414. }
  415. // If the bundle doesn't already exist, then add it.
  416. $bundle_name = 'bio_data_' . $term->id;
  417. $einfo = entity_get_info('TripalEntity');
  418. if (!in_array($bundle_name, array_keys($einfo['bundles']))) {
  419. // Make the label for the content type have capitalized words. The
  420. // exception is 'mRNA' which we know should not be uppercased.
  421. $label = ucwords(preg_replace('/_/', ' ', $term_name));
  422. if ($term_name == 'mRNA') {
  423. $label = $term_name;
  424. }
  425. // Insert the bundle.
  426. db_insert('tripal_bundle')
  427. ->fields(array(
  428. 'label' => $label,
  429. 'type' => 'TripalEntity',
  430. 'name' => $bundle_name,
  431. 'term_id' => $term->id,
  432. ))
  433. ->execute();
  434. }
  435. $bundle = tripal_load_bundle_entity(array('name' => $bundle_name));
  436. $modules = module_implements('bundle_create');
  437. foreach ($modules as $module) {
  438. $function = $module . '_bundle_create';
  439. $function($bundle, $storage_args);
  440. }
  441. // Clear the entity cache so that Drupal will read our
  442. // hook_entity_info() implementation.
  443. global $language;
  444. $langcode = $language->language;
  445. cache_clear_all("entity_info:$langcode", 'cache');
  446. variable_set('menu_rebuild_needed', TRUE);
  447. // Get the bundle object.
  448. $bundle = tripal_load_bundle_entity(array('name' => $bundle_name));
  449. tripal_create_bundle_fields($bundle, $term);
  450. $modules = module_implements('bundle_postcreate');
  451. foreach ($modules as $module) {
  452. $function = $module . '_bundle_postcreate';
  453. $function($bundle);
  454. }
  455. }
  456. catch (Exception $e) {
  457. $transaction->rollback();
  458. drupal_set_message(t("Failed to create content type: %message.",
  459. array('%message' => $e->getMessage())), 'error');
  460. return FALSE;
  461. }
  462. return $bundle;
  463. }
  464. /**
  465. * Retrieves a list of the content types.
  466. *
  467. * @return
  468. * An array of bundles. Each bundle is an object containing information
  469. * about that bundle.
  470. *
  471. * @ingroup tripal_entities_api
  472. */
  473. function tripal_get_content_types() {
  474. return db_select('tripal_bundle', 'tb')
  475. ->fields('tb')
  476. ->execute()
  477. ->fetchAll();
  478. }
  479. /**
  480. * Refreshes the bundle such that new fields added by modules will be found
  481. * during cron.
  482. *
  483. * @param $bundle_name
  484. * The name of the bundle to refresh (e.g. bio_data_4).
  485. *
  486. * @ingroup tripal_entities_api
  487. */
  488. function tripal_tripal_cron_notification() {
  489. $num_created = 0;
  490. // Get all bundle names to cycle through.
  491. $all_bundles = db_select('tripal_bundle', 'tb')
  492. ->fields('tb', array('name'))
  493. ->execute()->fetchAll();
  494. foreach ($all_bundles as $bundle_name){
  495. // Get the bundle object.
  496. $bundle = tripal_load_bundle_entity(array('name' => $bundle_name->name));
  497. if (!$bundle) {
  498. tripal_report_error('tripal', TRIPAL_ERROR, "Unrecognized bundle name '%bundle'.",
  499. array('%bundle' => $bundle_name));
  500. return FALSE;
  501. }
  502. // Allow modules to add fields to the new bundle.
  503. $modules = module_implements('bundle_fields_info');
  504. foreach ($modules as $module) {
  505. $function = $module . '_bundle_fields_info';
  506. $info = $function('TripalEntity', $bundle);
  507. foreach ($info as $field_name => $details) {
  508. // If the field already exists then skip it.
  509. $field = field_info_field($details['field_name']);
  510. if ($field) {
  511. continue;
  512. }
  513. // Create notification that new fields exist.
  514. $detail_info = ' Tripal has detected a new field ' . $details['field_name'] .' for ' . $bundle->label. ' content type is available for import.';
  515. $title = 'New field available for import';
  516. $actions['Import'] = 'admin/import/field/' . $details['field_name'] . '/' . $bundle_name->name . '/' . $module . '/field';
  517. $type = 'Field';
  518. $submitter_id = $details['field_name'] . '-' . $bundle_name->name . '-' . $module;
  519. tripal_add_notification($title, $detail_info, $type, $actions, $submitter_id);
  520. $num_created++;
  521. }
  522. }
  523. // Allow modules to add instances to the new bundle.
  524. $modules = module_implements('bundle_instances_info');
  525. foreach ($modules as $module) {
  526. $function = $module . '_bundle_instances_info';
  527. $info = $function('TripalEntity', $bundle);
  528. foreach ($info as $field_name => $details) {
  529. // If the field is already attached to this bundle then skip it.
  530. $field = field_info_field($details['field_name']);
  531. if ($field and array_key_exists('bundles', $field) and
  532. array_key_exists('TripalEntity', $field['bundles']) and
  533. in_array($bundle->name, $field['bundles']['TripalEntity'])) {
  534. continue;
  535. }
  536. // Create notification that new fields exist.
  537. $detail_info = ' Tripal has detected a new field ' . $details['field_name'] .' for ' . $bundle->label. ' content type is available for import.';
  538. $title = 'New field available for import';
  539. $actions['Import'] = 'admin/import/field/' . $details['field_name'] . '/' . $bundle->name . '/' . $module . '/instance';
  540. $type = 'Field';
  541. $submitter_id = $details['field_name'] . '-' . $bundle_name->name . '-' . $module;
  542. tripal_add_notification($title, $detail_info, $type, $actions, $submitter_id);
  543. $num_created++;
  544. }
  545. }
  546. }
  547. }
  548. /**
  549. * Retrieves information about a given content type.
  550. *
  551. * @param $bundle_name
  552. * The name of a bundle.
  553. *
  554. * @return
  555. * An object containing information about the bundle.
  556. *
  557. * @ingroup tripal_entities_api
  558. */
  559. function tripal_get_content_type($bundle_name) {
  560. return db_select('tripal_bundle', 'tb')
  561. ->fields('tb')
  562. ->condition('tb.name', $bundle_name)
  563. ->execute()
  564. ->fetchAll();
  565. }
  566. /**
  567. * Refreshes the bundle such that new fields added by modules will be found.
  568. *
  569. * @param $bundle_name
  570. * The name of the bundle to refresh (e.g. bio_data_4).
  571. * @param $term
  572. * The term object for the bundle.
  573. *
  574. * @return
  575. * The array of field instance names that were added.
  576. *
  577. * @ingroup tripal_entities_api
  578. */
  579. function tripal_create_bundle_fields($bundle, $term) {
  580. $added = array();
  581. // Allow modules to add fields to the new bundle.
  582. $modules = module_implements('bundle_fields_info');
  583. $field_info = array();
  584. foreach ($modules as $module) {
  585. $function = $module . '_bundle_fields_info';
  586. $temp = $function('TripalEntity', $bundle);
  587. if (is_array($temp)) {
  588. // TODO: it would be good to check this array to make sure it follows
  589. // protocol. It would help identify potential errors.
  590. $field_info = array_merge($field_info, $temp);
  591. }
  592. }
  593. // Allow modules to alter which fields should be attached to content
  594. // types they create.
  595. drupal_alter('bundle_fields_info', $field_info, $bundle, $term);
  596. // Iterate through all of the fields and create them.
  597. foreach ($field_info as $field_name => $details) {
  598. $field_type = $details['type'];
  599. // If the field already exists then skip it.
  600. $field = field_info_field($details['field_name']);
  601. if ($field) {
  602. continue;
  603. }
  604. // Create the field.
  605. $field = field_create_field($details);
  606. if (!$field) {
  607. tripal_set_message(t("Could not create new field: %field.",
  608. array('%field' => $details['field_name'])), TRIPAL_ERROR);
  609. }
  610. }
  611. // Allow modules to add instances to the new bundle.
  612. $modules = module_implements('bundle_instances_info');
  613. $instance_info = array();
  614. foreach ($modules as $module) {
  615. $function = $module . '_bundle_instances_info';
  616. $temp = $function('TripalEntity', $bundle);
  617. if (is_array($temp)) {
  618. // TODO: it would be good to check this array to make sure it follows
  619. // protocol. It would help identify potential errors.
  620. $instance_info = array_merge($instance_info, $temp);
  621. }
  622. }
  623. // Allow modules to alter which fields should be attached to content
  624. // types they create.
  625. drupal_alter('bundle_instances_info', $instance_info, $bundle, $term);
  626. // Get the list of existing instances
  627. $existing_instances = field_info_instances('TripalEntity', $bundle->name);
  628. // Iterate through all of the field instances and create them.
  629. foreach ($instance_info as $instance_name => $details) {
  630. // Make sure the instance has a term. If not, report it and skip the field.
  631. if (!array_key_exists('term_vocabulary', $details['settings'])) {
  632. tripal_report_error('tripal_fields', TRIPAL_WARNING,
  633. 'The field instance, !field, is missing the "term_vocabulary" setting. The field instance cannot be added. Please check the field settings.',
  634. ['!field' => $instance_name], ['drupal_set_message' => TRUE]);
  635. continue;
  636. }
  637. if (!array_key_exists('term_accession', $details['settings'])) {
  638. tripal_report_error('tripal_fields', TRIPAL_WARNING,
  639. 'The field instance, !field, is missing the "term_accession" setting. The field instance cannot be added. Please check the field settings.',
  640. ['!field' => $instance_name], ['drupal_set_message' => TRUE]);
  641. continue;}
  642. // Make sure the term exists. If not, skip the field instance and
  643. // report an error.
  644. $field_term_id = $details['settings']['term_vocabulary'] . ':' . $details['settings']['term_accession'];
  645. $field_term = tripal_get_term_details($details['settings']['term_vocabulary'], $details['settings']['term_accession']);
  646. if (!$field_term) {
  647. tripal_report_error('tripal_fields', TRIPAL_WARNING,
  648. 'The term, !term, for the field, !field, does not exist in the database. The ' .
  649. 'field instance cannot be added. Please make sure the term is correct and add it if necessary.',
  650. ['!term' => $field_term_id,
  651. '!field' => $instance_name],
  652. ['drupal_set_message' => TRUE]);
  653. continue;
  654. }
  655. // Make sure the term is not used for any other existing field instance.
  656. $skip = FALSE;
  657. foreach ($existing_instances as $existing_name => $existing_instance) {
  658. // If this instance term is the same as this exsiting term and the
  659. // instance name is not the same then we have a problem.
  660. $existing_term_id = $existing_instance['settings']['term_vocabulary'] . ':' . $existing_instance['settings']['term_accession'];
  661. $existing_field = field_info_field($existing_name);
  662. if ($existing_term_id == $field_term_id and $instance_name != $existing_name) {
  663. tripal_report_error('tripal_fields', TRIPAL_WARNING,
  664. 'The field, !field, uses a term, !term, that is already in use on this content type. The ' .
  665. 'field instance cannot be added.',
  666. ['!term' => $existing_term_id,
  667. '!field' => $instance_name],
  668. ['drupal_set_message' => TRUE]);
  669. $skip = TRUE;
  670. }
  671. // If the instance term is the same as this exsting term but the storage
  672. // types are different then we have a problem.
  673. $existing_storage = $existing_field['storage']['type'];
  674. $this_field_storage = $field_info[$details['field_name']]['storage']['type'];
  675. if ($existing_term_id == $field_term_id and $existing_storage != $this_field_storage) {
  676. tripal_report_error('tripal_fields', TRIPAL_WARNING,
  677. 'The field, !field, provided by the storage type, !type, uses a term, !term, that is already in use on this content type and provided by another storage backend. The ' .
  678. 'field instance cannot be added. Perhaps, consider a different term and adjust the data in the database.',
  679. ['!term' => $existing_term_id,
  680. '!type' => $this_field_storage,
  681. '!field' => $instance_name],
  682. ['drupal_set_message' => TRUE]);
  683. $skip = TRUE;
  684. }
  685. }
  686. if ($skip) {
  687. continue;
  688. }
  689. // If the field is already attached to this bundle then skip it.
  690. if (array_key_exists($instance_name, $existing_instances)) {
  691. continue;
  692. }
  693. // Create the field instance.
  694. $instance = field_create_instance($details);
  695. $existing_instances[$instance_name] = $instance;
  696. $added[] = $instance_name;
  697. }
  698. return $added;
  699. }
  700. /**
  701. * Updates an existing field and its attached instance to a bundle.
  702. *
  703. *
  704. * @param $field_name
  705. * The name of the field.
  706. * @param $field_info
  707. * An associative array containing the field information. The following
  708. * key/value pairs are supported:
  709. * - field_type: a valid field type. May be any of the Drupal default
  710. * fields, one created by the tripal_chado module or another custom module.
  711. * - widget_type: a valid widget type. May be any of the Drupal default
  712. * fields, one created by the tripal_chado module or another custom module.
  713. * - field_settings: an array of settings that are appropriate for the
  714. * selected field type.
  715. * - widget_settings: an array of settings that are appropriate for the
  716. * selected widget type.
  717. * - description: a default description for this field.
  718. * - label: a label used as a header for this field.
  719. * - is_required: indicates if the field is required in the edit form.
  720. * - cardinality: indicates the number of values this field can support.
  721. * the default is 1 (meaning only one value). Use a value of
  722. * FIELD_CARDINALITY_UNLIMITED for unlimited number of values.
  723. * - default_value: A default value for the field.
  724. * - format: A string indicating the format for the field. Must be
  725. * specific to the field.
  726. * @param $entity_type_name
  727. * The entity type name.
  728. * @param $bundle_name
  729. * The bundle name.
  730. *
  731. * @return
  732. * FALSE if the field could not be updated
  733. *
  734. * TODO: this function really shouldn't try to create an instance and
  735. * attach to a bundle at the same time.
  736. *
  737. * @ingroup tripal_entities_api
  738. */
  739. function tripal_update_bundle_field($field_name, $field_info, $entity_type_name, $bundle_name) {
  740. $field = field_info_field($field_name);
  741. // If the field doesn't exists or is not attached to this bundle then
  742. // just return, there is nothing left to do.
  743. if (!$field or !array_key_exists('bundles', $field) or
  744. !array_key_exists($entity_type_name, $field['bundles']) or
  745. !in_array($bundle_name, $field['bundles'][$entity_type_name])) {
  746. return FALSE;
  747. }
  748. $field['field_name'] = $field_name;
  749. if (array_key_exists('field_type', $field_info)) {
  750. $field['cardinality'] = $field_info['cardinality'];
  751. }
  752. if (array_key_exists('locked', $field_info)) {
  753. $field['locked'] = $field_info['locked'];
  754. }
  755. if (array_key_exists('storage', $field_info)) {
  756. $field['storage']['type'] = $field_info['storage'];
  757. }
  758. if (array_key_exists('field_settings', $field_info)) {
  759. $field['settings'] = $field_info['field_settings'];
  760. }
  761. field_update_field($field);
  762. $field_instance['field_name'] = $field_name;
  763. $field_instance['entity_type'] = $entity_type_name;
  764. $field_instance['bundle'] = $bundle_name;
  765. if (array_key_exists('label', $field_info)) {
  766. $field['label'] = $field_info['label'];
  767. }
  768. if (array_key_exists('description', $field_info)) {
  769. $field['description'] = $field_info['description'];
  770. }
  771. if (array_key_exists('widget', $field_info)) {
  772. if (array_key_exists('widget_type', $field_info['widget'])) {
  773. $field['widget']['type'] = $field_info['widget_type'];
  774. }
  775. if (array_key_exists('widget_settings', $field_info['widget'])) {
  776. $field['widget']['settings'] = $field_info['widget_settings'];
  777. }
  778. }
  779. if (array_key_exists('required', $field_info)) {
  780. $field['required'] = $field_info['is_required'];
  781. }
  782. if (array_key_exists('settings', $field_info)) {
  783. $field['settings'] = $field_info['field_settings'];
  784. }
  785. if (array_key_exists('default_value', $field_info)) {
  786. $field['default_value'] = $field_info['default_value'];
  787. }
  788. if (array_key_exists('format', $field_info)) {
  789. $field['format'] = $field_info['format'];
  790. }
  791. field_update_instance($field_instance);
  792. }
  793. /**
  794. * @section
  795. * Bundle Variables.
  796. */
  797. /**
  798. * Fetch the value for a given tripal variable.
  799. *
  800. * @param string $variable_name
  801. * The name of the variable as in tripal_variables.name.
  802. * @param int $bundle_id
  803. * The unique identfier for the bundle you want the value for.
  804. * @return text
  805. * The value of the specified variable for the specified bundle.
  806. *
  807. * @ingroup tripal_entities_api
  808. */
  809. function tripal_get_bundle_variable($variable_name, $bundle_id, $default = FALSE) {
  810. $variable = tripal_get_variable($variable_name);
  811. // Warn if we can't find the tripal_variable.
  812. if (!$variable) {
  813. return $default;
  814. }
  815. // Select the value for this variable.
  816. $value = db_select('tripal_bundle_variables', 'var')
  817. ->fields('var', array('value'))
  818. ->condition('var.bundle_id', $bundle_id)
  819. ->condition('var.variable_id', $variable->variable_id)
  820. ->execute()
  821. ->fetchField();
  822. // Warn if the value appears to be empty.
  823. if (!$value) {
  824. return $default;
  825. }
  826. return $value;
  827. }
  828. /**
  829. * Save the value of a tripal variable for a given bundle.
  830. *
  831. * @param string $variable_name
  832. * The name of the variable as in tripal_variables.name.
  833. * @param int $bundle_id
  834. * The unique identfier for the bundle you want the value for.
  835. * @param $text $value
  836. * The value of the variable for the given bundle.
  837. *
  838. * @ingroup tripal_entities_api
  839. */
  840. function tripal_set_bundle_variable($variable_name, $bundle_id, $value) {
  841. $variable = tripal_get_variable($variable_name);
  842. if (!$variable) {
  843. if($variable_name === 'hide_empty_field'){
  844. tripal_insert_variable(
  845. 'hide_empty_field',
  846. 'Structure->Tripal Content Type->edit checkbox to hide empty fields for that bundle.'
  847. );
  848. $variable = tripal_get_variable($variable_name);
  849. if (!$variable) {
  850. return FALSE;
  851. }
  852. }
  853. else {
  854. return FALSE;
  855. }
  856. }
  857. // And then we need to write the new format to the tripal_bundle_variables
  858. // table.
  859. $record = array(
  860. 'bundle_id' => $bundle_id,
  861. 'variable_id' => $variable->variable_id,
  862. 'value' => $value,
  863. );
  864. // Check whether there is already a format saved.
  865. $bundle_variable_id = db_select('tripal_bundle_variables', 'var')
  866. ->fields('var', array('bundle_variable_id'))
  867. ->condition('var.bundle_id', $record['bundle_id'])
  868. ->condition('var.variable_id', $record['variable_id'])
  869. ->execute()
  870. ->fetchField();
  871. if ($bundle_variable_id) {
  872. $record['bundle_variable_id'] = $bundle_variable_id;
  873. return drupal_write_record('tripal_bundle_variables', $record, 'bundle_variable_id');
  874. }
  875. else {
  876. return drupal_write_record('tripal_bundle_variables', $record);
  877. }
  878. }
  879. /**
  880. * @section
  881. * Title & URL Formats.
  882. */
  883. /**
  884. * Get Page Title Format for a given Tripal Entity Type.
  885. *
  886. * @param TripalBundle $bundle
  887. * The Entity object for the Tripal Bundle the title format is for.
  888. *
  889. * @ingroup tripal_entities_api
  890. */
  891. function tripal_get_title_format($bundle) {
  892. // Get the existing title format if it exists.
  893. $title_format = tripal_get_bundle_variable('title_format', $bundle->id);
  894. // If there isn't yet a title format for this bundle/type then we should
  895. // determine the default.
  896. if (!$title_format) {
  897. $title_format = tripal_get_default_title_format($bundle);
  898. tripal_save_title_format($bundle, $title_format);
  899. }
  900. return $title_format;
  901. }
  902. /**
  903. * Save Page Title Format for a given Tripal Entity Type.
  904. *
  905. * @param TripalBundle $entity
  906. * The Entity object for the Tripal Bundle the title format is for.
  907. * @param string $format
  908. * The pattern to be used when generating entity titles for the above type.
  909. *
  910. * @ingroup tripal_entities_api
  911. */
  912. function tripal_save_title_format($entity, $format) {
  913. return tripal_set_bundle_variable('title_format', $entity->id, $format);
  914. }
  915. /**
  916. * Determine the default title format to use for an entity.
  917. *
  918. * @param TripalBundle $bundle
  919. * The Entity object for the Tripal Bundle that the title format is for.
  920. *
  921. * @return string
  922. * A default title format.
  923. *
  924. * @ingroup tripal_entities_api
  925. */
  926. function tripal_get_default_title_format($bundle) {
  927. $format = '';
  928. // Retrieve all available tokens.
  929. $tokens = tripal_get_entity_tokens($bundle);
  930. // A) Check to see if more informed modules have suggested a title for this
  931. // type. Invoke hook_tripal_default_title_format() to get all suggestions
  932. // from other modules.
  933. $suggestions = module_invoke_all('tripal_default_title_format', $bundle, $tokens);
  934. if ($suggestions) {
  935. // Use the suggestion with the lightest weight.
  936. $lightest_key = NULL;
  937. foreach ($suggestions as $k => $s) {
  938. if ($lightest_key === NULL) $lightest_key = $k;
  939. if ($s['weight'] < $lightest_key) $lightest_key = $k;
  940. }
  941. $format = $suggestions[$lightest_key]['format'];
  942. return $format;
  943. }
  944. // B) Generate our own ugly title by simply comma-separating all the
  945. // required fields.
  946. if (!$format) {
  947. $tmp = array();
  948. // Check which tokens are required fields and join them into a default
  949. // format.
  950. foreach($tokens as $token) {
  951. if ($token['required']) {
  952. $tmp[] = $token['token'];
  953. }
  954. }
  955. $format = implode(', ', $tmp);
  956. return $format;
  957. }
  958. return $format;
  959. }
  960. /**
  961. * Returns an array of tokens based on Tripal Entity Fields.
  962. *
  963. * @param TripalBundle $bundle
  964. * The bundle entity for which you want tokens.
  965. * @return
  966. * An array of tokens where the key is the machine_name of the token.
  967. *
  968. * @ingroup tripal_entities_api
  969. */
  970. function tripal_get_entity_tokens($bundle, $options = array()) {
  971. $tokens = array();
  972. // Set default options.
  973. $options['required only'] = (isset($options['required only'])) ? $options['required only'] : FALSE;
  974. $options['include id'] = (isset($options['include id'])) ? $options['include id'] : TRUE;
  975. if ($options['include id']) {
  976. $token = '[TripalBundle__bundle_id]';
  977. $tokens[$token] = [
  978. 'label' => 'Bundle ID',
  979. 'description' => 'The unique identifier for this Tripal Content Type.',
  980. 'token' => $token,
  981. 'field_name' => NULL,
  982. 'required' => TRUE
  983. ];
  984. $token = '[TripalEntity__entity_id]';
  985. $tokens[$token] = [
  986. 'label' => 'Content/Entity ID',
  987. 'description' => 'The unique identifier for an individual piece of Tripal Content.',
  988. 'token' => $token,
  989. 'field_name' => NULL,
  990. 'required' => TRUE
  991. ];
  992. }
  993. $instances = field_info_instances('TripalEntity', $bundle->name);
  994. foreach ($instances as $instance_name => $instance) {
  995. if (!$instance['required'] and $options['required only']) {
  996. continue;
  997. }
  998. $use_field = FALSE;
  999. // Iterate through the TripalEntity fields and see if they have
  1000. // sub-elements, if so, add those as tokens too.
  1001. $field_name = $instance['field_name'];
  1002. if ($instance['entity_type'] == 'TripalEntity') {
  1003. if (tripal_load_include_field_class($field_name)) {
  1004. $field = field_info_field($field_name);
  1005. $field_obj = new $field_name($field, $instance);
  1006. $element_info = $field_obj->elementInfo();
  1007. $term_id = $instance['settings']['term_vocabulary'] . ':' . $instance['settings']['term_accession'];
  1008. if ($element_info and
  1009. array_key_exists($term_id, $element_info) and
  1010. array_key_exists('elements', $element_info[$term_id]) and count($element_info[$term_id]['elements']) > 0) {
  1011. $elements = $element_info[$term_id]['elements'];
  1012. _tripal_get_entity_tokens_for_elements($instance, $field_name, $elements, $tokens, $options);
  1013. }
  1014. else {
  1015. $use_field = TRUE;
  1016. }
  1017. }
  1018. else {
  1019. $use_field = TRUE;
  1020. }
  1021. }
  1022. else {
  1023. $use_field = TRUE;
  1024. }
  1025. // If we have no elements to add then just add the field as is.
  1026. if ($use_field) {
  1027. // Build the token from the field information.
  1028. $token = '[' . $instance['field_name'] . ']';
  1029. $tokens[$token] = [
  1030. 'label' => $instance['label'],
  1031. 'description' => $instance['description'],
  1032. 'token' => $token,
  1033. 'field_name' => $instance['field_name'],
  1034. 'required' => $instance['required']
  1035. ];
  1036. }
  1037. }
  1038. return $tokens;
  1039. }
  1040. /**
  1041. * A recursive helper function to get tokens for element sub fields.
  1042. *
  1043. * @param $instance
  1044. * A original field instance object.
  1045. * @param $parent
  1046. * The name of the parent. The first time this is called outside of
  1047. * recursion this should be the field name.
  1048. * @param $elements
  1049. * The array of elements to process.
  1050. * @param $tokens
  1051. * The array of tokens to be added to.
  1052. */
  1053. function _tripal_get_entity_tokens_for_elements($instance, $parent, $elements, &$tokens, $options) {
  1054. // Iterate through all of the elements and add tokens for each one.
  1055. foreach ($elements as $child_term_id => $details) {
  1056. // We don't need to add the entity element.
  1057. if ($child_term_id == 'entity') {
  1058. continue;
  1059. }
  1060. // Skip elements that aren't required.
  1061. $required = array_key_exists('required', $details) ? $details['required'] : FALSE;
  1062. if (!$required and $options['required only']) {
  1063. continue;
  1064. }
  1065. $token = '[' . $parent . ',' . $child_term_id . ']';
  1066. $label = $child_term_id;
  1067. if (array_key_exists('name', $details)) {
  1068. $label = $details['name'];
  1069. }
  1070. elseif (preg_match('/:/', $child_term_id)) {
  1071. list($vocabulary, $accession) = explode(':', $child_term_id);
  1072. $term = tripal_get_term_details($vocabulary, $accession);
  1073. $label = $term['name'];
  1074. }
  1075. // Add the token!
  1076. $tokens[$token] = [
  1077. 'label' => $label,
  1078. 'description' => array_key_exists('description', $details) ? $details['description'] : '',
  1079. 'token' => $token,
  1080. 'field_name' => $instance['field_name'],
  1081. 'required' => $required
  1082. ];
  1083. // Recurse to include sub elements
  1084. if (array_key_exists('elements', $details)) {
  1085. _tripal_get_entity_tokens_for_elements($instance, $parent . ',' . $child_term_id,
  1086. $details['elements'], $tokens, $options);
  1087. }
  1088. }
  1089. }
  1090. /**
  1091. * Replace all Tripal Tokens in a given string.
  1092. *
  1093. * NOTE: If there is no value for a token then the token is removed.
  1094. *
  1095. * @param string $string
  1096. * The string containing tokens.
  1097. * @param TripalEntity $entity
  1098. * The entity with field values used to find values of tokens.
  1099. * @param TripalBundle $bundle_entity
  1100. * The bundle enitity containing special values sometimes needed for token
  1101. * replacement.
  1102. *
  1103. * @return
  1104. * The string will all tokens replaced with values.
  1105. *
  1106. * @ingroup tripal_entities_api
  1107. */
  1108. function tripal_replace_entity_tokens($string, &$entity, $bundle_entity = NULL) {
  1109. // Determine which tokens were used in the format string
  1110. $used_tokens = [];
  1111. if (preg_match_all('/\[.*?\]/', $string, $matches)) {
  1112. $used_tokens = $matches[0];
  1113. }
  1114. // If there are no tokens then just return the string.
  1115. if (count($used_tokens) == 0) {
  1116. return $string;
  1117. }
  1118. // If the fields are not loaded for the entity then we want to load them
  1119. // but we won't do a field_attach_load() as that will load all of the
  1120. // fields. For syncing (publishing) of content loading all fields for
  1121. // all synced entities causes extreme slowness, so we'll only attach
  1122. // the necessary fields for replacing tokens.
  1123. $attach_fields = array();
  1124. foreach($used_tokens as $token) {
  1125. $token = preg_replace('/[\[\]]/', '', $token);
  1126. $elements = explode(',', $token);
  1127. $field_name = array_shift($elements);
  1128. //$field_name = str_replace(array('.','[',']'), array('__','',''), $field_name);
  1129. if (!property_exists($entity, $field_name) or empty($entity->{$field_name})) {
  1130. $field = field_info_field($field_name);
  1131. $storage = $field['storage'];
  1132. $attach_fields[$storage['type']]['storage'] = $storage;
  1133. $attach_fields[$storage['type']]['fields'][] = $field;
  1134. }
  1135. }
  1136. // If we have any fields that need attaching, then do so now.
  1137. if (count(array_keys($attach_fields)) > 0) {
  1138. foreach ($attach_fields as $storage_type => $details) {
  1139. $storage = $details['storage'];
  1140. $fields = $details['fields'];
  1141. $field_ids = array();
  1142. foreach ($fields as $field) {
  1143. $field_ids[$field['id']] = array($entity->id);
  1144. }
  1145. $entities = array($entity->id => $entity);
  1146. }
  1147. module_invoke($storage['module'], 'field_storage_load', 'TripalEntity',
  1148. $entities, FIELD_LOAD_CURRENT, $field_ids, array());
  1149. }
  1150. // Now that all necessary fields are attached process the tokens.
  1151. foreach($used_tokens as $token) {
  1152. $token = preg_replace('/[\[\]]/', '', $token);
  1153. $elements = explode(',', $token);
  1154. $field_name = array_shift($elements);
  1155. $value = '';
  1156. if (property_exists($entity, $field_name)) {
  1157. $value = '';
  1158. // Note: there is a memory leak in field_get_items() so we can't use it
  1159. // here or bulk publishing will slowly erode memory.
  1160. // $field_value = field_get_items('TripalEntity', $entity, $field_name);
  1161. if (array_key_exists('und', $entity->{$field_name}) and
  1162. array_key_exists(0, $entity->{$field_name}['und'])) {
  1163. $value = $entity->{$field_name}['und'][0]['value'];
  1164. // If the value is an array it means we have sub elements and we can
  1165. // descend through the array to look for matching value.
  1166. if (is_array($value) and count($elements) > 0) {
  1167. $value = _tripal_replace_entity_tokens_for_elements($elements, $value);
  1168. }
  1169. }
  1170. }
  1171. // The TripalBundle__bundle_id is a special token for substituting the
  1172. // bundle id.
  1173. elseif ($field_name === 'TripalBundle__bundle_id') {
  1174. // Load the bundle entity if we weren't given it.
  1175. if (!$bundle_entity) {
  1176. $bundle_entity = tripal_load_bundle_entity(array('name' => $entity->bundle));
  1177. }
  1178. // This token should be the id of the TripalBundle.
  1179. $value = $bundle_entity->id;
  1180. }
  1181. // The TripalBundle__bundle_id is a special token for substituting the
  1182. // entty id.
  1183. elseif ($field_name === 'TripalEntity__entity_id') {
  1184. // This token should be the id of the TripalEntity.
  1185. $value = $entity->id;
  1186. }
  1187. // We can't support tokens that have multiple elements (i.e. in an array).
  1188. if (is_array($value)) {
  1189. $string = str_replace('[' . $token . ']', '', $string);
  1190. }
  1191. else {
  1192. $string = str_replace('[' . $token . ']', $value, $string);
  1193. }
  1194. }
  1195. return $string;
  1196. }
  1197. /**
  1198. * A helper function for tripal_replace_entity_tokens to get token values.
  1199. *
  1200. * This helper function is used when the tokens are from subelements.
  1201. * @param $entity
  1202. */
  1203. function _tripal_replace_entity_tokens_for_elements($elements, $values) {
  1204. $term_id = array_shift($elements);
  1205. $value = $values[$term_id];
  1206. if (count($elements) == 0) {
  1207. return $value;
  1208. }
  1209. else {
  1210. _tripal_replace_entity_tokens_for_elements($elements, $value);
  1211. }
  1212. }
  1213. /**
  1214. * Formats the tokens for display.
  1215. *
  1216. * @param array $tokens
  1217. * A list of tokens generated via tripal_get_entity_tokens().
  1218. * @return
  1219. * Rendered output describing the available tokens.
  1220. *
  1221. * @ingroup tripal_entities_api
  1222. */
  1223. function theme_token_list($tokens) {
  1224. $header = array('Token', 'Name', 'Description');
  1225. $rows = array();
  1226. foreach ($tokens as $details) {
  1227. $rows[] = array(
  1228. $details['token'],
  1229. $details['label'],
  1230. $details['description'],
  1231. );
  1232. }
  1233. return theme('table', array('header' => $header, 'rows' => $rows));
  1234. }
  1235. /**
  1236. * Define the entity label callback. This will return the title.
  1237. *
  1238. * @param $entity
  1239. *
  1240. * @return mixed
  1241. *
  1242. * @ingroup tripal_entities_api
  1243. */
  1244. function tripal_entity_label($entity) {
  1245. if (property_exists($entity, 'title')) {
  1246. return $entity->title;
  1247. }
  1248. return NULL;
  1249. }
  1250. /**
  1251. * Retrieves details, including attached fields, for a given bundle.
  1252. *
  1253. * @param $bundle_name
  1254. * The name of the bundle (e.g. bio_data_xx)
  1255. *
  1256. * @return
  1257. * An array containing the name, label, controlled vocabulary details
  1258. * and a list of fields attached to the bundle. Returns FALSE
  1259. * if the bundle does not exist.
  1260. *
  1261. * @ingroup tripal_entities_api
  1262. */
  1263. function tripal_get_bundle_details($bundle_name) {
  1264. global $user;
  1265. $bundle = tripal_load_bundle_entity(array('name' => $bundle_name));
  1266. if (!$bundle) {
  1267. return FALSE;
  1268. }
  1269. $term = tripal_load_term_entity(array('term_id' => $bundle->term_id));
  1270. $vocab = $term->vocab;
  1271. $instances = field_info_instances('TripalEntity', $bundle->name);
  1272. $details = array(
  1273. 'name' => $bundle->name,
  1274. 'label' => $bundle->label,
  1275. 'term' => array(
  1276. 'accession' => $vocab->vocabulary . ':' . $term->accession,
  1277. 'name' => $term->name,
  1278. 'definition' => $term->definition,
  1279. 'url' => $term->url
  1280. ),
  1281. 'fields' => array(),
  1282. );
  1283. // Iterate through each feild and provide a discription of it and
  1284. // it's sub elements.
  1285. foreach ($instances as $instance) {
  1286. // Skip deleted fields.
  1287. if ($instance['deleted']) {
  1288. continue;
  1289. }
  1290. $field_name = $instance['field_name'];
  1291. $field = field_info_field($field_name);
  1292. $field_class = $field['type'];
  1293. $term_vocab = $instance['settings']['term_vocabulary'];
  1294. $term_accession = $instance['settings']['term_accession'];
  1295. $field_term = tripal_get_term_details($term_vocab, $term_accession);
  1296. $field_details = array(
  1297. 'name' => $field_name,
  1298. 'label' => $instance['label'],
  1299. 'term' => array(
  1300. 'accession' => $term_vocab . ":" . $term_accession,
  1301. 'name' => $field_term['name'],
  1302. 'definition' => $field_term['definition'],
  1303. 'url' => $field_term['url'],
  1304. ),
  1305. // These items can be overridden by the element_info array that
  1306. // is present in a TripalField instance. Here we set defaults.
  1307. 'required' => $instance['required'] ? TRUE : FALSE,
  1308. 'type' => 'xs:string',
  1309. 'readonly' => TRUE,
  1310. // The cardinatlity value always comes from the field.
  1311. 'cardinality' => $field['cardinality'],
  1312. );
  1313. if (tripal_load_include_field_class($field_class)) {
  1314. $field_obj = new $field_class($field, $instance);
  1315. $element_info = $field_obj->elementInfo();
  1316. $element_info = $element_info[$term_vocab . ':' . $term_accession];
  1317. // If the element info for this field sets required, type and readonly
  1318. // attributes then set those.
  1319. $field_details['required'] = array_key_exists('required', $element_info) ? $element_info['required'] : FALSE;
  1320. $field_details['type'] = array_key_exists('type', $element_info) ? $element_info['type'] : 'xs:string';
  1321. $field_details['readonly'] = array_key_exists('readonly', $element_info) ? $element_info['readonly'] : TRUE;
  1322. $field_details['label'] = array_key_exists('label', $element_info) ? $element_info['label'] : $field_details['label'];
  1323. $field_details['help'] = array_key_exists('help', $element_info) ? $element_info['help'] : '';
  1324. // If this field is an 'xs:complexType' then it will have sub elements.
  1325. // we need to add those as well.
  1326. if (array_key_exists('elements', $element_info) and is_array($element_info['elements'])) {
  1327. _tripal_get_bundle_field_element_details($element_info['elements'], $field_details);
  1328. }
  1329. $details['fields'][] = $field_details;
  1330. }
  1331. }
  1332. return $details;
  1333. }
  1334. /**
  1335. * A recursive helper function for the tripal_get_bundle_details.
  1336. *
  1337. * @param $elementInfo
  1338. *
  1339. * @ingroup tripal_entities_api
  1340. */
  1341. function _tripal_get_bundle_field_element_details($elements, &$field_details) {
  1342. $field_details['elements'] = array();
  1343. foreach ($elements as $element_key => $element_info) {
  1344. // Handle the entity element differnetly.
  1345. if ($element_key == 'entity') {
  1346. continue;
  1347. }
  1348. list($term_vocab, $term_accession) = explode(':', $element_key);
  1349. $term = tripal_get_term_details($term_vocab, $term_accession);
  1350. $element_details = array(
  1351. 'name' => $element_info['name'],
  1352. 'label' => array_key_exists('label', $element_info) ? $element_info['label'] : ucfirst(preg_replace('/_/', ' ', $term['name'])),
  1353. 'help' => array_key_exists('help', $element_info) ? $element_info['help'] : '',
  1354. 'term' => array(
  1355. 'accession' => $term_vocab . ':' . $term_accession,
  1356. 'name' => $term['name'],
  1357. 'definition' => $term['definition'],
  1358. 'url' => $term['url'],
  1359. ),
  1360. 'required' => array_key_exists('required', $element_info) ? $element_info['required'] : FALSE,
  1361. 'type' => array_key_exists('type', $element_info) ? $element_info['type'] : 'xs:string',
  1362. 'readonly' => array_key_exists('readonly', $element_info) ? $element_info['readonly'] : TRUE,
  1363. );
  1364. if (array_key_exists('elements', $element_info) and is_array($element_info['elements'])) {
  1365. _tripal_get_bundle_field_element_details($element_info['elements'], $element_details);
  1366. }
  1367. $field_details['elements'][] = $element_details;
  1368. }
  1369. }
  1370. /**
  1371. * Is this completed? It doesn't look right and I can't find it used anywhere
  1372. * in the existing code.
  1373. *
  1374. * @param $bundle_name
  1375. * The name of the bundle (e.g. bio_data_xx)
  1376. * @param unknown $values
  1377. *
  1378. * @throws Exception
  1379. *
  1380. *
  1381. */
  1382. function tripal_insert_entity($bundle_name, $values){
  1383. global $user;
  1384. $bundle = tripal_load_bundle_entity(array('name' => $bundle_name));
  1385. // Get the fields associated with this content type.
  1386. $instances = field_info_instances('TripalEntity', $bundle->name);
  1387. foreach ($instances as $instance) {
  1388. $field_name = $instance['field_name'];
  1389. $field = field_info_field($field_name);
  1390. $field_type = $field['type'];
  1391. $field_settings = $field['settings'];
  1392. $instance_settings = $instance['settings'];
  1393. $field_name = $field['field_name'];
  1394. $vocabulary = $instance['settings']['term_vocabulary'];
  1395. $accession = $instance['settings']['term_accession'];
  1396. $field_accession = $vocabulary . ':' . $accession;
  1397. $field_term = tripal_get_term_details($vocabulary, $accession);
  1398. $field_key = $field_term['name'];
  1399. $field_key = strtolower(preg_replace('/ /', '_', $key));
  1400. // There are three ways that a field value can be specified. Those
  1401. // are as the controlled vocabulary accession (e.g. GO:0000134), sa
  1402. // the field name or as the field key which is the term name with
  1403. // spaces replaced with underscores.
  1404. // First make sure that required fields are present.
  1405. if ($instance['required'] == TRUE) {
  1406. if (!array_key_exists($field_key, $values) and
  1407. !array_key_exists($field_accession, $values) and
  1408. !array_key_exists($field_name, $values)) {
  1409. throw new Exception(t('Cannot insert the record. Missing the required field "%missing".',
  1410. array('%missing' => $field_name)));
  1411. }
  1412. }
  1413. }
  1414. // Make sure that all required fields are present.
  1415. // TODO: make sure the user has permission to do this.
  1416. $ec = entity_get_controller('TripalEntity');
  1417. $entity = $ec->create(array(
  1418. 'bundle' => $bundle_name,
  1419. 'term_id' => $bundle->term_id,
  1420. ));
  1421. $entity = $entity->save();
  1422. }
  1423. /**
  1424. * Are we keeping this?
  1425. *
  1426. * @param $bundle_name
  1427. * @param $values
  1428. *
  1429. *
  1430. */
  1431. function tripal_update_entity($bundle_name, $values) {
  1432. }