dolibarr  9.0.0
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 <http://www.gnu.org/licenses/>.
19  * or see http://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  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)) $this->thirpartyobject=new Societe($this->db);
118  }
119 
120 
121  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
128  function write_header_example($outputlangs)
129  {
130  // phpcs:enable
131  return '';
132  }
133 
134  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
142  function write_title_example($outputlangs,$headerlinefields)
143  {
144  // phpcs:enable
145  $s=join($this->separator,array_map('cleansep',$headerlinefields));
146  return $s."\n";
147  }
148 
149  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
157  function write_record_example($outputlangs,$contentlinevalues)
158  {
159  // phpcs:enable
160  $s=join($this->separator,array_map('cleansep',$contentlinevalues));
161  return $s."\n";
162  }
163 
164  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
171  function write_footer_example($outputlangs)
172  {
173  // phpcs:enable
174  return '';
175  }
176 
177 
178 
179  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
186  function import_open_file($file)
187  {
188  // phpcs:enable
189  global $langs;
190  $ret=1;
191 
192  dol_syslog(get_class($this)."::open_file file=".$file);
193 
194  ini_set('auto_detect_line_endings',1); // For MAC compatibility
195 
196  $this->handle = fopen(dol_osencode($file), "r");
197  if (! $this->handle)
198  {
199  $langs->load("errors");
200  $this->error=$langs->trans("ErrorFailToOpenFile",$file);
201  $ret=-1;
202  }
203  else
204  {
205  $this->file=$file;
206  }
207 
208  return $ret;
209  }
210 
211 
212  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
219  function import_get_nb_of_lines($file)
220  {
221  // phpcs:enable
222  return dol_count_nb_of_line($file);
223  }
224 
225 
226  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
233  {
234  // phpcs:enable
235  return 0;
236  }
237 
238 
239  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
246  {
247  // phpcs:enable
248  global $conf;
249 
250  $arrayres=fgetcsv($this->handle,100000,$this->separator,$this->enclosure,$this->escape);
251 
252  // End of file
253  if ($arrayres === false) return false;
254 
255  //var_dump($this->handle);
256  //var_dump($arrayres);exit;
257  $newarrayres=array();
258  if ($arrayres && is_array($arrayres))
259  {
260  foreach($arrayres as $key => $val)
261  {
262  if (! empty($conf->global->IMPORT_CSV_FORCE_CHARSET)) // Forced charset
263  {
264  if (strtolower($conf->global->IMPORT_CSV_FORCE_CHARSET) == 'utf8')
265  {
266  $newarrayres[$key]['val']=$val;
267  $newarrayres[$key]['type']=(dol_strlen($val)?1:-1); // If empty we considere it's null
268  }
269  else
270  {
271  $newarrayres[$key]['val']=utf8_encode($val);
272  $newarrayres[$key]['type']=(dol_strlen($val)?1:-1); // If empty we considere it's null
273  }
274  }
275  else // Autodetect format (UTF8 or ISO)
276  {
277  if (utf8_check($val))
278  {
279  $newarrayres[$key]['val']=$val;
280  $newarrayres[$key]['type']=(dol_strlen($val)?1:-1); // If empty we considere it's null
281  }
282  else
283  {
284  $newarrayres[$key]['val']=utf8_encode($val);
285  $newarrayres[$key]['type']=(dol_strlen($val)?1:-1); // If empty we considere it's null
286  }
287  }
288  }
289 
290  $this->col=count($newarrayres);
291  }
292 
293  return $newarrayres;
294  }
295 
296  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
302  function import_close_file()
303  {
304  // phpcs:enable
305  fclose($this->handle);
306  return 0;
307  }
308 
309 
310  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
322  function import_insert($arrayrecord,$array_match_file_to_database,$objimport,$maxfields,$importid,$updatekeys)
323  {
324  // phpcs:enable
325  global $langs,$conf,$user;
326  global $thirdparty_static; // Specific to thirdparty import
327  global $tablewithentity_cache; // Cache to avoid to call desc at each rows on tables
328 
329  $error=0;
330  $warning=0;
331  $this->errors=array();
332  $this->warnings=array();
333 
334  //dol_syslog("import_csv.modules maxfields=".$maxfields." importid=".$importid);
335 
336  //var_dump($array_match_file_to_database);
337  //var_dump($arrayrecord);
338  $array_match_database_to_file=array_flip($array_match_file_to_database);
339  $sort_array_match_file_to_database=$array_match_file_to_database;
340  ksort($sort_array_match_file_to_database);
341 
342  //var_dump($sort_array_match_file_to_database);
343 
344  if (count($arrayrecord) == 0 || (count($arrayrecord) == 1 && empty($arrayrecord[0]['val'])))
345  {
346  //print 'W';
347  $this->warnings[$warning]['lib']=$langs->trans('EmptyLine');
348  $this->warnings[$warning]['type']='EMPTY';
349  $warning++;
350  }
351  else
352  {
353  $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)
354  $updatedone = false;
355  $insertdone = false;
356  // For each table to insert, me make a separate insert
357  foreach($objimport->array_import_tables[0] as $alias => $tablename)
358  {
359  // Build sql request
360  $sql='';
361  $listfields=array();
362  $listvalues=array();
363  $i=0;
364  $errorforthistable=0;
365 
366  // Define $tablewithentity_cache[$tablename] if not already defined
367  if (! isset($tablewithentity_cache[$tablename])) // keep this test with "isset"
368  {
369  dol_syslog("Check if table ".$tablename." has an entity field");
370  $resql=$this->db->DDLDescTable($tablename,'entity');
371  if ($resql)
372  {
373  $obj=$this->db->fetch_object($resql);
374  if ($obj) $tablewithentity_cache[$tablename]=1; // table contains entity field
375  else $tablewithentity_cache[$tablename]=0; // table does not contains entity field
376  }
377  else dol_print_error($this->db);
378  }
379  else
380  {
381  //dol_syslog("Table ".$tablename." check for entity into cache is ".$tablewithentity_cache[$tablename]);
382  }
383 
384 
385  // Loop on each fields in the match array: $key = 1..n, $val=alias of field (s.nom)
386  foreach($sort_array_match_file_to_database as $key => $val)
387  {
388  $fieldalias=preg_replace('/\..*$/i','',$val);
389  $fieldname=preg_replace('/^.*\./i','',$val);
390 
391  if ($alias != $fieldalias) continue; // Not a field of current table
392 
393  if ($key <= $maxfields)
394  {
395  // Set $newval with value to insert and set $listvalues with sql request part for insert
396  $newval='';
397  if ($arrayrecord[($key-1)]['type'] > 0) $newval=$arrayrecord[($key-1)]['val']; // If type of field into input file is not empty string (so defined into input file), we get value
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  {
404  $this->errors[$error]['lib']=$langs->trans('ErrorMissingMandatoryValue',$key);
405  $this->errors[$error]['type']='NOTNULL';
406  $errorforthistable++;
407  $error++;
408  }
409  // Test format only if field is not a missing mandatory field (field may be a value or empty but not mandatory)
410  else
411  {
412  // We convert field if required
413  if (! empty($objimport->array_import_convertvalue[0][$val]))
414  {
415  //print 'Must convert '.$newval.' with rule '.join(',',$objimport->array_import_convertvalue[0][$val]).'. ';
416  if ($objimport->array_import_convertvalue[0][$val]['rule']=='fetchidfromcodeid'
417  || $objimport->array_import_convertvalue[0][$val]['rule']=='fetchidfromref'
418  || $objimport->array_import_convertvalue[0][$val]['rule']=='fetchidfromcodeorlabel'
419  )
420  {
421  // 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.
422  $isidorref='id';
423  if (! is_numeric($newval) && $newval != '' && ! preg_match('/^id:/i',$newval)) $isidorref='ref';
424  $newval=preg_replace('/^(id|ref):/i','',$newval); // Remove id: or ref: that was used to force if field is id or ref
425  //print 'Val is now '.$newval.' and is type '.$isidorref."<br>\n";
426 
427  if ($isidorref == 'ref') // If value into input import file is a ref, we apply the function defined into descriptor
428  {
429  $file=(empty($objimport->array_import_convertvalue[0][$val]['classfile'])?$objimport->array_import_convertvalue[0][$val]['file']:$objimport->array_import_convertvalue[0][$val]['classfile']);
430  $class=$objimport->array_import_convertvalue[0][$val]['class'];
431  $method=$objimport->array_import_convertvalue[0][$val]['method'];
432  if ($this->cacheconvert[$file.'_'.$class.'_'.$method.'_'][$newval] != '')
433  {
434  $newval=$this->cacheconvert[$file.'_'.$class.'_'.$method.'_'][$newval];
435  }
436  else
437  {
438  $resultload = dol_include_once($file);
439  if (empty($resultload))
440  {
441  dol_print_error('', 'Error trying to call file='.$file.', class='.$class.', method='.$method);
442  break;
443  }
444  $classinstance=new $class($this->db);
445  // Try the fetch from code or ref
446  call_user_func_array(array($classinstance, $method),array('', $newval));
447  // If not found, try the fetch from label
448  if (! ($classinstance->id != '') && $objimport->array_import_convertvalue[0][$val]['rule']=='fetchidfromcodeorlabel')
449  {
450  call_user_func_array(array($classinstance, $method),array('', '', $newval));
451  }
452  $this->cacheconvert[$file.'_'.$class.'_'.$method.'_'][$newval]=$classinstance->id;
453  //print 'We have made a '.$class.'->'.$method.' to get id from code '.$newval.'. ';
454  if ($classinstance->id != '') // id may be 0, it is a found value
455  {
456  $newval=$classinstance->id;
457  }
458  else
459  {
460  if (!empty($objimport->array_import_convertvalue[0][$val]['dict'])) $this->errors[$error]['lib']=$langs->trans('ErrorFieldValueNotIn',$key,$newval,'code',$langs->transnoentitiesnoconv($objimport->array_import_convertvalue[0][$val]['dict']));
461  else if (!empty($objimport->array_import_convertvalue[0][$val]['element'])) $this->errors[$error]['lib']=$langs->trans('ErrorFieldRefNotIn',$key,$newval,$langs->transnoentitiesnoconv($objimport->array_import_convertvalue[0][$val]['element']));
462  else $this->errors[$error]['lib']='ErrorFieldValueNotIn';
463  $this->errors[$error]['type']='FOREIGNKEY';
464  $errorforthistable++;
465  $error++;
466  }
467  }
468  }
469  }
470  elseif ($objimport->array_import_convertvalue[0][$val]['rule']=='zeroifnull')
471  {
472  if (empty($newval)) $newval='0';
473  }
474  elseif ($objimport->array_import_convertvalue[0][$val]['rule']=='getcustomercodeifauto')
475  {
476  if (strtolower($newval) == 'auto')
477  {
478  $this->thirpartyobject->get_codeclient(0,0);
479  $newval=$this->thirpartyobject->code_client;
480  //print 'code_client='.$newval;
481  }
482  if (empty($newval)) $arrayrecord[($key-1)]['type']=-1; // If we get empty value, we will use "null"
483  }
484  elseif ($objimport->array_import_convertvalue[0][$val]['rule']=='getsuppliercodeifauto')
485  {
486  if (strtolower($newval) == 'auto')
487  {
488  $newval=$this->thirpartyobject->get_codefournisseur(0,1);
489  $newval=$this->thirpartyobject->code_fournisseur;
490  //print 'code_fournisseur='.$newval;
491  }
492  if (empty($newval)) $arrayrecord[($key-1)]['type']=-1; // If we get empty value, we will use "null"
493  }
494  elseif ($objimport->array_import_convertvalue[0][$val]['rule']=='getcustomeraccountancycodeifauto')
495  {
496  if (strtolower($newval) == 'auto')
497  {
498  $this->thirpartyobject->get_codecompta('customer');
499  $newval=$this->thirpartyobject->code_compta;
500  //print 'code_compta='.$newval;
501  }
502  if (empty($newval)) $arrayrecord[($key-1)]['type']=-1; // If we get empty value, we will use "null"
503  }
504  elseif ($objimport->array_import_convertvalue[0][$val]['rule']=='getsupplieraccountancycodeifauto')
505  {
506  if (strtolower($newval) == 'auto')
507  {
508  $this->thirpartyobject->get_codecompta('supplier');
509  $newval=$this->thirpartyobject->code_compta_fournisseur;
510  if (empty($newval)) $arrayrecord[($key-1)]['type']=-1; // If we get empty value, we will use "null"
511  //print 'code_compta_fournisseur='.$newval;
512  }
513  if (empty($newval)) $arrayrecord[($key-1)]['type']=-1; // If we get empty value, we will use "null"
514  }
515  elseif ($objimport->array_import_convertvalue[0][$val]['rule']=='getrefifauto')
516  {
517  $defaultref='';
518  // TODO provide the $modTask (module of generation of ref) as parameter of import_insert function
519  $obj = empty($conf->global->PROJECT_TASK_ADDON)?'mod_task_simple':$conf->global->PROJECT_TASK_ADDON;
520  if (! empty($conf->global->PROJECT_TASK_ADDON) && is_readable(DOL_DOCUMENT_ROOT ."/core/modules/project/task/".$conf->global->PROJECT_TASK_ADDON.".php"))
521  {
522  require_once DOL_DOCUMENT_ROOT ."/core/modules/project/task/".$conf->global->PROJECT_TASK_ADDON.'.php';
523  $modTask = new $obj;
524  $defaultref = $modTask->getNextValue(null,null);
525  }
526  if (is_numeric($defaultref) && $defaultref <= 0) $defaultref='';
527  $newval=$defaultref;
528  }
529 
530 
531  elseif ($objimport->array_import_convertvalue[0][$val]['rule']=='numeric')
532  {
533  $newval = price2num($newval);
534  }
535 
536  //print 'Val to use as insert is '.$newval.'<br>';
537  }
538 
539  // Test regexp
540  if (! empty($objimport->array_import_regex[0][$val]) && ($newval != ''))
541  {
542  // If test is "Must exist in a field@table"
543  if (preg_match('/^(.*)@(.*)$/',$objimport->array_import_regex[0][$val],$reg))
544  {
545  $field=$reg[1];
546  $table=$reg[2];
547 
548  // Load content of field@table into cache array
549  if (! is_array($this->cachefieldtable[$field.'@'.$table])) // If content of field@table not already loaded into cache
550  {
551  $sql="SELECT ".$field." as aliasfield FROM ".$table;
552  $resql=$this->db->query($sql);
553  if ($resql)
554  {
555  $num=$this->db->num_rows($resql);
556  $i=0;
557  while ($i < $num)
558  {
559  $obj=$this->db->fetch_object($resql);
560  if ($obj) $this->cachefieldtable[$field.'@'.$table][]=$obj->aliasfield;
561  $i++;
562  }
563  }
564  else
565  {
566  dol_print_error($this->db);
567  }
568  }
569 
570  // Now we check cache is not empty (should not) and key is into cache
571  if (! is_array($this->cachefieldtable[$field.'@'.$table]) || ! in_array($newval,$this->cachefieldtable[$field.'@'.$table]))
572  {
573  $this->errors[$error]['lib']=$langs->transnoentitiesnoconv('ErrorFieldValueNotIn',$key,$newval,$field,$table);
574  $this->errors[$error]['type']='FOREIGNKEY';
575  $errorforthistable++;
576  $error++;
577  }
578  }
579  // If test is just a static regex
580  else if (! preg_match('/'.$objimport->array_import_regex[0][$val].'/i',$newval))
581  {
582  //if ($key == 19) print "xxx".$newval."zzz".$objimport->array_import_regex[0][$val]."<br>";
583  $this->errors[$error]['lib']=$langs->transnoentitiesnoconv('ErrorWrongValueForField',$key,$newval,$objimport->array_import_regex[0][$val]);
584  $this->errors[$error]['type']='REGEX';
585  $errorforthistable++;
586  $error++;
587  }
588  }
589 
590  // Other tests
591  // ...
592  }
593 
594  // Define $listfields and $listvalues to build SQL request
595  $listfields[] = $fieldname;
596 
597  // Note: arrayrecord (and 'type') is filled with ->import_read_record called by import.php page before calling import_insert
598  if (empty($newval) && $arrayrecord[($key-1)]['type'] < 0) {
599  $listvalues[] = ($newval=='0'?$newval:"null");
600  } elseif (empty($newval) && $arrayrecord[($key-1)]['type'] == 0) {
601  $listvalues[] = "''";
602  } else {
603  $listvalues[] = "'".$this->db->escape($newval)."'";
604  }
605  }
606  $i++;
607  }
608 
609  // We add hidden fields (but only if there is at least one field to add into table)
610  if (!empty($listfields) && is_array($objimport->array_import_fieldshidden[0]))
611  {
612  // Loop on each hidden fields to add them into listfields/listvalues
613  foreach($objimport->array_import_fieldshidden[0] as $key => $val)
614  {
615  if (! preg_match('/^'.preg_quote($alias).'\./', $key)) continue; // Not a field of current table
616  if ($val == 'user->id')
617  {
618  $listfields[] = preg_replace('/^'.preg_quote($alias).'\./','',$key);
619  $listvalues[] = $user->id;
620  }
621  elseif (preg_match('/^lastrowid-/',$val))
622  {
623  $tmp=explode('-',$val);
624  $lastinsertid=(isset($last_insert_id_array[$tmp[1]]))?$last_insert_id_array[$tmp[1]]:0;
625  $keyfield = preg_replace('/^'.preg_quote($alias).'\./','',$key);
626  $listfields[] = $keyfield;
627  $listvalues[] = $lastinsertid;
628  //print $key."-".$val."-".$listfields."-".$listvalues."<br>";exit;
629  }
630  }
631  }
632  //print 'listfields='.$listfields.'<br>listvalues='.$listvalues.'<br>';
633 
634  // If no error for this $alias/$tablename, we have a complete $listfields and $listvalues that are defined
635  // so we can try to make the insert or update now.
636  if (! $errorforthistable)
637  {
638  //print "$alias/$tablename/$listfields/$listvalues<br>";
639  if (!empty($listfields))
640  {
641  $updatedone = false;
642  $insertdone = false;
643 
644  if (!empty($updatekeys)) {
645  // We do SELECT to get the rowid, if we already have the rowid, it's to be used below for related tables (extrafields)
646 
647  if (empty($lastinsertid)) { // No insert done yet for a parent table
648  $sqlSelect = 'SELECT rowid FROM '.$tablename;
649 
650  $data = array_combine($listfields, $listvalues);
651  $where = array();
652  $filters = array();
653  foreach ($updatekeys as $key) {
654  $col = $objimport->array_import_updatekeys[0][$key];
655  $key=preg_replace('/^.*\./i','',$key);
656  $where[] = $key.' = '.$data[$key];
657  $filters[] = $col.' = '.$data[$key];
658  }
659  $sqlSelect.= ' WHERE '.implode(' AND ', $where);
660 
661  $resql=$this->db->query($sqlSelect);
662  if($resql) {
663  $res = $this->db->fetch_object($resql);
664  if($resql->num_rows == 1) {
665  $lastinsertid = $res->rowid;
666  $last_insert_id_array[$tablename] = $lastinsertid;
667  } else if($resql->num_rows > 1) {
668  $this->errors[$error]['lib']=$langs->trans('MultipleRecordFoundWithTheseFilters', implode($filters, ', '));
669  $this->errors[$error]['type']='SQL';
670  $error++;
671  } else {
672  // No record found with filters, insert will be tried below
673  }
674  }
675  else
676  {
677  //print 'E';
678  $this->errors[$error]['lib']=$this->db->lasterror();
679  $this->errors[$error]['type']='SQL';
680  $error++;
681  }
682  } else {
683  // We have a last INSERT ID (got by previous pass), so we check if we have a row referencing this foreign key.
684  // This is required when updating table with some extrafields. When inserting a record in parent table, we can make
685  // a direct insert into subtable extrafields, but when me wake an update, the insertid is defined and the child record
686  // may already exists. So we rescan the extrafield table to know if record exists or not for the rowid.
687  // Note: For extrafield tablename, we have in importfieldshidden_array an enty 'extra.fk_object'=>'lastrowid-tableparent' so $keyfield is 'fk_object'
688  $sqlSelect = 'SELECT rowid FROM '.$tablename;
689 
690  if(empty($keyfield)) $keyfield = 'rowid';
691  $sqlSelect .= ' WHERE '.$keyfield.' = '.$lastinsertid;
692 
693  $resql=$this->db->query($sqlSelect);
694  if($resql) {
695  $res = $this->db->fetch_object($resql);
696  if($resql->num_rows == 1) {
697  // We have a row referencing this last foreign key, continue with UPDATE.
698  } else {
699  // No record found referencing this last foreign key,
700  // force $lastinsertid to 0 so we INSERT below.
701  $lastinsertid = 0;
702  }
703  }
704  else
705  {
706  //print 'E';
707  $this->errors[$error]['lib']=$this->db->lasterror();
708  $this->errors[$error]['type']='SQL';
709  $error++;
710  }
711  }
712 
713  if (!empty($lastinsertid)) {
714  // Build SQL UPDATE request
715  $sqlstart = 'UPDATE '.$tablename;
716 
717  $data = array_combine($listfields, $listvalues);
718  $set = array();
719  foreach ($data as $key => $val) {
720  $set[] = $key.' = '.$val;
721  }
722  $sqlstart.= ' SET '.implode(', ', $set);
723 
724  if(empty($keyfield)) $keyfield = 'rowid';
725  $sqlend = ' WHERE '.$keyfield.' = '.$lastinsertid;
726 
727  $sql = $sqlstart.$sqlend;
728 
729  // Run update request
730  $resql=$this->db->query($sql);
731  if($resql) {
732  // No error, update has been done. $this->db->db->affected_rows can be 0 if data hasn't changed
733  $updatedone = true;
734  }
735  else
736  {
737  //print 'E';
738  $this->errors[$error]['lib']=$this->db->lasterror();
739  $this->errors[$error]['type']='SQL';
740  $error++;
741  }
742  }
743  }
744 
745  // Update not done, we do insert
746  if (!$error && !$updatedone) {
747  // Build SQL INSERT request
748  $sqlstart = 'INSERT INTO '.$tablename.'('.implode(', ', $listfields).', import_key';
749  $sqlend = ') VALUES('.implode(', ', $listvalues).", '".$importid."'";
750  if (! empty($tablewithentity_cache[$tablename])) {
751  $sqlstart.= ', entity';
752  $sqlend.= ', '.$conf->entity;
753  }
754  if (! empty($objimport->array_import_tables_creator[0][$alias])) {
755  $sqlstart.= ', '.$objimport->array_import_tables_creator[0][$alias];
756  $sqlend.=', '.$user->id;
757  }
758  $sql = $sqlstart.$sqlend.')';
759  dol_syslog("import_csv.modules", LOG_DEBUG);
760 
761  // Run insert request
762  if ($sql)
763  {
764  $resql=$this->db->query($sql);
765  if ($resql)
766  {
767  $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).
768  $insertdone = true;
769  }
770  else
771  {
772  //print 'E';
773  $this->errors[$error]['lib']=$this->db->lasterror();
774  $this->errors[$error]['type']='SQL';
775  $error++;
776  }
777  }
778  }
779  }
780  /*else
781  {
782  dol_print_error('','ErrorFieldListEmptyFor '.$alias."/".$tablename);
783  }*/
784  }
785 
786  if ($error) break;
787  }
788 
789  if($updatedone) $this->nbupdate++;
790  if($insertdone) $this->nbinsert++;
791  }
792 
793  return 1;
794  }
795 }
796 
803 function cleansep($value)
804 {
805  return str_replace(array(',',';'),'/',$value);
806 };
print $object label
hash of file content (md5_file(dol_osencode($destfull))
Definition: edit.php:153
dol_osencode($str)
Return a string encoded into OS filesystem encoding.
write_footer_example($outputlangs)
Output footer of an example file for this format.
GETPOST($paramname, $check='none', $method=0, $filter=null, $options=null, $noreplace=0)
Return value of a param into GET or POST supervariable.
if(! empty($conf->facture->enabled) && $user->rights->facture->lire) if(! empty($conf->fournisseur->enabled) && $user->rights->fournisseur->facture->lire) if(! empty($conf->don->enabled) && $user->rights->societe->lire) if(! empty($conf->tax->enabled) && $user->rights->tax->charges->lire) if(! empty($conf->facture->enabled) &&! empty($conf->commande->enabled) && $user->rights->commande->lire &&empty($conf->global->WORKFLOW_DISABLE_CREATE_INVOICE_FROM_ORDER)) if(! empty($conf->facture->enabled) && $user->rights->facture->lire) if(! empty($conf->fournisseur->enabled) && $user->rights->fournisseur->facture->lire) $resql
Social contributions to pay.
Definition: index.php:1053
import_insert($arrayrecord, $array_match_file_to_database, $objimport, $maxfields, $importid, $updatekeys)
Insert a record into database.
cleansep($value)
Clean a string from separator.
import_close_file()
Close file handle.
__construct($db, $datatoimport)
Constructor.
dol_print_error($db='', $error='', $errors=null)
Affiche message erreur system avec toutes les informations pour faciliter le diagnostic et la remonte...
import_get_nb_of_lines($file)
Return nb of records.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='')
Write log message into outputs.
import_read_record()
Return array of next record in input file.
Class to manage third parties objects (customers, suppliers, prospects...)
if(! function_exists('dol_getprefix')) dol_include_once($relpath, $classname='')
Make an include_once using default root and alternate root if it fails.
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:520
Class to import CSV files.
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.
import_open_file($file)
Open input file.
$version
Dolibarr version of driver string.
price2num($amount, $rounding='', $alreadysqlnb=0)
Function that return a number with universal decimal format (decimal separator is &#39;...
dol_strlen($string, $stringencoding='UTF-8')
Make a strlen call.
import_read_header()
Input header line from file.