tripal.entities.api.inc 56 KB

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