tripal_chado.field_storage.inc 63 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808
  1. <?php
  2. /**
  3. * Implements hook_field_storage_info().
  4. */
  5. function tripal_chado_field_storage_info() {
  6. return array(
  7. 'field_chado_storage' => array(
  8. 'label' => t('Chado'),
  9. 'description' => t('Stores fields in the local Chado database.'),
  10. 'settings' => array(
  11. 'tripal_storage_api' => TRUE,
  12. ),
  13. // The logo_url key is supported by Tripal. It's not a Drupal key. It's
  14. // used for adding a logo or picture for the data store to help make it
  15. // more easily recognized on the field_ui_field_overview_form. Ideally
  16. // the URL should point to a relative path on the local Drupal site.
  17. 'logo_url' => url(drupal_get_path('module', 'tripal') . '/theme/images/250px-ChadoLogo.png'),
  18. ),
  19. );
  20. }
  21. /**
  22. * Implements hook_field_storage_write().
  23. */
  24. function tripal_chado_field_storage_write($entity_type, $entity, $op, $fields) {
  25. // Get the bundle and the term for this entity.
  26. $bundle = tripal_load_bundle_entity(array('name' => $entity->bundle));
  27. $term = entity_load('TripalTerm', array('id' => $entity->term_id));
  28. $term = reset($term);
  29. // Convert the Tripal term entity into the appropriate record in Chado.
  30. $dbxref = chado_get_dbxref(array('accession' => $term->accession, 'db_id' => array('name' => $term->vocab->vocabulary)));
  31. $cvterm = chado_get_cvterm(array('dbxref_id' => $dbxref->dbxref_id));
  32. // Get the base table, type field and record_id from the entity.
  33. $base_table = $entity->chado_table;
  34. $type_field = $entity->chado_column;
  35. $record = $entity->chado_record;
  36. $record_id = $entity->chado_record_id;
  37. $linker = property_exists($entity, 'chado_linker') ? $entity->chado_linker : '';
  38. $type_id = property_exists($entity, 'chado_type_id') ? $entity->chado_type_id : '';
  39. $type_value = property_exists($entity, 'chado_type_value') ? $entity->chado_type_value : '';
  40. $base_type_id = property_exists($entity, 'chado_base_type_id') ? $entity->chado_base_type_id : '';
  41. $base_schema = chado_get_schema($base_table);
  42. $base_pkey = $base_schema['primary key'][0];
  43. // Convert the fields into a key/value list of fields and their values.
  44. list($field_vals, $field_items) = tripal_chado_field_storage_write_merge_fields($fields, $entity_type, $entity);
  45. // Start out with the base table fields.
  46. $values = $field_vals[$base_table];
  47. // First, set the pkey for the record if this is an update.
  48. if ($record_id) {
  49. $values[$base_pkey] = $record_id;
  50. }
  51. // For content types that use a type_id in the base table then we need
  52. // to add in the type_id value.
  53. elseif ($type_field and !$linker) {
  54. $values[$type_field] = $cvterm->cvterm_id;
  55. }
  56. // If we have a linker table and there is a base_type_id then the base
  57. // table requires a type_id and we need to add it in.
  58. elseif ($linker and $base_type_id) {
  59. // If a base table has a 'type_id' field then we must have the user
  60. // specify the base table type as well.
  61. $base_type_column = FALSE;
  62. $schema = chado_get_schema($base_table);
  63. foreach ($schema['foreign keys'] as $fk_id => $details) {
  64. if ($details['table'] == 'cvterm') {
  65. foreach ($details['columns'] as $fk_left => $fk_right) {
  66. if ($fk_left == 'type_id') {
  67. $base_type_column = 'type_id';
  68. }
  69. }
  70. }
  71. }
  72. if ($base_type_column) {
  73. $values[$base_type_column] = $base_type_id;
  74. }
  75. }
  76. // Insert the record into the base table and get the record ID.
  77. $base_record_id = tripal_chado_field_storage_write_table($base_table, $values, $base_table);
  78. if (!$base_record_id) {
  79. throw new Exception('Unable to write fields to Chado: ' . print_r($field_items, TRUE));
  80. }
  81. // For content types that use a linker table we need to add a record into
  82. // the linker table.
  83. if ($type_field and $linker) {
  84. // If this is for a property table then there will be a value.
  85. if ($type_value) {
  86. $field_vals[$linker][] = [
  87. $base_pkey => $base_record_id,
  88. 'type_id' => $type_id,
  89. 'value' => $type_value,
  90. ];
  91. }
  92. // If there is no value then this is a cvterm table
  93. else {
  94. $args = array(':uniquename' => 'null');
  95. $sql = "
  96. SELECT *
  97. FROM {pub}
  98. WHERE uniquename = :uniquename
  99. ";
  100. $pub = chado_query($sql, $args)->fetchObject();
  101. if (!$pub) {
  102. throw new Exception('Unable to save record because the NULL publication is missing from the pub table. Please add a null record where the uniquename value is "null".');
  103. }
  104. $field_vals[$linker][] = [
  105. $base_pkey => $base_record_id,
  106. 'cvterm_id' => $cvterm->cvterm_id,
  107. 'pub_id' => $pub->pub_id,
  108. ];
  109. }
  110. }
  111. // If this is an insert then add the chado_entity record.
  112. if ($op == FIELD_STORAGE_INSERT) {
  113. // Add the record to the proper chado entity table
  114. $chado_entity_table = chado_get_bundle_entity_table($bundle);
  115. $record_id = db_insert($chado_entity_table)
  116. ->fields(array(
  117. 'entity_id' => $entity->id,
  118. 'record_id' => $base_record_id
  119. ))
  120. ->execute();
  121. if (!$record_id) {
  122. throw new Exception('Unable to insert new Chado entity.');
  123. }
  124. }
  125. // Now that we have handled the base table, we need to handle linking tables.
  126. foreach ($field_vals as $table_name => $details) {
  127. // Skip the base table as we've already dealt with it.
  128. if ($table_name == $base_table) {
  129. continue;
  130. }
  131. foreach ($details as $delta => $values) {
  132. $record_id = tripal_chado_field_storage_write_table($table_name, $values, $base_table, $base_pkey, $base_record_id);
  133. }
  134. }
  135. }
  136. /**
  137. * Write (inserts/updates/deletes) values for a Chado table.
  138. *
  139. * The $values array is of the same format used by chado_insert_record() and
  140. * chado_update_record(). However, both of those methods will use any nested
  141. * arrays (i.e. representing foreign keys) to select an appropriate record ID
  142. * that can be substituted as the value. Here, the nested arrays are
  143. * either inserted or updated as well, but the choice is determined if the
  144. * primary key value is present. If present an update occurs, if not present
  145. * then an insert occurs.
  146. *
  147. * This function is recursive and nested arrays from the lowest point of the
  148. * "tree" are dealt with first.
  149. *
  150. * @param $table_name
  151. * The name of the table on which the insertion/update is performed.
  152. * @param $values
  153. * The values array for the insertion.
  154. *
  155. * @throws Exception
  156. *
  157. * @return
  158. * The unique record ID.
  159. */
  160. function tripal_chado_field_storage_write_table($table_name, $values, $base_table, $base_pkey = NULL, $base_record_id = NULL) {
  161. $schema = chado_get_schema($table_name);
  162. $fkeys = $schema['foreign keys'];
  163. $pkey = $schema['primary key'][0];
  164. // Fields with a cardinality greater than 1 will often submit an
  165. // empty form. We want to remove these empty submissions. We can detect
  166. // them if all of the fields are empty.
  167. $num_empty = 0;
  168. foreach ($values as $column => $value) {
  169. if (!$value) {
  170. $num_empty++;
  171. }
  172. }
  173. if ($num_empty == count(array_keys($values))) {
  174. return '';
  175. }
  176. // If the primary key column has a value but all other values are empty then
  177. // this is a delete.
  178. if (array_key_exists($pkey, $values) and $values[$pkey]) {
  179. $num_vals = 0;
  180. foreach ($values as $value) {
  181. if ($value) {
  182. $num_vals++;
  183. }
  184. }
  185. if ($num_vals == 1) {
  186. $new_vals[$pkey] = $values[$pkey];
  187. if (!chado_delete_record($table_name, $new_vals)) {
  188. throw new Exception('Could not delete record from table: "' . $table_name . '".');
  189. }
  190. return '';
  191. }
  192. }
  193. // If the primary key column does not have a value then this is an insert.
  194. if (!array_key_exists($pkey, $values) or !$values[$pkey] or !isset($values[$pkey])) {
  195. // Before inserting, we want to make sure the record does not
  196. // already exist. Using the unique constraint check for a matching record.
  197. $options = array('is_duplicate' => TRUE);
  198. $is_duplicate = chado_select_record($table_name, array('*'), $values, $options);
  199. if($is_duplicate) {
  200. $record = chado_select_record($table_name, array('*'), $values);
  201. return $record[0]->$pkey;
  202. }
  203. // If this table_name is a linker table then we want to be sure to add in
  204. // the value for the $base_record_id it it isn't set. This would only
  205. // occur on an insert.
  206. if (array_key_exists($base_table, $fkeys) and $base_table != $table_name) {
  207. foreach ($fkeys[$base_table]['columns'] as $lkey => $rkey) {
  208. if ($rkey == $base_pkey and !array_key_exists($lkey, $values) or empty($values[$lkey])) {
  209. $values[$lkey] = $base_record_id;
  210. }
  211. }
  212. }
  213. // Insert the values array as a new record in the table but remove the
  214. // pkey as it should be set.
  215. $new_vals = $values;
  216. unset($new_vals[$pkey]);
  217. $record = chado_insert_record($table_name, $new_vals);
  218. if ($record === FALSE) {
  219. throw new Exception('Could not insert Chado record into table: "' . $table_name . '": ' . print_r($new_vals, TRUE));
  220. }
  221. return $record[$pkey];
  222. }
  223. // If we've made it to this point then this is an update.
  224. // TODO: what if the unique constraint matches another record? That is
  225. // not being tested for here.
  226. $match[$pkey] = $values[$pkey];
  227. if (!chado_update_record($table_name, $match, $values)) {
  228. drupal_set_message("Could not update Chado record in table: $table_name.", 'error');
  229. }
  230. return $values[$pkey];
  231. }
  232. /**
  233. * Implements hook_field_storage_pre_load().
  234. *
  235. * Adds a 'chado_record' object containing the base record for the
  236. * entity.
  237. */
  238. function tripal_chado_field_storage_pre_load($entity_type, $entities, $age,
  239. $fields, $options) {
  240. // Itereate through the entities and add in the Chado record.
  241. foreach ($entities as $id => $entity) {
  242. // Only deal with Tripal Entities.
  243. if ($entity_type != 'TripalEntity') {
  244. continue;
  245. }
  246. $record_id = NULL;
  247. if (property_exists($entity, 'chado_table')) {
  248. // Get the base table and record id for the fields of this entity.
  249. $base_table = $entity->chado_table;
  250. $type_field = $entity->chado_column;
  251. $record_id = $entity->chado_record_id;
  252. }
  253. else {
  254. $bundle = tripal_load_bundle_entity(array('name' => $entity->bundle));
  255. $base_table = $bundle->data_table;
  256. $type_field = $bundle->type_column;
  257. // Get the record id for the fields of this entity.
  258. $chado_entity_table = chado_get_bundle_entity_table($bundle);
  259. $details = db_select($chado_entity_table, 'ce')
  260. ->fields('ce')
  261. ->condition('entity_id', $entity->id)
  262. ->execute()
  263. ->fetchObject();
  264. if ($details) {
  265. $record_id = isset($details->record_id) ? $details->record_id : '';
  266. }
  267. $entity->chado_table = $base_table;
  268. $entity->chado_record_id = $record_id;
  269. $entity->chado_column = $type_field;
  270. }
  271. if ($record_id) {
  272. // Get this table's schema.
  273. $schema = chado_get_schema($base_table);
  274. $pkey_field = $schema['primary key'][0];
  275. // Get the base record if one exists
  276. $columns = array('*');
  277. $match = array($pkey_field => $record_id);
  278. $record = chado_generate_var($base_table, $match);
  279. $entity->chado_record = $record;
  280. }
  281. }
  282. }
  283. /**
  284. * Implements hook_field_storage_load().
  285. *
  286. * Responsible for loading the fields from the Chado database and adding
  287. * their values to the entity.
  288. */
  289. function tripal_chado_field_storage_load($entity_type, $entities, $age,
  290. $fields, $options) {
  291. $load_current = $age == FIELD_LOAD_CURRENT;
  292. global $language;
  293. $langcode = $language->language;
  294. foreach ($entities as $id => $entity) {
  295. $base_table = $entity->chado_table;
  296. $type_field = $entity->chado_column;
  297. $record_id = $entity->chado_record_id;
  298. $record = $entity->chado_record;
  299. $schema = chado_get_schema($base_table);
  300. // Iterate through the entity's fields so we can get the column names
  301. // that need to be selected from each of the tables represented.
  302. $tables = array();
  303. foreach ($fields as $field_id => $ids) {
  304. // By the time this hook runs, the relevant field definitions have been
  305. // populated and cached in FieldInfo, so calling field_info_field_by_id()
  306. // on each field individually is more efficient than loading all fields in
  307. // memory upfront with field_info_field_by_ids().
  308. $field = field_info_field_by_id($field_id);
  309. $field_name = $field['field_name'];
  310. $field_type = $field['type'];
  311. $field_module = $field['module'];
  312. // Get the instance for this field. If no instance exists then skip
  313. // loading of this field. This can happen when a field is deleted from
  314. // a bundle using the user UI form.
  315. // TODO: how to deal with deleted fields?
  316. $instance = field_info_instance($entity_type, $field_name, $entity->bundle);
  317. if (!$instance) {
  318. continue;
  319. }
  320. // Skip fields that don't map to a Chado table.
  321. if (!array_key_exists('settings', $instance) or
  322. !array_key_exists('chado_table', $instance['settings'])) {
  323. continue;
  324. }
  325. // Get the Chado table and column for this field.
  326. $field_table = $instance['settings']['chado_table'];
  327. $field_column = $instance['settings']['chado_column'];
  328. // There are only two types of fields: 1) fields that represent a single
  329. // column of the base table, or 2) fields that represent a linked record
  330. // in a many-to-one relationship with the base table.
  331. // Type 1: fields from base tables.
  332. if ($field_table == $base_table) {
  333. // Set an empty value by default, and if there is a record, then update.
  334. $entity->{$field_name}['und'][0]['value'] = '';
  335. if ($record and property_exists($record, $field_column)) {
  336. // If the field column is an object then it's a FK to another table.
  337. // and because $record object is created by the chado_generate_var()
  338. // function we must go one more level deeper to get the value
  339. if (is_object($record->$field_column)) {
  340. $fkey_column = $field_column;
  341. foreach($schema['foreign keys'] as $table => $fk_details) {
  342. foreach($fk_details['columns'] as $lfkey => $rfkey) {
  343. if ($lfkey == $field_column) {
  344. $fkey_column = $rfkey;
  345. }
  346. }
  347. }
  348. $entity->{$field_name}['und'][0]['chado-' . $field_table . '__' . $field_column] = $record->$field_column->$fkey_column;
  349. }
  350. else {
  351. // For non FK fields we'll make the field value be the same
  352. // as the column value.
  353. $entity->{$field_name}['und'][0]['value'] = $record->$field_column;
  354. $entity->{$field_name}['und'][0]['chado-' . $field_table . '__' . $field_column] = $record->$field_column;
  355. }
  356. }
  357. // Allow the creating module to alter the value if desired. The
  358. // module should do this if the field has any other form elements
  359. // that need populationg besides the value which was set above.
  360. tripal_load_include_field_class($field_type);
  361. if (class_exists($field_type) and is_subclass_of($field_type, 'TripalField')) {
  362. $tfield = new $field_type($field, $instance);
  363. $tfield->load($entity, array('record' => $record));
  364. }
  365. // For text fields that were not handled by a TripalField class we
  366. // want to automatically expand those fields.
  367. else {
  368. if ($schema['fields'][$field_column]['type'] == 'text') {
  369. $record = chado_expand_var($record, 'field', "$field_table.$field_column");
  370. $entity->{$field_name}['und'][0]['value'] = $record->$field_column;
  371. // Text fields that have a text_processing == 1 setting need a
  372. // special 'format' element too:
  373. if (array(key_exists('text_processing', $instance['settings']) and
  374. $instance['settings']['text_processing'] == 1)) {
  375. // TODO: we need a way to write the format back to the
  376. // instance settings if the user changes it when using the form.
  377. $entity->{$field_name}['und'][0]['format'] = array_key_exists('format', $instance['settings']) ? $instance['settings']['format'] : 'full_html';
  378. }
  379. }
  380. }
  381. }
  382. // Type 2: fields for linked records. These fields will have any number
  383. // of form elements that might need populating so we'll offload the
  384. // loading of these fields to the field itself.
  385. if ($field_table != $base_table) {
  386. // Set an empty value by default, and let the hook function update it.
  387. $entity->{$field_name}['und'][0]['value'] = '';
  388. tripal_load_include_field_class($field_type);
  389. if (class_exists($field_type) && method_exists($field_type, 'load')) {
  390. $tfield = new $field_type($field, $instance);
  391. $tfield->load($entity, array('record' => $record));
  392. }
  393. }
  394. } // end: foreach ($fields as $field_id => $ids) {
  395. } // end: foreach ($entities as $id => $entity) {
  396. }
  397. /**
  398. * Merges the values of all fields into a single array keyed by table name.
  399. */
  400. function tripal_chado_field_storage_write_merge_fields($fields, $entity_type, $entity) {
  401. $all_fields = array();
  402. $base_fields = array();
  403. $field_items = array();
  404. // Iterate through all of the fields and organize them into a
  405. // new fields array keyed by the table name
  406. foreach ($fields as $field_id => $ids) {
  407. // Get the field name and information about it.
  408. $field = field_info_field_by_id($field_id);
  409. $field_name = $field['field_name'];
  410. $instance = field_info_instance('TripalEntity', $field['field_name'], $entity->bundle);
  411. // Some fields don't add data to
  412. // Chado so they don't have a table, but they are still attached to the
  413. // entity. Just skip these.
  414. if (!array_key_exists('chado_table', $instance['settings'])) {
  415. continue;
  416. }
  417. $chado_table = $instance['settings']['chado_table'];
  418. $chado_column = $instance['settings']['chado_column'];
  419. $base_table = $instance['settings']['base_table'];
  420. // We want to iterate through the field's items. We will also store the
  421. // field values in the $field_items array to be returned by this function.
  422. $items = field_get_items($entity_type, $entity, $field_name);
  423. $temp = array();
  424. $field_items[$field_name] = $items;
  425. // If there are no items for the field and it's a base table field then
  426. // we need to set it to NULL so that the value can be removed.
  427. if (empty($items)) {
  428. if (empty($items) and ($chado_table == $base_table)) {
  429. $base_fields[$chado_table][$chado_column] = '__NULL__';
  430. }
  431. }
  432. else if (is_array($items)) {
  433. // Note: fields with cardinality ($delta) > 1 are multi-valued.
  434. foreach ($items as $delta => $item) {
  435. // A field may have multiple items. The field can use items
  436. // indexed with "chado-" to represent values that should map directly
  437. // to chado tables and fields.
  438. $value_set = FALSE;
  439. foreach ($item as $item_name => $value) {
  440. $matches = array();
  441. if (preg_match('/^chado-(.*?)__(.*?)$/', $item_name, $matches)) {
  442. $table_name = $matches[1];
  443. $column_name = $matches[2];
  444. // If this field belongs to the base table then we just add
  445. // those values in... there's no delta.
  446. if ($table_name == $base_table) {
  447. $base_fields[$table_name][$column_name] = $value;
  448. }
  449. else {
  450. $temp[$table_name][$delta][$column_name] = $value;
  451. }
  452. $value_set = TRUE;
  453. }
  454. }
  455. // If there is no value set for the field using the
  456. // chado-[table_name]__[field name] naming schema then check if a 'value'
  457. // item is present and if so use that for the table column value.
  458. if (!$value_set and array_key_exists('value', $items[$delta]) and
  459. !is_array($items[$delta]['value'])) {
  460. // If this field belongs to the base table then we just add
  461. // those values in... there's no delta.
  462. if ($base_table == $chado_table) {
  463. $base_fields[$chado_table][$chado_column] = $item['value'];
  464. }
  465. else {
  466. $temp[$chado_table][$delta][$chado_column] = $item['value'];
  467. }
  468. }
  469. }
  470. // Now merge the records for this field with the $new_fields array
  471. foreach ($temp as $table_name => $details) {
  472. foreach ($details as $delta => $list) {
  473. $all_fields[$table_name][] = $list;
  474. }
  475. }
  476. }
  477. }
  478. $all_fields = array_merge($base_fields, $all_fields);
  479. return [$all_fields, $field_items];
  480. }
  481. /**
  482. * Implements hook_field_storage_query().
  483. */
  484. function tripal_chado_field_storage_query($query) {
  485. // Initialize the result array.
  486. $result = array(
  487. 'TripalEntity' => array()
  488. );
  489. // There must always be an entity filter that includes the bundle. Otherwise
  490. // it would be too overwhelming to search every table of every content type
  491. // for a matching field.
  492. if (!array_key_exists('bundle', $query->entityConditions)) {
  493. return $result;
  494. }
  495. $bundle = tripal_load_bundle_entity(array('name' => $query->entityConditions['bundle']));
  496. if (!$bundle) {
  497. return;
  498. }
  499. $data_table = $bundle->data_table;
  500. $type_column = $bundle->type_column;
  501. $type_id = $bundle->type_id;
  502. $schema = chado_get_schema($data_table);
  503. $pkey = $schema['primary key'][0];
  504. // Initialize the Query object.
  505. $cquery = chado_db_select($data_table, 'base');
  506. $cquery->fields('base', array($pkey));
  507. // Iterate through all the conditions and add to the filters array
  508. // a chado_select_record compatible set of filters.
  509. foreach ($query->fieldConditions as $index => $condition) {
  510. $field = $condition['field'];
  511. $field_name = $field['field_name'];
  512. $field_type = $field['type'];
  513. // Skip conditions that don't belong to this storage type.
  514. if ($field['storage']['type'] != 'field_chado_storage') {
  515. continue;
  516. }
  517. // The Chado settings for a field are part of the instance and each bundle
  518. // can have the same field but with different Chado mappings. Therefore,
  519. // we need to iterate through the bundles to get the field instances.
  520. foreach ($field['bundles']['TripalEntity'] as $bundle_name) {
  521. // If there is a bundle filter for the entity and if the field is not
  522. // associated with the bundle then skip it.
  523. if (array_key_exists('bundle', $query->entityConditions)) {
  524. if (strtolower($query->entityConditions['bundle']['operator']) == 'in' and
  525. !array_key_exists($bundle_name, $query->entityConditions['bundle']['value'])) {
  526. continue;
  527. }
  528. else if ($query->entityConditions['bundle']['value'] != $bundle_name) {
  529. continue;
  530. }
  531. }
  532. // Allow the field to update the query object.
  533. $instance = field_info_instance('TripalEntity', $field['field_name'], $bundle_name);
  534. if (tripal_load_include_field_class($field_type)) {
  535. $field_obj = new $field_type($field, $instance);
  536. $field_obj->query($cquery, $condition);
  537. }
  538. // If there is not a ChadoField class for this field then add the
  539. // condition as is.
  540. else {
  541. $alias = $field['field_name'];
  542. $chado_table = $instance['settings']['chado_table'];
  543. $base_table = $instance['settings']['base_table'];
  544. $bschema = chado_get_schema($base_table);
  545. $bpkey = $bschema['primary key'][0];
  546. if ($chado_table == $base_table) {
  547. // Get the base table column that is associated with the term
  548. // passed as $condition['column'].
  549. $base_field = chado_get_semweb_column($chado_table, $condition['column']);
  550. $matches = array();
  551. $key = $condition['value'];
  552. $op = array_key_exists('operator', $condition) ? $condition['operator'] : '=';
  553. if (preg_match('/^(.+);(.+)$/', $key, $matches)) {
  554. $key = $matches[1];
  555. $op = $matches[2];
  556. }
  557. switch ($op) {
  558. case 'eq':
  559. $op = '=';
  560. break;
  561. case 'gt':
  562. $op = '>';
  563. break;
  564. case 'gte':
  565. $op = '>=';
  566. break;
  567. case 'lt':
  568. $op = '<';
  569. break;
  570. case 'lte':
  571. $op = '<=';
  572. break;
  573. case '<>':
  574. case 'ne':
  575. $op = '!=';
  576. break;
  577. case 'LIKE':
  578. case 'contains':
  579. $op = 'LIKE';
  580. if (!preg_match('/\%/', $key)) {
  581. $key = '%' . $key . '%';
  582. }
  583. break;
  584. case 'NOT LIKE':
  585. $op = 'NOT LIKE';
  586. if (!preg_match('/\%/', $key)) {
  587. $key = '%' . $key . '%';
  588. }
  589. break;
  590. case 'starts':
  591. $op = 'LIKE';
  592. $key = $key . '%';
  593. break;
  594. default:
  595. $op = '=';
  596. }
  597. $cquery->condition('base.' . $base_field , $key, $op);
  598. }
  599. if ($chado_table != $base_table) {
  600. // TODO: I don't think we'll get here because linker fields will
  601. // always have a custom field that should implement a query()
  602. // function. But just in case here's a note to handle it.
  603. }
  604. }
  605. }
  606. } // end foreach ($query->fieldConditions as $index => $condition) {
  607. // Now join with the chado entity table to get published records only.
  608. $chado_entity_table = chado_get_bundle_entity_table($bundle);
  609. $cquery->join($chado_entity_table, 'CE', "CE.record_id = base.$pkey");
  610. $cquery->join('tripal_entity', 'TE', "CE.entity_id = TE.id");
  611. $cquery->fields('CE', array('entity_id'));
  612. $cquery->fields('TE', array('bundle'));
  613. if (array_key_exists('start', $query->range)) {
  614. $cquery->range($query->range['start'], $query->range['length']);
  615. }
  616. // Make sure we only get records of the correct entity type
  617. $cquery->condition('TE.bundle', $query->entityConditions['bundle']['value']);
  618. // Iterate through all the property conditions. These will be filters
  619. // on the tripal_entity table.
  620. foreach ($query->propertyConditions as $index => $condition) {
  621. $cquery->condition('TE.' . $condition['column'], $condition['value']);
  622. }
  623. // If there is an entity_id filter then apply that.
  624. if (array_key_exists('entity_id', $query->entityConditions)) {
  625. $value = $query->entityConditions['entity_id']['value'];
  626. $op = '';
  627. if (array_key_exists('op', $query->entityConditions['entity_id'])) {
  628. $op = $query->entityConditions['entity_id']['op'];
  629. }
  630. // Handle a single entity_id
  631. if (!is_array($value)) {
  632. switch ($op) {
  633. case 'CONTAINS':
  634. $op = 'LIKE';
  635. $value = '%' . $value . '%';
  636. break;
  637. case 'STARTS_WITH':
  638. $op = 'LIKE';
  639. $value = $value . '%';
  640. break;
  641. case 'BETWEEN':
  642. // This case doesn't make sense for a single value. So, just set it
  643. // equal to the end.
  644. $op = '=';
  645. default:
  646. $op = $op ? $op : '=';
  647. }
  648. }
  649. // Handle multiple entitie IDs.
  650. else {
  651. switch ($op) {
  652. case 'CONTAINS':
  653. $op = 'IN';
  654. break;
  655. case 'STARTS_WITH':
  656. $op = 'IN';
  657. break;
  658. case 'BETWEEN':
  659. $op = 'BETWEEN';
  660. default:
  661. $op = 'IN';
  662. }
  663. }
  664. if ($op == 'BETWEEN') {
  665. $cquery->condition('TE.id', $value[0], '>');
  666. $cquery->condition('TE.id', $value[1], '<');
  667. }
  668. else {
  669. $cquery->condition('TE.id', $value, $op);
  670. }
  671. }
  672. // Now set any ordering.
  673. foreach ($query->order as $index => $sort) {
  674. // Add in property ordering.
  675. if ($sort['type'] == 'property') {
  676. // TODO: support ordering by bundle properties.
  677. }
  678. // Add in filter ordering
  679. if ($sort['type'] == 'field') {
  680. $field = $sort['specifier']['field'];
  681. $field_type = $field['type'];
  682. $field_name = $field['field_name'];
  683. // Skip sorts that don't belong to this storage type.
  684. if ($field['storage']['type'] != 'field_chado_storage') {
  685. continue;
  686. }
  687. $column = $sort['specifier']['column'];
  688. $direction = $sort['direction'];
  689. // The Chado settings for a field are part of the instance and each bundle
  690. // can have the same field but with different Chado mappings. Therefore,
  691. // we need to iterate through the bundles to get the field instances.
  692. foreach ($field['bundles']['TripalEntity'] as $bundle_name) {
  693. // If there is a bundle filter for the entity and if the field is not
  694. // associated with the bundle then skip it.
  695. if (array_key_exists('bundle', $query->entityConditions)) {
  696. if (strtolower($query->entityConditions['bundle']['operator']) == 'in' and
  697. !array_key_exists($bundle_name, $query->entityConditions['bundle']['value'])) {
  698. continue;
  699. }
  700. else if ($query->entityConditions['bundle']['value'] != $bundle_name) {
  701. continue;
  702. }
  703. }
  704. // See if there is a ChadoField class for this instance. If not then do
  705. // our best to order the field.
  706. $instance = field_info_instance('TripalEntity', $field_name, $bundle_name);
  707. if (tripal_load_include_field_class($field_type)) {
  708. $field_obj = new $field_type($field, $instance);
  709. $field_obj->queryOrder($cquery, array('column' => $column, 'direction' => $direction));
  710. }
  711. // There is no class so do our best to order the data by this field
  712. else {
  713. $base_table = $instance['settings']['base_table'];
  714. $chado_table = $instance['settings']['chado_table'];
  715. $table_column = chado_get_semweb_column($chado_table, $column);
  716. if ($table_column) {
  717. if ($chado_table == $base_table) {
  718. $cquery->orderBy('base.' . $table_column, $direction);
  719. }
  720. else {
  721. // TODO: how do we handle a field that doesn't map to the base table.
  722. // We would expect that all of these would be custom field and
  723. // the ChadoField::queryOrder() function would be implemented.
  724. }
  725. }
  726. else {
  727. // TODO: handle when the name can't be matched to a table column.
  728. }
  729. }
  730. } // end foreach ($field['bundles']['TripalEntity'] as $bundle_name) {
  731. } // end if ($sort['type'] == 'field') {
  732. } // end foreach ($query->order as $index => $sort) {
  733. // Only include records that are deleted. Tripal doesn't keep track of
  734. // records that are deleted that need purging separately so we can do nothing
  735. // with this.
  736. if (property_exists($query, 'deleted') and $query->deleted) {
  737. // There won't ever be field data marked as deleted so just created a
  738. // condition that always evaluates to false.
  739. $cquery->where('1=0');
  740. }
  741. // Please keep these dpm's they help with debugging
  742. // dpm($cquery->__toString());
  743. // dpm($cquery->getArguments());
  744. $records = $cquery->execute();
  745. // If this is not a count query then return the results.
  746. $result = array();
  747. while ($record = $records->fetchObject()) {
  748. $ids = array($record->entity_id, 0, $record->bundle);
  749. $result['TripalEntity'][$record->entity_id] = entity_create_stub_entity('TripalEntity', $ids);
  750. }
  751. return $result;
  752. }
  753. function tripal_chado_field_storage_bundle_mapping_form_get_defaults($form, $form_state) {
  754. // The term for the content type should already be set in the form state.
  755. $term = $form_state['values']['term'];
  756. // Get the form default values.
  757. $default = array(
  758. 'table' => '',
  759. 'has_all' => '',
  760. 'use_linker' => '',
  761. 'use_prop' => '',
  762. 'type_column' => '',
  763. 'base_selected_term' => '',
  764. 'prop_selected_term' => '',
  765. 'prop_term_value' => '',
  766. 'stage' => 'table-select',
  767. );
  768. // Get the stage.
  769. if (array_key_exists('chado-stage', $form_state)) {
  770. $default['stage'] = $form_state['chado-stage'];
  771. }
  772. if (array_key_exists('base_chado_table', $form_state['values'])
  773. and $form_state['values']['base_chado_table']) {
  774. $default['table'] = $form_state['values']['base_chado_table'];
  775. }
  776. else {
  777. $mapped_table = chado_get_cvterm_mapping(['cvterm_id' => $term->cvterm_id]);
  778. if ($mapped_table) {
  779. $default['table'] = $mapped_table->chado_table;
  780. }
  781. }
  782. if (array_key_exists('chado_table_has_all', $form_state['values'])
  783. and $form_state['values']['chado_table_has_all']) {
  784. $default['has_all'] = $form_state['values']['chado_table_has_all'];
  785. }
  786. if (array_key_exists('chado_type_use_linker', $form_state['values'])
  787. and $form_state['values']['chado_type_use_linker']) {
  788. $default['use_linker'] = $form_state['values']['chado_type_use_linker'];
  789. }
  790. if (array_key_exists('chado_type_use_prop', $form_state['values'])
  791. and $form_state['values']['chado_type_use_prop']) {
  792. $default['use_prop'] = $form_state['values']['chado_type_use_prop'];
  793. }
  794. if (array_key_exists('type_column', $form_state['values'])
  795. and $form_state['values']['type_column']) {
  796. $default['type_column'] = $form_state['values']['type_column'];
  797. }
  798. if (array_key_exists('prop_term_value', $form_state['values'])
  799. and $form_state['values']['prop_term_value']) {
  800. $default['prop_term_value'] = $form_state['values']['prop_term_value'];
  801. }
  802. if (array_key_exists('term_name1', $form_state['values'])) {
  803. $default['base_selected_term'] = tripal_get_term_lookup_form_result($form, $form_state, '', 1);
  804. }
  805. if (array_key_exists('term_name2', $form_state['values'])) {
  806. $default['prop_selected_term'] = tripal_get_term_lookup_form_result($form, $form_state, '', 2);
  807. }
  808. return $default;
  809. }
  810. /**
  811. * Implements hook_field_storage_bundle_mapping_form().
  812. *
  813. * This is a Tripal added hook to the field storage API.
  814. */
  815. function tripal_chado_field_storage_bundle_mapping_form($form, &$form_state, $term, &$submit_disabled) {
  816. $selected_term_id = (is_object($term)) ? $term->cvterm_id : NULL;
  817. $submit_disabled = TRUE;
  818. // Get the form defaults values from the form state.
  819. $default = tripal_chado_field_storage_bundle_mapping_form_get_defaults($form, $form_state);
  820. // Initialize the form.
  821. $form = array();
  822. $form['selected_cvterm_id'] = array(
  823. '#type' => 'value',
  824. '#value' => $selected_term_id,
  825. );
  826. tripal_chado_field_storage_bundle_mapping_form_summary($form, $form_state, $default);
  827. if ($default['stage'] == 'table-select') {
  828. tripal_chado_field_storage_bundle_mapping_form_table_select($form, $form_state, $term, $default);
  829. }
  830. else if ($default['stage'] == 'has-all-select') {
  831. tripal_chado_field_storage_bundle_mapping_form_has_all_select($form, $form_state, $term, $default);
  832. }
  833. else if ($default['stage'] == 'type-select') {
  834. tripal_chado_field_storage_bundle_mapping_form_type_select($form, $form_state, $term, $default);
  835. }
  836. else if ($default['stage'] == 'prop-select') {
  837. tripal_chado_field_storage_bundle_mapping_form_prop_select($form, $form_state, $term, $default);
  838. }
  839. else if ($default['stage'] == 'prop-settings') {
  840. tripal_chado_field_storage_bundle_mapping_form_prop_settings($form, $form_state, $term, $default);
  841. }
  842. else if ($default['stage'] == 'linker-select') {
  843. tripal_chado_field_storage_bundle_mapping_form_linker_select($form, $form_state, $term, $default);
  844. }
  845. else if ($default['stage'] == 'linker-settings') {
  846. tripal_chado_field_storage_bundle_mapping_form_linker_settings($form, $form_state, $term, $default);
  847. }
  848. else if ($default['stage'] == 'complete') {
  849. $submit_disabled = FALSE;
  850. }
  851. $form['chado-settings-reset'] = array(
  852. '#type' => 'submit',
  853. '#value' => t('Reset'),
  854. '#name' => 'chado-settings-reset',
  855. '#validate' => [
  856. 'tripal_chado_field_storage_bundle_mapping_form_validate',
  857. 'tripal_admin_add_type_form_validate'
  858. ],
  859. );
  860. return $form;
  861. }
  862. /**
  863. * Adds form elements for the summary of the selection.
  864. */
  865. function tripal_chado_field_storage_bundle_mapping_form_summary(&$form, &$form_state, $default) {
  866. $rows = [];
  867. $headers = [];
  868. // If we're on the first step then just return, there is no summary.
  869. if ($default['stage'] == 'table-select') {
  870. return;
  871. }
  872. // Make sure the form values are set.
  873. $form['base_chado_table'] = [
  874. '#type' => 'value',
  875. '#value' => $default['table'],
  876. ];
  877. $form['chado_table_has_all'] = [
  878. '#type' => 'value',
  879. '#value' => $default['has_all'],
  880. ];
  881. $form['type_column'] = [
  882. '#type' => 'value',
  883. '#value' => $default['type_column'],
  884. ];
  885. $form['chado_type_use_prop'] = [
  886. '#type' => 'value',
  887. '#value' => $default['use_prop'],
  888. ];
  889. $form['prop_term'] = [
  890. '#type' => 'value',
  891. '#value' => $default['prop_selected_term'],
  892. ];
  893. $form['base_term'] = [
  894. '#type' => 'value',
  895. '#value' => $default['base_selected_term'],
  896. ];
  897. $form['prop_term_value'] = [
  898. '#type' => 'value',
  899. '#value' => $default['prop_term_value'],
  900. ];
  901. $form['chado_type_use_linker'] = [
  902. '#type' => 'value',
  903. '#value' => $default['use_linker'],
  904. ];
  905. //
  906. // Add the base table row.
  907. //
  908. $rows[] = [
  909. [
  910. 'data' => 'Chado Base Table',
  911. 'header' => TRUE,
  912. 'width' => '20%',
  913. ],
  914. $default['table'],
  915. ];
  916. //
  917. // Add the row indicating if all of the records are of the type.
  918. //
  919. if ($default['has_all'] == 'Yes' or $default['has_all'] == 'No') {
  920. $message = 'Yes. All records in the ' . $default['table'] . ' table are of this type.';
  921. if($default['has_all'] == 'No') {
  922. $message = 'No. All records in the ' . $default['table'] . ' table are not of this type.';
  923. }
  924. $rows[] = [
  925. [
  926. 'data' => 'All are of this type?',
  927. 'header' => TRUE,
  928. 'width' => '20%',
  929. ],
  930. $message,
  931. ];
  932. }
  933. //
  934. // Add the row indicating if the type_column is used.
  935. //
  936. if ($default['type_column']) {
  937. $message = $default['type_column'];
  938. if ($default['type_column'] == 'none') {
  939. $message = 'No type column is needed.';
  940. }
  941. $rows[] = [
  942. [
  943. 'data' => 'Type Column',
  944. 'header' => TRUE,
  945. 'width' => '20%',
  946. ],
  947. $message,
  948. ];
  949. }
  950. //
  951. // Add the row indicating that the record can be distinguished with a prop.
  952. //
  953. if ($default['use_prop']) {
  954. $message = 'Yes. The field is distinguishable using a property record.';
  955. if ($default['use_prop'] == 'No') {
  956. $message = 'No. The field is not distinguishable using a property record.';
  957. }
  958. $rows[] = [
  959. [
  960. 'data' => 'Use a property?',
  961. 'header' => TRUE,
  962. 'width' => '20%',
  963. ],
  964. $message,
  965. ];
  966. }
  967. //
  968. // Add the row for the base type for a property mapping
  969. //
  970. if ($default['use_prop'] == 'Yes' and $default['base_selected_term']) {
  971. $term = $default['base_selected_term'][0];
  972. $rows[] = [
  973. [
  974. 'data' => 'Base Type',
  975. 'header' => TRUE,
  976. 'width' => '20%',
  977. ],
  978. $term->name . ' (' . $term->dbxref_id->db_id->name . ':' . $term->dbxref_id->accession .')',
  979. ];
  980. }
  981. //
  982. // Add the row for the type for a property mapping
  983. //
  984. if ($default['prop_selected_term']) {
  985. $term = $default['prop_selected_term'][0];
  986. $rows[] = [
  987. [
  988. 'data' => 'Property Type',
  989. 'header' => TRUE,
  990. 'width' => '20%',
  991. ],
  992. $term->name . ' (' . $term->dbxref_id->db_id->name . ':' . $term->dbxref_id->accession .')',
  993. ];
  994. }
  995. //
  996. // Add the row for the value for a property mapping
  997. //
  998. if ($default['prop_term_value']) {
  999. $rows[] = [
  1000. [
  1001. 'data' => 'Property Value',
  1002. 'header' => TRUE,
  1003. 'width' => '20%',
  1004. ],
  1005. $default['prop_term_value'],
  1006. ];
  1007. }
  1008. //
  1009. // Add the row for the linker table selection
  1010. //
  1011. if ($default['use_linker']) {
  1012. $message = 'Yes. The field is distinguishable using a cvterm linker table. The Content Type will be used to find records in the linker table';
  1013. if ($default['use_linker'] == 'No') {
  1014. $message = 'No. The field is not distinguishable using a cvterm linker table.';
  1015. }
  1016. $rows[] = [
  1017. [
  1018. 'data' => 'Use a Chado cvterm linker?',
  1019. 'header' => TRUE,
  1020. 'width' => '20%',
  1021. ],
  1022. $message,
  1023. ];
  1024. }
  1025. //
  1026. // Add the row for the base type for a property mapping
  1027. //
  1028. if ($default['use_linker'] == 'Yes' and $default['base_selected_term']) {
  1029. $term = $default['base_selected_term'][0];
  1030. $rows[] = [
  1031. [
  1032. 'data' => 'Base Type',
  1033. 'header' => TRUE,
  1034. 'width' => '20%',
  1035. ],
  1036. $term->name . ' (' . $term->dbxref_id->db_id->name . ':' . $term->dbxref_id->accession .')',
  1037. ];
  1038. }
  1039. $table = array(
  1040. 'header' => $headers,
  1041. 'rows' => $rows,
  1042. 'attributes' => array(
  1043. ),
  1044. 'sticky' => FALSE,
  1045. 'caption' => '',
  1046. 'colgroups' => array(),
  1047. 'empty' => '',
  1048. );
  1049. $form['chado_settings_summary'] = [
  1050. '#type' => 'markup',
  1051. '#markup' => theme_table($table),
  1052. '#weight' => -100,
  1053. ];
  1054. if ($default['stage'] == 'complete') {
  1055. $form['im_ready'] = [
  1056. '#type' => 'markup',
  1057. '#markup' => '<p>Your content type is ready for creation! Please click the "Create Content Type" button below.</p>',
  1058. ];
  1059. }
  1060. if ($default['stage'] == 'stop') {
  1061. $form['im_ready'] = [
  1062. '#type' => 'markup',
  1063. '#markup' => '<p>Unfortunately, it is not possible to create this conent type. Please check your selections above. If you need help creating a content type, you may reach out to the Tripal Community for assistance.</p>',
  1064. ];
  1065. }
  1066. }
  1067. /**
  1068. * Adds form elements for Chado table selection step
  1069. */
  1070. function tripal_chado_field_storage_bundle_mapping_form_table_select(&$form, &$form_state, $term, $default) {
  1071. $base_tables = chado_get_base_tables();
  1072. $options = array(0 => '-- Select table --');
  1073. foreach ($base_tables AS $tablename) {
  1074. $options[$tablename] = $tablename;
  1075. }
  1076. $form['base_chado_table'] = array(
  1077. '#type' => 'select',
  1078. '#title' => 'Chado table',
  1079. '#options' => $options,
  1080. '#description' => 'Select the Chado table into which the primary records for this content type will be stored.',
  1081. '#default_value' => $default['table'],
  1082. '#ajax' => array(
  1083. 'callback' => "tripal_admin_add_type_form_ajax_callback",
  1084. 'wrapper' => "tripal-add-type-form",
  1085. 'effect' => 'fade',
  1086. 'method' => 'replace'
  1087. ),
  1088. );
  1089. $form['table-select-continue'] = array(
  1090. '#type' => 'submit',
  1091. '#value' => t('Continue'),
  1092. '#name' => 'chado-table-select-continue',
  1093. '#validate' => [
  1094. 'tripal_chado_field_storage_bundle_mapping_form_validate',
  1095. 'tripal_admin_add_type_form_validate'
  1096. ],
  1097. );
  1098. }
  1099. /**
  1100. * Adds form elements for step 1: Chado type field selection.
  1101. */
  1102. function tripal_chado_field_storage_bundle_mapping_form_has_all_select(&$form, &$form_state, $term, $default) {
  1103. // Get the schema for this table.
  1104. $schema = chado_get_schema($default['table']);
  1105. // If the selected base table is 'cvterm' then handle it specially.
  1106. if ($default['table'] == 'cvterm') {
  1107. tripal_chado_field_storage_bundle_mapping_form_add_cvterm($form,
  1108. $form_state, $term, $default);
  1109. if ($default['use_cvterm'] == 'cv' and $default['cv_id']) {
  1110. $submit_disabled = FALSE;
  1111. }
  1112. if ($default['use_cvterm'] == 'parent') {
  1113. $submit_disabled = FALSE;
  1114. }
  1115. return;
  1116. }
  1117. $term_name = $term->name;
  1118. // Form elements to determine if all records in base table are of this type.
  1119. $form['chado_table_has_all'] = array(
  1120. '#type' => 'radios',
  1121. '#options' => array(
  1122. 'Yes' => 'Yes',
  1123. 'No' => 'No'
  1124. ),
  1125. '#title' => 'Are all records in the "' . $default['table'] .
  1126. '" table of type "'. $term_name . '"?',
  1127. '#description' => 'Select "No" if the "' .
  1128. $default['table'] . '" table houses more than just data of type "' .
  1129. $term_name . '".',
  1130. '#default_value' => $default['has_all'],
  1131. );
  1132. $form['chado-has-all-select-continue'] = array(
  1133. '#type' => 'submit',
  1134. '#value' => t('Continue'),
  1135. '#name' => 'chado-has-all-select-continue',
  1136. '#validate' => [
  1137. 'tripal_chado_field_storage_bundle_mapping_form_validate',
  1138. 'tripal_admin_add_type_form_validate'
  1139. ],
  1140. );
  1141. }
  1142. /*
  1143. // If all the records in the table are of this type then we're done.
  1144. if ($default['has_all'] == 'Yes') {
  1145. $submit_disabled = FALSE;
  1146. return $form;
  1147. }
  1148. // If this table has a field that maps to a cvterm record then we want
  1149. // to ask if the user wants to use that field.
  1150. tripal_chado_field_storage_bundle_mapping_form_add_type($form,
  1151. $form_state, $term, $default);
  1152. // If the type_column is set then we're done! We know the deafult table
  1153. // and column to map this data type.
  1154. if (!empty($default['type_column']) and $default['type_column'] != 'none') {
  1155. $submit_disabled = FALSE;
  1156. return $form;
  1157. }
  1158. // Let's set the names of the linker and prop table for use below.
  1159. $linker_table = $default['table'] . '_cvterm';
  1160. $prop_table = $default['table']. 'prop';
  1161. $linker_exists = chado_table_exists($linker_table);
  1162. $prop_exists = chado_table_exists($prop_table);
  1163. // Ask the user if they want to use a linker table if it exists.
  1164. if ($prop_exists) {
  1165. tripal_chado_field_storage_bundle_mapping_form_add_prop($form,
  1166. $form_state, $term, $prop_table, $default);
  1167. // If the user wants to use the property table then we're done!
  1168. if ($default['use_prop'] == 'Yes') {
  1169. $submit_disabled = FALSE;
  1170. return $form;
  1171. }
  1172. // Ask if the user wants to use the linker table if it exists.
  1173. if ($linker_exists) {
  1174. tripal_chado_field_storage_bundle_mapping_form_add_linker($form,
  1175. $form_state, $term, $linker_table, $default);
  1176. // If the user wants to use the linker table then we're done!
  1177. if ($default['use_linker'] == 'Yes') {
  1178. $submit_disabled = FALSE;
  1179. return $form;
  1180. }
  1181. }
  1182. }
  1183. // A prop table doesn't exist then ask the user if they want
  1184. // to use the linker table to associate records.
  1185. else if ($linker_exists) {
  1186. tripal_chado_field_storage_bundle_mapping_form_add_prop($form,
  1187. $form_state, $term, $prop_table, $default);
  1188. // If the user wants to use the linker table then we're done!
  1189. if ($default['use_linker'] == 'Yes') {
  1190. $submit_disabled = FALSE;
  1191. return $form;
  1192. }
  1193. }
  1194. $form['notice'] = array(
  1195. '#type' => 'item',
  1196. '#markup' => '<font color="red">Unfortunately, the options selected above do not allow for mapping of this content type to records in Chado.</font>'
  1197. );
  1198. return $form;
  1199. }
  1200. */
  1201. /**
  1202. * Adds form elements for step 1: Chado type field selection.
  1203. */
  1204. function tripal_chado_field_storage_bundle_mapping_form_type_select(&$form, &$form_state, $term, $default) {
  1205. $term_name = $term->name;
  1206. $column_options = tripal_chado_field_storage_bundle_mapping_form_get_type_fks_options($default['table']);
  1207. $default_column = !empty($default['type_column']) ? $default['type_column'] : 'type_id';
  1208. $form['type_column'] = array(
  1209. '#type' => 'select',
  1210. '#title' => 'Type Column',
  1211. '#options' => $column_options,
  1212. '#description' => 'Please select the column in the "' .
  1213. $default['table'] . '" table that will identify a record as being of type "' .
  1214. $term_name . '". If you select "--None--" then you will be asked
  1215. if the type can be identified using a property or linker table.
  1216. Only fields that have a foreign key to the cvterm table will be listed.',
  1217. '#default_value' => $default_column
  1218. );
  1219. $form['chado-type-select-continue'] = array(
  1220. '#type' => 'submit',
  1221. '#value' => t('Continue'),
  1222. '#name' => 'chado-type-select-continue',
  1223. '#validate' => [
  1224. 'tripal_chado_field_storage_bundle_mapping_form_validate',
  1225. 'tripal_admin_add_type_form_validate'
  1226. ],
  1227. );
  1228. }
  1229. /**
  1230. *
  1231. */
  1232. function tripal_chado_field_storage_bundle_mapping_form_prop_select(&$form, &$form_state, $term, $default) {
  1233. $prop_table = $default['table']. 'prop';
  1234. $form['chado_type_use_prop'] = array(
  1235. '#type' => 'radios',
  1236. '#title' => 'Do you want to use the "' . $prop_table . '" table
  1237. to distinguish between content types?',
  1238. '#options' => array(
  1239. 'Yes' => 'Yes',
  1240. 'No' => 'No'
  1241. ),
  1242. '#description' => t('Sometimes records can be distringuished
  1243. using a value in property table, especially if there is no column
  1244. in the specified Chado table to identify the
  1245. record type. In these cases the property table can be used.'),
  1246. '#default_value' => $default['use_prop'],
  1247. );
  1248. $form['chado-prop-select-continue'] = array(
  1249. '#type' => 'submit',
  1250. '#value' => t('Continue'),
  1251. '#name' => 'chado-prop-select-continue',
  1252. '#validate' => [
  1253. 'tripal_chado_field_storage_bundle_mapping_form_validate',
  1254. 'tripal_admin_add_type_form_validate'
  1255. ],
  1256. );
  1257. }
  1258. function tripal_chado_field_storage_bundle_mapping_form_prop_settings(&$form, &$form_state, $term, $default){
  1259. $prop_term_value = $default['prop_term_value'];
  1260. $base_type_column = tripal_chado_field_storage_bundle_mapping_form_get_base_type_column($default['table']);
  1261. $validate =[
  1262. 'tripal_chado_field_storage_bundle_mapping_form_validate',
  1263. 'tripal_admin_add_type_form_validate'
  1264. ];
  1265. if ($base_type_column) {
  1266. $description = t('The ' . $default['table'] . ' table of Chado requires
  1267. that each record have a type. You have indicated that this
  1268. content type is not distinguished by a column in the base tabe but
  1269. instead by a property. However, the ' . $default['table'] . ' table requires
  1270. that a value be given for the ' . $base_type_column . '. Please indicate
  1271. what this type should be. For example, suppose this content type is a SNP (SO:0000694) and
  1272. you store SNPs in Chado in the feature table as "genetic_marker" (SO:0001645), however
  1273. the record is defined as a SNP through a corresponding record in the featurprop
  1274. table that has a type of "type" (rdfs:type) and a value of "SNP".
  1275. In this case the content type should be SNP (SO:0001645) and here the
  1276. "genetic_marker" (SO:0001645) term should be provided. The "type" term
  1277. should be used in the Property Type field below and "SNP" as the Property Value.');
  1278. tripal_get_term_lookup_form($form, $form_state, '',
  1279. 'Base Type', $description, FALSE, '', 1,
  1280. 'tripal_admin_add_type_form_ajax_callback', 'tripal-add-type-form',
  1281. $validate, -2);
  1282. }
  1283. // We need a term lookup form for the property type.
  1284. $description = t('The content type "' . $term->name . '" must be
  1285. associated with a property type. The property type must be the
  1286. name of a term in a controlled vocabulary and the controlled
  1287. vocabulary should already be loaded into Tripal. Please select
  1288. the property type that will be used to identify records of this
  1289. type');
  1290. tripal_get_term_lookup_form($form, $form_state, '',
  1291. 'Property Type', $description, FALSE, '', 2,
  1292. 'tripal_admin_add_type_form_ajax_callback', 'tripal-add-type-form',
  1293. $validate, -8);
  1294. $form['prop_term_value'] = array(
  1295. '#type' => 'textfield',
  1296. '#title' => 'Property Value',
  1297. '#description' => t('All properties have a type and a value. Above you
  1298. indicated the type of property. Now you must specify the value
  1299. that this properly must have in order to be considered of
  1300. type "' . $term->name . '".'),
  1301. '#default_value' => $prop_term_value,
  1302. );
  1303. $form['chado-prop-settings-continue'] = array(
  1304. '#type' => 'submit',
  1305. '#value' => t('Continue'),
  1306. '#name' => 'chado-prop-settings-continue',
  1307. '#validate' => [
  1308. 'tripal_chado_field_storage_bundle_mapping_form_validate',
  1309. 'tripal_admin_add_type_form_validate'
  1310. ],
  1311. );
  1312. }
  1313. /**
  1314. *
  1315. */
  1316. function tripal_chado_field_storage_bundle_mapping_form_linker_select(&$form, &$form_state, $term, $default) {
  1317. $linker_table = $default['table'] . '_cvterm';
  1318. $form['chado_type_use_linker'] = array(
  1319. '#type' => 'radios',
  1320. '#title' => 'Do you want to use the "' . $linker_table . '" table
  1321. to distinguish between content types?',
  1322. '#options' => array(
  1323. 'Yes' => 'Yes',
  1324. 'No' => 'No'
  1325. ),
  1326. '#description' => t('Sometimes records can be distringuished
  1327. using a linker table, especially if there is no column
  1328. in the specified Chado table to identify the
  1329. record type. In these cases the linker table can be used.'),
  1330. '#default_value' => $default['use_linker'],
  1331. );
  1332. $form['chado-linker-select-continue'] = array(
  1333. '#type' => 'submit',
  1334. '#value' => t('Continue'),
  1335. '#name' => 'chado-linker-select-continue',
  1336. '#validate' => [
  1337. 'tripal_chado_field_storage_bundle_mapping_form_validate',
  1338. 'tripal_admin_add_type_form_validate'
  1339. ],
  1340. );
  1341. }
  1342. /**
  1343. *
  1344. */
  1345. function tripal_chado_field_storage_bundle_mapping_form_linker_settings(&$form, &$form_state, $term, $default){
  1346. $base_type_column = tripal_chado_field_storage_bundle_mapping_form_get_base_type_column($default['table']);
  1347. $validate =[
  1348. 'tripal_chado_field_storage_bundle_mapping_form_validate',
  1349. 'tripal_admin_add_type_form_validate'
  1350. ];
  1351. $description = t('The ' . $default['table'] . ' table of Chado requires
  1352. that each record have a type. You have indicated that this
  1353. content type is not distinguished by a column in the base tabe but
  1354. instead by a cvterm linker table. However, the ' . $default['table'] . ' table requires
  1355. that a value be given for the ' . $base_type_column . '. Please indicate
  1356. what this type should be.');
  1357. tripal_get_term_lookup_form($form, $form_state, '',
  1358. 'Base Type', $description, FALSE, '', 1,
  1359. 'tripal_admin_add_type_form_ajax_callback', 'tripal-add-type-form',
  1360. $validate, -10);
  1361. $form['chado-linker-settings-continue'] = array(
  1362. '#type' => 'submit',
  1363. '#value' => t('Continue'),
  1364. '#name' => 'chado-linker-settings-continue',
  1365. '#validate' => [
  1366. 'tripal_chado_field_storage_bundle_mapping_form_validate',
  1367. 'tripal_admin_add_type_form_validate'
  1368. ],
  1369. );
  1370. }
  1371. /**
  1372. *
  1373. */
  1374. function tripal_chado_field_storage_bundle_mapping_form_get_type_fks_options($table) {
  1375. // Get the list of columns in the default table.
  1376. $schema = chado_get_schema($table);
  1377. $column_options = array('none' => '--None--');
  1378. $cvt_fkeys = (isset($schema['foreign keys']['cvterm'])) ? array_keys($schema['foreign keys']['cvterm']['columns']) : array();
  1379. foreach ($schema['fields'] as $column_name => $column_details) {
  1380. if (in_array($column_name, $cvt_fkeys)) {
  1381. $column_options[$column_name] = $column_name;
  1382. }
  1383. }
  1384. return $column_options;
  1385. }
  1386. /**
  1387. *
  1388. */
  1389. function tripal_chado_field_storage_bundle_mapping_form_get_base_type_column($table) {
  1390. // If a base table has a 'type_id' field then we must have the user
  1391. // specify the base table type as well.
  1392. $base_type_column = FALSE;
  1393. $schema = chado_get_schema($table);
  1394. foreach ($schema['foreign keys'] as $fk_id => $details) {
  1395. if ($details['table'] == 'cvterm') {
  1396. foreach ($details['columns'] as $fk_left => $fk_right) {
  1397. if ($fk_left == 'type_id') {
  1398. $base_type_column = 'type_id';
  1399. }
  1400. }
  1401. }
  1402. }
  1403. return $base_type_column;
  1404. }
  1405. /**
  1406. * Implements hook_field_stoage_bundle_mapping_form_validate().
  1407. */
  1408. function tripal_chado_field_storage_bundle_mapping_form_validate($form, &$form_state) {
  1409. // Don't do validation on an ajax callback.
  1410. if (array_key_exists('#ajax', $form_state['triggering_element'])) {
  1411. return;
  1412. }
  1413. // Get the form values.
  1414. $default = tripal_chado_field_storage_bundle_mapping_form_get_defaults($form, $form_state);
  1415. $clicked_button = $form_state['clicked_button']['#name'];
  1416. // Check if prop and linker tables exist. We'll use these values later.
  1417. $prop_table = $default['table'] . 'prop';
  1418. $prop_exists = chado_table_exists($prop_table);
  1419. $linker_table = $default['table'] . '_cvterm';
  1420. $linker_exists = chado_table_exists($linker_table);
  1421. //
  1422. // Valiate the table select stage
  1423. //
  1424. if ($clicked_button == 'chado-table-select-continue') {
  1425. // Make sure a default table is selected
  1426. if (!$default['table']) {
  1427. form_set_error('base_chado_table', 'Please select a default table.');
  1428. return;
  1429. }
  1430. $form_state['chado-stage'] = 'has-all-select';
  1431. }
  1432. //
  1433. // Valiate the has all select stage
  1434. //
  1435. if ($clicked_button == 'chado-has-all-select-continue') {
  1436. if ($default['has_all'] == 'Yes') {
  1437. $form_state['chado-stage'] = 'complete';
  1438. }
  1439. else {
  1440. $column_options = tripal_chado_field_storage_bundle_mapping_form_get_type_fks_options($default['table']);
  1441. // If this table has fields that link to the cvterm table then
  1442. // let the user select the type column. The column_options is empty if
  1443. // it equals 1 because it has the --none-- element.
  1444. if (count($column_options) > 1) {
  1445. $form_state['chado-stage'] = 'type-select';
  1446. }
  1447. // Otherwise, see if there are other options....
  1448. else {
  1449. // If there is no type_id or the type_id column should not be
  1450. // used then we need to let the user select if they want to
  1451. // use the prop table or a cvterm linking table. We'll offer the
  1452. // prop table first.
  1453. if ($prop_exists) {
  1454. $form_state['chado-stage'] = 'prop-select';
  1455. }
  1456. else {
  1457. if ($linker_exists) {
  1458. $form_state['chado-stage'] = 'linker-select';
  1459. }
  1460. else {
  1461. $form_state['chado-stage'] = 'stop';
  1462. }
  1463. }
  1464. }
  1465. }
  1466. }
  1467. //
  1468. // Valiate the type select stage
  1469. //
  1470. if ($clicked_button == 'chado-type-select-continue') {
  1471. if ($default['type_column'] != 'none') {
  1472. $form_state['chado-stage'] = 'complete';
  1473. }
  1474. else {
  1475. // If there is no type_id or the type_id column should not be
  1476. // used then we need to let the user select if they want to
  1477. // use the prop table or a cvterm linking table. We'll offer the
  1478. // prop table first.
  1479. if ($prop_exists) {
  1480. $form_state['chado-stage'] = 'prop-select';
  1481. }
  1482. else {
  1483. if ($linker_exists) {
  1484. $form_state['chado-stage'] = 'linker-select';
  1485. }
  1486. else {
  1487. $form_state['chado-stage'] = 'stop';
  1488. }
  1489. }
  1490. }
  1491. }
  1492. //
  1493. // Valiate the property select stage
  1494. //
  1495. if ($clicked_button == 'chado-prop-select-continue') {
  1496. if ($default['use_prop'] == 'Yes') {
  1497. $form_state['chado-stage'] = 'prop-settings';
  1498. }
  1499. else if ($default['use_prop'] == 'No') {
  1500. if ($linker_exists) {
  1501. $form_state['chado-stage'] = 'linker-select';
  1502. }
  1503. else {
  1504. $form_state['chado-stage'] = 'stop';
  1505. }
  1506. }
  1507. else {
  1508. form_set_error('chado_type_use_prop', 'Please select a value.');
  1509. }
  1510. }
  1511. //
  1512. // Validate the property settings stage
  1513. //
  1514. if ($clicked_button == 'chado-prop-settings-continue') {
  1515. // If a base type was needed then make sure we have a value selected.
  1516. $valid = TRUE;
  1517. if (array_key_exists('term_name1', $form_state['values'])) {
  1518. $base_selected = $default['base_selected_term'];
  1519. if (count($base_selected) == 0) {
  1520. form_set_error('term_match1][term_name1', 'Please select a base table type vocabulary term.');
  1521. $valid = FALSE;
  1522. }
  1523. if (count($base_selected) > 1) {
  1524. form_set_error('term_match1][term_name1', 'Please select only one base table type vocabulary term.');
  1525. $valid = FALSE;
  1526. }
  1527. }
  1528. // Make sure we only have one property type selected
  1529. $prop_selected = $default['prop_selected_term'];
  1530. if (count($prop_selected) == 0) {
  1531. form_set_error('term_match2][term_name2', 'Please select a prpoerty type vocabulary term.');
  1532. $valid = FALSE;
  1533. }
  1534. if (count($prop_selected) > 1) {
  1535. form_set_error('term_match2][term_name2', 'Please select only one property type vocabulary term.');
  1536. $valid = FALSE;
  1537. }
  1538. if (!$default['prop_term_value']) {
  1539. form_set_error('prop_term_value', 'Please provide a property value.');
  1540. $valid = FALSE;
  1541. }
  1542. if (!$valid) {
  1543. return;
  1544. }
  1545. // If we're here then alll validations passed and we are good to go!
  1546. $form_state['chado-stage'] = 'complete';
  1547. }
  1548. //
  1549. // Validate the linker settings stage
  1550. //
  1551. if ($clicked_button == 'chado-linker-select-continue') {
  1552. if ($default['use_linker'] == 'Yes') {
  1553. // If our base table has a type_id then we need need to make the
  1554. // user provide a value for it, otherwise we're done.
  1555. $base_type_column = tripal_chado_field_storage_bundle_mapping_form_get_base_type_column($default['table']);
  1556. if ($base_type_column) {
  1557. $form_state['chado-stage'] = 'linker-settings';
  1558. }
  1559. else {
  1560. $form_state['chado-stage'] = 'complete';
  1561. }
  1562. }
  1563. else if ($default['use_linker'] == 'No') {
  1564. $form_state['chado-stage'] = 'stop';
  1565. }
  1566. else {
  1567. form_set_error('chado_type_use_linker', 'Please select a value.');
  1568. }
  1569. }
  1570. if ($clicked_button == 'chado-linker-settings-continue') {
  1571. $valid = TRUE;
  1572. if (array_key_exists('term_name1', $form_state['values'])) {
  1573. $base_selected = $default['base_selected_term'];
  1574. if (count($base_selected) == 0) {
  1575. form_set_error('term_match1][term_name1', 'Please select a base table type vocabulary term.');
  1576. $valid = FALSE;
  1577. }
  1578. if (count($base_selected) > 1) {
  1579. form_set_error('term_match1][term_name1', 'Please select only one base table type vocabulary term.');
  1580. $valid = FALSE;
  1581. }
  1582. }
  1583. if (!$valid) {
  1584. return;
  1585. }
  1586. // If we're here then alll validations passed and we are good to go!
  1587. $form_state['chado-stage'] = 'complete';
  1588. }
  1589. //
  1590. // Check for a reset.
  1591. //
  1592. if ($clicked_button == 'chado-settings-reset') {
  1593. $form_state['chado-stage'] = 'table-select';
  1594. $valid = FALSE;
  1595. }
  1596. }
  1597. /**
  1598. * Implements hook_field_stoage_bundle_mapping_form_submit().
  1599. *
  1600. * Here we do no action on submit other than set the storage_args
  1601. * variable that is passed by reference.
  1602. */
  1603. function tripal_chado_field_storage_bundle_mapping_form_submit($form,
  1604. &$form_state, $term, &$storage_args) {
  1605. $default = tripal_chado_field_storage_bundle_mapping_form_get_defaults($form, $form_state);
  1606. // If we have a type_column then we know this type uses a column in the
  1607. // base table, so we can set the storage args and return.
  1608. if ($default['type_column'] and $default['type_column'] != 'none') {
  1609. $storage_args['data_table'] = $default['table'];
  1610. $storage_args['type_column'] = $default['type_column'];
  1611. return;
  1612. }
  1613. // If the user indicated that all the records in a table are of this type.
  1614. if ($default['has_all'] == 'Yes') {
  1615. $storage_args['data_table'] = $default['table'];
  1616. $storage_args['type_id'] = $form_state['values']['selected_cvterm_id'];
  1617. $storage_args['type_linker_table'] = '';
  1618. $storage_args['type_column'] = '';
  1619. $storage_args['type_value'] = '';
  1620. }
  1621. // If the user indicated they wanted to use the prop table then we'll
  1622. // set the storage args and return.
  1623. else if ($default['use_prop'] == 'Yes') {
  1624. $storage_args['data_table'] = $default['table'];
  1625. $storage_args['type_linker_table'] = $default['table'] . 'prop';
  1626. $storage_args['type_column'] = 'type_id';
  1627. $storage_args['type_id'] = $form_state['values']['prop_term'][0]->cvterm_id;
  1628. $storage_args['type_value'] = $default['prop_term_value'];
  1629. if (is_array($form_state['values']['base_term'])) {
  1630. $storage_args['base_type_id'] = $form_state['values']['base_term'][0]->cvterm_id;
  1631. }
  1632. }
  1633. // If the user indicated they wanted to use the linker tables then we'll
  1634. // set the storage args and return.
  1635. else if ($default['use_linker'] == 'Yes') {
  1636. $storage_args['data_table'] = $default['table'];
  1637. $storage_args['type_id'] = $form_state['values']['selected_cvterm_id'];
  1638. $storage_args['type_linker_table'] = $default['table'] . '_cvterm';
  1639. $storage_args['type_column'] = 'cvterm_id';
  1640. if (is_array($form_state['values']['base_term'])) {
  1641. $storage_args['base_type_id'] = $form_state['values']['base_term'][0]->cvterm_id;
  1642. }
  1643. }
  1644. }