dolibarr  16.0.1
import_csv.modules.php
Go to the documentation of this file.
1 <?php
2 /* Copyright (C) 2006-2012 Laurent Destailleur <eldy@users.sourceforge.net>
3  * Copyright (C) 2009-2012 Regis Houssin <regis.houssin@inodbox.com>
4  * Copyright (C) 2012 Christophe Battarel <christophe.battarel@altairis.fr>
5  * Copyright (C) 2012-2016 Juanjo Menent <jmenent@2byte.es>
6  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 3 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program. If not, see <https://www.gnu.org/licenses/>.
19  * or see https://www.gnu.org/
20  */
21 
28 require_once DOL_DOCUMENT_ROOT.'/core/modules/import/modules_import.php';
29 
30 
34 class ImportCsv extends ModeleImports
35 {
39  public $db;
40 
41  public $datatoimport;
42 
46  public $error = '';
47 
51  public $errors = array();
52 
56  public $id;
57 
61  public $label;
62 
63  public $extension; // Extension of files imported by driver
64 
69  public $version = 'dolibarr';
70 
71  public $label_lib; // Label of external lib used by driver
72 
73  public $version_lib; // Version of external lib used by driver
74 
75  public $separator;
76 
77  public $file; // Path of file
78 
79  public $handle; // Handle fichier
80 
81  public $cacheconvert = array(); // Array to cache list of value found after a convertion
82 
83  public $cachefieldtable = array(); // Array to cache list of value found into fields@tables
84 
85  public $nbinsert = 0; // # of insert done during the import
86 
87  public $nbupdate = 0; // # of update done during the import
88 
89 
96  public function __construct($db, $datatoimport)
97  {
98  global $conf, $langs;
99  $this->db = $db;
100 
101  $this->separator = (GETPOST('separator') ?GETPOST('separator') : (empty($conf->global->IMPORT_CSV_SEPARATOR_TO_USE) ? ',' : $conf->global->IMPORT_CSV_SEPARATOR_TO_USE));
102  $this->enclosure = '"';
103  $this->escape = '"';
104 
105  $this->id = 'csv'; // Same value then xxx in file name export_xxx.modules.php
106  $this->label = 'Csv'; // Label of driver
107  $this->desc = $langs->trans("CSVFormatDesc", $this->separator, $this->enclosure, $this->escape);
108  $this->extension = 'csv'; // Extension for generated file by this driver
109  $this->picto = 'mime/other'; // Picto
110  $this->version = '1.34'; // Driver version
111 
112  // If driver use an external library, put its name here
113  $this->label_lib = 'Dolibarr';
114  $this->version_lib = DOL_VERSION;
115 
116  $this->datatoimport = $datatoimport;
117  if (preg_match('/^societe_/', $datatoimport)) {
118  $this->thirpartyobject = new Societe($this->db);
119  }
120  }
121 
122 
123  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
130  public function write_header_example($outputlangs)
131  {
132  // phpcs:enable
133  return '';
134  }
135 
136  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
144  public function write_title_example($outputlangs, $headerlinefields)
145  {
146  // phpcs:enable
147  $s = join($this->separator, array_map('cleansep', $headerlinefields));
148  return $s."\n";
149  }
150 
151  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
159  public function write_record_example($outputlangs, $contentlinevalues)
160  {
161  // phpcs:enable
162  $s = join($this->separator, array_map('cleansep', $contentlinevalues));
163  return $s."\n";
164  }
165 
166  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
173  public function write_footer_example($outputlangs)
174  {
175  // phpcs:enable
176  return '';
177  }
178 
179 
180  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
187  public function import_open_file($file)
188  {
189  // phpcs:enable
190  global $langs;
191  $ret = 1;
192 
193  dol_syslog(get_class($this)."::open_file file=".$file);
194 
195  ini_set('auto_detect_line_endings', 1); // For MAC compatibility
196 
197  $this->handle = fopen(dol_osencode($file), "r");
198  if (!$this->handle) {
199  $langs->load("errors");
200  $this->error = $langs->trans("ErrorFailToOpenFile", $file);
201  $ret = -1;
202  } else {
203  $this->file = $file;
204  }
205 
206  return $ret;
207  }
208 
209 
210  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
217  public function import_get_nb_of_lines($file)
218  {
219  // phpcs:enable
220  return dol_count_nb_of_line($file);
221  }
222 
223 
224  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
230  public function import_read_header()
231  {
232  // phpcs:enable
233  return 0;
234  }
235 
236 
237  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
243  public function import_read_record()
244  {
245  // phpcs:enable
246  global $conf;
247 
248  $arrayres = fgetcsv($this->handle, 100000, $this->separator, $this->enclosure, $this->escape);
249 
250  // End of file
251  if ($arrayres === false) {
252  return false;
253  }
254 
255  //var_dump($this->handle);
256  //var_dump($arrayres);exit;
257  $newarrayres = array();
258  if ($arrayres && is_array($arrayres)) {
259  foreach ($arrayres as $key => $val) {
260  if (!empty($conf->global->IMPORT_CSV_FORCE_CHARSET)) { // Forced charset
261  if (strtolower($conf->global->IMPORT_CSV_FORCE_CHARSET) == 'utf8') {
262  $newarrayres[$key]['val'] = $val;
263  $newarrayres[$key]['type'] = (dol_strlen($val) ? 1 : -1); // If empty we considere it's null
264  } else {
265  $newarrayres[$key]['val'] = utf8_encode($val);
266  $newarrayres[$key]['type'] = (dol_strlen($val) ? 1 : -1); // If empty we considere it's null
267  }
268  } else // Autodetect format (UTF8 or ISO)
269  {
270  if (utf8_check($val)) {
271  $newarrayres[$key]['val'] = $val;
272  $newarrayres[$key]['type'] = (dol_strlen($val) ? 1 : -1); // If empty we considere it's null
273  } else {
274  $newarrayres[$key]['val'] = utf8_encode($val);
275  $newarrayres[$key]['type'] = (dol_strlen($val) ? 1 : -1); // If empty we considere it's null
276  }
277  }
278  }
279 
280  $this->col = count($newarrayres);
281  }
282 
283  return $newarrayres;
284  }
285 
286  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
292  public function import_close_file()
293  {
294  // phpcs:enable
295  fclose($this->handle);
296  return 0;
297  }
298 
299 
300  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
312  public function import_insert($arrayrecord, $array_match_file_to_database, $objimport, $maxfields, $importid, $updatekeys)
313  {
314  // phpcs:enable
315  global $langs, $conf, $user;
316  global $thirdparty_static; // Specific to thirdparty import
317  global $tablewithentity_cache; // Cache to avoid to call desc at each rows on tables
318 
319  $error = 0;
320  $warning = 0;
321  $this->errors = array();
322  $this->warnings = array();
323 
324  //dol_syslog("import_csv.modules maxfields=".$maxfields." importid=".$importid);
325 
326  //var_dump($array_match_file_to_database);
327  //var_dump($arrayrecord); exit;
328 
329  $array_match_database_to_file = array_flip($array_match_file_to_database);
330  $sort_array_match_file_to_database = $array_match_file_to_database;
331  ksort($sort_array_match_file_to_database);
332 
333  //var_dump($sort_array_match_file_to_database);
334 
335  if (count($arrayrecord) == 0 || (count($arrayrecord) == 1 && empty($arrayrecord[0]['val']))) {
336  //print 'W';
337  $this->warnings[$warning]['lib'] = $langs->trans('EmptyLine');
338  $this->warnings[$warning]['type'] = 'EMPTY';
339  $warning++;
340  } else {
341  $last_insert_id_array = array(); // store the last inserted auto_increment id for each table, so that dependent tables can be inserted with the appropriate id (eg: extrafields fk_object will be set with the last inserted object's id)
342  $updatedone = false;
343  $insertdone = false;
344  // For each table to insert, me make a separate insert
345  foreach ($objimport->array_import_tables[0] as $alias => $tablename) {
346  // Build sql request
347  $sql = '';
348  $listfields = array();
349  $listvalues = array();
350  $i = 0;
351  $errorforthistable = 0;
352 
353  // Define $tablewithentity_cache[$tablename] if not already defined
354  if (!isset($tablewithentity_cache[$tablename])) { // keep this test with "isset"
355  dol_syslog("Check if table ".$tablename." has an entity field");
356  $resql = $this->db->DDLDescTable($tablename, 'entity');
357  if ($resql) {
358  $obj = $this->db->fetch_object($resql);
359  if ($obj) {
360  $tablewithentity_cache[$tablename] = 1; // table contains entity field
361  } else {
362  $tablewithentity_cache[$tablename] = 0; // table does not contains entity field
363  }
364  } else {
365  dol_print_error($this->db);
366  }
367  } else {
368  //dol_syslog("Table ".$tablename." check for entity into cache is ".$tablewithentity_cache[$tablename]);
369  }
370 
371  // Define array to convert fields ('c.ref', ...) into column index (1, ...)
372  $arrayfield = array();
373  foreach ($sort_array_match_file_to_database as $key => $val) {
374  $arrayfield[$val] = ($key - 1);
375  }
376 
377  // $arrayrecord start at key 0
378  // $sort_array_match_file_to_database start at key 1
379 
380  // Loop on each fields in the match array: $key = 1..n, $val=alias of field (s.nom)
381  foreach ($sort_array_match_file_to_database as $key => $val) {
382  $fieldalias = preg_replace('/\..*$/i', '', $val);
383  $fieldname = preg_replace('/^.*\./i', '', $val);
384 
385  if ($alias != $fieldalias) {
386  continue; // Not a field of current table
387  }
388 
389  if ($key <= $maxfields) {
390  // Set $newval with value to insert and set $listvalues with sql request part for insert
391  $newval = '';
392  if ($arrayrecord[($key - 1)]['type'] > 0) {
393  $newval = $arrayrecord[($key - 1)]['val']; // If type of field into input file is not empty string (so defined into input file), we get value
394  }
395 
396  //var_dump($newval);var_dump($val);
397  //var_dump($objimport->array_import_convertvalue[0][$val]);
398 
399  // Make some tests on $newval
400 
401  // Is it a required field ?
402  if (preg_match('/\*/', $objimport->array_import_fields[0][$val]) && ((string) $newval == '')) {
403  $this->errors[$error]['lib'] = $langs->trans('ErrorMissingMandatoryValue', $key);
404  $this->errors[$error]['type'] = 'NOTNULL';
405  $errorforthistable++;
406  $error++;
407  } else {
408  // Test format only if field is not a missing mandatory field (field may be a value or empty but not mandatory)
409  // We convert field if required
410  if (!empty($objimport->array_import_convertvalue[0][$val])) {
411  //print 'Must convert '.$newval.' with rule '.join(',',$objimport->array_import_convertvalue[0][$val]).'. ';
412  if ($objimport->array_import_convertvalue[0][$val]['rule'] == 'fetchidfromcodeid'
413  || $objimport->array_import_convertvalue[0][$val]['rule'] == 'fetchidfromref'
414  || $objimport->array_import_convertvalue[0][$val]['rule'] == 'fetchidfromcodeorlabel'
415  ) {
416  // New val can be an id or ref. If it start with id: it is forced to id, if it start with ref: it is forced to ref. It not, we try to guess.
417  $isidorref = 'id';
418  if (!is_numeric($newval) && $newval != '' && !preg_match('/^id:/i', $newval)) {
419  $isidorref = 'ref';
420  }
421 
422  $newval = preg_replace('/^(id|ref):/i', '', $newval); // Remove id: or ref: that was used to force if field is id or ref
423  //print 'Newval is now "'.$newval.'" and is type '.$isidorref."<br>\n";
424 
425  if ($isidorref == 'ref') { // If value into input import file is a ref, we apply the function defined into descriptor
426  $file = (empty($objimport->array_import_convertvalue[0][$val]['classfile']) ? $objimport->array_import_convertvalue[0][$val]['file'] : $objimport->array_import_convertvalue[0][$val]['classfile']);
427  $class = $objimport->array_import_convertvalue[0][$val]['class'];
428  $method = $objimport->array_import_convertvalue[0][$val]['method'];
429  if ($this->cacheconvert[$file.'_'.$class.'_'.$method.'_'][$newval] != '') {
430  $newval = $this->cacheconvert[$file.'_'.$class.'_'.$method.'_'][$newval];
431  } else {
432  $resultload = dol_include_once($file);
433  if (empty($resultload)) {
434  dol_print_error('', 'Error trying to call file='.$file.', class='.$class.', method='.$method);
435  break;
436  }
437  $classinstance = new $class($this->db);
438  if ($class == 'CGenericDic') {
439  $classinstance->element = $objimport->array_import_convertvalue[0][$val]['element'];
440  $classinstance->table_element = $objimport->array_import_convertvalue[0][$val]['table_element'];
441  }
442 
443  // Try the fetch from code or ref
444  $param_array = array('', $newval);
445  if ($class == 'AccountingAccount') {
446  //var_dump($arrayrecord[0]['val']);
447  /*include_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountancysystem.class.php';
448  $tmpchartofaccount = new AccountancySystem($this->db);
449  $tmpchartofaccount->fetch($conf->global->CHARTOFACCOUNTS);
450  //var_dump($tmpchartofaccount->ref.' - '.$arrayrecord[0]['val']);
451  if ((! ($conf->global->CHARTOFACCOUNTS > 0)) || $tmpchartofaccount->ref != $arrayrecord[0]['val'])
452  {
453  $this->errors[$error]['lib']=$langs->trans('ErrorImportOfChartLimitedToCurrentChart', $tmpchartofaccount->ref);
454  $this->errors[$error]['type']='RESTRICTONCURRENCTCHART';
455  $errorforthistable++;
456  $error++;
457  }*/
458  $param_array = array('', $newval, 0, $arrayrecord[0]['val']); // Param to fetch parent from account, in chart.
459  }
460 
461  call_user_func_array(array($classinstance, $method), $param_array);
462  // If not found, try the fetch from label
463  if (!($classinstance->id != '') && $objimport->array_import_convertvalue[0][$val]['rule'] == 'fetchidfromcodeorlabel') {
464  $param_array = array('', '', $newval);
465  call_user_func_array(array($classinstance, $method), $param_array);
466  }
467  $this->cacheconvert[$file.'_'.$class.'_'.$method.'_'][$newval] = $classinstance->id;
468  //print 'We have made a '.$class.'->'.$method.' to get id from code '.$newval.'. ';
469  if ($classinstance->id != '') { // id may be 0, it is a found value
470  $newval = $classinstance->id;
471  } else {
472  if (!empty($objimport->array_import_convertvalue[0][$val]['dict'])) {
473  $this->errors[$error]['lib'] = $langs->trans('ErrorFieldValueNotIn', num2Alpha($key - 1), $newval, 'code', $langs->transnoentitiesnoconv($objimport->array_import_convertvalue[0][$val]['dict']));
474  } elseif (!empty($objimport->array_import_convertvalue[0][$val]['element'])) {
475  $this->errors[$error]['lib'] = $langs->trans('ErrorFieldRefNotIn', num2Alpha($key - 1), $newval, $langs->transnoentitiesnoconv($objimport->array_import_convertvalue[0][$val]['element']));
476  } else {
477  $this->errors[$error]['lib'] = 'ErrorBadDefinitionOfImportProfile';
478  }
479  $this->errors[$error]['type'] = 'FOREIGNKEY';
480  $errorforthistable++;
481  $error++;
482  }
483  }
484  }
485  } elseif ($objimport->array_import_convertvalue[0][$val]['rule'] == 'fetchidfromcodeandlabel') {
486  $isidorref = 'id';
487  if (!is_numeric($newval) && $newval != '' && !preg_match('/^id:/i', $newval)) {
488  $isidorref = 'ref';
489  }
490  $newval = preg_replace('/^(id|ref):/i', '', $newval);
491 
492  if ($isidorref == 'ref') {
493  $file = (empty($objimport->array_import_convertvalue[0][$val]['classfile']) ? $objimport->array_import_convertvalue[0][$val]['file'] : $objimport->array_import_convertvalue[0][$val]['classfile']);
494  $class = $objimport->array_import_convertvalue[0][$val]['class'];
495  $method = $objimport->array_import_convertvalue[0][$val]['method'];
496  $codefromfield = $objimport->array_import_convertvalue[0][$val]['codefromfield'];
497  $code = $arrayrecord[$arrayfield[$codefromfield]]['val'];
498  if ($this->cacheconvert[$file.'_'.$class.'_'.$method.'_'.$code][$newval] != '') {
499  $newval = $this->cacheconvert[$file.'_'.$class.'_'.$method.'_'.$code][$newval];
500  } else {
501  $resultload = dol_include_once($file);
502  if (empty($resultload)) {
503  dol_print_error('', 'Error trying to call file='.$file.', class='.$class.', method='.$method.', code='.$code);
504  break;
505  }
506  $classinstance = new $class($this->db);
507  // Try the fetch from code and ref
508  $param_array = array('', $newval, $code);
509  call_user_func_array(array($classinstance, $method), $param_array);
510  $this->cacheconvert[$file.'_'.$class.'_'.$method.'_'.$code][$newval] = $classinstance->id;
511  if ($classinstance->id > 0) { // we found record
512  $newval = $classinstance->id;
513  } else {
514  if (!empty($objimport->array_import_convertvalue[0][$val]['dict'])) {
515  $this->errors[$error]['lib'] = $langs->trans('ErrorFieldValueNotIn', num2Alpha($key - 1), $newval, 'scale', $langs->transnoentitiesnoconv($objimport->array_import_convertvalue[0][$val]['dict']));
516  } else {
517  $this->errors[$error]['lib'] = 'ErrorFieldValueNotIn';
518  }
519  $this->errors[$error]['type'] = 'FOREIGNKEY';
520  $errorforthistable++;
521  $error++;
522  }
523  }
524  }
525  } elseif ($objimport->array_import_convertvalue[0][$val]['rule'] == 'zeroifnull') {
526  if (empty($newval)) {
527  $newval = '0';
528  }
529  } elseif ($objimport->array_import_convertvalue[0][$val]['rule'] == 'fetchidfromcodeunits' || $objimport->array_import_convertvalue[0][$val]['rule'] == 'fetchscalefromcodeunits') {
530  $file = (empty($objimport->array_import_convertvalue[0][$val]['classfile']) ? $objimport->array_import_convertvalue[0][$val]['file'] : $objimport->array_import_convertvalue[0][$val]['classfile']);
531  $class = $objimport->array_import_convertvalue[0][$val]['class'];
532  $method = $objimport->array_import_convertvalue[0][$val]['method'];
533  $units = $objimport->array_import_convertvalue[0][$val]['units'];
534  if ($this->cacheconvert[$file.'_'.$class.'_'.$method.'_'.$units][$newval] != '') {
535  $newval = $this->cacheconvert[$file.'_'.$class.'_'.$method.'_'.$units][$newval];
536  } else {
537  $resultload = dol_include_once($file);
538  if (empty($resultload)) {
539  dol_print_error('', 'Error trying to call file='.$file.', class='.$class.', method='.$method.', units='.$units);
540  break;
541  }
542  $classinstance = new $class($this->db);
543  // Try the fetch from code or ref
544  call_user_func_array(array($classinstance, $method), array('', '', $newval, $units));
545  $scaleorid = (($objimport->array_import_convertvalue[0][$val]['rule'] == 'fetchidfromcodeunits') ? $classinstance->id : $classinstance->scale);
546  $this->cacheconvert[$file.'_'.$class.'_'.$method.'_'.$units][$newval] = $scaleorid;
547  //print 'We have made a '.$class.'->'.$method." to get a value from key '".$newval."' and we got '".$scaleorid."'.";exit;
548  if ($classinstance->id > 0) { // we found record
549  $newval = $scaleorid ? $scaleorid : 0;
550  } else {
551  if (!empty($objimport->array_import_convertvalue[0][$val]['dict'])) {
552  $this->errors[$error]['lib'] = $langs->trans('ErrorFieldValueNotIn', num2Alpha($key - 1), $newval, 'scale', $langs->transnoentitiesnoconv($objimport->array_import_convertvalue[0][$val]['dict']));
553  } else {
554  $this->errors[$error]['lib'] = 'ErrorFieldValueNotIn';
555  }
556  $this->errors[$error]['type'] = 'FOREIGNKEY';
557  $errorforthistable++;
558  $error++;
559  }
560  }
561  } elseif ($objimport->array_import_convertvalue[0][$val]['rule'] == 'getcustomercodeifauto') {
562  if (strtolower($newval) == 'auto') {
563  $this->thirpartyobject->get_codeclient(0, 0);
564  $newval = $this->thirpartyobject->code_client;
565  //print 'code_client='.$newval;
566  }
567  if (empty($newval)) {
568  $arrayrecord[($key - 1)]['type'] = -1; // If we get empty value, we will use "null"
569  }
570  } elseif ($objimport->array_import_convertvalue[0][$val]['rule'] == 'getsuppliercodeifauto') {
571  if (strtolower($newval) == 'auto') {
572  $newval = $this->thirpartyobject->get_codefournisseur(0, 1);
573  $newval = $this->thirpartyobject->code_fournisseur;
574  //print 'code_fournisseur='.$newval;
575  }
576  if (empty($newval)) {
577  $arrayrecord[($key - 1)]['type'] = -1; // If we get empty value, we will use "null"
578  }
579  } elseif ($objimport->array_import_convertvalue[0][$val]['rule'] == 'getcustomeraccountancycodeifauto') {
580  if (strtolower($newval) == 'auto') {
581  $this->thirpartyobject->get_codecompta('customer');
582  $newval = $this->thirpartyobject->code_compta;
583  //print 'code_compta='.$newval;
584  }
585  if (empty($newval)) {
586  $arrayrecord[($key - 1)]['type'] = -1; // If we get empty value, we will use "null"
587  }
588  } elseif ($objimport->array_import_convertvalue[0][$val]['rule'] == 'getsupplieraccountancycodeifauto') {
589  if (strtolower($newval) == 'auto') {
590  $this->thirpartyobject->get_codecompta('supplier');
591  $newval = $this->thirpartyobject->code_compta_fournisseur;
592  if (empty($newval)) {
593  $arrayrecord[($key - 1)]['type'] = -1; // If we get empty value, we will use "null"
594  }
595  //print 'code_compta_fournisseur='.$newval;
596  }
597  if (empty($newval)) {
598  $arrayrecord[($key - 1)]['type'] = -1; // If we get empty value, we will use "null"
599  }
600  } elseif ($objimport->array_import_convertvalue[0][$val]['rule'] == 'getrefifauto') {
601  if (strtolower($newval) == 'auto') {
602  $defaultref = '';
603 
604  $classModForNumber = $objimport->array_import_convertvalue[0][$val]['class'];
605  $pathModForNumber = $objimport->array_import_convertvalue[0][$val]['path'];
606 
607  if (!empty($classModForNumber) && !empty($pathModForNumber) && is_readable(DOL_DOCUMENT_ROOT.$pathModForNumber)) {
608  require_once DOL_DOCUMENT_ROOT.$pathModForNumber;
609  $modForNumber = new $classModForNumber;
610 
611  $tmpobject = null;
612  // Set the object with the date property when we can
613  if (!empty($objimport->array_import_convertvalue[0][$val]['classobject'])) {
614  $pathForObject = $objimport->array_import_convertvalue[0][$val]['pathobject'];
615  require_once DOL_DOCUMENT_ROOT.$pathForObject;
616  $tmpclassobject = $objimport->array_import_convertvalue[0][$val]['classobject'];
617  $tmpobject = new $tmpclassobject($this->db);
618  foreach ($arrayfield as $tmpkey => $tmpval) { // $arrayfield is array('c.ref'=>0, ...)
619  if (in_array($tmpkey, array('t.date', 'c.date_commande'))) {
620  $tmpobject->date = dol_stringtotime($arrayrecord[$arrayfield[$tmpkey]]['val'], 1);
621  }
622  }
623  }
624 
625  $defaultref = $modForNumber->getNextValue(null, $tmpobject);
626  }
627  if (is_numeric($defaultref) && $defaultref <= 0) { // If error
628  $defaultref = '';
629  }
630  $newval = $defaultref;
631  }
632  } elseif ($objimport->array_import_convertvalue[0][$val]['rule'] == 'compute') {
633  $file = (empty($objimport->array_import_convertvalue[0][$val]['classfile']) ? $objimport->array_import_convertvalue[0][$val]['file'] : $objimport->array_import_convertvalue[0][$val]['classfile']);
634  $class = $objimport->array_import_convertvalue[0][$val]['class'];
635  $method = $objimport->array_import_convertvalue[0][$val]['method'];
636  $resultload = dol_include_once($file);
637  if (empty($resultload)) {
638  dol_print_error('', 'Error trying to call file='.$file.', class='.$class.', method='.$method);
639  break;
640  }
641  $classinstance = new $class($this->db);
642  $res = call_user_func_array(array($classinstance, $method), array(&$arrayrecord, $listfields, ($key - 1)));
643  $newval = $res; // We get new value computed.
644  } elseif ($objimport->array_import_convertvalue[0][$val]['rule'] == 'numeric') {
645  $newval = price2num($newval);
646  } elseif ($objimport->array_import_convertvalue[0][$val]['rule'] == 'accountingaccount') {
647  if (empty($conf->global->ACCOUNTING_MANAGE_ZERO)) {
648  $newval = rtrim(trim($newval), "0");
649  } else {
650  $newval = trim($newval);
651  }
652  }
653 
654  //print 'Val to use as insert is '.$newval.'<br>';
655  }
656 
657  // Test regexp
658  if (!empty($objimport->array_import_regex[0][$val]) && ($newval != '')) {
659  // If test is "Must exist in a field@table or field@table:..."
660  $reg = array();
661  if (preg_match('/^(.+)@([^:]+)(:.+)?$/', $objimport->array_import_regex[0][$val], $reg)) {
662  $field = $reg[1];
663  $table = $reg[2];
664  $filter = !empty($reg[3]) ?substr($reg[3], 1) : '';
665 
666  $cachekey = $field.'@'.$table;
667  if (!empty($filter)) {
668  $cachekey .= ':'.$filter;
669  }
670 
671  // Load content of field@table into cache array
672  if (!is_array($this->cachefieldtable[$cachekey])) { // If content of field@table not already loaded into cache
673  $sql = "SELECT ".$field." as aliasfield FROM ".$table;
674  if (!empty($filter)) {
675  $sql .= ' WHERE '.$filter;
676  }
677 
678  $resql = $this->db->query($sql);
679  if ($resql) {
680  $num = $this->db->num_rows($resql);
681  $i = 0;
682  while ($i < $num) {
683  $obj = $this->db->fetch_object($resql);
684  if ($obj) {
685  $this->cachefieldtable[$cachekey][] = $obj->aliasfield;
686  }
687  $i++;
688  }
689  } else {
690  dol_print_error($this->db);
691  }
692  }
693 
694  // Now we check cache is not empty (should not) and key is into cache
695  if (!is_array($this->cachefieldtable[$cachekey]) || !in_array($newval, $this->cachefieldtable[$cachekey])) {
696  $tableforerror = $table;
697  if (!empty($filter)) {
698  $tableforerror .= ':'.$filter;
699  }
700  $this->errors[$error]['lib'] = $langs->transnoentitiesnoconv('ErrorFieldValueNotIn', num2Alpha($key - 1), $newval, $field, $tableforerror);
701  $this->errors[$error]['type'] = 'FOREIGNKEY';
702  $errorforthistable++;
703  $error++;
704  }
705  } elseif (!preg_match('/'.$objimport->array_import_regex[0][$val].'/i', $newval)) {
706  // If test is just a static regex
707  //if ($key == 19) print "xxx".$newval."zzz".$objimport->array_import_regex[0][$val]."<br>";
708  $this->errors[$error]['lib'] = $langs->transnoentitiesnoconv('ErrorWrongValueForField', num2Alpha($key - 1), $newval, $objimport->array_import_regex[0][$val]);
709  $this->errors[$error]['type'] = 'REGEX';
710  $errorforthistable++;
711  $error++;
712  }
713  }
714 
715  // Check HTML injection
716  $inj = testSqlAndScriptInject($newval, 0);
717  if ($inj) {
718  $this->errors[$error]['lib'] = $langs->transnoentitiesnoconv('ErrorHtmlInjectionForField', num2Alpha($key - 1), dol_trunc($newval, 100));
719  $this->errors[$error]['type'] = 'HTMLINJECTION';
720  $errorforthistable++;
721  $error++;
722  }
723 
724  // Other tests
725  // ...
726  }
727 
728  // Define $listfields and $listvalues to build SQL request
729  if ($conf->socialnetworks->enabled && strpos($fieldname, "socialnetworks") !== false) {
730  if (!in_array("socialnetworks", $listfields)) {
731  $listfields[] = "socialnetworks";
732  }
733  if (!empty($newval) && $arrayrecord[($key - 1)]['type'] > 0) {
734  $socialkey = array_search("socialnetworks", $listfields);
735  $socialnetwork = explode("_", $fieldname)[1];
736  if (empty($listvalues[$socialkey]) || $listvalues[$socialkey] == "null") {
737  $json = new stdClass();
738  $json->$socialnetwork = $newval;
739  $listvalues[$socialkey] = json_encode($json);
740  } else {
741  $jsondata = $listvalues[$socialkey];
742  $json = json_decode($jsondata);
743  $json->$socialnetwork = $newval;
744  $listvalues[$socialkey] = json_encode($json);
745  }
746  }
747  } else {
748  $listfields[] = $fieldname;
749  // Note: arrayrecord (and 'type') is filled with ->import_read_record called by import.php page before calling import_insert
750  if (empty($newval) && $arrayrecord[($key - 1)]['type'] < 0) {
751  $listvalues[] = ($newval == '0' ? $newval : "null");
752  } elseif (empty($newval) && $arrayrecord[($key - 1)]['type'] == 0) {
753  $listvalues[] = "''";
754  } else {
755  $listvalues[] = "'".$this->db->escape($newval)."'";
756  }
757  }
758  }
759  $i++;
760  }
761 
762  // We add hidden fields (but only if there is at least one field to add into table)
763  // We process here all the fields that were declared into the array $this->import_fieldshidden_array of the descriptor file.
764  // Previously we processed the ->import_fields_array.
765  if (!empty($listfields) && is_array($objimport->array_import_fieldshidden[0])) {
766  // Loop on each hidden fields to add them into listfields/listvalues
767  foreach ($objimport->array_import_fieldshidden[0] as $key => $val) {
768  if (!preg_match('/^'.preg_quote($alias, '/').'\./', $key)) {
769  continue; // Not a field of current table
770  }
771  if ($val == 'user->id') {
772  $listfields[] = preg_replace('/^'.preg_quote($alias, '/').'\./', '', $key);
773  $listvalues[] = ((int) $user->id);
774  } elseif (preg_match('/^lastrowid-/', $val)) {
775  $tmp = explode('-', $val);
776  $lastinsertid = (isset($last_insert_id_array[$tmp[1]])) ? $last_insert_id_array[$tmp[1]] : 0;
777  $keyfield = preg_replace('/^'.preg_quote($alias, '/').'\./', '', $key);
778  $listfields[] = $keyfield;
779  $listvalues[] = $lastinsertid;
780  //print $key."-".$val."-".$listfields."-".$listvalues."<br>";exit;
781  } elseif (preg_match('/^const-/', $val)) {
782  $tmp = explode('-', $val, 2);
783  $listfields[] = preg_replace('/^'.preg_quote($alias, '/').'\./', '', $key);
784  $listvalues[] = "'".$this->db->escape($tmp[1])."'";
785  } elseif (preg_match('/^rule-/', $val)) {
786  $fieldname = $key;
787  if (!empty($objimport->array_import_convertvalue[0][$fieldname])) {
788  if ($objimport->array_import_convertvalue[0][$fieldname]['rule'] == 'compute') {
789  $file = (empty($objimport->array_import_convertvalue[0][$fieldname]['classfile']) ? $objimport->array_import_convertvalue[0][$fieldname]['file'] : $objimport->array_import_convertvalue[0][$fieldname]['classfile']);
790  $class = $objimport->array_import_convertvalue[0][$fieldname]['class'];
791  $method = $objimport->array_import_convertvalue[0][$fieldname]['method'];
792  $resultload = dol_include_once($file);
793  if (empty($resultload)) {
794  dol_print_error('', 'Error trying to call file=' . $file . ', class=' . $class . ', method=' . $method);
795  break;
796  }
797  $classinstance = new $class($this->db);
798  $res = call_user_func_array(array($classinstance, $method), array(&$arrayrecord, $listfields, ($key - 1)));
799  $fieldArr = explode('.', $fieldname);
800  if (count($fieldArr) > 0) {
801  $fieldname = $fieldArr[1];
802  }
803  $listfields[] = $fieldname;
804  $listvalues[] = $res;
805  }
806  }
807  } else {
808  $this->errors[$error]['lib'] = 'Bad value of profile setup '.$val.' for array_import_fieldshidden';
809  $this->errors[$error]['type'] = 'Import profile setup';
810  $error++;
811  }
812  }
813  }
814  //print 'listfields='.$listfields.'<br>listvalues='.$listvalues.'<br>';
815 
816  // If no error for this $alias/$tablename, we have a complete $listfields and $listvalues that are defined
817  // so we can try to make the insert or update now.
818  if (!$errorforthistable) {
819  //print "$alias/$tablename/$listfields/$listvalues<br>";
820  if (!empty($listfields)) {
821  $updatedone = false;
822  $insertdone = false;
823 
824  $is_table_category_link = false;
825  $fname = 'rowid';
826  if (strpos($tablename, '_categorie_') !== false) {
827  $is_table_category_link = true;
828  $fname='*';
829  }
830 
831  if (!empty($updatekeys)) {
832  // We do SELECT to get the rowid, if we already have the rowid, it's to be used below for related tables (extrafields)
833 
834  if (empty($lastinsertid)) { // No insert done yet for a parent table
835  $sqlSelect = "SELECT ".$fname." FROM ".$tablename;
836 
837  $data = array_combine($listfields, $listvalues);
838  $where = array(); // filters to forge SQL request
839  $filters = array(); // filters to forge output error message
840  foreach ($updatekeys as $key) {
841  $col = $objimport->array_import_updatekeys[0][$key];
842  $key = preg_replace('/^.*\./i', '', $key);
843  if ($conf->socialnetworks->enabled && strpos($key, "socialnetworks") !== false) {
844  $tmp = explode("_", $key);
845  $key = $tmp[0];
846  $socialnetwork = $tmp[1];
847  $jsondata = $data[$key];
848  $json = json_decode($jsondata);
849  $stringtosearch = json_encode($socialnetwork).':'.json_encode($json->$socialnetwork);
850  //var_dump($stringtosearch);
851  //var_dump($this->db->escape($stringtosearch)); // This provide a value for sql string (but not for a like)
852  $where[] = $key." LIKE '%".$this->db->escapeforlike($this->db->escape($stringtosearch))."%'";
853  $filters[] = $col." LIKE '%".$this->db->escapeforlike($this->db->escape($stringtosearch))."%'";
854  //var_dump($where[1]); // This provide a value for sql string inside a like
855  } else {
856  $where[] = $key.' = '.$data[$key];
857  $filters[] = $col.' = '.$data[$key];
858  }
859  }
860  $sqlSelect .= " WHERE ".implode(' AND ', $where);
861 
862  $resql = $this->db->query($sqlSelect);
863  if ($resql) {
864  $num_rows = $this->db->num_rows($resql);
865  if ($num_rows == 1) {
866  $res = $this->db->fetch_object($resql);
867  $lastinsertid = $res->rowid;
868  if ($is_table_category_link) $lastinsertid = 'linktable'; // used to apply update on tables like llx_categorie_product and avoid being blocked for all file content if at least one entry already exists
869  $last_insert_id_array[$tablename] = $lastinsertid;
870  } elseif ($num_rows > 1) {
871  $this->errors[$error]['lib'] = $langs->trans('MultipleRecordFoundWithTheseFilters', implode(', ', $filters));
872  $this->errors[$error]['type'] = 'SQL';
873  $error++;
874  } else {
875  // No record found with filters, insert will be tried below
876  }
877  } else {
878  //print 'E';
879  $this->errors[$error]['lib'] = $this->db->lasterror();
880  $this->errors[$error]['type'] = 'SQL';
881  $error++;
882  }
883  } else {
884  // We have a last INSERT ID (got by previous pass), so we check if we have a row referencing this foreign key.
885  // This is required when updating table with some extrafields. When inserting a record in parent table, we can make
886  // a direct insert into subtable extrafields, but when me wake an update, the insertid is defined and the child record
887  // may already exists. So we rescan the extrafield table to know if record exists or not for the rowid.
888  // Note: For extrafield tablename, we have in importfieldshidden_array an enty 'extra.fk_object'=>'lastrowid-tableparent' so $keyfield is 'fk_object'
889  $sqlSelect = "SELECT rowid FROM ".$tablename;
890 
891  if (empty($keyfield)) {
892  $keyfield = 'rowid';
893  }
894  $sqlSelect .= " WHERE ".$keyfield." = ".((int) $lastinsertid);
895 
896  $resql = $this->db->query($sqlSelect);
897  if ($resql) {
898  $res = $this->db->fetch_object($resql);
899  if ($this->db->num_rows($resql) == 1) {
900  // We have a row referencing this last foreign key, continue with UPDATE.
901  } else {
902  // No record found referencing this last foreign key,
903  // force $lastinsertid to 0 so we INSERT below.
904  $lastinsertid = 0;
905  }
906  } else {
907  //print 'E';
908  $this->errors[$error]['lib'] = $this->db->lasterror();
909  $this->errors[$error]['type'] = 'SQL';
910  $error++;
911  }
912  }
913 
914  if (!empty($lastinsertid)) {
915  // We db escape social network field because he isn't in field creation
916  if (in_array("socialnetworks", $listfields)) {
917  $socialkey = array_search("socialnetworks", $listfields);
918  $tmpsql = $listvalues[$socialkey];
919  $listvalues[$socialkey] = "'".$this->db->escape($tmpsql)."'";
920  }
921 
922  // Build SQL UPDATE request
923  $sqlstart = "UPDATE ".$tablename;
924 
925  $data = array_combine($listfields, $listvalues);
926  $set = array();
927  foreach ($data as $key => $val) {
928  $set[] = $key." = ".$val;
929  }
930  $sqlstart .= " SET ".implode(', ', $set);
931 
932  if (empty($keyfield)) {
933  $keyfield = 'rowid';
934  }
935  $sqlend = " WHERE ".$keyfield." = ".((int) $lastinsertid);
936 
937  if ($is_table_category_link) {
938  $sqlend = " WHERE " . implode(' AND ', $where);
939  }
940 
941  $sql = $sqlstart.$sqlend;
942 
943  // Run update request
944  $resql = $this->db->query($sql);
945  if ($resql) {
946  // No error, update has been done. $this->db->db->affected_rows can be 0 if data hasn't changed
947  $updatedone = true;
948  } else {
949  //print 'E';
950  $this->errors[$error]['lib'] = $this->db->lasterror();
951  $this->errors[$error]['type'] = 'SQL';
952  $error++;
953  }
954  }
955  }
956 
957  // Update not done, we do insert
958  if (!$error && !$updatedone) {
959  // We db escape social network field because he isn't in field creation
960  if (in_array("socialnetworks", $listfields)) {
961  $socialkey = array_search("socialnetworks", $listfields);
962  $tmpsql = $listvalues[$socialkey];
963  $listvalues[$socialkey] = "'".$this->db->escape($tmpsql)."'";
964  }
965 
966  // Build SQL INSERT request
967  $sqlstart = "INSERT INTO ".$tablename."(".implode(", ", $listfields).", import_key";
968  $sqlend = ") VALUES(".implode(', ', $listvalues).", '".$this->db->escape($importid)."'";
969  if (!empty($tablewithentity_cache[$tablename])) {
970  $sqlstart .= ", entity";
971  $sqlend .= ", ".$conf->entity;
972  }
973  if (!empty($objimport->array_import_tables_creator[0][$alias])) {
974  $sqlstart .= ", ".$objimport->array_import_tables_creator[0][$alias];
975  $sqlend .= ", ".$user->id;
976  }
977  $sql = $sqlstart.$sqlend.")";
978  //dol_syslog("import_csv.modules", LOG_DEBUG);
979 
980  // Run insert request
981  if ($sql) {
982  $resql = $this->db->query($sql);
983  if ($resql) {
984  $last_insert_id_array[$tablename] = $this->db->last_insert_id($tablename); // store the last inserted auto_increment id for each table, so that child tables can be inserted with the appropriate id. This must be done just after the INSERT request, else we risk losing the id (because another sql query will be issued somewhere in Dolibarr).
985  $insertdone = true;
986  } else {
987  //print 'E';
988  $this->errors[$error]['lib'] = $this->db->lasterror();
989  $this->errors[$error]['type'] = 'SQL';
990  $error++;
991  }
992  }
993  }
994  }
995  /*else
996  {
997  dol_print_error('','ErrorFieldListEmptyFor '.$alias."/".$tablename);
998  }*/
999  }
1000 
1001  if ($error) {
1002  break;
1003  }
1004  }
1005 
1006  if ($updatedone) {
1007  $this->nbupdate++;
1008  }
1009  if ($insertdone) {
1010  $this->nbinsert++;
1011  }
1012  }
1013 
1014  return 1;
1015  }
1016 }
1017 
1024 function cleansep($value)
1025 {
1026  return str_replace(array(',', ';'), '/', $value);
1027 };
if(!function_exists('dol_getprefix')) dol_include_once($relpath, $classname= '')
Make an include_once using default root and alternate root if it fails.
dol_osencode($str)
Return a string encoded into OS filesystem encoding.
GETPOST($paramname, $check= 'alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0)
Return value of a param into GET or POST supervariable.
write_footer_example($outputlangs)
Output footer of an example file for this format.
import_insert($arrayrecord, $array_match_file_to_database, $objimport, $maxfields, $importid, $updatekeys)
Insert a record into database.
cleansep($value)
Clean a string from separator.
$conf db
API class for accounts.
Definition: inc.php:41
import_close_file()
Close file handle.
__construct($db, $datatoimport)
Constructor.
dol_stringtotime($string, $gm=1)
Convert a string date into a GM Timestamps date Warning: YYYY-MM-DDTHH:MM:SS+02:00 (RFC3339) is not s...
Definition: date.lib.php:383
num2Alpha($n)
Return a numeric value into an Excel like column number.
import_get_nb_of_lines($file)
Return nb of records.
import_read_record()
Return array of next record in input file.
Class to manage third parties objects (customers, suppliers, prospects...)
dol_strlen($string, $stringencoding= 'UTF-8')
Make a strlen call.
price2num($amount, $rounding= '', $option=0)
Function that return a number with universal decimal format (decimal separator is &#39;...
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename= '', $restricttologhandler= '', $logcontext=null)
Write log message into outputs.
utf8_check($str)
Check if a string is in UTF8.
dol_count_nb_of_line($file)
Count number of lines in a file.
Definition: files.lib.php:549
Class to import CSV files.
if(isModEnabled('facture')&&!empty($user->rights->facture->lire)) if((isModEnabled('fournisseur')&&empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD)&&$user->rights->fournisseur->facture->lire)||(isModEnabled('supplier_invoice')&&$user->rights->supplier_invoice->lire)) if(isModEnabled('don')&&!empty($user->rights->don->lire)) if(isModEnabled('tax')&&!empty($user->rights->tax->charges->lire)) if(isModEnabled('facture')&&isModEnabled('commande')&&$user->rights->commande->lire &&empty($conf->global->WORKFLOW_DISABLE_CREATE_INVOICE_FROM_ORDER)) $resql
Social contributions to pay.
Definition: index.php:742
write_header_example($outputlangs)
Output header of an example file for this format.
Parent class for import file readers.
write_title_example($outputlangs, $headerlinefields)
Output title line of an example file for this format.
write_record_example($outputlangs, $contentlinevalues)
Output record of an example file for this format.
testSqlAndScriptInject($val, $type)
Security: WAF layer for SQL Injection and XSS Injection (scripts) protection (Filters on GET...
Definition: main.inc.php:87
dol_print_error($db= '', $error= '', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
import_open_file($file)
Open input file.
dol_trunc($string, $size=40, $trunc= 'right', $stringencoding= 'UTF-8', $nodot=0, $display=0)
Truncate a string to a particular length adding &#39;…&#39; if string larger than length. ...
import_read_header()
Input header line from file.