tripal_bulk_loader.loader.inc 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672
  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. // Open File
  196. $file_handle = fopen($node->file, 'r');
  197. // Set defaults
  198. if (preg_match('/(t|true|1)/', $node->file_has_header)) {
  199. fgets($file_handle, 4096);
  200. }
  201. $num_records = 0;
  202. $num_lines = 0;
  203. $num_errors = 0;
  204. $interval = intval($total_lines * 0.10);
  205. if ($interval == 0) {
  206. $interval = 1;
  207. }
  208. // Start Transaction
  209. switch (variable_get('tripal_bulk_loader_transactions','row')) {
  210. case "none":
  211. break;
  212. case "all":
  213. tripal_db_start_transaction();
  214. $savepoint = "";
  215. break;
  216. case "row":
  217. tripal_db_start_transaction();
  218. $savepoint = "last_row_complete";
  219. break;
  220. }
  221. while (!feof($file_handle)) {
  222. // Clear variables
  223. // Was added to fix memory leak
  224. unset($line); unset($raw_line);
  225. unset($data); unset($data_keys);
  226. unset($priority); unset($sql);
  227. unset($result);
  228. $raw_line = fgets($file_handle, 4096);
  229. $raw_line = trim($raw_line);
  230. if (empty($raw_line)) {
  231. continue;
  232. } // skips blank lines
  233. $line = explode("\t", $raw_line);
  234. $num_lines++;
  235. // update the job status every 10% of lines processed for the current group
  236. if ($node->job_id and $num_lines % $interval == 0) {
  237. // percentage of lines processed for the current group
  238. $group_progress = round(($num_lines/$total_lines)*100);
  239. // percentage of lines processed for all groups
  240. // <previous group index> * 100 + <current group progress>
  241. // --------------------------------------------------------
  242. // <total number of groups>
  243. // For example, if you were in the third group of 3 constant sets
  244. // and had a group percentage of 50% then the job progress would be
  245. // (2*100 + 50%) / 3 = 250%/3 = 83%
  246. $job_progress = round(((($group_index-1)*100)+$group_progress)/$total_num_groups);
  247. tripal_job_set_progress($node->job_id, $job_progress);
  248. }
  249. $data = $default_data;
  250. $data_keys = array_keys($data);
  251. foreach ($data_keys as $priority) {
  252. $status = process_data_array_for_line($priority, $data, $default_data, $field2column, $record2priority, $line, $nid, $num_lines, $group_index);
  253. if (!$status ) {
  254. // Encountered an error
  255. if (variable_get('tripal_bulk_loader_transactions','row') != 'none') {
  256. tripal_db_rollback_transaction($savepoint);
  257. }
  258. $failed = TRUE;
  259. break;
  260. }
  261. } // end of foreach table in default data array
  262. if ($failed) {
  263. break;
  264. }
  265. else {
  266. // Row inserted successfully
  267. // Set savepoint if supplied
  268. if ($savepoint) {
  269. if ($num_lines == 1) {
  270. tripal_db_set_savepoint_transaction($savepoint);
  271. }
  272. else {
  273. // Tell it to remove the previous savepoint of the same name
  274. tripal_db_set_savepoint_transaction($savepoint, TRUE);
  275. }
  276. }
  277. }
  278. } //end of foreach line of file
  279. // END Transaction
  280. if (variable_get('tripal_bulk_loader_transactions','row') != 'none') {
  281. tripal_db_commit_transaction();
  282. }
  283. if ($failed) {
  284. break;
  285. }
  286. } //end of foreach constant set
  287. // check that data was inserted and update job_status
  288. $sql = 'SELECT count(*) as num_tables FROM {tripal_bulk_loader_inserted} WHERE nid=%d GROUP BY nid';
  289. $result = db_fetch_object(db_query($sql, $nid));
  290. if ($result->num_tables > 0) {
  291. $node->job_status = 'Data Inserted';
  292. drupal_write_record('node', $node, 'nid');
  293. }
  294. // set the status of the job (in the node not the tripal jobs)
  295. if ($loaded_without_errors) {
  296. $status = 'Loading Completed Successfully';
  297. }
  298. else {
  299. $status = 'Errors Encountered';
  300. }
  301. db_query("UPDATE {tripal_bulk_loader} SET job_status='%s' WHERE nid=%d", $status, $nid);
  302. }
  303. /**
  304. *
  305. *
  306. */
  307. function process_data_array_for_line($priority, &$data, &$default_data, $field2column, $record2priority, $line, $nid, $line_num, $group_index) {
  308. $table_data = $data[$priority];
  309. $no_errors = TRUE;
  310. $table = $table_data['table'];
  311. $values = $table_data['values_array'];
  312. //watchdog('T_bulk_loader','Original:<pre>'.print_r($table_data, TRUE).'</pre>', array(), WATCHDOG_NOTICE);
  313. //print 'default values:'.print_r($values,TRUE)."\n";
  314. if ($table_data['need_further_processing']) {
  315. $values = tripal_bulk_loader_add_spreadsheetdata_to_values($values, $line, $field2column[$priority]);
  316. if (!$values) {
  317. watchdog('T_bulk_loader', 'Line ' . $line_num . ' Spreadsheet Added:' . print_r($values, TRUE), array(), WATCHDOG_NOTICE);
  318. }
  319. $values = tripal_bulk_loader_add_foreignkey_to_values($values, $data, $record2priority);
  320. if (!$values) {
  321. watchdog('T_bulk_loader', 'Line ' . $line_num . ' FK Added:<pre>' . print_r($values, TRUE) . print_r($data[$priority], TRUE) . '</pre>', array(), WATCHDOG_NOTICE);
  322. }
  323. }
  324. $values = tripal_bulk_loader_regex_tranform_values($values, $table_data, $line);
  325. if (!$values) {
  326. watchdog('T_bulk_loader', 'Line ' . $line_num . ' Regex:<pre>' . print_r($values, TRUE) . print_r($table_data, TRUE) . '</pre>' . '</pre>', array(), WATCHDOG_NOTICE);
  327. }
  328. if (!$values) {
  329. $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);
  330. watchdog('T_bulk_loader', $msg, array(), WATCHDOG_WARNING);
  331. print "ERROR: " . $msg . "\n";
  332. $data[$priority]['error'] = TRUE;
  333. $no_errors = FALSE;
  334. }
  335. $table_desc = module_invoke_all('chado_' . $table . '_schema');
  336. if (preg_match('/optional/', $table_array['mode'])) {
  337. // Check all db required fields are set
  338. $fields = $table_desc['fields'];
  339. foreach ($fields as $field => $def) {
  340. // a field is considered missing if it cannot be null and there is no default
  341. // value for it or it is of type 'serial'
  342. if ($def['not null'] == 1 and !array_key_exists($field, $insert_values) and !isset($def['default']) and strcmp($def['type'], serial)!=0) {
  343. $msg = 'Line ' . $line_num . ' ' . $table_data['record_id'] . ' (' . $table_data['mode'] . ') Missing Database Required Value: ' . $table . '.' . $field;
  344. watchdog('T_bulk_loader', $msg, array(), WATCHDOG_NOTICE);
  345. $data[$priority]['error'] = TRUE;
  346. }
  347. }
  348. } //end of if optional record
  349. // Check required fields are present
  350. foreach ($table_data['required'] as $field => $required) {
  351. if ($required) {
  352. if (!isset($values[$field])) {
  353. $msg = 'Line ' . $line_num . ' ' . $table_data['record_id'] . ' (' . $table_data['mode'] . ') Missing Template Required Value: ' . $table . '.' . $field;
  354. watchdog('T_bulk_loader', $msg, array(), WATCHDOG_NOTICE);
  355. $data[$priority]['error'] = TRUE;
  356. }
  357. }
  358. }
  359. // add new values array into the data array
  360. $data[$priority]['values_array'] = $values;
  361. // check if it is already inserted
  362. if ($table_data['inserted']) {
  363. //watchdog('T_bulk_loader','Already Inserted:'.print_r($values,TRUE),array(),WATCHDOG_NOTICE);
  364. return $no_errors;
  365. }
  366. // if there was an error already -> don't insert
  367. if ($data[$priority]['error']) {
  368. return $no_errors;
  369. }
  370. $header = '';
  371. if (isset($values['feature_id'])) {
  372. $header = $values['feature_id']['uniquename'] . ' ' . $table_data['record_id'];
  373. }
  374. else {
  375. $header = $values['uniquename'] . ' ' . $table_data['record_id'];
  376. }
  377. // if insert unique then check to ensure unique
  378. if (preg_match('/insert_unique/', $table_data['mode'])) {
  379. $unique = tripal_core_chado_select($table, array_keys($table_desc['fields']), $values, array('has_record' => TRUE));
  380. //print 'Unique?'.print_r(array('table' => $table, 'columns' => array_keys($table_desc['fields']), 'values' => $values),TRUE).' returns '.$unique."\n";
  381. if ($unique > 0) {
  382. //$default_data[$priority]['inserted'] = TRUE;
  383. //watchdog('T_bulk_loader', $header.': Not unique ('.$unique.'):'.print_r($values,'values')."\n".print_r($data,TRUE),array(),WATCHDOG_NOTICE);;
  384. return $no_errors;
  385. }
  386. }
  387. if (!preg_match('/select/', $table_data['mode'])) {
  388. //watchdog('T_bulk_loader',$header.': Inserting:'.print_r($values, TRUE), array(), WATCHDOG_NOTICE);
  389. if (variable_get('tripal_bulk_loader_prepare',TRUE)) {
  390. $options = array('statement_name' => 'record_'.$priority);
  391. if ($line_num == 1 && $group_index == 1) {
  392. $options['prepare'] = TRUE;
  393. }
  394. }
  395. else {
  396. $options = array();
  397. }
  398. $record = tripal_core_chado_insert($table, $values, $options);
  399. if (!$record) {
  400. $msg = 'Line ' . $line_num . ' ' . $table_data['record_id'] . ' (' . $table_data['mode'] . ') Unable to insert record into ' . $table . ' where values:' . print_r($values, TRUE);
  401. watchdog('T_bulk_loader', $msg, array(), WATCHDOG_ERROR);
  402. print "ERROR: " . $msg . "\n";
  403. $data[$priority]['error'] = TRUE;
  404. $no_errors = FALSE;
  405. }
  406. else {
  407. //add changes back to values array
  408. $data[$priority]['values_array'] = $record;
  409. $values = $record;
  410. // if mode=insert_once then ensure we only insert it once
  411. if (preg_match('/insert_once/', $table_data['mode'])) {
  412. $default_data[$priority]['inserted'] = TRUE;
  413. }
  414. // add to tripal_bulk_loader_inserted
  415. $insert_record = db_fetch_object(db_query(
  416. "SELECT * FROM {tripal_bulk_loader_inserted} WHERE table_inserted_into='%s' AND nid=%d",
  417. $table,
  418. $nid
  419. ));
  420. if ($insert_record) {
  421. $insert_record->ids_inserted .= ',' . $values[ $table_desc['primary key'][0] ];
  422. drupal_write_record('tripal_bulk_loader_inserted', $insert_record, 'tripal_bulk_loader_inserted_id');
  423. //print 'Update: '.print_r($insert_record,TRUE)."\n";
  424. return $no_errors;
  425. }
  426. else {
  427. $insert_record = array(
  428. 'nid' => $nid,
  429. 'table_inserted_into' => $table,
  430. 'table_primary_key' => $table_desc['primary key'][0],
  431. 'ids_inserted' => $values[ $table_desc['primary key'][0] ],
  432. );
  433. //print 'New: '.print_r($insert_record,TRUE)."\n";
  434. $success = drupal_write_record('tripal_bulk_loader_inserted', $insert_record);
  435. return $no_errors;
  436. }//end of if insert record
  437. } //end of if insert was successful
  438. }
  439. else {
  440. $exists = tripal_core_chado_select($table, array_keys($table_desc['fields']), $values, array('has_record' => TRUE));
  441. if (!$exists) {
  442. // No record on select
  443. $msg = 'Line ' . $line_num . ' ' . $table_data['record_id'] . ' (' . $table_data['mode'] . ') No Matching record in ' . $table . ' where values:' . print_r($values, TRUE);
  444. watchdog('T_bulk_loader', $msg, array(), WATCHDOG_WARNING);
  445. $data[$priority]['error'] = TRUE;
  446. $no_errors = FALSE;
  447. }
  448. }
  449. return $no_errors;
  450. }
  451. /**
  452. * This function adds the file data to the values array
  453. *
  454. * @param $values
  455. * The default values array -contains all constants
  456. * @param $line
  457. * An array of values for the current line
  458. * @param $field2column
  459. * An array mapping values fields to line columns
  460. * @return
  461. * Supplemented values array
  462. */
  463. function tripal_bulk_loader_add_spreadsheetdata_to_values($values, $line, $field2column) {
  464. foreach ($values as $field => $value) {
  465. if (is_array($value)) {
  466. continue;
  467. }
  468. $column = $field2column[$field] - 1;
  469. if ($column < 0) {
  470. continue;
  471. }
  472. if (preg_match('/\S+/', $line[$column])) {
  473. $values[$field] = $line[$column];
  474. }
  475. else {
  476. unset($values[$field]);
  477. }
  478. }
  479. return $values;
  480. }
  481. /**
  482. * Handles foreign keys in the values array.
  483. *
  484. * Specifically, if the value for a field is an array then it is assumed that the array contains
  485. * the name of the record whose values array should be substituted here. Thus the foreign
  486. * record is looked up and the values array is substituted in.
  487. *
  488. */
  489. function tripal_bulk_loader_add_foreignkey_to_values($values, $data, $record2priority) {
  490. foreach ($values as $field => $value) {
  491. if (is_array($value)) {
  492. $foreign_record = $value['foreign record'];
  493. $foreign_priority = $record2priority[$foreign_record];
  494. $foreign_values = $data[$foreign_priority]['values_array'];
  495. // add to current values array
  496. $values[$field] = $foreign_values;
  497. }
  498. }
  499. return $values;
  500. }
  501. /**
  502. * Uses a supplied regex to transform spreadsheet values
  503. *
  504. * @param $values
  505. * The select/insert values array for the given table
  506. * @param $table_data
  507. * The data array for the given table
  508. */
  509. function tripal_bulk_loader_regex_tranform_values($values, $table_data, $line) {
  510. if (empty($table_data['regex_transform']) OR !is_array($table_data['regex_transform'])) {
  511. return $values;
  512. }
  513. //watchdog('T_bulk_loader','Regex Transformation:<pre>'.print_r($table_data['regex_transform'], TRUE).'</pre>', array(), WATCHDOG_NOTICE);
  514. foreach ($table_data['regex_transform'] as $field => $regex_array) {
  515. if (!is_array($regex_array['replace'])) {
  516. continue;
  517. }
  518. //print 'Match:'.print_r($regex_array['pattern'],TRUE)."\n";
  519. //print 'Replace:'.print_r($regex_array['replace'],TRUE)."\n";
  520. //print 'Was:'.$values[$field]."\n";
  521. // Check for <#column:\d+#> notation
  522. // if present replace with that column in the current line
  523. foreach ($regex_array['replace'] as $key => $replace) {
  524. if (preg_match_all('/<#column:(\d+)#>/', $replace, $matches)) {
  525. foreach ($matches[1] as $k => $column_num) {
  526. $replace = preg_replace('/' . $matches[0][$k] .'/', $line[$column_num-1], $replace);
  527. }
  528. $regex_array['replace'][$key] = $replace;
  529. }
  530. }
  531. // do the full replacement
  532. $old_value = $values[$field];
  533. $new_value = preg_replace($regex_array['pattern'], $regex_array['replace'], $old_value);
  534. $values[$field] = $new_value;
  535. if ($values[$field] === '') {
  536. unset($values[$field]);
  537. }
  538. //print 'Now:'.$values[$field]."\n";
  539. }
  540. return $values;
  541. }
  542. /**
  543. * Flattens an array up to two levels
  544. * Used for printing of arrays without taking up much space
  545. */
  546. function tripal_bulk_loader_flatten_array($values) {
  547. $flattened_values = array();
  548. foreach ($values as $k => $v) {
  549. if (is_array($v)) {
  550. $vstr = array();
  551. foreach ($v as $vk => $vv) {
  552. if (strlen($vv) > 20) {
  553. $vstr[] = $vk . '=>' . substr($vv, 0, 20) . '...';
  554. }
  555. else {
  556. $vstr[] = $vk . '=>' . $vv;
  557. }
  558. }
  559. $v = '{' . implode(',', $vstr) . '}';
  560. }
  561. elseif (strlen($v) > 20) {
  562. $v = substr($v, 0, 20) . '...';
  563. }
  564. $flattened_values[] = $k . '=>' . $v;
  565. }
  566. return implode(', ', $flattened_values);
  567. }