tripal_bulk_loader.loader.inc 24 KB

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