tripal_chado.field_storage.inc 63 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799
  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. // Iterate through the field's items. Fields with cardinality ($delta) > 1
  421. // are multi-valued.
  422. $items = field_get_items($entity_type, $entity, $field_name);
  423. $temp = array();
  424. $field_items[$field_name] = $items;
  425. if (is_array($items)) {
  426. foreach ($items as $delta => $item) {
  427. // A field may have multiple items. The field can use items
  428. // indexed with "chado-" to represent values that should map directly
  429. // to chado tables and fields.
  430. $value_set = FALSE;
  431. foreach ($item as $item_name => $value) {
  432. $matches = array();
  433. if (preg_match('/^chado-(.*?)__(.*?)$/', $item_name, $matches)) {
  434. $table_name = $matches[1];
  435. $column_name = $matches[2];
  436. // If this field belongs to the base table then we just add
  437. // those values in... there's no delta.
  438. if ($table_name == $base_table) {
  439. $base_fields[$table_name][$column_name] = $value;
  440. }
  441. else {
  442. $temp[$table_name][$delta][$column_name] = $value;
  443. }
  444. $value_set = TRUE;
  445. }
  446. }
  447. // If there is no value set for the field using the
  448. // chado-[table_name]__[field name] naming schema then check if a 'value'
  449. // item is present and if so use that for the table column value.
  450. if (!$value_set and array_key_exists('value', $items[$delta]) and
  451. !is_array($items[$delta]['value'])) {
  452. // If this field belongs to the base table then we just add
  453. // those values in... there's no delta.
  454. if ($base_table == $chado_table) {
  455. $base_fields[$chado_table][$chado_column] = $item['value'];
  456. }
  457. else {
  458. $temp[$chado_table][$delta][$chado_column] = $item['value'];
  459. }
  460. }
  461. }
  462. // Now merge the records for this field with the $new_fields array
  463. foreach ($temp as $table_name => $details) {
  464. foreach ($details as $delta => $list) {
  465. $all_fields[$table_name][] = $list;
  466. }
  467. }
  468. }
  469. }
  470. $all_fields = array_merge($base_fields, $all_fields);
  471. return [$all_fields, $field_items];
  472. }
  473. /**
  474. * Implements hook_field_storage_query().
  475. */
  476. function tripal_chado_field_storage_query($query) {
  477. // Initialize the result array.
  478. $result = array(
  479. 'TripalEntity' => array()
  480. );
  481. // There must always be an entity filter that includes the bundle. Otherwise
  482. // it would be too overwhelming to search every table of every content type
  483. // for a matching field.
  484. if (!array_key_exists('bundle', $query->entityConditions)) {
  485. return $result;
  486. }
  487. $bundle = tripal_load_bundle_entity(array('name' => $query->entityConditions['bundle']));
  488. if (!$bundle) {
  489. return;
  490. }
  491. $data_table = $bundle->data_table;
  492. $type_column = $bundle->type_column;
  493. $type_id = $bundle->type_id;
  494. $schema = chado_get_schema($data_table);
  495. $pkey = $schema['primary key'][0];
  496. // Initialize the Query object.
  497. $cquery = chado_db_select($data_table, 'base');
  498. $cquery->fields('base', array($pkey));
  499. // Iterate through all the conditions and add to the filters array
  500. // a chado_select_record compatible set of filters.
  501. foreach ($query->fieldConditions as $index => $condition) {
  502. $field = $condition['field'];
  503. $field_name = $field['field_name'];
  504. $field_type = $field['type'];
  505. // Skip conditions that don't belong to this storage type.
  506. if ($field['storage']['type'] != 'field_chado_storage') {
  507. continue;
  508. }
  509. // The Chado settings for a field are part of the instance and each bundle
  510. // can have the same field but with different Chado mappings. Therefore,
  511. // we need to iterate through the bundles to get the field instances.
  512. foreach ($field['bundles']['TripalEntity'] as $bundle_name) {
  513. // If there is a bundle filter for the entity and if the field is not
  514. // associated with the bundle then skip it.
  515. if (array_key_exists('bundle', $query->entityConditions)) {
  516. if (strtolower($query->entityConditions['bundle']['operator']) == 'in' and
  517. !array_key_exists($bundle_name, $query->entityConditions['bundle']['value'])) {
  518. continue;
  519. }
  520. else if ($query->entityConditions['bundle']['value'] != $bundle_name) {
  521. continue;
  522. }
  523. }
  524. // Allow the field to update the query object.
  525. $instance = field_info_instance('TripalEntity', $field['field_name'], $bundle_name);
  526. if (tripal_load_include_field_class($field_type)) {
  527. $field_obj = new $field_type($field, $instance);
  528. $field_obj->query($cquery, $condition);
  529. }
  530. // If there is not a ChadoField class for this field then add the
  531. // condition as is.
  532. else {
  533. $alias = $field['field_name'];
  534. $chado_table = $instance['settings']['chado_table'];
  535. $base_table = $instance['settings']['base_table'];
  536. $bschema = chado_get_schema($base_table);
  537. $bpkey = $bschema['primary key'][0];
  538. if ($chado_table == $base_table) {
  539. // Get the base table column that is associated with the term
  540. // passed as $condition['column'].
  541. $base_field = chado_get_semweb_column($chado_table, $condition['column']);
  542. $matches = array();
  543. $key = $condition['value'];
  544. $op = array_key_exists('operator', $condition) ? $condition['operator'] : '=';
  545. if (preg_match('/^(.+);(.+)$/', $key, $matches)) {
  546. $key = $matches[1];
  547. $op = $matches[2];
  548. }
  549. switch ($op) {
  550. case 'eq':
  551. $op = '=';
  552. break;
  553. case 'gt':
  554. $op = '>';
  555. break;
  556. case 'gte':
  557. $op = '>=';
  558. break;
  559. case 'lt':
  560. $op = '<';
  561. break;
  562. case 'lte':
  563. $op = '<=';
  564. break;
  565. case '<>':
  566. case 'ne':
  567. $op = '!=';
  568. break;
  569. case 'LIKE':
  570. case 'contains':
  571. $op = 'LIKE';
  572. if (!preg_match('/\%/', $key)) {
  573. $key = '%' . $key . '%';
  574. }
  575. break;
  576. case 'NOT LIKE':
  577. $op = 'NOT LIKE';
  578. if (!preg_match('/\%/', $key)) {
  579. $key = '%' . $key . '%';
  580. }
  581. break;
  582. case 'starts':
  583. $op = 'LIKE';
  584. $key = $key . '%';
  585. break;
  586. default:
  587. $op = '=';
  588. }
  589. $cquery->condition('base.' . $base_field , $key, $op);
  590. }
  591. if ($chado_table != $base_table) {
  592. // TODO: I don't think we'll get here because linker fields will
  593. // always have a custom field that should implement a query()
  594. // function. But just in case here's a note to handle it.
  595. }
  596. }
  597. }
  598. } // end foreach ($query->fieldConditions as $index => $condition) {
  599. // Now join with the chado entity table to get published records only.
  600. $chado_entity_table = chado_get_bundle_entity_table($bundle);
  601. $cquery->join($chado_entity_table, 'CE', "CE.record_id = base.$pkey");
  602. $cquery->join('tripal_entity', 'TE', "CE.entity_id = TE.id");
  603. $cquery->fields('CE', array('entity_id'));
  604. $cquery->fields('TE', array('bundle'));
  605. if (array_key_exists('start', $query->range)) {
  606. $cquery->range($query->range['start'], $query->range['length']);
  607. }
  608. // Make sure we only get records of the correct entity type
  609. $cquery->condition('TE.bundle', $query->entityConditions['bundle']['value']);
  610. // Iterate through all the property conditions. These will be filters
  611. // on the tripal_entity table.
  612. foreach ($query->propertyConditions as $index => $condition) {
  613. $cquery->condition('TE.' . $condition['column'], $condition['value']);
  614. }
  615. // If there is an entity_id filter then apply that.
  616. if (array_key_exists('entity_id', $query->entityConditions)) {
  617. $value = $query->entityConditions['entity_id']['value'];
  618. $op = '';
  619. if (array_key_exists('op', $query->entityConditions['entity_id'])) {
  620. $op = $query->entityConditions['entity_id']['op'];
  621. }
  622. // Handle a single entity_id
  623. if (!is_array($value)) {
  624. switch ($op) {
  625. case 'CONTAINS':
  626. $op = 'LIKE';
  627. $value = '%' . $value . '%';
  628. break;
  629. case 'STARTS_WITH':
  630. $op = 'LIKE';
  631. $value = $value . '%';
  632. break;
  633. case 'BETWEEN':
  634. // This case doesn't make sense for a single value. So, just set it
  635. // equal to the end.
  636. $op = '=';
  637. default:
  638. $op = $op ? $op : '=';
  639. }
  640. }
  641. // Handle multiple entitie IDs.
  642. else {
  643. switch ($op) {
  644. case 'CONTAINS':
  645. $op = 'IN';
  646. break;
  647. case 'STARTS_WITH':
  648. $op = 'IN';
  649. break;
  650. case 'BETWEEN':
  651. $op = 'BETWEEN';
  652. default:
  653. $op = 'IN';
  654. }
  655. }
  656. if ($op == 'BETWEEN') {
  657. $cquery->condition('TE.id', $value[0], '>');
  658. $cquery->condition('TE.id', $value[1], '<');
  659. }
  660. else {
  661. $cquery->condition('TE.id', $value, $op);
  662. }
  663. }
  664. // Now set any ordering.
  665. foreach ($query->order as $index => $sort) {
  666. // Add in property ordering.
  667. if ($sort['type'] == 'property') {
  668. // TODO: support ordering by bundle properties.
  669. }
  670. // Add in filter ordering
  671. if ($sort['type'] == 'field') {
  672. $field = $sort['specifier']['field'];
  673. $field_type = $field['type'];
  674. $field_name = $field['field_name'];
  675. // Skip sorts that don't belong to this storage type.
  676. if ($field['storage']['type'] != 'field_chado_storage') {
  677. continue;
  678. }
  679. $column = $sort['specifier']['column'];
  680. $direction = $sort['direction'];
  681. // The Chado settings for a field are part of the instance and each bundle
  682. // can have the same field but with different Chado mappings. Therefore,
  683. // we need to iterate through the bundles to get the field instances.
  684. foreach ($field['bundles']['TripalEntity'] as $bundle_name) {
  685. // If there is a bundle filter for the entity and if the field is not
  686. // associated with the bundle then skip it.
  687. if (array_key_exists('bundle', $query->entityConditions)) {
  688. if (strtolower($query->entityConditions['bundle']['operator']) == 'in' and
  689. !array_key_exists($bundle_name, $query->entityConditions['bundle']['value'])) {
  690. continue;
  691. }
  692. else if ($query->entityConditions['bundle']['value'] != $bundle_name) {
  693. continue;
  694. }
  695. }
  696. // See if there is a ChadoField class for this instance. If not then do
  697. // our best to order the field.
  698. $instance = field_info_instance('TripalEntity', $field_name, $bundle_name);
  699. if (tripal_load_include_field_class($field_type)) {
  700. $field_obj = new $field_type($field, $instance);
  701. $field_obj->queryOrder($cquery, array('column' => $column, 'direction' => $direction));
  702. }
  703. // There is no class so do our best to order the data by this field
  704. else {
  705. $base_table = $instance['settings']['base_table'];
  706. $chado_table = $instance['settings']['chado_table'];
  707. $table_column = chado_get_semweb_column($chado_table, $column);
  708. if ($table_column) {
  709. if ($chado_table == $base_table) {
  710. $cquery->orderBy('base.' . $table_column, $direction);
  711. }
  712. else {
  713. // TODO: how do we handle a field that doesn't map to the base table.
  714. // We would expect that all of these would be custom field and
  715. // the ChadoField::queryOrder() function would be implemented.
  716. }
  717. }
  718. else {
  719. // TODO: handle when the name can't be matched to a table column.
  720. }
  721. }
  722. } // end foreach ($field['bundles']['TripalEntity'] as $bundle_name) {
  723. } // end if ($sort['type'] == 'field') {
  724. } // end foreach ($query->order as $index => $sort) {
  725. // Only include records that are deleted. Tripal doesn't keep track of
  726. // records that are deleted that need purging separately so we can do nothing
  727. // with this.
  728. if (property_exists($query, 'deleted') and $query->deleted) {
  729. // There won't ever be field data marked as deleted so just created a
  730. // condition that always evaluates to false.
  731. $cquery->where('1=0');
  732. }
  733. // Please keep these dpm's they help with debugging
  734. // dpm($cquery->__toString());
  735. // dpm($cquery->getArguments());
  736. $records = $cquery->execute();
  737. // If this is not a count query then return the results.
  738. $result = array();
  739. while ($record = $records->fetchObject()) {
  740. $ids = array($record->entity_id, 0, $record->bundle);
  741. $result['TripalEntity'][$record->entity_id] = entity_create_stub_entity('TripalEntity', $ids);
  742. }
  743. return $result;
  744. }
  745. function tripal_chado_field_storage_bundle_mapping_form_get_defaults($form, $form_state) {
  746. // The term for the content type should already be set in the form state.
  747. $term = $form_state['values']['term'];
  748. // Get the form default values.
  749. $default = array(
  750. 'table' => '',
  751. 'has_all' => '',
  752. 'use_linker' => '',
  753. 'use_prop' => '',
  754. 'type_column' => '',
  755. 'base_selected_term' => '',
  756. 'prop_selected_term' => '',
  757. 'prop_term_value' => '',
  758. 'stage' => 'table-select',
  759. );
  760. // Get the stage.
  761. if (array_key_exists('chado-stage', $form_state)) {
  762. $default['stage'] = $form_state['chado-stage'];
  763. }
  764. if (array_key_exists('base_chado_table', $form_state['values'])
  765. and $form_state['values']['base_chado_table']) {
  766. $default['table'] = $form_state['values']['base_chado_table'];
  767. }
  768. else {
  769. $mapped_table = chado_get_cvterm_mapping(['cvterm_id' => $term->cvterm_id]);
  770. if ($mapped_table) {
  771. $default['table'] = $mapped_table->chado_table;
  772. }
  773. }
  774. if (array_key_exists('chado_table_has_all', $form_state['values'])
  775. and $form_state['values']['chado_table_has_all']) {
  776. $default['has_all'] = $form_state['values']['chado_table_has_all'];
  777. }
  778. if (array_key_exists('chado_type_use_linker', $form_state['values'])
  779. and $form_state['values']['chado_type_use_linker']) {
  780. $default['use_linker'] = $form_state['values']['chado_type_use_linker'];
  781. }
  782. if (array_key_exists('chado_type_use_prop', $form_state['values'])
  783. and $form_state['values']['chado_type_use_prop']) {
  784. $default['use_prop'] = $form_state['values']['chado_type_use_prop'];
  785. }
  786. if (array_key_exists('type_column', $form_state['values'])
  787. and $form_state['values']['type_column']) {
  788. $default['type_column'] = $form_state['values']['type_column'];
  789. }
  790. if (array_key_exists('prop_term_value', $form_state['values'])
  791. and $form_state['values']['prop_term_value']) {
  792. $default['prop_term_value'] = $form_state['values']['prop_term_value'];
  793. }
  794. if (array_key_exists('term_name1', $form_state['values'])) {
  795. $default['base_selected_term'] = tripal_get_term_lookup_form_result($form, $form_state, '', 1);
  796. }
  797. if (array_key_exists('term_name2', $form_state['values'])) {
  798. $default['prop_selected_term'] = tripal_get_term_lookup_form_result($form, $form_state, '', 2);
  799. }
  800. return $default;
  801. }
  802. /**
  803. * Implements hook_field_storage_bundle_mapping_form().
  804. *
  805. * This is a Tripal added hook to the field storage API.
  806. */
  807. function tripal_chado_field_storage_bundle_mapping_form($form, &$form_state, $term, &$submit_disabled) {
  808. $selected_term_id = (is_object($term)) ? $term->cvterm_id : NULL;
  809. $submit_disabled = TRUE;
  810. // Get the form defaults values from the form state.
  811. $default = tripal_chado_field_storage_bundle_mapping_form_get_defaults($form, $form_state);
  812. // Initialize the form.
  813. $form = array();
  814. $form['selected_cvterm_id'] = array(
  815. '#type' => 'value',
  816. '#value' => $selected_term_id,
  817. );
  818. tripal_chado_field_storage_bundle_mapping_form_summary($form, $form_state, $default);
  819. if ($default['stage'] == 'table-select') {
  820. tripal_chado_field_storage_bundle_mapping_form_table_select($form, $form_state, $term, $default);
  821. }
  822. else if ($default['stage'] == 'has-all-select') {
  823. tripal_chado_field_storage_bundle_mapping_form_has_all_select($form, $form_state, $term, $default);
  824. }
  825. else if ($default['stage'] == 'type-select') {
  826. tripal_chado_field_storage_bundle_mapping_form_type_select($form, $form_state, $term, $default);
  827. }
  828. else if ($default['stage'] == 'prop-select') {
  829. tripal_chado_field_storage_bundle_mapping_form_prop_select($form, $form_state, $term, $default);
  830. }
  831. else if ($default['stage'] == 'prop-settings') {
  832. tripal_chado_field_storage_bundle_mapping_form_prop_settings($form, $form_state, $term, $default);
  833. }
  834. else if ($default['stage'] == 'linker-select') {
  835. tripal_chado_field_storage_bundle_mapping_form_linker_select($form, $form_state, $term, $default);
  836. }
  837. else if ($default['stage'] == 'linker-settings') {
  838. tripal_chado_field_storage_bundle_mapping_form_linker_settings($form, $form_state, $term, $default);
  839. }
  840. else if ($default['stage'] == 'complete') {
  841. $submit_disabled = FALSE;
  842. }
  843. $form['chado-settings-reset'] = array(
  844. '#type' => 'submit',
  845. '#value' => t('Reset'),
  846. '#name' => 'chado-settings-reset',
  847. '#validate' => [
  848. 'tripal_chado_field_storage_bundle_mapping_form_validate',
  849. 'tripal_admin_add_type_form_validate'
  850. ],
  851. );
  852. return $form;
  853. }
  854. /**
  855. * Adds form elements for the summary of the selection.
  856. */
  857. function tripal_chado_field_storage_bundle_mapping_form_summary(&$form, &$form_state, $default) {
  858. $rows = [];
  859. $headers = [];
  860. // If we're on the first step then just return, there is no summary.
  861. if ($default['stage'] == 'table-select') {
  862. return;
  863. }
  864. // Make sure the form values are set.
  865. $form['base_chado_table'] = [
  866. '#type' => 'value',
  867. '#value' => $default['table'],
  868. ];
  869. $form['chado_table_has_all'] = [
  870. '#type' => 'value',
  871. '#value' => $default['has_all'],
  872. ];
  873. $form['type_column'] = [
  874. '#type' => 'value',
  875. '#value' => $default['type_column'],
  876. ];
  877. $form['chado_type_use_prop'] = [
  878. '#type' => 'value',
  879. '#value' => $default['use_prop'],
  880. ];
  881. $form['prop_term'] = [
  882. '#type' => 'value',
  883. '#value' => $default['prop_selected_term'],
  884. ];
  885. $form['base_term'] = [
  886. '#type' => 'value',
  887. '#value' => $default['base_selected_term'],
  888. ];
  889. $form['prop_term_value'] = [
  890. '#type' => 'value',
  891. '#value' => $default['prop_term_value'],
  892. ];
  893. $form['chado_type_use_linker'] = [
  894. '#type' => 'value',
  895. '#value' => $default['use_linker'],
  896. ];
  897. //
  898. // Add the base table row.
  899. //
  900. $rows[] = [
  901. [
  902. 'data' => 'Chado Base Table',
  903. 'header' => TRUE,
  904. 'width' => '20%',
  905. ],
  906. $default['table'],
  907. ];
  908. //
  909. // Add the row indicating if all of the records are of the type.
  910. //
  911. if ($default['has_all'] == 'Yes' or $default['has_all'] == 'No') {
  912. $message = 'Yes. All records in the ' . $default['table'] . ' table are of this type.';
  913. if($default['has_all'] == 'No') {
  914. $message = 'No. All records in the ' . $default['table'] . ' table are not of this type.';
  915. }
  916. $rows[] = [
  917. [
  918. 'data' => 'All are of this type?',
  919. 'header' => TRUE,
  920. 'width' => '20%',
  921. ],
  922. $message,
  923. ];
  924. }
  925. //
  926. // Add the row indicating if the type_column is used.
  927. //
  928. if ($default['type_column']) {
  929. $message = $default['type_column'];
  930. if ($default['type_column'] == 'none') {
  931. $message = 'No type column is needed.';
  932. }
  933. $rows[] = [
  934. [
  935. 'data' => 'Type Column',
  936. 'header' => TRUE,
  937. 'width' => '20%',
  938. ],
  939. $message,
  940. ];
  941. }
  942. //
  943. // Add the row indicating that the record can be distinguished with a prop.
  944. //
  945. if ($default['use_prop']) {
  946. $message = 'Yes. The field is distinguishable using a property record.';
  947. if ($default['use_prop'] == 'No') {
  948. $message = 'No. The field is not distinguishable using a property record.';
  949. }
  950. $rows[] = [
  951. [
  952. 'data' => 'Use a property?',
  953. 'header' => TRUE,
  954. 'width' => '20%',
  955. ],
  956. $message,
  957. ];
  958. }
  959. //
  960. // Add the row for the base type for a property mapping
  961. //
  962. if ($default['use_prop'] == 'Yes' and $default['base_selected_term']) {
  963. $term = $default['base_selected_term'][0];
  964. $rows[] = [
  965. [
  966. 'data' => 'Base Type',
  967. 'header' => TRUE,
  968. 'width' => '20%',
  969. ],
  970. $term->name . ' (' . $term->dbxref_id->db_id->name . ':' . $term->dbxref_id->accession .')',
  971. ];
  972. }
  973. //
  974. // Add the row for the type for a property mapping
  975. //
  976. if ($default['prop_selected_term']) {
  977. $term = $default['prop_selected_term'][0];
  978. $rows[] = [
  979. [
  980. 'data' => 'Property Type',
  981. 'header' => TRUE,
  982. 'width' => '20%',
  983. ],
  984. $term->name . ' (' . $term->dbxref_id->db_id->name . ':' . $term->dbxref_id->accession .')',
  985. ];
  986. }
  987. //
  988. // Add the row for the value for a property mapping
  989. //
  990. if ($default['prop_term_value']) {
  991. $rows[] = [
  992. [
  993. 'data' => 'Property Value',
  994. 'header' => TRUE,
  995. 'width' => '20%',
  996. ],
  997. $default['prop_term_value'],
  998. ];
  999. }
  1000. //
  1001. // Add the row for the linker table selection
  1002. //
  1003. if ($default['use_linker']) {
  1004. $message = 'Yes. The field is distinguishable using a cvterm linker table. The Content Type will be used to find records in the linker table';
  1005. if ($default['use_linker'] == 'No') {
  1006. $message = 'No. The field is not distinguishable using a cvterm linker table.';
  1007. }
  1008. $rows[] = [
  1009. [
  1010. 'data' => 'Use a Chado cvterm linker?',
  1011. 'header' => TRUE,
  1012. 'width' => '20%',
  1013. ],
  1014. $message,
  1015. ];
  1016. }
  1017. //
  1018. // Add the row for the base type for a property mapping
  1019. //
  1020. if ($default['use_linker'] == 'Yes' and $default['base_selected_term']) {
  1021. $term = $default['base_selected_term'][0];
  1022. $rows[] = [
  1023. [
  1024. 'data' => 'Base Type',
  1025. 'header' => TRUE,
  1026. 'width' => '20%',
  1027. ],
  1028. $term->name . ' (' . $term->dbxref_id->db_id->name . ':' . $term->dbxref_id->accession .')',
  1029. ];
  1030. }
  1031. $table = array(
  1032. 'header' => $headers,
  1033. 'rows' => $rows,
  1034. 'attributes' => array(
  1035. ),
  1036. 'sticky' => FALSE,
  1037. 'caption' => '',
  1038. 'colgroups' => array(),
  1039. 'empty' => '',
  1040. );
  1041. $form['chado_settings_summary'] = [
  1042. '#type' => 'markup',
  1043. '#markup' => theme_table($table),
  1044. '#weight' => -100,
  1045. ];
  1046. if ($default['stage'] == 'complete') {
  1047. $form['im_ready'] = [
  1048. '#type' => 'markup',
  1049. '#markup' => '<p>Your content type is ready for creation! Please click the "Create Content Type" button below.</p>',
  1050. ];
  1051. }
  1052. if ($default['stage'] == 'stop') {
  1053. $form['im_ready'] = [
  1054. '#type' => 'markup',
  1055. '#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>',
  1056. ];
  1057. }
  1058. }
  1059. /**
  1060. * Adds form elements for Chado table selection step
  1061. */
  1062. function tripal_chado_field_storage_bundle_mapping_form_table_select(&$form, &$form_state, $term, $default) {
  1063. $base_tables = chado_get_base_tables();
  1064. $options = array(0 => '-- Select table --');
  1065. foreach ($base_tables AS $tablename) {
  1066. $options[$tablename] = $tablename;
  1067. }
  1068. $form['base_chado_table'] = array(
  1069. '#type' => 'select',
  1070. '#title' => 'Chado table',
  1071. '#options' => $options,
  1072. '#description' => 'Select the Chado table into which the primary records for this content type will be stored.',
  1073. '#default_value' => $default['table'],
  1074. '#ajax' => array(
  1075. 'callback' => "tripal_admin_add_type_form_ajax_callback",
  1076. 'wrapper' => "tripal-add-type-form",
  1077. 'effect' => 'fade',
  1078. 'method' => 'replace'
  1079. ),
  1080. );
  1081. $form['table-select-continue'] = array(
  1082. '#type' => 'submit',
  1083. '#value' => t('Continue'),
  1084. '#name' => 'chado-table-select-continue',
  1085. '#validate' => [
  1086. 'tripal_chado_field_storage_bundle_mapping_form_validate',
  1087. 'tripal_admin_add_type_form_validate'
  1088. ],
  1089. );
  1090. }
  1091. /**
  1092. * Adds form elements for step 1: Chado type field selection.
  1093. */
  1094. function tripal_chado_field_storage_bundle_mapping_form_has_all_select(&$form, &$form_state, $term, $default) {
  1095. // Get the schema for this table.
  1096. $schema = chado_get_schema($default['table']);
  1097. // If the selected base table is 'cvterm' then handle it specially.
  1098. if ($default['table'] == 'cvterm') {
  1099. tripal_chado_field_storage_bundle_mapping_form_add_cvterm($form,
  1100. $form_state, $term, $default);
  1101. if ($default['use_cvterm'] == 'cv' and $default['cv_id']) {
  1102. $submit_disabled = FALSE;
  1103. }
  1104. if ($default['use_cvterm'] == 'parent') {
  1105. $submit_disabled = FALSE;
  1106. }
  1107. return;
  1108. }
  1109. $term_name = $term->name;
  1110. // Form elements to determine if all records in base table are of this type.
  1111. $form['chado_table_has_all'] = array(
  1112. '#type' => 'radios',
  1113. '#options' => array(
  1114. 'Yes' => 'Yes',
  1115. 'No' => 'No'
  1116. ),
  1117. '#title' => 'Are all records in the "' . $default['table'] .
  1118. '" table of type "'. $term_name . '"?',
  1119. '#description' => 'Select "No" if the "' .
  1120. $default['table'] . '" table houses more than just data of type "' .
  1121. $term_name . '".',
  1122. '#default_value' => $default['has_all'],
  1123. );
  1124. $form['chado-has-all-select-continue'] = array(
  1125. '#type' => 'submit',
  1126. '#value' => t('Continue'),
  1127. '#name' => 'chado-has-all-select-continue',
  1128. '#validate' => [
  1129. 'tripal_chado_field_storage_bundle_mapping_form_validate',
  1130. 'tripal_admin_add_type_form_validate'
  1131. ],
  1132. );
  1133. }
  1134. /*
  1135. // If all the records in the table are of this type then we're done.
  1136. if ($default['has_all'] == 'Yes') {
  1137. $submit_disabled = FALSE;
  1138. return $form;
  1139. }
  1140. // If this table has a field that maps to a cvterm record then we want
  1141. // to ask if the user wants to use that field.
  1142. tripal_chado_field_storage_bundle_mapping_form_add_type($form,
  1143. $form_state, $term, $default);
  1144. // If the type_column is set then we're done! We know the deafult table
  1145. // and column to map this data type.
  1146. if (!empty($default['type_column']) and $default['type_column'] != 'none') {
  1147. $submit_disabled = FALSE;
  1148. return $form;
  1149. }
  1150. // Let's set the names of the linker and prop table for use below.
  1151. $linker_table = $default['table'] . '_cvterm';
  1152. $prop_table = $default['table']. 'prop';
  1153. $linker_exists = chado_table_exists($linker_table);
  1154. $prop_exists = chado_table_exists($prop_table);
  1155. // Ask the user if they want to use a linker table if it exists.
  1156. if ($prop_exists) {
  1157. tripal_chado_field_storage_bundle_mapping_form_add_prop($form,
  1158. $form_state, $term, $prop_table, $default);
  1159. // If the user wants to use the property table then we're done!
  1160. if ($default['use_prop'] == 'Yes') {
  1161. $submit_disabled = FALSE;
  1162. return $form;
  1163. }
  1164. // Ask if the user wants to use the linker table if it exists.
  1165. if ($linker_exists) {
  1166. tripal_chado_field_storage_bundle_mapping_form_add_linker($form,
  1167. $form_state, $term, $linker_table, $default);
  1168. // If the user wants to use the linker table then we're done!
  1169. if ($default['use_linker'] == 'Yes') {
  1170. $submit_disabled = FALSE;
  1171. return $form;
  1172. }
  1173. }
  1174. }
  1175. // A prop table doesn't exist then ask the user if they want
  1176. // to use the linker table to associate records.
  1177. else if ($linker_exists) {
  1178. tripal_chado_field_storage_bundle_mapping_form_add_prop($form,
  1179. $form_state, $term, $prop_table, $default);
  1180. // If the user wants to use the linker table then we're done!
  1181. if ($default['use_linker'] == 'Yes') {
  1182. $submit_disabled = FALSE;
  1183. return $form;
  1184. }
  1185. }
  1186. $form['notice'] = array(
  1187. '#type' => 'item',
  1188. '#markup' => '<font color="red">Unfortunately, the options selected above do not allow for mapping of this content type to records in Chado.</font>'
  1189. );
  1190. return $form;
  1191. }
  1192. */
  1193. /**
  1194. * Adds form elements for step 1: Chado type field selection.
  1195. */
  1196. function tripal_chado_field_storage_bundle_mapping_form_type_select(&$form, &$form_state, $term, $default) {
  1197. $term_name = $term->name;
  1198. $column_options = tripal_chado_field_storage_bundle_mapping_form_get_type_fks_options($default['table']);
  1199. $default_column = !empty($default['type_column']) ? $default['type_column'] : 'type_id';
  1200. $form['type_column'] = array(
  1201. '#type' => 'select',
  1202. '#title' => 'Type Column',
  1203. '#options' => $column_options,
  1204. '#description' => 'Please select the column in the "' .
  1205. $default['table'] . '" table that will identify a record as being of type "' .
  1206. $term_name . '". If you select "--None--" then you will be asked
  1207. if the type can be identified using a property or linker table.
  1208. Only fields that have a foreign key to the cvterm table will be listed.',
  1209. '#default_value' => $default_column
  1210. );
  1211. $form['chado-type-select-continue'] = array(
  1212. '#type' => 'submit',
  1213. '#value' => t('Continue'),
  1214. '#name' => 'chado-type-select-continue',
  1215. '#validate' => [
  1216. 'tripal_chado_field_storage_bundle_mapping_form_validate',
  1217. 'tripal_admin_add_type_form_validate'
  1218. ],
  1219. );
  1220. }
  1221. /**
  1222. *
  1223. */
  1224. function tripal_chado_field_storage_bundle_mapping_form_prop_select(&$form, &$form_state, $term, $default) {
  1225. $prop_table = $default['table']. 'prop';
  1226. $form['chado_type_use_prop'] = array(
  1227. '#type' => 'radios',
  1228. '#title' => 'Do you want to use the "' . $prop_table . '" table
  1229. to distinguish between content types?',
  1230. '#options' => array(
  1231. 'Yes' => 'Yes',
  1232. 'No' => 'No'
  1233. ),
  1234. '#description' => t('Sometimes records can be distringuished
  1235. using a value in property table, especially if there is no column
  1236. in the specified Chado table to identify the
  1237. record type. In these cases the property table can be used.'),
  1238. '#default_value' => $default['use_prop'],
  1239. );
  1240. $form['chado-prop-select-continue'] = array(
  1241. '#type' => 'submit',
  1242. '#value' => t('Continue'),
  1243. '#name' => 'chado-prop-select-continue',
  1244. '#validate' => [
  1245. 'tripal_chado_field_storage_bundle_mapping_form_validate',
  1246. 'tripal_admin_add_type_form_validate'
  1247. ],
  1248. );
  1249. }
  1250. function tripal_chado_field_storage_bundle_mapping_form_prop_settings(&$form, &$form_state, $term, $default){
  1251. $prop_term_value = $default['prop_term_value'];
  1252. $base_type_column = tripal_chado_field_storage_bundle_mapping_form_get_base_type_column($default['table']);
  1253. $validate =[
  1254. 'tripal_chado_field_storage_bundle_mapping_form_validate',
  1255. 'tripal_admin_add_type_form_validate'
  1256. ];
  1257. if ($base_type_column) {
  1258. $description = t('The ' . $default['table'] . ' table of Chado requires
  1259. that each record have a type. You have indicated that this
  1260. content type is not distinguished by a column in the base tabe but
  1261. instead by a property. However, the ' . $default['table'] . ' table requires
  1262. that a value be given for the ' . $base_type_column . '. Please indicate
  1263. what this type should be. For example, suppose this content type is a SNP (SO:0000694) and
  1264. you store SNPs in Chado in the feature table as "genetic_marker" (SO:0001645), however
  1265. the record is defined as a SNP through a corresponding record in the featurprop
  1266. table that has a type of "type" (rdfs:type) and a value of "SNP".
  1267. In this case the content type should be SNP (SO:0001645) and here the
  1268. "genetic_marker" (SO:0001645) term should be provided. The "type" term
  1269. should be used in the Property Type field below and "SNP" as the Property Value.');
  1270. tripal_get_term_lookup_form($form, $form_state, '',
  1271. 'Base Type', $description, FALSE, '', 1,
  1272. 'tripal_admin_add_type_form_ajax_callback', 'tripal-add-type-form',
  1273. $validate, -2);
  1274. }
  1275. // We need a term lookup form for the property type.
  1276. $description = t('The content type "' . $term->name . '" must be
  1277. associated with a property type. The property type must be the
  1278. name of a term in a controlled vocabulary and the controlled
  1279. vocabulary should already be loaded into Tripal. Please select
  1280. the property type that will be used to identify records of this
  1281. type');
  1282. tripal_get_term_lookup_form($form, $form_state, '',
  1283. 'Property Type', $description, FALSE, '', 2,
  1284. 'tripal_admin_add_type_form_ajax_callback', 'tripal-add-type-form',
  1285. $validate, -8);
  1286. $form['prop_term_value'] = array(
  1287. '#type' => 'textfield',
  1288. '#title' => 'Property Value',
  1289. '#description' => t('All properties have a type and a value. Above you
  1290. indicated the type of property. Now you must specify the value
  1291. that this properly must have in order to be considered of
  1292. type "' . $term->name . '".'),
  1293. '#default_value' => $prop_term_value,
  1294. );
  1295. $form['chado-prop-settings-continue'] = array(
  1296. '#type' => 'submit',
  1297. '#value' => t('Continue'),
  1298. '#name' => 'chado-prop-settings-continue',
  1299. '#validate' => [
  1300. 'tripal_chado_field_storage_bundle_mapping_form_validate',
  1301. 'tripal_admin_add_type_form_validate'
  1302. ],
  1303. );
  1304. }
  1305. /**
  1306. *
  1307. */
  1308. function tripal_chado_field_storage_bundle_mapping_form_linker_select(&$form, &$form_state, $term, $default) {
  1309. $linker_table = $default['table'] . '_cvterm';
  1310. $form['chado_type_use_linker'] = array(
  1311. '#type' => 'radios',
  1312. '#title' => 'Do you want to use the "' . $linker_table . '" table
  1313. to distinguish between content types?',
  1314. '#options' => array(
  1315. 'Yes' => 'Yes',
  1316. 'No' => 'No'
  1317. ),
  1318. '#description' => t('Sometimes records can be distringuished
  1319. using a linker table, especially if there is no column
  1320. in the specified Chado table to identify the
  1321. record type. In these cases the linker table can be used.'),
  1322. '#default_value' => $default['use_linker'],
  1323. );
  1324. $form['chado-linker-select-continue'] = array(
  1325. '#type' => 'submit',
  1326. '#value' => t('Continue'),
  1327. '#name' => 'chado-linker-select-continue',
  1328. '#validate' => [
  1329. 'tripal_chado_field_storage_bundle_mapping_form_validate',
  1330. 'tripal_admin_add_type_form_validate'
  1331. ],
  1332. );
  1333. }
  1334. /**
  1335. *
  1336. */
  1337. function tripal_chado_field_storage_bundle_mapping_form_linker_settings(&$form, &$form_state, $term, $default){
  1338. $base_type_column = tripal_chado_field_storage_bundle_mapping_form_get_base_type_column($default['table']);
  1339. $validate =[
  1340. 'tripal_chado_field_storage_bundle_mapping_form_validate',
  1341. 'tripal_admin_add_type_form_validate'
  1342. ];
  1343. $description = t('The ' . $default['table'] . ' table of Chado requires
  1344. that each record have a type. You have indicated that this
  1345. content type is not distinguished by a column in the base tabe but
  1346. instead by a cvterm linker table. However, the ' . $default['table'] . ' table requires
  1347. that a value be given for the ' . $base_type_column . '. Please indicate
  1348. what this type should be.');
  1349. tripal_get_term_lookup_form($form, $form_state, '',
  1350. 'Base Type', $description, FALSE, '', 1,
  1351. 'tripal_admin_add_type_form_ajax_callback', 'tripal-add-type-form',
  1352. $validate, -10);
  1353. $form['chado-linker-settings-continue'] = array(
  1354. '#type' => 'submit',
  1355. '#value' => t('Continue'),
  1356. '#name' => 'chado-linker-settings-continue',
  1357. '#validate' => [
  1358. 'tripal_chado_field_storage_bundle_mapping_form_validate',
  1359. 'tripal_admin_add_type_form_validate'
  1360. ],
  1361. );
  1362. }
  1363. /**
  1364. *
  1365. */
  1366. function tripal_chado_field_storage_bundle_mapping_form_get_type_fks_options($table) {
  1367. // Get the list of columns in the default table.
  1368. $schema = chado_get_schema($table);
  1369. $column_options = array('none' => '--None--');
  1370. $cvt_fkeys = (isset($schema['foreign keys']['cvterm'])) ? array_keys($schema['foreign keys']['cvterm']['columns']) : array();
  1371. foreach ($schema['fields'] as $column_name => $column_details) {
  1372. if (in_array($column_name, $cvt_fkeys)) {
  1373. $column_options[$column_name] = $column_name;
  1374. }
  1375. }
  1376. return $column_options;
  1377. }
  1378. /**
  1379. *
  1380. */
  1381. function tripal_chado_field_storage_bundle_mapping_form_get_base_type_column($table) {
  1382. // If a base table has a 'type_id' field then we must have the user
  1383. // specify the base table type as well.
  1384. $base_type_column = FALSE;
  1385. $schema = chado_get_schema($table);
  1386. foreach ($schema['foreign keys'] as $fk_id => $details) {
  1387. if ($details['table'] == 'cvterm') {
  1388. foreach ($details['columns'] as $fk_left => $fk_right) {
  1389. if ($fk_left == 'type_id') {
  1390. $base_type_column = 'type_id';
  1391. }
  1392. }
  1393. }
  1394. }
  1395. return $base_type_column;
  1396. }
  1397. /**
  1398. * Implements hook_field_stoage_bundle_mapping_form_validate().
  1399. */
  1400. function tripal_chado_field_storage_bundle_mapping_form_validate($form, &$form_state) {
  1401. // Don't do validation on an ajax callback.
  1402. if (array_key_exists('#ajax', $form_state['triggering_element'])) {
  1403. return;
  1404. }
  1405. // Get the form values.
  1406. $default = tripal_chado_field_storage_bundle_mapping_form_get_defaults($form, $form_state);
  1407. $clicked_button = $form_state['clicked_button']['#name'];
  1408. // Check if prop and linker tables exist. We'll use these values later.
  1409. $prop_table = $default['table'] . 'prop';
  1410. $prop_exists = chado_table_exists($prop_table);
  1411. $linker_table = $default['table'] . '_cvterm';
  1412. $linker_exists = chado_table_exists($linker_table);
  1413. //
  1414. // Valiate the table select stage
  1415. //
  1416. if ($clicked_button == 'chado-table-select-continue') {
  1417. // Make sure a default table is selected
  1418. if (!$default['table']) {
  1419. form_set_error('base_chado_table', 'Please select a default table.');
  1420. return;
  1421. }
  1422. $form_state['chado-stage'] = 'has-all-select';
  1423. }
  1424. //
  1425. // Valiate the has all select stage
  1426. //
  1427. if ($clicked_button == 'chado-has-all-select-continue') {
  1428. if ($default['has_all'] == 'Yes') {
  1429. $form_state['chado-stage'] = 'complete';
  1430. }
  1431. else {
  1432. $column_options = tripal_chado_field_storage_bundle_mapping_form_get_type_fks_options($default['table']);
  1433. // If this table has fields that link to the cvterm table then
  1434. // let the user select the type column. The column_options is empty if
  1435. // it equals 1 because it has the --none-- element.
  1436. if (count($column_options) > 1) {
  1437. $form_state['chado-stage'] = 'type-select';
  1438. }
  1439. // Otherwise, see if there are other options....
  1440. else {
  1441. // If there is no type_id or the type_id column should not be
  1442. // used then we need to let the user select if they want to
  1443. // use the prop table or a cvterm linking table. We'll offer the
  1444. // prop table first.
  1445. if ($prop_exists) {
  1446. $form_state['chado-stage'] = 'prop-select';
  1447. }
  1448. else {
  1449. if ($linker_exists) {
  1450. $form_state['chado-stage'] = 'linker-select';
  1451. }
  1452. else {
  1453. $form_state['chado-stage'] = 'stop';
  1454. }
  1455. }
  1456. }
  1457. }
  1458. }
  1459. //
  1460. // Valiate the type select stage
  1461. //
  1462. if ($clicked_button == 'chado-type-select-continue') {
  1463. if ($default['type_column'] != 'none') {
  1464. $form_state['chado-stage'] = 'complete';
  1465. }
  1466. else {
  1467. // If there is no type_id or the type_id column should not be
  1468. // used then we need to let the user select if they want to
  1469. // use the prop table or a cvterm linking table. We'll offer the
  1470. // prop table first.
  1471. if ($prop_exists) {
  1472. $form_state['chado-stage'] = 'prop-select';
  1473. }
  1474. else {
  1475. if ($linker_exists) {
  1476. $form_state['chado-stage'] = 'linker-select';
  1477. }
  1478. else {
  1479. $form_state['chado-stage'] = 'stop';
  1480. }
  1481. }
  1482. }
  1483. }
  1484. //
  1485. // Valiate the property select stage
  1486. //
  1487. if ($clicked_button == 'chado-prop-select-continue') {
  1488. if ($default['use_prop'] == 'Yes') {
  1489. $form_state['chado-stage'] = 'prop-settings';
  1490. }
  1491. else if ($default['use_prop'] == 'No') {
  1492. if ($linker_exists) {
  1493. $form_state['chado-stage'] = 'linker-select';
  1494. }
  1495. else {
  1496. $form_state['chado-stage'] = 'stop';
  1497. }
  1498. }
  1499. else {
  1500. form_set_error('chado_type_use_prop', 'Please select a value.');
  1501. }
  1502. }
  1503. //
  1504. // Validate the property settings stage
  1505. //
  1506. if ($clicked_button == 'chado-prop-settings-continue') {
  1507. // If a base type was needed then make sure we have a value selected.
  1508. $valid = TRUE;
  1509. if (array_key_exists('term_name1', $form_state['values'])) {
  1510. $base_selected = $default['base_selected_term'];
  1511. if (count($base_selected) == 0) {
  1512. form_set_error('term_match1][term_name1', 'Please select a base table type vocabulary term.');
  1513. $valid = FALSE;
  1514. }
  1515. if (count($base_selected) > 1) {
  1516. form_set_error('term_match1][term_name1', 'Please select only one base table type vocabulary term.');
  1517. $valid = FALSE;
  1518. }
  1519. }
  1520. // Make sure we only have one property type selected
  1521. $prop_selected = $default['prop_selected_term'];
  1522. if (count($prop_selected) == 0) {
  1523. form_set_error('term_match2][term_name2', 'Please select a prpoerty type vocabulary term.');
  1524. $valid = FALSE;
  1525. }
  1526. if (count($prop_selected) > 1) {
  1527. form_set_error('term_match2][term_name2', 'Please select only one property type vocabulary term.');
  1528. $valid = FALSE;
  1529. }
  1530. if (!$default['prop_term_value']) {
  1531. form_set_error('prop_term_value', 'Please provide a property value.');
  1532. $valid = FALSE;
  1533. }
  1534. if (!$valid) {
  1535. return;
  1536. }
  1537. // If we're here then alll validations passed and we are good to go!
  1538. $form_state['chado-stage'] = 'complete';
  1539. }
  1540. //
  1541. // Validate the linker settings stage
  1542. //
  1543. if ($clicked_button == 'chado-linker-select-continue') {
  1544. if ($default['use_linker'] == 'Yes') {
  1545. // If our base table has a type_id then we need need to make the
  1546. // user provide a value for it, otherwise we're done.
  1547. $base_type_column = tripal_chado_field_storage_bundle_mapping_form_get_base_type_column($default['table']);
  1548. if ($base_type_column) {
  1549. $form_state['chado-stage'] = 'linker-settings';
  1550. }
  1551. else {
  1552. $form_state['chado-stage'] = 'complete';
  1553. }
  1554. }
  1555. else if ($default['use_linker'] == 'No') {
  1556. $form_state['chado-stage'] = 'stop';
  1557. }
  1558. else {
  1559. form_set_error('chado_type_use_linker', 'Please select a value.');
  1560. }
  1561. }
  1562. if ($clicked_button == 'chado-linker-settings-continue') {
  1563. $valid = TRUE;
  1564. if (array_key_exists('term_name1', $form_state['values'])) {
  1565. $base_selected = $default['base_selected_term'];
  1566. if (count($base_selected) == 0) {
  1567. form_set_error('term_match1][term_name1', 'Please select a base table type vocabulary term.');
  1568. $valid = FALSE;
  1569. }
  1570. if (count($base_selected) > 1) {
  1571. form_set_error('term_match1][term_name1', 'Please select only one base table type vocabulary term.');
  1572. $valid = FALSE;
  1573. }
  1574. }
  1575. if (!$valid) {
  1576. return;
  1577. }
  1578. // If we're here then alll validations passed and we are good to go!
  1579. $form_state['chado-stage'] = 'complete';
  1580. }
  1581. //
  1582. // Check for a reset.
  1583. //
  1584. if ($clicked_button == 'chado-settings-reset') {
  1585. $form_state['chado-stage'] = 'table-select';
  1586. $valid = FALSE;
  1587. }
  1588. }
  1589. /**
  1590. * Implements hook_field_stoage_bundle_mapping_form_submit().
  1591. *
  1592. * Here we do no action on submit other than set the storage_args
  1593. * variable that is passed by reference.
  1594. */
  1595. function tripal_chado_field_storage_bundle_mapping_form_submit($form,
  1596. &$form_state, $term, &$storage_args) {
  1597. $default = tripal_chado_field_storage_bundle_mapping_form_get_defaults($form, $form_state);
  1598. // If we have a type_column then we know this type uses a column in the
  1599. // base table, so we can set the storage args and return.
  1600. if ($default['type_column'] and $default['type_column'] != 'none') {
  1601. $storage_args['data_table'] = $default['table'];
  1602. $storage_args['type_column'] = $default['type_column'];
  1603. return;
  1604. }
  1605. // If the user indicated that all the records in a table are of this type.
  1606. if ($default['has_all'] == 'Yes') {
  1607. $storage_args['data_table'] = $default['table'];
  1608. $storage_args['type_id'] = $form_state['values']['selected_cvterm_id'];
  1609. $storage_args['type_linker_table'] = '';
  1610. $storage_args['type_column'] = '';
  1611. $storage_args['type_value'] = '';
  1612. }
  1613. // If the user indicated they wanted to use the prop table then we'll
  1614. // set the storage args and return.
  1615. else if ($default['use_prop'] == 'Yes') {
  1616. $storage_args['data_table'] = $default['table'];
  1617. $storage_args['type_linker_table'] = $default['table'] . 'prop';
  1618. $storage_args['type_column'] = 'type_id';
  1619. $storage_args['type_id'] = $form_state['values']['prop_term'][0]->cvterm_id;
  1620. $storage_args['type_value'] = $default['prop_term_value'];
  1621. if (is_array($form_state['values']['base_term'])) {
  1622. $storage_args['base_type_id'] = $form_state['values']['base_term'][0]->cvterm_id;
  1623. }
  1624. }
  1625. // If the user indicated they wanted to use the linker tables then we'll
  1626. // set the storage args and return.
  1627. else if ($default['use_linker'] == 'Yes') {
  1628. $storage_args['data_table'] = $default['table'];
  1629. $storage_args['type_id'] = $form_state['values']['selected_cvterm_id'];
  1630. $storage_args['type_linker_table'] = $default['table'] . '_cvterm';
  1631. $storage_args['type_column'] = 'cvterm_id';
  1632. if (is_array($form_state['values']['base_term'])) {
  1633. $storage_args['base_type_id'] = $form_state['values']['base_term'][0]->cvterm_id;
  1634. }
  1635. }
  1636. }