tripal.entities.api.inc 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590
  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 = TRUE;
  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. }