tripal_bulk_loader.loader.inc 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628
  1. <?php
  2. /**
  3. * @file
  4. * @todo Add file header description
  5. */
  6. /**
  7. * Add Loader Job Form
  8. *
  9. * This form is meant to be included on the node page to allow users to submit/re-submit
  10. * loading jobs
  11. */
  12. function tripal_bulk_loader_add_loader_job_form($form_state, $node) {
  13. $form = array();
  14. $form['nid'] = array(
  15. '#type' => 'hidden',
  16. '#value' => $node->nid,
  17. );
  18. $form['file'] = array(
  19. '#type' => 'hidden',
  20. '#value' => $node->file
  21. );
  22. $form['job_id'] = array(
  23. '#type' => 'hidden',
  24. '#value' => $node->job_id,
  25. );
  26. $form['submit'] = array(
  27. '#type' => 'submit',
  28. '#value' => ($node->job_id) ? 'Re-Submit Job' : 'Submit Job',
  29. );
  30. $form['submit-cancel'] = array(
  31. '#type' => ($node->job_id)? 'submit' : 'hidden',
  32. '#value' => 'Cancel Job',
  33. );
  34. $form['submit-revert'] = array(
  35. '#type' => ($node->job_id) ? 'submit' : 'hidden',
  36. '#value' => 'Revert',
  37. );
  38. return $form;
  39. }
  40. /**
  41. * Add Loader Job Form (Submit)
  42. */
  43. function tripal_bulk_loader_add_loader_job_form_submit($form, $form_state) {
  44. global $user;
  45. if (preg_match('/Submit Job/', $form_state['values']['op'])) {
  46. //Submit Tripal Job
  47. $job_args[1] = $form_state['values']['nid'];
  48. if (is_readable($form_state['values']['file'])) {
  49. $fname = basename($form_state['values']['file']);
  50. $job_id = tripal_add_job("Bulk Loading Job: $fname", 'tripal_bulk_loader', 'tripal_bulk_loader_load_data', $job_args, $user->uid);
  51. // add job_id to bulk_loader node
  52. $success = db_query("UPDATE {tripal_bulk_loader} SET job_id=%d WHERE nid=%d", $job_id, $form_state['values']['nid']);
  53. // change status
  54. db_query("UPDATE {tripal_bulk_loader} SET job_status='%s' WHERE nid=%d", 'Submitted to Queue', $form_state['values']['nid']);
  55. }
  56. else {
  57. drupal_set_message(t("Can not open %file. Job not scheduled.", array('%file' => $form_state['values']['file'])));
  58. }
  59. }
  60. elseif (preg_match('/Re-Submit Job/', $form_state['values']['op'])) {
  61. tripal_jobs_rerun($form_state['values']['job_id']);
  62. db_query("UPDATE {tripal_bulk_loader} SET job_status='%s' WHERE nid=%d", 'Submitted to Queue', $form_state['values']['nid']);
  63. }
  64. elseif (preg_match('/Cancel Job/', $form_state['values']['op'])) {
  65. db_query("UPDATE {tripal_bulk_loader} SET job_status='%s' WHERE nid=%d", 'Job Cancelled', $form_state['values']['nid']);
  66. tripal_jobs_cancel($form_state['values']['job_id']);
  67. }
  68. elseif (preg_match('/Revert/', $form_state['values']['op'])) {
  69. // Remove the records from the database that were already inserted
  70. $resource = db_query('SELECT * FROM {tripal_bulk_loader_inserted} WHERE nid=%d ORDER BY tripal_bulk_loader_inserted_id DESC', $form_state['values']['nid']);
  71. while ($r = db_fetch_object($resource)) {
  72. $ids = preg_split('/,/', $r->ids_inserted);
  73. db_query('DELETE FROM %s WHERE %s IN (%s)', $r->table_inserted_into, $r->table_primary_key, $r->ids_inserted);
  74. $result = db_fetch_object(db_query('SELECT true as present FROM %s WHERE %s IN (%s)', $r->table_inserted_into, $r->table_primary_key, $r->ids_inserted));
  75. if (!$result->present) {
  76. drupal_set_message(t('Successfully Removed data Inserted into the %tableto table.', array('%tableto' => $r->table_inserted_into)));
  77. db_query('DELETE FROM {tripal_bulk_loader_inserted} WHERE tripal_bulk_loader_inserted_id=%d', $r->tripal_bulk_loader_inserted_id);
  78. }
  79. else {
  80. drupal_set_message(t('Unable to remove data Inserted into the %tableto table!', array('%tableto' => $r->table_inserted_into)), 'error');
  81. }
  82. }
  83. // reset status
  84. db_query("UPDATE {tripal_bulk_loader} SET job_status='%s' WHERE nid=%d", 'Reverted -Data Deleted', $form_state['values']['nid']);
  85. }
  86. }
  87. /**
  88. * Tripal Bulk Loader
  89. *
  90. * This is the function that's run by tripal_launch_jobs to bulk load chado data.
  91. *
  92. * @param $nid
  93. * The Node ID of the bulk loading job node to be loaded. All other needed data is expected to be
  94. * in the node (ie: template ID and file)
  95. *
  96. * Note: Instead of returning a value this function updates the tripal_bulk_loader.status.
  97. * Errors are thrown through watchdog and can be viewed at admin/reports/dblog.
  98. */
  99. function tripal_bulk_loader_load_data($nid) {
  100. // ensure no timeout
  101. set_time_limit(0);
  102. // set the status of the job (in the node not the tripal jobs)
  103. db_query("UPDATE {tripal_bulk_loader} SET job_status='%s' WHERE nid=%d", 'Loading...', $nid);
  104. $node = node_load($nid);
  105. print "Template: " . $node->template->name . " (" . $node->template_id . ")\n";
  106. $total_lines = trim(`wc --lines < $node->file`);
  107. print "File: " . $node->file . " (" . $total_lines . " lines)\n";
  108. // Prep Work ==================================================================================
  109. $loaded_without_errors = TRUE;
  110. // Generate default values array
  111. $default_data = array();
  112. $field2column = array();
  113. $record2priority = array();
  114. foreach ($node->template->template_array as $priority => $record_array) {
  115. if (!is_array($record_array)) {
  116. continue;
  117. }
  118. //watchdog('T_bulk_loader','1)'.$record_array['record_id']." => \n<pre>".print_r($record_array,TRUE).'</pre>', array(), WATCHDOG_NOTICE);
  119. foreach ($record_array['fields'] as $field_index => $field_array) {
  120. $default_data[$priority]['table'] = $record_array['table'];
  121. $default_data[$priority]['mode'] = ($record_array['mode']) ? $record_array['mode'] : 'insert_unique';
  122. $default_data[$priority]['record_id'] = $record_array['record_id'];
  123. $record2priority[$record_array['record_id']] = $priority;
  124. $default_data[$priority]['required'][$field_array['field']] = $field_array['required'];
  125. $one = $default_data[$priority];
  126. if (isset($field_array['regex'])) {
  127. $default_data[$priority]['regex_transform'][$field_array['field']] = $field_array['regex'];
  128. }
  129. $two = $default_data[$priority];
  130. if (preg_match('/table field/', $field_array['type'])) {
  131. $default_data[$priority]['values_array'][$field_array['field']] = '';
  132. $default_data[$priority]['need_further_processing'] = TRUE;
  133. $field2column[$priority][$field_array['field']] = $field_array['spreadsheet column'];
  134. }
  135. elseif (preg_match('/constant/', $field_array['type'])) {
  136. $default_data[$priority]['values_array'][$field_array['field']] = $field_array['constant value'];
  137. }
  138. elseif (preg_match('/foreign key/', $field_array['type'])) {
  139. $default_data[$priority]['values_array'][$field_array['field']] = array();
  140. $default_data[$priority]['values_array'][$field_array['field']]['foreign record'] = $field_array['foreign key'];
  141. $default_data[$priority]['need_further_processing'] = TRUE;
  142. }
  143. else {
  144. print 'WARNING: Unsupported type: ' . $field_array['type'] . ' for ' . $table . '.' . $field_array['field'] . "!\n";
  145. }
  146. $three = $default_data[$priority];
  147. //watchdog('T_bulk_loader','A)'.$field_index.':<pre>Field Array =>'.print_r($field_array,TRUE)."Initial => \n".print_r($one, TRUE)."\nAfter Regex =>".print_r($two, TRUE)."Final =>\n".print_r($three,TRUE).'</pre>', array(), WATCHDOG_NOTICE);
  148. } // end of foreach field
  149. //watchdog('T_bulk_loader','2)'.$record_array['record_id'].':<pre>'.print_r($default_data[$priority], TRUE).'</pre>', array(), WATCHDOG_NOTICE);
  150. } //end of foreach record
  151. ///////////////////////////////////////////////
  152. // For each set of constants
  153. ///////////////////////////////////////////////
  154. $original_default_data = $default_data;
  155. $group_index = 0;
  156. $total_num_groups = sizeof($node->constants);
  157. foreach ($node->constants as $group_id => $set) {
  158. // revert default data array for next set of constants
  159. $default_data = $original_default_data;
  160. $group_index++;
  161. // Add constants
  162. if (!empty($set)) {
  163. print "Constants:\n";
  164. foreach ($set as $priority => $record) {
  165. foreach ($record as $field_id => $field) {
  166. print "\t- " . $field['chado_table'] . '.' . $field['chado_field'] . ' = ' . $field['value'] . "\n";
  167. if ($default_data[$priority]['table'] == $field['chado_table']) {
  168. if (isset($default_data[$priority]['values_array'][$field['chado_field']])) {
  169. if (isset($field2column[$priority][$field['chado_field']])) {
  170. $field2column[$priority][$field['chado_field']] = $field['value'];
  171. }
  172. else {
  173. $default_data[$priority]['values_array'][$field['chado_field']] = $field['value'];
  174. }
  175. }
  176. else {
  177. print "ERROR: Template has changed after constants were assigned!\n";
  178. watchdog('T_bulk_loader', 'Template has changed after constants were assigned', array(), WATCHDOG_NOTICE);
  179. exit(1);
  180. }
  181. }
  182. else {
  183. print "ERROR: Template has changed after constants were assigned!\n";
  184. watchdog('T_bulk_loader', 'Template has changed after constants were assigned', array(), WATCHDOG_NOTICE);
  185. exit(1);
  186. }
  187. }
  188. }
  189. }
  190. //print "Default Data:".print_r($default_data,TRUE)."\n";
  191. //watchdog('T_bulk_loader','Default Data:<pre>'.print_r($default_data, TRUE).'</pre>', array(), WATCHDOG_NOTICE);
  192. //print "\nDefault Values Array: ".print_r($default_data, TRUE)."\n";
  193. //print "\nField to Column Mapping: ".print_r($field2column, TRUE)."\n";
  194. // Parse File adding records as we go ========================================================
  195. $file_handle = fopen($node->file, 'r');
  196. if (preg_match('/(t|true|1)/', $node->file_has_header)) {
  197. fgets($file_handle, 4096);
  198. }
  199. $num_records = 0;
  200. $num_lines = 0;
  201. $num_errors = 0;
  202. $interval = intval($total_lines * 0.10);
  203. if ($interval == 0) {
  204. $interval = 1;
  205. }
  206. while (!feof($file_handle)) {
  207. // Clear variables
  208. // Was added to fix memory leak
  209. unset($line); unset($raw_line);
  210. unset($data); unset($data_keys);
  211. unset($priority); unset($sql);
  212. unset($result);
  213. $raw_line = fgets($file_handle, 4096);
  214. $raw_line = trim($raw_line);
  215. if (empty($raw_line)) {
  216. continue;
  217. } // skips blank lines
  218. $line = explode("\t", $raw_line);
  219. $num_lines++;
  220. // update the job status every 10% of lines processed for the current group
  221. if ($node->job_id and $num_lines % $interval == 0) {
  222. // percentage of lines processed for the current group
  223. $group_progress = round(($num_lines/$total_lines)*100);
  224. // percentage of lines processed for all groups
  225. // <previous group index> * 100 + <current group progress>
  226. // --------------------------------------------------------
  227. // <total number of groups>
  228. // For example, if you were in the third group of 3 constant sets
  229. // and had a group percentage of 50% then the job progress would be
  230. // (2*100 + 50%) / 3 = 250%/3 = 83%
  231. $job_progress = round(((($group_index-1)*100)+$group_progress)/$total_num_groups);
  232. /**
  233. print "\nProgress Update:\n"
  234. ."\t- ".$num_lines." lines have been processed for the current constant set.\n"
  235. ."\t- ".$group_progress."% of the lines in the file have been processed for the current constant set.\n"
  236. ."\t- ".$job_progress."% of the current job has been completed.\n";
  237. */
  238. tripal_job_set_progress($node->job_id, $job_progress);
  239. }
  240. $data = $default_data;
  241. $data_keys = array_keys($data);
  242. foreach ($data_keys as $priority) {
  243. $status = process_data_array_for_line($priority, $data, $default_data, $field2column, $record2priority, $line, $nid, $num_lines, $group_index);
  244. if (!$status ) {
  245. $loaded_without_errors = FALSE;
  246. }
  247. } // end of foreach table in default data array
  248. } //end of foreach line of file
  249. } //end of foreach constant set
  250. // check that data was inserted and update job_status
  251. $sql = 'SELECT count(*) as num_tables FROM {tripal_bulk_loader_inserted} WHERE nid=%d GROUP BY nid';
  252. $result = db_fetch_object(db_query($sql, $nid));
  253. if ($result->num_tables > 0) {
  254. $node->job_status = 'Data Inserted';
  255. drupal_write_record('node', $node, 'nid');
  256. }
  257. // set the status of the job (in the node not the tripal jobs)
  258. if ($loaded_without_errors) {
  259. $status = 'Loading Completed Successfully';
  260. }
  261. else {
  262. $status = 'Errors Encountered';
  263. }
  264. db_query("UPDATE {tripal_bulk_loader} SET job_status='%s' WHERE nid=%d", $status, $nid);
  265. }
  266. /**
  267. *
  268. *
  269. */
  270. function process_data_array_for_line($priority, &$data, &$default_data, $field2column, $record2priority, $line, $nid, $line_num, $group_index) {
  271. $table_data = $data[$priority];
  272. $no_errors = TRUE;
  273. $table = $table_data['table'];
  274. $values = $table_data['values_array'];
  275. //watchdog('T_bulk_loader','Original:<pre>'.print_r($table_data, TRUE).'</pre>', array(), WATCHDOG_NOTICE);
  276. //print 'default values:'.print_r($values,TRUE)."\n";
  277. if ($table_data['need_further_processing']) {
  278. $values = tripal_bulk_loader_add_spreadsheetdata_to_values($values, $line, $field2column[$priority]);
  279. if (!$values) {
  280. watchdog('T_bulk_loader', 'Line ' . $line_num . ' Spreadsheet Added:' . print_r($values, TRUE), array(), WATCHDOG_NOTICE);
  281. }
  282. $values = tripal_bulk_loader_add_foreignkey_to_values($values, $data, $record2priority);
  283. if (!$values) {
  284. watchdog('T_bulk_loader', 'Line ' . $line_num . ' FK Added:<pre>' . print_r($values, TRUE) . print_r($data[$priority], TRUE) . '</pre>', array(), WATCHDOG_NOTICE);
  285. }
  286. }
  287. $values = tripal_bulk_loader_regex_tranform_values($values, $table_data, $line);
  288. if (!$values) {
  289. watchdog('T_bulk_loader', 'Line ' . $line_num . ' Regex:<pre>' . print_r($values, TRUE) . print_r($table_data, TRUE) . '</pre>' . '</pre>', array(), WATCHDOG_NOTICE);
  290. }
  291. if (!$values) {
  292. $msg = 'Line ' . $line_num . ' ' . $table_data['record_id'] . ' (' . $table_data['mode'] . ') Aborted due to error in previous record. Values of current record:' . print_r($table_data['values_array'], TRUE);
  293. watchdog('T_bulk_loader', $msg, array(), WATCHDOG_WARNING);
  294. print "ERROR: " . $msg . "\n";
  295. $data[$priority]['error'] = TRUE;
  296. $no_errors = FALSE;
  297. }
  298. $table_desc = module_invoke_all('chado_' . $table . '_schema');
  299. if (preg_match('/optional/', $table_array['mode'])) {
  300. // Check all db required fields are set
  301. $fields = $table_desc['fields'];
  302. foreach ($fields as $field => $def) {
  303. // a field is considered missing if it cannot be null and there is no default
  304. // value for it or it is of type 'serial'
  305. if ($def['not null'] == 1 and !array_key_exists($field, $insert_values) and !isset($def['default']) and strcmp($def['type'], serial)!=0) {
  306. $msg = 'Line ' . $line_num . ' ' . $table_data['record_id'] . ' (' . $table_data['mode'] . ') Missing Database Required Value: ' . $table . '.' . $field;
  307. watchdog('T_bulk_loader', $msg, array(), WATCHDOG_NOTICE);
  308. $data[$priority]['error'] = TRUE;
  309. }
  310. }
  311. } //end of if optional record
  312. // Check required fields are present
  313. foreach ($table_data['required'] as $field => $required) {
  314. if ($required) {
  315. if (!isset($values[$field])) {
  316. $msg = 'Line ' . $line_num . ' ' . $table_data['record_id'] . ' (' . $table_data['mode'] . ') Missing Template Required Value: ' . $table . '.' . $field;
  317. watchdog('T_bulk_loader', $msg, array(), WATCHDOG_NOTICE);
  318. $data[$priority]['error'] = TRUE;
  319. }
  320. }
  321. }
  322. // add new values array into the data array
  323. $data[$priority]['values_array'] = $values;
  324. // check if it is already inserted
  325. if ($table_data['inserted']) {
  326. //watchdog('T_bulk_loader','Already Inserted:'.print_r($values,TRUE),array(),WATCHDOG_NOTICE);
  327. return $no_errors;
  328. }
  329. // if there was an error already -> don't insert
  330. if ($data[$priority]['error']) {
  331. return $no_errors;
  332. }
  333. $header = '';
  334. if (isset($values['feature_id'])) {
  335. $header = $values['feature_id']['uniquename'] . ' ' . $table_data['record_id'];
  336. }
  337. else {
  338. $header = $values['uniquename'] . ' ' . $table_data['record_id'];
  339. }
  340. // if insert unique then check to ensure unique
  341. if (preg_match('/insert_unique/', $table_data['mode'])) {
  342. $unique = tripal_core_chado_select($table, array_keys($table_desc['fields']), $values, array('has_record' => TRUE));
  343. //print 'Unique?'.print_r(array('table' => $table, 'columns' => array_keys($table_desc['fields']), 'values' => $values),TRUE).' returns '.$unique."\n";
  344. if ($unique > 0) {
  345. //$default_data[$priority]['inserted'] = TRUE;
  346. //watchdog('T_bulk_loader', $header.': Not unique ('.$unique.'):'.print_r($values,'values')."\n".print_r($data,TRUE),array(),WATCHDOG_NOTICE);;
  347. return $no_errors;
  348. }
  349. }
  350. if (!preg_match('/select/', $table_data['mode'])) {
  351. //watchdog('T_bulk_loader',$header.': Inserting:'.print_r($values, TRUE), array(), WATCHDOG_NOTICE);
  352. if (variable_get('tripal_bulk_loader_prepare',TRUE)) {
  353. $options = array('statement_name' => $priority);
  354. if ($line_num == 1 && $group_index == 1) {
  355. $options['prepare'] = TRUE;
  356. }
  357. }
  358. else {
  359. $options = array();
  360. }
  361. $record = tripal_core_chado_insert($table, $values, $options);
  362. if (!$record) {
  363. $msg = 'Line ' . $line_num . ' ' . $table_data['record_id'] . ' (' . $table_data['mode'] . ') Unable to insert record into ' . $table . ' where values:' . print_r($values, TRUE);
  364. watchdog('T_bulk_loader', $msg, array(), WATCHDOG_ERROR);
  365. print "ERROR: " . $msg . "\n";
  366. $data[$priority]['error'] = TRUE;
  367. $no_errors = FALSE;
  368. }
  369. else {
  370. //add changes back to values array
  371. $data[$priority]['values_array'] = $record;
  372. $values = $record;
  373. // if mode=insert_once then ensure we only insert it once
  374. if (preg_match('/insert_once/', $table_data['mode'])) {
  375. $default_data[$priority]['inserted'] = TRUE;
  376. }
  377. // add to tripal_bulk_loader_inserted
  378. $insert_record = db_fetch_object(db_query(
  379. "SELECT * FROM {tripal_bulk_loader_inserted} WHERE table_inserted_into='%s' AND nid=%d",
  380. $table,
  381. $nid
  382. ));
  383. if ($insert_record) {
  384. $insert_record->ids_inserted .= ',' . $values[ $table_desc['primary key'][0] ];
  385. drupal_write_record('tripal_bulk_loader_inserted', $insert_record, 'tripal_bulk_loader_inserted_id');
  386. //print 'Update: '.print_r($insert_record,TRUE)."\n";
  387. return $no_errors;
  388. }
  389. else {
  390. $insert_record = array(
  391. 'nid' => $nid,
  392. 'table_inserted_into' => $table,
  393. 'table_primary_key' => $table_desc['primary key'][0],
  394. 'ids_inserted' => $values[ $table_desc['primary key'][0] ],
  395. );
  396. //print 'New: '.print_r($insert_record,TRUE)."\n";
  397. $success = drupal_write_record('tripal_bulk_loader_inserted', $insert_record);
  398. return $no_errors;
  399. }//end of if insert record
  400. } //end of if insert was successful
  401. }
  402. else {
  403. $exists = tripal_core_chado_select($table, array_keys($table_desc['fields']), $values, array('has_record' => TRUE));
  404. if (!$exists) {
  405. // No record on select
  406. $msg = 'Line ' . $line_num . ' ' . $table_data['record_id'] . ' (' . $table_data['mode'] . ') No Matching record in ' . $table . ' where values:' . print_r($values, TRUE);
  407. watchdog('T_bulk_loader', $msg, array(), WATCHDOG_WARNING);
  408. $data[$priority]['error'] = TRUE;
  409. }
  410. }
  411. return $no_errors;
  412. }
  413. /**
  414. * This function adds the file data to the values array
  415. *
  416. * @param $values
  417. * The default values array -contains all constants
  418. * @param $line
  419. * An array of values for the current line
  420. * @param $field2column
  421. * An array mapping values fields to line columns
  422. * @return
  423. * Supplemented values array
  424. */
  425. function tripal_bulk_loader_add_spreadsheetdata_to_values($values, $line, $field2column) {
  426. foreach ($values as $field => $value) {
  427. if (is_array($value)) {
  428. continue;
  429. }
  430. $column = $field2column[$field] - 1;
  431. if ($column < 0) {
  432. continue;
  433. }
  434. if (preg_match('/\S+/', $line[$column])) {
  435. $values[$field] = $line[$column];
  436. }
  437. else {
  438. unset($values[$field]);
  439. }
  440. }
  441. return $values;
  442. }
  443. /**
  444. * Handles foreign keys in the values array.
  445. *
  446. * Specifically, if the value for a field is an array then it is assumed that the array contains
  447. * the name of the record whose values array should be substituted here. Thus the foreign
  448. * record is looked up and the values array is substituted in.
  449. *
  450. */
  451. function tripal_bulk_loader_add_foreignkey_to_values($values, $data, $record2priority) {
  452. foreach ($values as $field => $value) {
  453. if (is_array($value)) {
  454. $foreign_record = $value['foreign record'];
  455. $foreign_priority = $record2priority[$foreign_record];
  456. $foreign_values = $data[$foreign_priority]['values_array'];
  457. // add to current values array
  458. $values[$field] = $foreign_values;
  459. }
  460. }
  461. return $values;
  462. }
  463. /**
  464. * Uses a supplied regex to transform spreadsheet values
  465. *
  466. * @param $values
  467. * The select/insert values array for the given table
  468. * @param $table_data
  469. * The data array for the given table
  470. */
  471. function tripal_bulk_loader_regex_tranform_values($values, $table_data, $line) {
  472. if (empty($table_data['regex_transform']) OR !is_array($table_data['regex_transform'])) {
  473. return $values;
  474. }
  475. //watchdog('T_bulk_loader','Regex Transformation:<pre>'.print_r($table_data['regex_transform'], TRUE).'</pre>', array(), WATCHDOG_NOTICE);
  476. foreach ($table_data['regex_transform'] as $field => $regex_array) {
  477. if (!is_array($regex_array['replace'])) {
  478. continue;
  479. }
  480. //print 'Match:'.print_r($regex_array['pattern'],TRUE)."\n";
  481. //print 'Replace:'.print_r($regex_array['replace'],TRUE)."\n";
  482. //print 'Was:'.$values[$field]."\n";
  483. // Check for <#column:\d+#> notation
  484. // if present replace with that column in the current line
  485. foreach ($regex_array['replace'] as $key => $replace) {
  486. if (preg_match_all('/<#column:(\d+)#>/', $replace, $matches)) {
  487. foreach ($matches[1] as $k => $column_num) {
  488. $replace = preg_replace('/' . $matches[0][$k] .'/', $line[$column_num-1], $replace);
  489. }
  490. $regex_array['replace'][$key] = $replace;
  491. }
  492. }
  493. // do the full replacement
  494. $old_value = $values[$field];
  495. $new_value = preg_replace($regex_array['pattern'], $regex_array['replace'], $old_value);
  496. $values[$field] = $new_value;
  497. if ($values[$field] === '') {
  498. unset($values[$field]);
  499. }
  500. //print 'Now:'.$values[$field]."\n";
  501. }
  502. return $values;
  503. }
  504. /**
  505. * Flattens an array up to two levels
  506. * Used for printing of arrays without taking up much space
  507. */
  508. function tripal_bulk_loader_flatten_array($values) {
  509. $flattened_values = array();
  510. foreach ($values as $k => $v) {
  511. if (is_array($v)) {
  512. $vstr = array();
  513. foreach ($v as $vk => $vv) {
  514. if (strlen($vv) > 20) {
  515. $vstr[] = $vk . '=>' . substr($vv, 0, 20) . '...';
  516. }
  517. else {
  518. $vstr[] = $vk . '=>' . $vv;
  519. }
  520. }
  521. $v = '{' . implode(',', $vstr) . '}';
  522. }
  523. elseif (strlen($v) > 20) {
  524. $v = substr($v, 0, 20) . '...';
  525. }
  526. $flattened_values[] = $k . '=>' . $v;
  527. }
  528. return implode(', ', $flattened_values);
  529. }