tripal_bulk_loader.loader.inc 23 KB

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