tripal.entities.api.inc 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653
  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 $job
  384. * The job ID if this is launched via a job.
  385. *
  386. * @return
  387. * The bundle object or FALSE if failure.
  388. *
  389. * @ingroup tripal_entities_api
  390. */
  391. function tripal_create_bundle($args, $job = NULL) {
  392. $vocabulary = $args['vocabulary'];
  393. $accession = $args['accession'];
  394. $term_name = $args['term_name'];
  395. $storage_args = $args['storage_args'];
  396. $message_args = [
  397. 'job' => $job,
  398. 'print' => TRUE,
  399. 'watchdog' => TRUE,
  400. ];
  401. tripal_report_error('tripal_entities', TRIPAL_INFO,
  402. "Creation of a content type is performed using a database transaction. " .
  403. "If it fails or is terminated prematurely then all insertions and " .
  404. "updates are rolled back and will not be found in the database",
  405. [], $message_args);
  406. $transaction = db_transaction();
  407. try {
  408. // First create the TripalVocab if it doesn't already exist.
  409. $vocab = tripal_load_vocab_entity(array('vocabulary' => $vocabulary));
  410. if (!$vocab) {
  411. $vocab = entity_get_controller('TripalVocab')->create(array('vocabulary' => $vocabulary));
  412. if ($vocab) {
  413. $vocab->save();
  414. }
  415. else {
  416. $transaction->rollback();
  417. tripal_report_error('tripal_entities', TRIPAL_ERROR,
  418. 'Unable to create TripalVocab :vocab', array(':vocab' => $vocabulary), $message_args);
  419. return FALSE;
  420. }
  421. }
  422. // Next create the TripalTerm if it doesn't already exist.
  423. $term = tripal_load_term_entity(array(
  424. 'vocabulary' => $vocabulary,
  425. 'accession' => $accession
  426. ));
  427. if (!$term) {
  428. $targs = array('vocab_id' => $vocab->id, 'accession' => $accession, 'name' => $term_name);
  429. $term = entity_get_controller('TripalTerm')->create($targs);
  430. if ($term) {
  431. $term = $term->save();
  432. }
  433. else {
  434. $transaction->rollback();
  435. tripal_report_error('tripal_entities', TRIPAL_ERROR,
  436. 'Unable to create TripalTerm :term', array(':term' => $term_name), $message_args);
  437. return FALSE;
  438. }
  439. }
  440. // If the bundle doesn't already exist, then add it.
  441. $bundle_name = 'bio_data_' . $term->id;
  442. $einfo = entity_get_info('TripalEntity');
  443. if (!in_array($bundle_name, array_keys($einfo['bundles']))) {
  444. // Make the label for the content type have capitalized words. The
  445. // exception is 'mRNA' which we know should not be uppercased.
  446. $label = ucwords(preg_replace('/_/', ' ', $term_name));
  447. if ($term_name == 'mRNA') {
  448. $label = $term_name;
  449. }
  450. // Insert the bundle.
  451. db_insert('tripal_bundle')
  452. ->fields(array(
  453. 'label' => $label,
  454. 'type' => 'TripalEntity',
  455. 'name' => $bundle_name,
  456. 'term_id' => $term->id,
  457. ))
  458. ->execute();
  459. }
  460. $bundle = tripal_load_bundle_entity(array('name' => $bundle_name));
  461. if (!$bundle) {
  462. $transaction->rollback();
  463. tripal_report_error('tripal_entities', TRIPAL_ERROR,
  464. 'Unable to create Tripal Bundle :name.', array(':name' => $bundle_name), $message_args);
  465. return FALSE;
  466. }
  467. $modules = module_implements('bundle_create');
  468. foreach ($modules as $module) {
  469. $function = $module . '_bundle_create';
  470. if (function_exists($function)) {
  471. $function($bundle, $storage_args);
  472. }
  473. }
  474. // Clear the entity cache so that Drupal will read our
  475. // hook_entity_info() implementation.
  476. global $language;
  477. $langcode = $language->language;
  478. cache_clear_all("entity_info:$langcode", 'cache');
  479. variable_set('menu_rebuild_needed', TRUE);
  480. // Get the bundle object.
  481. $bundle = tripal_load_bundle_entity(array('name' => $bundle_name));
  482. if (!$bundle) {
  483. $transaction->rollback();
  484. tripal_report_error('tripal_entities', TRIPAL_ERROR,
  485. 'Unable to load Tripal Bundle :name after cache clear.', array(':name' => $bundle_name), $message_args);
  486. return FALSE;
  487. }
  488. tripal_create_bundle_fields($bundle, $term);
  489. // Specifically commiting here since we have a fully featured bundle.
  490. // Post-create hook implementations assume we have a
  491. // created bundle so we don't want to rollback if a
  492. // custom implementation causes an exception.
  493. unset($transaction);
  494. }
  495. catch (Exception $e) {
  496. $transaction->rollback();
  497. $message_args['drupal_set_message'] = TRUE;
  498. tripal_report_error('tripal_entities', TRIPAL_ERROR,
  499. "Failed to create content type: %message.", ['%message' => $e->getMessage()], $message_args);
  500. return FALSE;
  501. }
  502. // Call any custom hook_bundle_postcreate() implementations.
  503. // This is done outside of the try/catch & transaction
  504. // since it occurs after creation and thus should not cause
  505. // a rollback of the creation on error.
  506. $modules = module_implements('bundle_postcreate');
  507. foreach ($modules as $module) {
  508. $function = $module . '_bundle_postcreate';
  509. if (function_exists($function)) {
  510. $function($bundle);
  511. }
  512. }
  513. // Set admin access for the new bundle.
  514. tripal_admin_access($bundle);
  515. // Report that we're done.
  516. tripal_report_error('tripal_entities', TRIPAL_INFO, "Done.", [], $message_args);
  517. return $bundle;
  518. }
  519. /**
  520. * Retrieves a list of the content types.
  521. *
  522. * @return
  523. * An array of bundles. Each bundle is an object containing information
  524. * about that bundle.
  525. *
  526. * @ingroup tripal_entities_api
  527. */
  528. function tripal_get_content_types() {
  529. return db_select('tripal_bundle', 'tb')
  530. ->fields('tb')
  531. ->execute()
  532. ->fetchAll();
  533. }
  534. /**
  535. * Refreshes the bundle such that new fields added by modules will be found
  536. * during cron.
  537. *
  538. * @param $bundle_name
  539. * The name of the bundle to refresh (e.g. bio_data_4).
  540. *
  541. * @ingroup tripal_entities_api
  542. */
  543. function tripal_tripal_cron_notification() {
  544. $num_created = 0;
  545. // Get all bundle names to cycle through.
  546. $all_bundles = db_select('tripal_bundle', 'tb')
  547. ->fields('tb', array('name'))
  548. ->execute()->fetchAll();
  549. foreach ($all_bundles as $bundle_name){
  550. // Get the bundle object.
  551. $bundle = tripal_load_bundle_entity(array('name' => $bundle_name->name));
  552. if (!$bundle) {
  553. tripal_report_error('tripal', TRIPAL_ERROR, "Unrecognized bundle name '%bundle'.",
  554. array('%bundle' => $bundle_name));
  555. return FALSE;
  556. }
  557. // Allow modules to add fields to the new bundle.
  558. $modules = module_implements('bundle_fields_info');
  559. foreach ($modules as $module) {
  560. $function = $module . '_bundle_fields_info';
  561. $info = $function('TripalEntity', $bundle);
  562. foreach ($info as $field_name => $details) {
  563. // If the field already exists then skip it.
  564. $field = field_info_field($details['field_name']);
  565. if ($field) {
  566. continue;
  567. }
  568. // Create notification that new fields exist.
  569. $detail_info = ' Tripal has detected a new field ' . $details['field_name'] .' for ' . $bundle->label. ' content type is available for import.';
  570. $title = 'New field available for import';
  571. $actions['Import'] = 'admin/import/field/' . $details['field_name'] . '/' . $bundle_name->name . '/' . $module . '/field';
  572. $type = 'Field';
  573. $submitter_id = $details['field_name'] . '-' . $bundle_name->name . '-' . $module;
  574. tripal_add_notification($title, $detail_info, $type, $actions, $submitter_id);
  575. $num_created++;
  576. }
  577. }
  578. // Allow modules to add instances to the new bundle.
  579. $modules = module_implements('bundle_instances_info');
  580. foreach ($modules as $module) {
  581. $function = $module . '_bundle_instances_info';
  582. $info = $function('TripalEntity', $bundle);
  583. foreach ($info as $field_name => $details) {
  584. // If the field is already attached to this bundle then skip it.
  585. $field = field_info_field($details['field_name']);
  586. if ($field and array_key_exists('bundles', $field) and
  587. array_key_exists('TripalEntity', $field['bundles']) and
  588. in_array($bundle->name, $field['bundles']['TripalEntity'])) {
  589. continue;
  590. }
  591. // Create notification that new fields exist.
  592. $detail_info = ' Tripal has detected a new field ' . $details['field_name'] .' for ' . $bundle->label. ' content type is available for import.';
  593. $title = 'New field available for import';
  594. $actions['Import'] = 'admin/import/field/' . $details['field_name'] . '/' . $bundle->name . '/' . $module . '/instance';
  595. $type = 'Field';
  596. $submitter_id = $details['field_name'] . '-' . $bundle_name->name . '-' . $module;
  597. tripal_add_notification($title, $detail_info, $type, $actions, $submitter_id);
  598. $num_created++;
  599. }
  600. }
  601. }
  602. }
  603. /**
  604. * Retrieves information about a given content type.
  605. *
  606. * @param $bundle_name
  607. * The name of a bundle.
  608. *
  609. * @return
  610. * An object containing information about the bundle.
  611. *
  612. * @ingroup tripal_entities_api
  613. */
  614. function tripal_get_content_type($bundle_name) {
  615. return db_select('tripal_bundle', 'tb')
  616. ->fields('tb')
  617. ->condition('tb.name', $bundle_name)
  618. ->execute()
  619. ->fetchAll();
  620. }
  621. /**
  622. * Refreshes the bundle such that new fields added by modules will be found.
  623. *
  624. * @param $bundle_name
  625. * The name of the bundle to refresh (e.g. bio_data_4).
  626. * @param $term
  627. * The term object for the bundle.
  628. *
  629. * @return
  630. * The array of field instance names that were added.
  631. *
  632. * @ingroup tripal_entities_api
  633. */
  634. function tripal_create_bundle_fields($bundle, $term) {
  635. $added = array();
  636. // Allow modules to add fields to the new bundle.
  637. $modules = module_implements('bundle_fields_info');
  638. $field_info = array();
  639. foreach ($modules as $module) {
  640. $function = $module . '_bundle_fields_info';
  641. $temp = $function('TripalEntity', $bundle);
  642. if (is_array($temp)) {
  643. // TODO: it would be good to check this array to make sure it follows
  644. // protocol. It would help identify potential errors.
  645. $field_info = array_merge($field_info, $temp);
  646. }
  647. }
  648. // Allow modules to alter which fields should be attached to content
  649. // types they create.
  650. drupal_alter('bundle_fields_info', $field_info, $bundle, $term);
  651. // Iterate through all of the fields and create them.
  652. foreach ($field_info as $field_name => $details) {
  653. $field_type = $details['type'];
  654. // If the field already exists then skip it.
  655. $field = field_info_field($details['field_name']);
  656. if ($field) {
  657. continue;
  658. }
  659. // Create the field.
  660. $field = field_create_field($details);
  661. if (!$field) {
  662. tripal_set_message(t("Could not create new field: %field.",
  663. array('%field' => $details['field_name'])), TRIPAL_ERROR);
  664. }
  665. }
  666. // Allow modules to add instances to the new bundle.
  667. $modules = module_implements('bundle_instances_info');
  668. $instance_info = array();
  669. foreach ($modules as $module) {
  670. $function = $module . '_bundle_instances_info';
  671. $temp = $function('TripalEntity', $bundle);
  672. if (is_array($temp)) {
  673. // TODO: it would be good to check this array to make sure it follows
  674. // protocol. It would help identify potential errors.
  675. $instance_info = array_merge($instance_info, $temp);
  676. }
  677. }
  678. // Allow modules to alter which fields should be attached to content
  679. // types they create.
  680. drupal_alter('bundle_instances_info', $instance_info, $bundle, $term);
  681. // Get the list of existing instances
  682. $existing_instances = field_info_instances('TripalEntity', $bundle->name);
  683. // Iterate through all of the field instances and create them.
  684. foreach ($instance_info as $instance_name => $details) {
  685. // Make sure the instance has a term. If not, report it and skip the field.
  686. if (!array_key_exists('term_vocabulary', $details['settings'])) {
  687. tripal_report_error('tripal_fields', TRIPAL_WARNING,
  688. 'The field instance, !field, is missing the "term_vocabulary" setting. The field instance cannot be added. Please check the field settings.',
  689. ['!field' => $instance_name], ['drupal_set_message' => TRUE]);
  690. continue;
  691. }
  692. if (!array_key_exists('term_accession', $details['settings'])) {
  693. tripal_report_error('tripal_fields', TRIPAL_WARNING,
  694. 'The field instance, !field, is missing the "term_accession" setting. The field instance cannot be added. Please check the field settings.',
  695. ['!field' => $instance_name], ['drupal_set_message' => TRUE]);
  696. continue;}
  697. // Make sure the term exists. If not, skip the field instance and
  698. // report an error.
  699. $field_term_id = $details['settings']['term_vocabulary'] . ':' . $details['settings']['term_accession'];
  700. $field_term = tripal_get_term_details($details['settings']['term_vocabulary'], $details['settings']['term_accession']);
  701. if (!$field_term) {
  702. tripal_report_error('tripal_fields', TRIPAL_WARNING,
  703. 'The term, !term, for the field, !field, does not exist in the database. The ' .
  704. 'field instance cannot be added. Please make sure the term is correct and add it if necessary.',
  705. ['!term' => $field_term_id,
  706. '!field' => $instance_name],
  707. ['drupal_set_message' => TRUE]);
  708. continue;
  709. }
  710. // Make sure the term is not used for any other existing field instance.
  711. $skip = FALSE;
  712. foreach ($existing_instances as $existing_name => $existing_instance) {
  713. // If this instance term is the same as this exsiting term and the
  714. // instance name is not the same then we have a problem.
  715. $existing_term_id = $existing_instance['settings']['term_vocabulary'] . ':' . $existing_instance['settings']['term_accession'];
  716. $existing_field = field_info_field($existing_name);
  717. if ($existing_term_id == $field_term_id and $instance_name != $existing_name) {
  718. tripal_report_error('tripal_fields', TRIPAL_WARNING,
  719. 'The field, !field, uses a term, !term, that is already in use on this content type. The ' .
  720. 'field instance cannot be added.',
  721. ['!term' => $existing_term_id,
  722. '!field' => $instance_name],
  723. ['drupal_set_message' => TRUE]);
  724. $skip = TRUE;
  725. }
  726. // If the instance term is the same as this exsting term but the storage
  727. // types are different then we have a problem.
  728. $existing_storage = $existing_field['storage']['type'];
  729. $this_field_storage = $field_info[$details['field_name']]['storage']['type'];
  730. if ($existing_term_id == $field_term_id and $existing_storage != $this_field_storage) {
  731. tripal_report_error('tripal_fields', TRIPAL_WARNING,
  732. '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 ' .
  733. 'field instance cannot be added. Perhaps, consider a different term and adjust the data in the database.',
  734. ['!term' => $existing_term_id,
  735. '!type' => $this_field_storage,
  736. '!field' => $instance_name],
  737. ['drupal_set_message' => TRUE]);
  738. $skip = TRUE;
  739. }
  740. }
  741. if ($skip) {
  742. continue;
  743. }
  744. // If the field is already attached to this bundle then skip it.
  745. if (array_key_exists($instance_name, $existing_instances)) {
  746. continue;
  747. }
  748. // Create the field instance.
  749. $instance = field_create_instance($details);
  750. $existing_instances[$instance_name] = $instance;
  751. $added[] = $instance_name;
  752. }
  753. return $added;
  754. }
  755. /**
  756. * Updates an existing field and its attached instance to a bundle.
  757. *
  758. *
  759. * @param $field_name
  760. * The name of the field.
  761. * @param $field_info
  762. * An associative array containing the field information. The following
  763. * key/value pairs are supported:
  764. * - field_type: a valid field type. May be any of the Drupal default
  765. * fields, one created by the tripal_chado module or another custom module.
  766. * - widget_type: a valid widget type. May be any of the Drupal default
  767. * fields, one created by the tripal_chado module or another custom module.
  768. * - field_settings: an array of settings that are appropriate for the
  769. * selected field type.
  770. * - widget_settings: an array of settings that are appropriate for the
  771. * selected widget type.
  772. * - description: a default description for this field.
  773. * - label: a label used as a header for this field.
  774. * - is_required: indicates if the field is required in the edit form.
  775. * - cardinality: indicates the number of values this field can support.
  776. * the default is 1 (meaning only one value). Use a value of
  777. * FIELD_CARDINALITY_UNLIMITED for unlimited number of values.
  778. * - default_value: A default value for the field.
  779. * - format: A string indicating the format for the field. Must be
  780. * specific to the field.
  781. * @param $entity_type_name
  782. * The entity type name.
  783. * @param $bundle_name
  784. * The bundle name.
  785. *
  786. * @return
  787. * FALSE if the field could not be updated
  788. *
  789. * TODO: this function really shouldn't try to create an instance and
  790. * attach to a bundle at the same time.
  791. *
  792. * @ingroup tripal_entities_api
  793. */
  794. function tripal_update_bundle_field($field_name, $field_info, $entity_type_name, $bundle_name) {
  795. $field = field_info_field($field_name);
  796. // If the field doesn't exists or is not attached to this bundle then
  797. // just return, there is nothing left to do.
  798. if (!$field or !array_key_exists('bundles', $field) or
  799. !array_key_exists($entity_type_name, $field['bundles']) or
  800. !in_array($bundle_name, $field['bundles'][$entity_type_name])) {
  801. return FALSE;
  802. }
  803. $field['field_name'] = $field_name;
  804. if (array_key_exists('field_type', $field_info)) {
  805. $field['cardinality'] = $field_info['cardinality'];
  806. }
  807. if (array_key_exists('locked', $field_info)) {
  808. $field['locked'] = $field_info['locked'];
  809. }
  810. if (array_key_exists('storage', $field_info)) {
  811. $field['storage']['type'] = $field_info['storage'];
  812. }
  813. if (array_key_exists('field_settings', $field_info)) {
  814. $field['settings'] = $field_info['field_settings'];
  815. }
  816. field_update_field($field);
  817. $field_instance['field_name'] = $field_name;
  818. $field_instance['entity_type'] = $entity_type_name;
  819. $field_instance['bundle'] = $bundle_name;
  820. if (array_key_exists('label', $field_info)) {
  821. $field['label'] = $field_info['label'];
  822. }
  823. if (array_key_exists('description', $field_info)) {
  824. $field['description'] = $field_info['description'];
  825. }
  826. if (array_key_exists('widget', $field_info)) {
  827. if (array_key_exists('widget_type', $field_info['widget'])) {
  828. $field['widget']['type'] = $field_info['widget_type'];
  829. }
  830. if (array_key_exists('widget_settings', $field_info['widget'])) {
  831. $field['widget']['settings'] = $field_info['widget_settings'];
  832. }
  833. }
  834. if (array_key_exists('required', $field_info)) {
  835. $field['required'] = $field_info['is_required'];
  836. }
  837. if (array_key_exists('settings', $field_info)) {
  838. $field['settings'] = $field_info['field_settings'];
  839. }
  840. if (array_key_exists('default_value', $field_info)) {
  841. $field['default_value'] = $field_info['default_value'];
  842. }
  843. if (array_key_exists('format', $field_info)) {
  844. $field['format'] = $field_info['format'];
  845. }
  846. field_update_instance($field_instance);
  847. }
  848. /**
  849. * @section
  850. * Bundle Variables.
  851. */
  852. /**
  853. * Fetch the value for a given tripal variable.
  854. *
  855. * @param string $variable_name
  856. * The name of the variable as in tripal_variables.name.
  857. * @param int $bundle_id
  858. * The unique identfier for the bundle you want the value for.
  859. * @return text
  860. * The value of the specified variable for the specified bundle.
  861. *
  862. * @ingroup tripal_entities_api
  863. */
  864. function tripal_get_bundle_variable($variable_name, $bundle_id, $default = FALSE) {
  865. $variable = tripal_get_variable($variable_name);
  866. // Warn if we can't find the tripal_variable.
  867. if (!$variable) {
  868. return $default;
  869. }
  870. // Select the value for this variable.
  871. $value = db_select('tripal_bundle_variables', 'var')
  872. ->fields('var', array('value'))
  873. ->condition('var.bundle_id', $bundle_id)
  874. ->condition('var.variable_id', $variable->variable_id)
  875. ->execute()
  876. ->fetchField();
  877. // Warn if the value appears to be empty.
  878. if (!$value) {
  879. return $default;
  880. }
  881. return $value;
  882. }
  883. /**
  884. * Save the value of a tripal variable for a given bundle.
  885. *
  886. * @param string $variable_name
  887. * The name of the variable as in tripal_variables.name.
  888. * @param int $bundle_id
  889. * The unique identfier for the bundle you want the value for.
  890. * @param $text $value
  891. * The value of the variable for the given bundle.
  892. *
  893. * @ingroup tripal_entities_api
  894. */
  895. function tripal_set_bundle_variable($variable_name, $bundle_id, $value) {
  896. $variable = tripal_get_variable($variable_name);
  897. if (!$variable) {
  898. if($variable_name === 'hide_empty_field'){
  899. tripal_insert_variable(
  900. 'hide_empty_field',
  901. 'Structure->Tripal Content Type->edit checkbox to hide empty fields for that bundle.'
  902. );
  903. $variable = tripal_get_variable($variable_name);
  904. if (!$variable) {
  905. return FALSE;
  906. }
  907. }
  908. else {
  909. return FALSE;
  910. }
  911. }
  912. // And then we need to write the new format to the tripal_bundle_variables
  913. // table.
  914. $record = array(
  915. 'bundle_id' => $bundle_id,
  916. 'variable_id' => $variable->variable_id,
  917. 'value' => $value,
  918. );
  919. // Check whether there is already a format saved.
  920. $bundle_variable_id = db_select('tripal_bundle_variables', 'var')
  921. ->fields('var', array('bundle_variable_id'))
  922. ->condition('var.bundle_id', $record['bundle_id'])
  923. ->condition('var.variable_id', $record['variable_id'])
  924. ->execute()
  925. ->fetchField();
  926. if ($bundle_variable_id) {
  927. $record['bundle_variable_id'] = $bundle_variable_id;
  928. return drupal_write_record('tripal_bundle_variables', $record, 'bundle_variable_id');
  929. }
  930. else {
  931. return drupal_write_record('tripal_bundle_variables', $record);
  932. }
  933. }
  934. /**
  935. * @section
  936. * Title & URL Formats.
  937. */
  938. /**
  939. * Get Page Title Format for a given Tripal Entity Type.
  940. *
  941. * @param TripalBundle $bundle
  942. * The Entity object for the Tripal Bundle the title format is for.
  943. *
  944. * @ingroup tripal_entities_api
  945. */
  946. function tripal_get_title_format($bundle) {
  947. // Get the existing title format if it exists.
  948. $title_format = tripal_get_bundle_variable('title_format', $bundle->id);
  949. // If there isn't yet a title format for this bundle/type then we should
  950. // determine the default.
  951. if (!$title_format) {
  952. $title_format = tripal_get_default_title_format($bundle);
  953. tripal_save_title_format($bundle, $title_format);
  954. }
  955. return $title_format;
  956. }
  957. /**
  958. * Save Page Title Format for a given Tripal Entity Type.
  959. *
  960. * @param TripalBundle $entity
  961. * The Entity object for the Tripal Bundle the title format is for.
  962. * @param string $format
  963. * The pattern to be used when generating entity titles for the above type.
  964. *
  965. * @ingroup tripal_entities_api
  966. */
  967. function tripal_save_title_format($entity, $format) {
  968. return tripal_set_bundle_variable('title_format', $entity->id, $format);
  969. }
  970. /**
  971. * Determine the default title format to use for an entity.
  972. *
  973. * @param TripalBundle $bundle
  974. * The Entity object for the Tripal Bundle that the title format is for.
  975. *
  976. * @return string
  977. * A default title format.
  978. *
  979. * @ingroup tripal_entities_api
  980. */
  981. function tripal_get_default_title_format($bundle) {
  982. $format = '';
  983. // Retrieve all available tokens.
  984. $tokens = tripal_get_entity_tokens($bundle);
  985. // A) Check to see if more informed modules have suggested a title for this
  986. // type. Invoke hook_tripal_default_title_format() to get all suggestions
  987. // from other modules.
  988. $suggestions = module_invoke_all('tripal_default_title_format', $bundle, $tokens);
  989. if ($suggestions) {
  990. // Use the suggestion with the lightest weight.
  991. $lightest_key = NULL;
  992. foreach ($suggestions as $k => $s) {
  993. if ($lightest_key === NULL) $lightest_key = $k;
  994. if ($s['weight'] < $lightest_key) $lightest_key = $k;
  995. }
  996. $format = $suggestions[$lightest_key]['format'];
  997. return $format;
  998. }
  999. // B) Generate our own ugly title by simply comma-separating all the
  1000. // required fields.
  1001. if (!$format) {
  1002. $tmp = array();
  1003. // Check which tokens are required fields and join them into a default
  1004. // format.
  1005. foreach($tokens as $token) {
  1006. if ($token['required']) {
  1007. $tmp[] = $token['token'];
  1008. }
  1009. }
  1010. $format = implode(', ', $tmp);
  1011. return $format;
  1012. }
  1013. return $format;
  1014. }
  1015. /**
  1016. * Returns an array of tokens based on Tripal Entity Fields.
  1017. *
  1018. * @param TripalBundle $bundle
  1019. * The bundle entity for which you want tokens.
  1020. * @return
  1021. * An array of tokens where the key is the machine_name of the token.
  1022. *
  1023. * @ingroup tripal_entities_api
  1024. */
  1025. function tripal_get_entity_tokens($bundle, $options = array()) {
  1026. $tokens = array();
  1027. // Set default options.
  1028. $options['required only'] = (isset($options['required only'])) ? $options['required only'] : FALSE;
  1029. $options['include id'] = (isset($options['include id'])) ? $options['include id'] : TRUE;
  1030. if ($options['include id']) {
  1031. $token = '[TripalBundle__bundle_id]';
  1032. $tokens[$token] = [
  1033. 'label' => 'Bundle ID',
  1034. 'description' => 'The unique identifier for this Tripal Content Type.',
  1035. 'token' => $token,
  1036. 'field_name' => NULL,
  1037. 'required' => TRUE
  1038. ];
  1039. $token = '[TripalEntity__entity_id]';
  1040. $tokens[$token] = [
  1041. 'label' => 'Content/Entity ID',
  1042. 'description' => 'The unique identifier for an individual piece of Tripal Content.',
  1043. 'token' => $token,
  1044. 'field_name' => NULL,
  1045. 'required' => TRUE
  1046. ];
  1047. }
  1048. $instances = field_info_instances('TripalEntity', $bundle->name);
  1049. foreach ($instances as $instance_name => $instance) {
  1050. if (!$instance['required'] and $options['required only']) {
  1051. continue;
  1052. }
  1053. $use_field = FALSE;
  1054. // Iterate through the TripalEntity fields and see if they have
  1055. // sub-elements, if so, add those as tokens too.
  1056. $field_name = $instance['field_name'];
  1057. if ($instance['entity_type'] == 'TripalEntity') {
  1058. if (tripal_load_include_field_class($field_name)) {
  1059. $field = field_info_field($field_name);
  1060. $field_obj = new $field_name($field, $instance);
  1061. $element_info = $field_obj->elementInfo();
  1062. $term_id = $instance['settings']['term_vocabulary'] . ':' . $instance['settings']['term_accession'];
  1063. if ($element_info and
  1064. array_key_exists($term_id, $element_info) and
  1065. array_key_exists('elements', $element_info[$term_id]) and count($element_info[$term_id]['elements']) > 0) {
  1066. $elements = $element_info[$term_id]['elements'];
  1067. _tripal_get_entity_tokens_for_elements($instance, $field_name, $elements, $tokens, $options);
  1068. }
  1069. else {
  1070. $use_field = TRUE;
  1071. }
  1072. }
  1073. else {
  1074. $use_field = TRUE;
  1075. }
  1076. }
  1077. else {
  1078. $use_field = TRUE;
  1079. }
  1080. // If we have no elements to add then just add the field as is.
  1081. if ($use_field) {
  1082. // Build the token from the field information.
  1083. $token = '[' . $instance['field_name'] . ']';
  1084. $tokens[$token] = [
  1085. 'label' => $instance['label'],
  1086. 'description' => $instance['description'],
  1087. 'token' => $token,
  1088. 'field_name' => $instance['field_name'],
  1089. 'required' => $instance['required']
  1090. ];
  1091. }
  1092. }
  1093. return $tokens;
  1094. }
  1095. /**
  1096. * A recursive helper function to get tokens for element sub fields.
  1097. *
  1098. * @param $instance
  1099. * A original field instance object.
  1100. * @param $parent
  1101. * The name of the parent. The first time this is called outside of
  1102. * recursion this should be the field name.
  1103. * @param $elements
  1104. * The array of elements to process.
  1105. * @param $tokens
  1106. * The array of tokens to be added to.
  1107. */
  1108. function _tripal_get_entity_tokens_for_elements($instance, $parent, $elements, &$tokens, $options) {
  1109. // Iterate through all of the elements and add tokens for each one.
  1110. foreach ($elements as $child_term_id => $details) {
  1111. // We don't need to add the entity element.
  1112. if ($child_term_id == 'entity') {
  1113. continue;
  1114. }
  1115. // Skip elements that aren't required.
  1116. $required = array_key_exists('required', $details) ? $details['required'] : FALSE;
  1117. if (!$required and $options['required only']) {
  1118. continue;
  1119. }
  1120. $token = '[' . $parent . ',' . $child_term_id . ']';
  1121. $label = $child_term_id;
  1122. if (array_key_exists('name', $details)) {
  1123. $label = $details['name'];
  1124. }
  1125. elseif (preg_match('/:/', $child_term_id)) {
  1126. list($vocabulary, $accession) = explode(':', $child_term_id);
  1127. $term = tripal_get_term_details($vocabulary, $accession);
  1128. $label = $term['name'];
  1129. }
  1130. // Add the token!
  1131. $tokens[$token] = [
  1132. 'label' => $label,
  1133. 'description' => array_key_exists('description', $details) ? $details['description'] : '',
  1134. 'token' => $token,
  1135. 'field_name' => $instance['field_name'],
  1136. 'required' => $required
  1137. ];
  1138. // Recurse to include sub elements
  1139. if (array_key_exists('elements', $details)) {
  1140. _tripal_get_entity_tokens_for_elements($instance, $parent . ',' . $child_term_id,
  1141. $details['elements'], $tokens, $options);
  1142. }
  1143. }
  1144. }
  1145. /**
  1146. * Replace all Tripal Tokens in a given string.
  1147. *
  1148. * NOTE: If there is no value for a token then the token is removed.
  1149. *
  1150. * @param string $string
  1151. * The string containing tokens.
  1152. * @param TripalEntity $entity
  1153. * The entity with field values used to find values of tokens.
  1154. * @param TripalBundle $bundle_entity
  1155. * The bundle enitity containing special values sometimes needed for token
  1156. * replacement.
  1157. *
  1158. * @return
  1159. * The string will all tokens replaced with values.
  1160. *
  1161. * @ingroup tripal_entities_api
  1162. */
  1163. function tripal_replace_entity_tokens($string, &$entity, $bundle_entity = NULL) {
  1164. // Determine which tokens were used in the format string
  1165. $used_tokens = [];
  1166. if (preg_match_all('/\[.*?\]/', $string, $matches)) {
  1167. $used_tokens = $matches[0];
  1168. }
  1169. // If there are no tokens then just return the string.
  1170. if (count($used_tokens) == 0) {
  1171. return $string;
  1172. }
  1173. // If the fields are not loaded for the entity then we want to load them
  1174. // but we won't do a field_attach_load() as that will load all of the
  1175. // fields. For syncing (publishing) of content loading all fields for
  1176. // all synced entities causes extreme slowness, so we'll only attach
  1177. // the necessary fields for replacing tokens.
  1178. $attach_fields = array();
  1179. foreach($used_tokens as $token) {
  1180. $token = preg_replace('/[\[\]]/', '', $token);
  1181. $elements = explode(',', $token);
  1182. $field_name = array_shift($elements);
  1183. //$field_name = str_replace(array('.','[',']'), array('__','',''), $field_name);
  1184. if (!property_exists($entity, $field_name) or empty($entity->{$field_name})) {
  1185. $field = field_info_field($field_name);
  1186. $storage = $field['storage'];
  1187. $attach_fields[$storage['type']]['storage'] = $storage;
  1188. $attach_fields[$storage['type']]['fields'][] = $field;
  1189. }
  1190. }
  1191. // If we have any fields that need attaching, then do so now.
  1192. if (count(array_keys($attach_fields)) > 0) {
  1193. foreach ($attach_fields as $storage_type => $details) {
  1194. $storage = $details['storage'];
  1195. $fields = $details['fields'];
  1196. $field_ids = array();
  1197. foreach ($fields as $field) {
  1198. $field_ids[$field['id']] = array($entity->id);
  1199. }
  1200. $entities = array($entity->id => $entity);
  1201. }
  1202. module_invoke($storage['module'], 'field_storage_load', 'TripalEntity',
  1203. $entities, FIELD_LOAD_CURRENT, $field_ids, array());
  1204. }
  1205. // Now that all necessary fields are attached process the tokens.
  1206. foreach($used_tokens as $token) {
  1207. $token = preg_replace('/[\[\]]/', '', $token);
  1208. $elements = explode(',', $token);
  1209. $field_name = array_shift($elements);
  1210. $value = '';
  1211. if (property_exists($entity, $field_name)) {
  1212. $value = '';
  1213. // Note: there is a memory leak in field_get_items() so we can't use it
  1214. // here or bulk publishing will slowly erode memory.
  1215. // $field_value = field_get_items('TripalEntity', $entity, $field_name);
  1216. if (array_key_exists('und', $entity->{$field_name}) and
  1217. array_key_exists(0, $entity->{$field_name}['und'])) {
  1218. $value = $entity->{$field_name}['und'][0]['value'];
  1219. // If the value is an array it means we have sub elements and we can
  1220. // descend through the array to look for matching value.
  1221. if (is_array($value) and count($elements) > 0) {
  1222. $value = _tripal_replace_entity_tokens_for_elements($elements, $value);
  1223. }
  1224. }
  1225. }
  1226. // The TripalBundle__bundle_id is a special token for substituting the
  1227. // bundle id.
  1228. elseif ($field_name === 'TripalBundle__bundle_id') {
  1229. // Load the bundle entity if we weren't given it.
  1230. if (!$bundle_entity) {
  1231. $bundle_entity = tripal_load_bundle_entity(array('name' => $entity->bundle));
  1232. }
  1233. // This token should be the id of the TripalBundle.
  1234. $value = $bundle_entity->id;
  1235. }
  1236. // The TripalBundle__bundle_id is a special token for substituting the
  1237. // entty id.
  1238. elseif ($field_name === 'TripalEntity__entity_id') {
  1239. // This token should be the id of the TripalEntity.
  1240. $value = $entity->id;
  1241. }
  1242. // We can't support tokens that have multiple elements (i.e. in an array).
  1243. if (is_array($value)) {
  1244. $string = str_replace('[' . $token . ']', '', $string);
  1245. }
  1246. else {
  1247. $string = str_replace('[' . $token . ']', $value, $string);
  1248. }
  1249. }
  1250. return $string;
  1251. }
  1252. /**
  1253. * A helper function for tripal_replace_entity_tokens to get token values.
  1254. *
  1255. * This helper function is used when the tokens are from subelements.
  1256. * @param $entity
  1257. */
  1258. function _tripal_replace_entity_tokens_for_elements($elements, $values) {
  1259. $term_id = array_shift($elements);
  1260. $value = $values[$term_id];
  1261. if (count($elements) == 0) {
  1262. return $value;
  1263. }
  1264. else {
  1265. _tripal_replace_entity_tokens_for_elements($elements, $value);
  1266. }
  1267. }
  1268. /**
  1269. * Formats the tokens for display.
  1270. *
  1271. * @param array $tokens
  1272. * A list of tokens generated via tripal_get_entity_tokens().
  1273. * @return
  1274. * Rendered output describing the available tokens.
  1275. *
  1276. * @ingroup tripal_entities_api
  1277. */
  1278. function theme_token_list($tokens) {
  1279. $header = array('Token', 'Name', 'Description');
  1280. $rows = array();
  1281. foreach ($tokens as $details) {
  1282. $rows[] = array(
  1283. $details['token'],
  1284. $details['label'],
  1285. $details['description'],
  1286. );
  1287. }
  1288. return theme('table', array('header' => $header, 'rows' => $rows));
  1289. }
  1290. /**
  1291. * Define the entity label callback. This will return the title.
  1292. *
  1293. * @param $entity
  1294. *
  1295. * @return mixed
  1296. *
  1297. * @ingroup tripal_entities_api
  1298. */
  1299. function tripal_entity_label($entity) {
  1300. if (property_exists($entity, 'title')) {
  1301. return $entity->title;
  1302. }
  1303. return NULL;
  1304. }
  1305. /**
  1306. * Retrieves details, including attached fields, for a given bundle.
  1307. *
  1308. * @param $bundle_name
  1309. * The name of the bundle (e.g. bio_data_xx)
  1310. *
  1311. * @return
  1312. * An array containing the name, label, controlled vocabulary details
  1313. * and a list of fields attached to the bundle. Returns FALSE
  1314. * if the bundle does not exist.
  1315. *
  1316. * @ingroup tripal_entities_api
  1317. */
  1318. function tripal_get_bundle_details($bundle_name) {
  1319. global $user;
  1320. $bundle = tripal_load_bundle_entity(array('name' => $bundle_name));
  1321. if (!$bundle) {
  1322. return FALSE;
  1323. }
  1324. $term = tripal_load_term_entity(array('term_id' => $bundle->term_id));
  1325. $vocab = $term->vocab;
  1326. $instances = field_info_instances('TripalEntity', $bundle->name);
  1327. $details = array(
  1328. 'name' => $bundle->name,
  1329. 'label' => $bundle->label,
  1330. 'term' => array(
  1331. 'accession' => $vocab->vocabulary . ':' . $term->accession,
  1332. 'name' => $term->name,
  1333. 'definition' => $term->definition,
  1334. 'url' => $term->url
  1335. ),
  1336. 'fields' => array(),
  1337. );
  1338. // Iterate through each feild and provide a discription of it and
  1339. // it's sub elements.
  1340. foreach ($instances as $instance) {
  1341. // Skip deleted fields.
  1342. if ($instance['deleted']) {
  1343. continue;
  1344. }
  1345. $field_name = $instance['field_name'];
  1346. $field = field_info_field($field_name);
  1347. $field_class = $field['type'];
  1348. $term_vocab = $instance['settings']['term_vocabulary'];
  1349. $term_accession = $instance['settings']['term_accession'];
  1350. $field_term = tripal_get_term_details($term_vocab, $term_accession);
  1351. $field_details = array(
  1352. 'name' => $field_name,
  1353. 'label' => $instance['label'],
  1354. 'term' => array(
  1355. 'accession' => $term_vocab . ":" . $term_accession,
  1356. 'name' => $field_term['name'],
  1357. 'definition' => $field_term['definition'],
  1358. 'url' => $field_term['url'],
  1359. ),
  1360. // These items can be overridden by the element_info array that
  1361. // is present in a TripalField instance. Here we set defaults.
  1362. 'required' => $instance['required'] ? TRUE : FALSE,
  1363. 'type' => 'xs:string',
  1364. 'readonly' => TRUE,
  1365. // The cardinatlity value always comes from the field.
  1366. 'cardinality' => $field['cardinality'],
  1367. );
  1368. if (tripal_load_include_field_class($field_class)) {
  1369. $field_obj = new $field_class($field, $instance);
  1370. $element_info = $field_obj->elementInfo();
  1371. $element_info = $element_info[$term_vocab . ':' . $term_accession];
  1372. // If the element info for this field sets required, type and readonly
  1373. // attributes then set those.
  1374. $field_details['required'] = array_key_exists('required', $element_info) ? $element_info['required'] : FALSE;
  1375. $field_details['type'] = array_key_exists('type', $element_info) ? $element_info['type'] : 'xs:string';
  1376. $field_details['readonly'] = array_key_exists('readonly', $element_info) ? $element_info['readonly'] : TRUE;
  1377. $field_details['label'] = array_key_exists('label', $element_info) ? $element_info['label'] : $field_details['label'];
  1378. $field_details['help'] = array_key_exists('help', $element_info) ? $element_info['help'] : '';
  1379. // If this field is an 'xs:complexType' then it will have sub elements.
  1380. // we need to add those as well.
  1381. if (array_key_exists('elements', $element_info) and is_array($element_info['elements'])) {
  1382. _tripal_get_bundle_field_element_details($element_info['elements'], $field_details);
  1383. }
  1384. $details['fields'][] = $field_details;
  1385. }
  1386. }
  1387. return $details;
  1388. }
  1389. /**
  1390. * A recursive helper function for the tripal_get_bundle_details.
  1391. *
  1392. * @param $elementInfo
  1393. *
  1394. * @ingroup tripal_entities_api
  1395. */
  1396. function _tripal_get_bundle_field_element_details($elements, &$field_details) {
  1397. $field_details['elements'] = array();
  1398. foreach ($elements as $element_key => $element_info) {
  1399. // Handle the entity element differnetly.
  1400. if ($element_key == 'entity') {
  1401. continue;
  1402. }
  1403. list($term_vocab, $term_accession) = explode(':', $element_key);
  1404. $term = tripal_get_term_details($term_vocab, $term_accession);
  1405. $element_details = array(
  1406. 'name' => $element_info['name'],
  1407. 'label' => array_key_exists('label', $element_info) ? $element_info['label'] : ucfirst(preg_replace('/_/', ' ', $term['name'])),
  1408. 'help' => array_key_exists('help', $element_info) ? $element_info['help'] : '',
  1409. 'term' => array(
  1410. 'accession' => $term_vocab . ':' . $term_accession,
  1411. 'name' => $term['name'],
  1412. 'definition' => $term['definition'],
  1413. 'url' => $term['url'],
  1414. ),
  1415. 'required' => array_key_exists('required', $element_info) ? $element_info['required'] : FALSE,
  1416. 'type' => array_key_exists('type', $element_info) ? $element_info['type'] : 'xs:string',
  1417. 'readonly' => array_key_exists('readonly', $element_info) ? $element_info['readonly'] : TRUE,
  1418. );
  1419. if (array_key_exists('elements', $element_info) and is_array($element_info['elements'])) {
  1420. _tripal_get_bundle_field_element_details($element_info['elements'], $element_details);
  1421. }
  1422. $field_details['elements'][] = $element_details;
  1423. }
  1424. }
  1425. /**
  1426. * Is this completed? It doesn't look right and I can't find it used anywhere
  1427. * in the existing code.
  1428. *
  1429. * @param $bundle_name
  1430. * The name of the bundle (e.g. bio_data_xx)
  1431. * @param unknown $values
  1432. *
  1433. * @throws Exception
  1434. *
  1435. *
  1436. */
  1437. function tripal_insert_entity($bundle_name, $values){
  1438. global $user;
  1439. $bundle = tripal_load_bundle_entity(array('name' => $bundle_name));
  1440. // Get the fields associated with this content type.
  1441. $instances = field_info_instances('TripalEntity', $bundle->name);
  1442. foreach ($instances as $instance) {
  1443. $field_name = $instance['field_name'];
  1444. $field = field_info_field($field_name);
  1445. $field_type = $field['type'];
  1446. $field_settings = $field['settings'];
  1447. $instance_settings = $instance['settings'];
  1448. $field_name = $field['field_name'];
  1449. $vocabulary = $instance['settings']['term_vocabulary'];
  1450. $accession = $instance['settings']['term_accession'];
  1451. $field_accession = $vocabulary . ':' . $accession;
  1452. $field_term = tripal_get_term_details($vocabulary, $accession);
  1453. $field_key = $field_term['name'];
  1454. $field_key = strtolower(preg_replace('/ /', '_', $key));
  1455. // There are three ways that a field value can be specified. Those
  1456. // are as the controlled vocabulary accession (e.g. GO:0000134), sa
  1457. // the field name or as the field key which is the term name with
  1458. // spaces replaced with underscores.
  1459. // First make sure that required fields are present.
  1460. if ($instance['required'] == TRUE) {
  1461. if (!array_key_exists($field_key, $values) and
  1462. !array_key_exists($field_accession, $values) and
  1463. !array_key_exists($field_name, $values)) {
  1464. throw new Exception(t('Cannot insert the record. Missing the required field "%missing".',
  1465. array('%missing' => $field_name)));
  1466. }
  1467. }
  1468. }
  1469. // Make sure that all required fields are present.
  1470. // TODO: make sure the user has permission to do this.
  1471. $ec = entity_get_controller('TripalEntity');
  1472. $entity = $ec->create(array(
  1473. 'bundle' => $bundle_name,
  1474. 'term_id' => $bundle->term_id,
  1475. ));
  1476. $entity = $entity->save();
  1477. }
  1478. /**
  1479. * Are we keeping this?
  1480. *
  1481. * @param $bundle_name
  1482. * @param $values
  1483. *
  1484. *
  1485. */
  1486. function tripal_update_entity($bundle_name, $values) {
  1487. }