Merge pull request #15644 from Hystepik/develop#1

New #8172 : PHPExcel replaced by PHPSpreadSheet
This commit is contained in:
Laurent Destailleur 2020-12-07 23:06:21 +01:00 committed by GitHub
commit 86e1082138
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -25,7 +25,11 @@
* \brief File to load import files with Excel format * \brief File to load import files with Excel format
*/ */
require_once DOL_DOCUMENT_ROOT.'/core/modules/import/modules_import.php'; use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
require_once DOL_DOCUMENT_ROOT . '/core/modules/import/modules_import.php';
/** /**
@ -107,17 +111,22 @@ class ImportXlsx extends ModeleImports
$this->extension = 'xlsx'; // Extension for generated file by this driver $this->extension = 'xlsx'; // Extension for generated file by this driver
$this->picto = 'mime/xls'; // Picto (This is not used by the example file code as Mime type, too bad ...) $this->picto = 'mime/xls'; // Picto (This is not used by the example file code as Mime type, too bad ...)
$this->version = '1.0'; // Driver version $this->version = '1.0'; // Driver version
// If driver use an external library, put its name here // If driver use an external library, put its name here
require_once PHPEXCEL_PATH.'PHPExcel.php'; require_once DOL_DOCUMENT_ROOT . '/includes/phpoffice/autoloader.php';
require_once PHPEXCEL_PATH.'PHPExcel/Style/Alignment.php'; require_once DOL_DOCUMENT_ROOT . '/includes/Psr/autoloader.php';
if (!class_exists('ZipArchive')) // For Excel2007, PHPExcel need ZipArchive require_once PHPEXCELNEW_PATH . 'Spreadsheet.php';
$this->workbook = new Spreadsheet();
//if ($this->id == 'excel2007new')
{ {
$langs->load("errors"); if (!class_exists('ZipArchive')) // For Excel2007
$this->error = $langs->trans('ErrorPHPNeedModule', 'zip'); {
return -1; $langs->load("errors");
$this->error = $langs->trans('ErrorPHPNeedModule', 'zip');
return -1;
} }
$this->label_lib = 'PhpExcel'; }
$this->label_lib = 'PhpSpreadSheet';
$this->version_lib = '1.8.0'; $this->version_lib = '1.8.0';
$this->datatoimport = $datatoimport; $this->datatoimport = $datatoimport;
@ -135,21 +144,12 @@ class ImportXlsx extends ModeleImports
public function write_header_example($outputlangs) public function write_header_example($outputlangs)
{ {
// phpcs:enable // phpcs:enable
global $user, $conf, $langs; global $user, $conf, $langs, $file;
// create a temporary object, the final output will be generated in footer // create a temporary object, the final output will be generated in footer
if (!empty($conf->global->MAIN_USE_FILECACHE_EXPORT_EXCEL_DIR)) { $this->workbook->getProperties()->setCreator($user->getFullName($outputlangs) . ' - Dolibarr ' . DOL_VERSION);
$cacheMethod = PHPExcel_CachedObjectStorageFactory::cache_to_discISAM; $this->workbook->getProperties()->setTitle($outputlangs->trans("Import") . ' - ' . $file);
$cacheSettings = array( $this->workbook->getProperties()->setSubject($outputlangs->trans("Import") . ' - ' . $file);
'dir' => $conf->global->MAIN_USE_FILECACHE_EXPORT_EXCEL_DIR $this->workbook->getProperties()->setDescription($outputlangs->trans("Import") . ' - ' . $file);
);
PHPExcel_Settings::setCacheStorageMethod($cacheMethod, $cacheSettings);
}
$this->workbook = new PHPExcel();
$this->workbook->getProperties()->setCreator($user->getFullName($outputlangs).' - Dolibarr '.DOL_VERSION);
$this->workbook->getProperties()->setTitle($outputlangs->trans("Import").' - '.$file);
$this->workbook->getProperties()->setSubject($outputlangs->trans("Import").' - '.$file);
$this->workbook->getProperties()->setDescription($outputlangs->trans("Import").' - '.$file);
$this->workbook->setActiveSheetIndex(0); $this->workbook->setActiveSheetIndex(0);
$this->workbook->getActiveSheet()->setTitle($outputlangs->trans("Sheet")); $this->workbook->getActiveSheet()->setTitle($outputlangs->trans("Sheet"));
@ -171,7 +171,7 @@ class ImportXlsx extends ModeleImports
// phpcs:enable // phpcs:enable
global $conf; global $conf;
$this->workbook->getActiveSheet()->getStyle('1')->getFont()->setBold(true); $this->workbook->getActiveSheet()->getStyle('1')->getFont()->setBold(true);
$this->workbook->getActiveSheet()->getStyle('1')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_LEFT); $this->workbook->getActiveSheet()->getStyle('1')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_LEFT);
$col = 0; $col = 0;
foreach ($headerlinefields as $field) { foreach ($headerlinefields as $field) {
@ -217,7 +217,7 @@ class ImportXlsx extends ModeleImports
// phpcs:enable // phpcs:enable
// return the file content as a string // return the file content as a string
$tempfile = tempnam(sys_get_temp_dir(), 'dol'); $tempfile = tempnam(sys_get_temp_dir(), 'dol');
$objWriter = new PHPExcel_Writer_Excel2007($this->workbook); $objWriter = new PhpOffice\PhpSpreadsheet\Writer\Xlsx($this->workbook);
$objWriter->save($tempfile); $objWriter->save($tempfile);
$this->workbook->disconnectWorksheets(); $this->workbook->disconnectWorksheets();
unset($this->workbook); unset($this->workbook);
@ -242,9 +242,9 @@ class ImportXlsx extends ModeleImports
global $langs; global $langs;
$ret = 1; $ret = 1;
dol_syslog(get_class($this)."::open_file file=".$file); dol_syslog(get_class($this) . "::open_file file=" . $file);
$reader = new PHPExcel_Reader_Excel2007(); $reader = new Xlsx();
$this->workbook = $reader->load($file); $this->workbook = $reader->load($file);
$this->record = 1; $this->record = 1;
$this->file = $file; $this->file = $file;
@ -263,7 +263,7 @@ class ImportXlsx extends ModeleImports
public function import_get_nb_of_lines($file) public function import_get_nb_of_lines($file)
{ {
// phpcs:enable // phpcs:enable
$reader = new PHPExcel_Reader_Excel2007(); $reader = new Xlsx();
$this->workbook = $reader->load($file); $this->workbook = $reader->load($file);
$rowcount = $this->workbook->getActiveSheet()->getHighestDataRow(); $rowcount = $this->workbook->getActiveSheet()->getHighestDataRow();
@ -286,8 +286,10 @@ class ImportXlsx extends ModeleImports
// phpcs:enable // phpcs:enable
// This is not called by the import code !!! // This is not called by the import code !!!
$this->headers = array(); $this->headers = array();
$colcount = PHPExcel_Cell::columnIndexFromString($this->workbook->getActiveSheet()->getHighestDataColumn()); $xlsx = new Xlsx();
for ($col = 0; $col < $colcount; $col++) { $info = $xlsx->listWorksheetinfo($this->file);
$countcolumns = $info[0]['totalColumns'];
for ($col = 0; $col < $countcolumns; $col++) {
$this->headers[$col] = $this->workbook->getActiveSheet()->getCellByColumnAndRow($col, 1)->getValue(); $this->headers[$col] = $this->workbook->getActiveSheet()->getCellByColumnAndRow($col, 1)->getValue();
} }
return 0; return 0;
@ -309,8 +311,10 @@ class ImportXlsx extends ModeleImports
if ($this->record > $rowcount) if ($this->record > $rowcount)
return false; return false;
$array = array(); $array = array();
$colcount = PHPExcel_Cell::columnIndexFromString($this->workbook->getActiveSheet()->getHighestDataColumn(0)); $xlsx = new Xlsx();
for ($col = 0; $col < $colcount; $col++) { $info = $xlsx->listWorksheetinfo($this->file);
$countcolumns = $info[0]['totalColumns'];
for ($col = 0; $col < $countcolumns; $col++) {
$val = $this->workbook->getActiveSheet()->getCellByColumnAndRow($col, $this->record)->getValue(); $val = $this->workbook->getActiveSheet()->getCellByColumnAndRow($col, $this->record)->getValue();
$array[$col]['val'] = $val; $array[$col]['val'] = $val;
$array[$col]['type'] = (dol_strlen($val) ? 1 : -1); // If empty we consider it null $array[$col]['type'] = (dol_strlen($val) ? 1 : -1); // If empty we consider it null
@ -368,8 +372,7 @@ class ImportXlsx extends ModeleImports
//var_dump($sort_array_match_file_to_database); //var_dump($sort_array_match_file_to_database);
if (count($arrayrecord) == 0 || (count($arrayrecord) == 1 && empty($arrayrecord[0]['val']))) if (count($arrayrecord) == 0 || (count($arrayrecord) == 1 && empty($arrayrecord[0]['val']))) {
{
//print 'W'; //print 'W';
$this->warnings[$warning]['lib'] = $langs->trans('EmptyLine'); $this->warnings[$warning]['lib'] = $langs->trans('EmptyLine');
$this->warnings[$warning]['type'] = 'EMPTY'; $this->warnings[$warning]['type'] = 'EMPTY';
@ -379,8 +382,7 @@ class ImportXlsx extends ModeleImports
$updatedone = false; $updatedone = false;
$insertdone = false; $insertdone = false;
// For each table to insert, me make a separate insert // For each table to insert, me make a separate insert
foreach ($objimport->array_import_tables[0] as $alias => $tablename) foreach ($objimport->array_import_tables[0] as $alias => $tablename) {
{
// Build sql request // Build sql request
$sql = ''; $sql = '';
$listfields = array(); $listfields = array();
@ -391,10 +393,9 @@ class ImportXlsx extends ModeleImports
// Define $tablewithentity_cache[$tablename] if not already defined // Define $tablewithentity_cache[$tablename] if not already defined
if (!isset($tablewithentity_cache[$tablename])) // keep this test with "isset" if (!isset($tablewithentity_cache[$tablename])) // keep this test with "isset"
{ {
dol_syslog("Check if table ".$tablename." has an entity field"); dol_syslog("Check if table " . $tablename . " has an entity field");
$resql = $this->db->DDLDescTable($tablename, 'entity'); $resql = $this->db->DDLDescTable($tablename, 'entity');
if ($resql) if ($resql) {
{
$obj = $this->db->fetch_object($resql); $obj = $this->db->fetch_object($resql);
if ($obj) $tablewithentity_cache[$tablename] = 1; // table contains entity field if ($obj) $tablewithentity_cache[$tablename] = 1; // table contains entity field
else $tablewithentity_cache[$tablename] = 0; // table does not contains entity field else $tablewithentity_cache[$tablename] = 0; // table does not contains entity field
@ -410,15 +411,13 @@ class ImportXlsx extends ModeleImports
} }
// Loop on each fields in the match array: $key = 1..n, $val=alias of field (s.nom) // Loop on each fields in the match array: $key = 1..n, $val=alias of field (s.nom)
foreach ($sort_array_match_file_to_database as $key => $val) foreach ($sort_array_match_file_to_database as $key => $val) {
{
$fieldalias = preg_replace('/\..*$/i', '', $val); $fieldalias = preg_replace('/\..*$/i', '', $val);
$fieldname = preg_replace('/^.*\./i', '', $val); $fieldname = preg_replace('/^.*\./i', '', $val);
if ($alias != $fieldalias) continue; // Not a field of current table if ($alias != $fieldalias) continue; // Not a field of current table
if ($key <= $maxfields) if ($key <= $maxfields) {
{
// Set $newval with value to insert and set $listvalues with sql request part for insert // Set $newval with value to insert and set $listvalues with sql request part for insert
$newval = ''; $newval = '';
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 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
@ -426,8 +425,7 @@ class ImportXlsx extends ModeleImports
// Make some tests on $newval // Make some tests on $newval
// Is it a required field ? // Is it a required field ?
if (preg_match('/\*/', $objimport->array_import_fields[0][$val]) && ((string) $newval == '')) if (preg_match('/\*/', $objimport->array_import_fields[0][$val]) && ((string) $newval == '')) {
{
$this->errors[$error]['lib'] = $langs->trans('ErrorMissingMandatoryValue', $key); $this->errors[$error]['lib'] = $langs->trans('ErrorMissingMandatoryValue', $key);
$this->errors[$error]['type'] = 'NOTNULL'; $this->errors[$error]['type'] = 'NOTNULL';
$errorforthistable++; $errorforthistable++;
@ -436,14 +434,13 @@ class ImportXlsx extends ModeleImports
// Test format only if field is not a missing mandatory field (field may be a value or empty but not mandatory) // Test format only if field is not a missing mandatory field (field may be a value or empty but not mandatory)
else { else {
// We convert field if required // We convert field if required
if (!empty($objimport->array_import_convertvalue[0][$val])) if (!empty($objimport->array_import_convertvalue[0][$val])) {
{
//print 'Must convert '.$newval.' with rule '.join(',',$objimport->array_import_convertvalue[0][$val]).'. '; //print 'Must convert '.$newval.' with rule '.join(',',$objimport->array_import_convertvalue[0][$val]).'. ';
if ($objimport->array_import_convertvalue[0][$val]['rule'] == 'fetchidfromcodeid' if (
$objimport->array_import_convertvalue[0][$val]['rule'] == 'fetchidfromcodeid'
|| $objimport->array_import_convertvalue[0][$val]['rule'] == 'fetchidfromref' || $objimport->array_import_convertvalue[0][$val]['rule'] == 'fetchidfromref'
|| $objimport->array_import_convertvalue[0][$val]['rule'] == 'fetchidfromcodeorlabel' || $objimport->array_import_convertvalue[0][$val]['rule'] == 'fetchidfromcodeorlabel'
) ) {
{
// 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. // 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.
$isidorref = 'id'; $isidorref = 'id';
if (!is_numeric($newval) && $newval != '' && !preg_match('/^id:/i', $newval)) $isidorref = 'ref'; if (!is_numeric($newval) && $newval != '' && !preg_match('/^id:/i', $newval)) $isidorref = 'ref';
@ -454,21 +451,18 @@ class ImportXlsx extends ModeleImports
$file = (empty($objimport->array_import_convertvalue[0][$val]['classfile']) ? $objimport->array_import_convertvalue[0][$val]['file'] : $objimport->array_import_convertvalue[0][$val]['classfile']); $file = (empty($objimport->array_import_convertvalue[0][$val]['classfile']) ? $objimport->array_import_convertvalue[0][$val]['file'] : $objimport->array_import_convertvalue[0][$val]['classfile']);
$class = $objimport->array_import_convertvalue[0][$val]['class']; $class = $objimport->array_import_convertvalue[0][$val]['class'];
$method = $objimport->array_import_convertvalue[0][$val]['method']; $method = $objimport->array_import_convertvalue[0][$val]['method'];
if ($this->cacheconvert[$file.'_'.$class.'_'.$method.'_'][$newval] != '') if ($this->cacheconvert[$file . '_' . $class . '_' . $method . '_'][$newval] != '') {
{ $newval = $this->cacheconvert[$file . '_' . $class . '_' . $method . '_'][$newval];
$newval = $this->cacheconvert[$file.'_'.$class.'_'.$method.'_'][$newval];
} else { } else {
$resultload = dol_include_once($file); $resultload = dol_include_once($file);
if (empty($resultload)) if (empty($resultload)) {
{ dol_print_error('', 'Error trying to call file=' . $file . ', class=' . $class . ', method=' . $method);
dol_print_error('', 'Error trying to call file='.$file.', class='.$class.', method='.$method);
break; break;
} }
$classinstance = new $class($this->db); $classinstance = new $class($this->db);
// Try the fetch from code or ref // Try the fetch from code or ref
$param_array = array('', $newval); $param_array = array('', $newval);
if ($class == 'AccountingAccount') if ($class == 'AccountingAccount') {
{
//var_dump($arrayrecord[0]['val']); //var_dump($arrayrecord[0]['val']);
/*include_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountancysystem.class.php'; /*include_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountancysystem.class.php';
$tmpchartofaccount = new AccountancySystem($this->db); $tmpchartofaccount = new AccountancySystem($this->db);
@ -485,12 +479,11 @@ class ImportXlsx extends ModeleImports
} }
call_user_func_array(array($classinstance, $method), $param_array); call_user_func_array(array($classinstance, $method), $param_array);
// If not found, try the fetch from label // If not found, try the fetch from label
if (!($classinstance->id != '') && $objimport->array_import_convertvalue[0][$val]['rule'] == 'fetchidfromcodeorlabel') if (!($classinstance->id != '') && $objimport->array_import_convertvalue[0][$val]['rule'] == 'fetchidfromcodeorlabel') {
{
$param_array = array('', '', $newval); $param_array = array('', '', $newval);
call_user_func_array(array($classinstance, $method), $param_array); call_user_func_array(array($classinstance, $method), $param_array);
} }
$this->cacheconvert[$file.'_'.$class.'_'.$method.'_'][$newval] = $classinstance->id; $this->cacheconvert[$file . '_' . $class . '_' . $method . '_'][$newval] = $classinstance->id;
//print 'We have made a '.$class.'->'.$method.' to get id from code '.$newval.'. '; //print 'We have made a '.$class.'->'.$method.' to get id from code '.$newval.'. ';
if ($classinstance->id != '') // id may be 0, it is a found value if ($classinstance->id != '') // id may be 0, it is a found value
{ {
@ -516,19 +509,19 @@ class ImportXlsx extends ModeleImports
$method = $objimport->array_import_convertvalue[0][$val]['method']; $method = $objimport->array_import_convertvalue[0][$val]['method'];
$codefromfield = $objimport->array_import_convertvalue[0][$val]['codefromfield']; $codefromfield = $objimport->array_import_convertvalue[0][$val]['codefromfield'];
$code = $arrayrecord[$arrayfield[$codefromfield]]['val']; $code = $arrayrecord[$arrayfield[$codefromfield]]['val'];
if ($this->cacheconvert[$file.'_'.$class.'_'.$method.'_'.$code][$newval] != '') { if ($this->cacheconvert[$file . '_' . $class . '_' . $method . '_' . $code][$newval] != '') {
$newval = $this->cacheconvert[$file.'_'.$class.'_'.$method.'_'.$code][$newval]; $newval = $this->cacheconvert[$file . '_' . $class . '_' . $method . '_' . $code][$newval];
} else { } else {
$resultload = dol_include_once($file); $resultload = dol_include_once($file);
if (empty($resultload)) { if (empty($resultload)) {
dol_print_error('', 'Error trying to call file='.$file.', class='.$class.', method='.$method.', code='.$code); dol_print_error('', 'Error trying to call file=' . $file . ', class=' . $class . ', method=' . $method . ', code=' . $code);
break; break;
} }
$classinstance = new $class($this->db); $classinstance = new $class($this->db);
// Try the fetch from code and ref // Try the fetch from code and ref
$param_array = array('', $newval, $code); $param_array = array('', $newval, $code);
call_user_func_array(array($classinstance, $method), $param_array); call_user_func_array(array($classinstance, $method), $param_array);
$this->cacheconvert[$file.'_'.$class.'_'.$method.'_'.$code][$newval] = $classinstance->id; $this->cacheconvert[$file . '_' . $class . '_' . $method . '_' . $code][$newval] = $classinstance->id;
if ($classinstance->id > 0) // we found record if ($classinstance->id > 0) // we found record
{ {
$newval = $classinstance->id; $newval = $classinstance->id;
@ -548,21 +541,19 @@ class ImportXlsx extends ModeleImports
$class = $objimport->array_import_convertvalue[0][$val]['class']; $class = $objimport->array_import_convertvalue[0][$val]['class'];
$method = $objimport->array_import_convertvalue[0][$val]['method']; $method = $objimport->array_import_convertvalue[0][$val]['method'];
$units = $objimport->array_import_convertvalue[0][$val]['units']; $units = $objimport->array_import_convertvalue[0][$val]['units'];
if ($this->cacheconvert[$file.'_'.$class.'_'.$method.'_'.$units][$newval] != '') if ($this->cacheconvert[$file . '_' . $class . '_' . $method . '_' . $units][$newval] != '') {
{ $newval = $this->cacheconvert[$file . '_' . $class . '_' . $method . '_' . $units][$newval];
$newval = $this->cacheconvert[$file.'_'.$class.'_'.$method.'_'.$units][$newval];
} else { } else {
$resultload = dol_include_once($file); $resultload = dol_include_once($file);
if (empty($resultload)) if (empty($resultload)) {
{ dol_print_error('', 'Error trying to call file=' . $file . ', class=' . $class . ', method=' . $method . ', units=' . $units);
dol_print_error('', 'Error trying to call file='.$file.', class='.$class.', method='.$method.', units='.$units);
break; break;
} }
$classinstance = new $class($this->db); $classinstance = new $class($this->db);
// Try the fetch from code or ref // Try the fetch from code or ref
call_user_func_array(array($classinstance, $method), array('', '', $newval, $units)); call_user_func_array(array($classinstance, $method), array('', '', $newval, $units));
$scaleorid = (($objimport->array_import_convertvalue[0][$val]['rule'] == 'fetchidfromcodeunits') ? $classinstance->id : $classinstance->scale); $scaleorid = (($objimport->array_import_convertvalue[0][$val]['rule'] == 'fetchidfromcodeunits') ? $classinstance->id : $classinstance->scale);
$this->cacheconvert[$file.'_'.$class.'_'.$method.'_'.$units][$newval] = $scaleorid; $this->cacheconvert[$file . '_' . $class . '_' . $method . '_' . $units][$newval] = $scaleorid;
//print 'We have made a '.$class.'->'.$method." to get a value from key '".$newval."' and we got '".$scaleorid."'.";exit; //print 'We have made a '.$class.'->'.$method." to get a value from key '".$newval."' and we got '".$scaleorid."'.";exit;
if ($classinstance->id > 0) // we found record if ($classinstance->id > 0) // we found record
{ {
@ -576,32 +567,28 @@ class ImportXlsx extends ModeleImports
} }
} }
} elseif ($objimport->array_import_convertvalue[0][$val]['rule'] == 'getcustomercodeifauto') { } elseif ($objimport->array_import_convertvalue[0][$val]['rule'] == 'getcustomercodeifauto') {
if (strtolower($newval) == 'auto') if (strtolower($newval) == 'auto') {
{
$this->thirpartyobject->get_codeclient(0, 0); $this->thirpartyobject->get_codeclient(0, 0);
$newval = $this->thirpartyobject->code_client; $newval = $this->thirpartyobject->code_client;
//print 'code_client='.$newval; //print 'code_client='.$newval;
} }
if (empty($newval)) $arrayrecord[($key - 1)]['type'] = -1; // If we get empty value, we will use "null" if (empty($newval)) $arrayrecord[($key - 1)]['type'] = -1; // If we get empty value, we will use "null"
} elseif ($objimport->array_import_convertvalue[0][$val]['rule'] == 'getsuppliercodeifauto') { } elseif ($objimport->array_import_convertvalue[0][$val]['rule'] == 'getsuppliercodeifauto') {
if (strtolower($newval) == 'auto') if (strtolower($newval) == 'auto') {
{
$newval = $this->thirpartyobject->get_codefournisseur(0, 1); $newval = $this->thirpartyobject->get_codefournisseur(0, 1);
$newval = $this->thirpartyobject->code_fournisseur; $newval = $this->thirpartyobject->code_fournisseur;
//print 'code_fournisseur='.$newval; //print 'code_fournisseur='.$newval;
} }
if (empty($newval)) $arrayrecord[($key - 1)]['type'] = -1; // If we get empty value, we will use "null" if (empty($newval)) $arrayrecord[($key - 1)]['type'] = -1; // If we get empty value, we will use "null"
} elseif ($objimport->array_import_convertvalue[0][$val]['rule'] == 'getcustomeraccountancycodeifauto') { } elseif ($objimport->array_import_convertvalue[0][$val]['rule'] == 'getcustomeraccountancycodeifauto') {
if (strtolower($newval) == 'auto') if (strtolower($newval) == 'auto') {
{
$this->thirpartyobject->get_codecompta('customer'); $this->thirpartyobject->get_codecompta('customer');
$newval = $this->thirpartyobject->code_compta; $newval = $this->thirpartyobject->code_compta;
//print 'code_compta='.$newval; //print 'code_compta='.$newval;
} }
if (empty($newval)) $arrayrecord[($key - 1)]['type'] = -1; // If we get empty value, we will use "null" if (empty($newval)) $arrayrecord[($key - 1)]['type'] = -1; // If we get empty value, we will use "null"
} elseif ($objimport->array_import_convertvalue[0][$val]['rule'] == 'getsupplieraccountancycodeifauto') { } elseif ($objimport->array_import_convertvalue[0][$val]['rule'] == 'getsupplieraccountancycodeifauto') {
if (strtolower($newval) == 'auto') if (strtolower($newval) == 'auto') {
{
$this->thirpartyobject->get_codecompta('supplier'); $this->thirpartyobject->get_codecompta('supplier');
$newval = $this->thirpartyobject->code_compta_fournisseur; $newval = $this->thirpartyobject->code_compta_fournisseur;
if (empty($newval)) $arrayrecord[($key - 1)]['type'] = -1; // If we get empty value, we will use "null" if (empty($newval)) $arrayrecord[($key - 1)]['type'] = -1; // If we get empty value, we will use "null"
@ -612,9 +599,8 @@ class ImportXlsx extends ModeleImports
$defaultref = ''; $defaultref = '';
// TODO provide the $modTask (module of generation of ref) as parameter of import_insert function // TODO provide the $modTask (module of generation of ref) as parameter of import_insert function
$obj = empty($conf->global->PROJECT_TASK_ADDON) ? 'mod_task_simple' : $conf->global->PROJECT_TASK_ADDON; $obj = empty($conf->global->PROJECT_TASK_ADDON) ? 'mod_task_simple' : $conf->global->PROJECT_TASK_ADDON;
if (!empty($conf->global->PROJECT_TASK_ADDON) && is_readable(DOL_DOCUMENT_ROOT."/core/modules/project/task/".$conf->global->PROJECT_TASK_ADDON.".php")) if (!empty($conf->global->PROJECT_TASK_ADDON) && is_readable(DOL_DOCUMENT_ROOT . "/core/modules/project/task/" . $conf->global->PROJECT_TASK_ADDON . ".php")) {
{ require_once DOL_DOCUMENT_ROOT . "/core/modules/project/task/" . $conf->global->PROJECT_TASK_ADDON . '.php';
require_once DOL_DOCUMENT_ROOT."/core/modules/project/task/".$conf->global->PROJECT_TASK_ADDON.'.php';
$modTask = new $obj; $modTask = new $obj;
$defaultref = $modTask->getNextValue(null, null); $defaultref = $modTask->getNextValue(null, null);
} }
@ -625,9 +611,8 @@ class ImportXlsx extends ModeleImports
$class = $objimport->array_import_convertvalue[0][$val]['class']; $class = $objimport->array_import_convertvalue[0][$val]['class'];
$method = $objimport->array_import_convertvalue[0][$val]['method']; $method = $objimport->array_import_convertvalue[0][$val]['method'];
$resultload = dol_include_once($file); $resultload = dol_include_once($file);
if (empty($resultload)) if (empty($resultload)) {
{ dol_print_error('', 'Error trying to call file=' . $file . ', class=' . $class . ', method=' . $method);
dol_print_error('', 'Error trying to call file='.$file.', class='.$class.', method='.$method);
break; break;
} }
$classinstance = new $class($this->db); $classinstance = new $class($this->db);
@ -649,34 +634,29 @@ class ImportXlsx extends ModeleImports
} }
// Test regexp // Test regexp
if (!empty($objimport->array_import_regex[0][$val]) && ($newval != '')) if (!empty($objimport->array_import_regex[0][$val]) && ($newval != '')) {
{
// If test is "Must exist in a field@table or field@table:..." // If test is "Must exist in a field@table or field@table:..."
if (preg_match('/^(.+)@([^:]+)(:.+)?$/', $objimport->array_import_regex[0][$val], $reg)) if (preg_match('/^(.+)@([^:]+)(:.+)?$/', $objimport->array_import_regex[0][$val], $reg)) {
{
$field = $reg[1]; $field = $reg[1];
$table = $reg[2]; $table = $reg[2];
$filter = !empty($reg[3]) ?substr($reg[3], 1) : ''; $filter = !empty($reg[3]) ? substr($reg[3], 1) : '';
$cachekey = $field.'@'.$table; $cachekey = $field . '@' . $table;
if (!empty($filter)) $cachekey .= ':'.$filter; if (!empty($filter)) $cachekey .= ':' . $filter;
// Load content of field@table into cache array // Load content of field@table into cache array
if (!is_array($this->cachefieldtable[$cachekey])) // If content of field@table not already loaded into cache if (!is_array($this->cachefieldtable[$cachekey])) // If content of field@table not already loaded into cache
{ {
$sql = "SELECT ".$field." as aliasfield FROM ".$table; $sql = "SELECT " . $field . " as aliasfield FROM " . $table;
if (!empty($filter)) if (!empty($filter)) {
{ $sql .= ' WHERE ' . $filter;
$sql .= ' WHERE '.$filter;
} }
$resql = $this->db->query($sql); $resql = $this->db->query($sql);
if ($resql) if ($resql) {
{
$num = $this->db->num_rows($resql); $num = $this->db->num_rows($resql);
$i = 0; $i = 0;
while ($i < $num) while ($i < $num) {
{
$obj = $this->db->fetch_object($resql); $obj = $this->db->fetch_object($resql);
if ($obj) $this->cachefieldtable[$cachekey][] = $obj->aliasfield; if ($obj) $this->cachefieldtable[$cachekey][] = $obj->aliasfield;
$i++; $i++;
@ -687,10 +667,9 @@ class ImportXlsx extends ModeleImports
} }
// Now we check cache is not empty (should not) and key is into cache // Now we check cache is not empty (should not) and key is into cache
if (!is_array($this->cachefieldtable[$cachekey]) || !in_array($newval, $this->cachefieldtable[$cachekey])) if (!is_array($this->cachefieldtable[$cachekey]) || !in_array($newval, $this->cachefieldtable[$cachekey])) {
{
$tableforerror = $table; $tableforerror = $table;
if (!empty($filter)) $tableforerror .= ':'.$filter; if (!empty($filter)) $tableforerror .= ':' . $filter;
$this->errors[$error]['lib'] = $langs->transnoentitiesnoconv('ErrorFieldValueNotIn', $key, $newval, $field, $tableforerror); $this->errors[$error]['lib'] = $langs->transnoentitiesnoconv('ErrorFieldValueNotIn', $key, $newval, $field, $tableforerror);
$this->errors[$error]['type'] = 'FOREIGNKEY'; $this->errors[$error]['type'] = 'FOREIGNKEY';
$errorforthistable++; $errorforthistable++;
@ -698,7 +677,7 @@ class ImportXlsx extends ModeleImports
} }
} }
// If test is just a static regex // If test is just a static regex
elseif (!preg_match('/'.$objimport->array_import_regex[0][$val].'/i', $newval)) { elseif (!preg_match('/' . $objimport->array_import_regex[0][$val] . '/i', $newval)) {
//if ($key == 19) print "xxx".$newval."zzz".$objimport->array_import_regex[0][$val]."<br>"; //if ($key == 19) print "xxx".$newval."zzz".$objimport->array_import_regex[0][$val]."<br>";
$this->errors[$error]['lib'] = $langs->transnoentitiesnoconv('ErrorWrongValueForField', $key, $newval, $objimport->array_import_regex[0][$val]); $this->errors[$error]['lib'] = $langs->transnoentitiesnoconv('ErrorWrongValueForField', $key, $newval, $objimport->array_import_regex[0][$val]);
$this->errors[$error]['type'] = 'REGEX'; $this->errors[$error]['type'] = 'REGEX';
@ -717,37 +696,32 @@ class ImportXlsx extends ModeleImports
// Note: arrayrecord (and 'type') is filled with ->import_read_record called by import.php page before calling import_insert // Note: arrayrecord (and 'type') is filled with ->import_read_record called by import.php page before calling import_insert
if (empty($newval) && $arrayrecord[($key - 1)]['type'] < 0) $listvalues[] = ($newval == '0' ? $newval : "null"); if (empty($newval) && $arrayrecord[($key - 1)]['type'] < 0) $listvalues[] = ($newval == '0' ? $newval : "null");
elseif (empty($newval) && $arrayrecord[($key - 1)]['type'] == 0) $listvalues[] = "''"; elseif (empty($newval) && $arrayrecord[($key - 1)]['type'] == 0) $listvalues[] = "''";
else $listvalues[] = "'".$this->db->escape($newval)."'"; else $listvalues[] = "'" . $this->db->escape($newval) . "'";
} }
$i++; $i++;
} }
// We add hidden fields (but only if there is at least one field to add into table) // We add hidden fields (but only if there is at least one field to add into table)
if (!empty($listfields) && is_array($objimport->array_import_fieldshidden[0])) if (!empty($listfields) && is_array($objimport->array_import_fieldshidden[0])) {
{
// Loop on each hidden fields to add them into listfields/listvalues // Loop on each hidden fields to add them into listfields/listvalues
foreach ($objimport->array_import_fieldshidden[0] as $key => $val) foreach ($objimport->array_import_fieldshidden[0] as $key => $val) {
{ if (!preg_match('/^' . preg_quote($alias, '/') . '\./', $key)) continue; // Not a field of current table
if (!preg_match('/^'.preg_quote($alias, '/').'\./', $key)) continue; // Not a field of current table if ($val == 'user->id') {
if ($val == 'user->id') $listfields[] = preg_replace('/^' . preg_quote($alias, '/') . '\./', '', $key);
{
$listfields[] = preg_replace('/^'.preg_quote($alias, '/').'\./', '', $key);
$listvalues[] = $user->id; $listvalues[] = $user->id;
} elseif (preg_match('/^lastrowid-/', $val)) } elseif (preg_match('/^lastrowid-/', $val)) {
{
$tmp = explode('-', $val); $tmp = explode('-', $val);
$lastinsertid = (isset($last_insert_id_array[$tmp[1]])) ? $last_insert_id_array[$tmp[1]] : 0; $lastinsertid = (isset($last_insert_id_array[$tmp[1]])) ? $last_insert_id_array[$tmp[1]] : 0;
$keyfield = preg_replace('/^'.preg_quote($alias, '/').'\./', '', $key); $keyfield = preg_replace('/^' . preg_quote($alias, '/') . '\./', '', $key);
$listfields[] = $keyfield; $listfields[] = $keyfield;
$listvalues[] = $lastinsertid; $listvalues[] = $lastinsertid;
//print $key."-".$val."-".$listfields."-".$listvalues."<br>";exit; //print $key."-".$val."-".$listfields."-".$listvalues."<br>";exit;
} elseif (preg_match('/^const-/', $val)) } elseif (preg_match('/^const-/', $val)) {
{
$tmp = explode('-', $val, 2); $tmp = explode('-', $val, 2);
$listfields[] = preg_replace('/^'.preg_quote($alias, '/').'\./', '', $key); $listfields[] = preg_replace('/^' . preg_quote($alias, '/') . '\./', '', $key);
$listvalues[] = "'".$tmp[1]."'"; $listvalues[] = "'" . $tmp[1] . "'";
} else { } else {
$this->errors[$error]['lib'] = 'Bad value of profile setup '.$val.' for array_import_fieldshidden'; $this->errors[$error]['lib'] = 'Bad value of profile setup ' . $val . ' for array_import_fieldshidden';
$this->errors[$error]['type'] = 'Import profile setup'; $this->errors[$error]['type'] = 'Import profile setup';
$error++; $error++;
} }
@ -757,18 +731,16 @@ class ImportXlsx extends ModeleImports
// If no error for this $alias/$tablename, we have a complete $listfields and $listvalues that are defined // If no error for this $alias/$tablename, we have a complete $listfields and $listvalues that are defined
// so we can try to make the insert or update now. // so we can try to make the insert or update now.
if (!$errorforthistable) if (!$errorforthistable) {
{
//print "$alias/$tablename/$listfields/$listvalues<br>"; //print "$alias/$tablename/$listfields/$listvalues<br>";
if (!empty($listfields)) if (!empty($listfields)) {
{
$updatedone = false; $updatedone = false;
$insertdone = false; $insertdone = false;
if (!empty($updatekeys)) { if (!empty($updatekeys)) {
// We do SELECT to get the rowid, if we already have the rowid, it's to be used below for related tables (extrafields) // We do SELECT to get the rowid, if we already have the rowid, it's to be used below for related tables (extrafields)
if (empty($lastinsertid)) { // No insert done yet for a parent table if (empty($lastinsertid)) { // No insert done yet for a parent table
$sqlSelect = 'SELECT rowid FROM '.$tablename; $sqlSelect = 'SELECT rowid FROM ' . $tablename;
$data = array_combine($listfields, $listvalues); $data = array_combine($listfields, $listvalues);
$where = array(); $where = array();
@ -776,10 +748,10 @@ class ImportXlsx extends ModeleImports
foreach ($updatekeys as $key) { foreach ($updatekeys as $key) {
$col = $objimport->array_import_updatekeys[0][$key]; $col = $objimport->array_import_updatekeys[0][$key];
$key = preg_replace('/^.*\./i', '', $key); $key = preg_replace('/^.*\./i', '', $key);
$where[] = $key.' = '.$data[$key]; $where[] = $key . ' = ' . $data[$key];
$filters[] = $col.' = '.$data[$key]; $filters[] = $col . ' = ' . $data[$key];
} }
$sqlSelect .= ' WHERE '.implode(' AND ', $where); $sqlSelect .= ' WHERE ' . implode(' AND ', $where);
$resql = $this->db->query($sqlSelect); $resql = $this->db->query($sqlSelect);
if ($resql) { if ($resql) {
@ -806,10 +778,10 @@ class ImportXlsx extends ModeleImports
// a direct insert into subtable extrafields, but when me wake an update, the insertid is defined and the child record // a direct insert into subtable extrafields, but when me wake an update, the insertid is defined and the child record
// may already exists. So we rescan the extrafield table to know if record exists or not for the rowid. // may already exists. So we rescan the extrafield table to know if record exists or not for the rowid.
// Note: For extrafield tablename, we have in importfieldshidden_array an enty 'extra.fk_object'=>'lastrowid-tableparent' so $keyfield is 'fk_object' // Note: For extrafield tablename, we have in importfieldshidden_array an enty 'extra.fk_object'=>'lastrowid-tableparent' so $keyfield is 'fk_object'
$sqlSelect = 'SELECT rowid FROM '.$tablename; $sqlSelect = 'SELECT rowid FROM ' . $tablename;
if (empty($keyfield)) $keyfield = 'rowid'; if (empty($keyfield)) $keyfield = 'rowid';
$sqlSelect .= ' WHERE '.$keyfield.' = '.$lastinsertid; $sqlSelect .= ' WHERE ' . $keyfield . ' = ' . $lastinsertid;
$resql = $this->db->query($sqlSelect); $resql = $this->db->query($sqlSelect);
if ($resql) { if ($resql) {
@ -831,19 +803,19 @@ class ImportXlsx extends ModeleImports
if (!empty($lastinsertid)) { if (!empty($lastinsertid)) {
// Build SQL UPDATE request // Build SQL UPDATE request
$sqlstart = 'UPDATE '.$tablename; $sqlstart = 'UPDATE ' . $tablename;
$data = array_combine($listfields, $listvalues); $data = array_combine($listfields, $listvalues);
$set = array(); $set = array();
foreach ($data as $key => $val) { foreach ($data as $key => $val) {
$set[] = $key.' = '.$val; $set[] = $key . ' = ' . $val;
} }
$sqlstart .= ' SET '.implode(', ', $set); $sqlstart .= ' SET ' . implode(', ', $set);
if (empty($keyfield)) $keyfield = 'rowid'; if (empty($keyfield)) $keyfield = 'rowid';
$sqlend = ' WHERE '.$keyfield.' = '.$lastinsertid; $sqlend = ' WHERE ' . $keyfield . ' = ' . $lastinsertid;
$sql = $sqlstart.$sqlend; $sql = $sqlstart . $sqlend;
// Run update request // Run update request
$resql = $this->db->query($sql); $resql = $this->db->query($sql);
@ -862,25 +834,23 @@ class ImportXlsx extends ModeleImports
// Update not done, we do insert // Update not done, we do insert
if (!$error && !$updatedone) { if (!$error && !$updatedone) {
// Build SQL INSERT request // Build SQL INSERT request
$sqlstart = 'INSERT INTO '.$tablename.'('.implode(', ', $listfields).', import_key'; $sqlstart = 'INSERT INTO ' . $tablename . '(' . implode(', ', $listfields) . ', import_key';
$sqlend = ') VALUES('.implode(', ', $listvalues).", '".$this->db->escape($importid)."'"; $sqlend = ') VALUES(' . implode(', ', $listvalues) . ", '" . $this->db->escape($importid) . "'";
if (!empty($tablewithentity_cache[$tablename])) { if (!empty($tablewithentity_cache[$tablename])) {
$sqlstart .= ', entity'; $sqlstart .= ', entity';
$sqlend .= ', '.$conf->entity; $sqlend .= ', ' . $conf->entity;
} }
if (!empty($objimport->array_import_tables_creator[0][$alias])) { if (!empty($objimport->array_import_tables_creator[0][$alias])) {
$sqlstart .= ', '.$objimport->array_import_tables_creator[0][$alias]; $sqlstart .= ', ' . $objimport->array_import_tables_creator[0][$alias];
$sqlend .= ', '.$user->id; $sqlend .= ', ' . $user->id;
} }
$sql = $sqlstart.$sqlend.')'; $sql = $sqlstart . $sqlend . ')';
dol_syslog("import_xlsx.modules", LOG_DEBUG); dol_syslog("import_xlsx.modules", LOG_DEBUG);
// Run insert request // Run insert request
if ($sql) if ($sql) {
{
$resql = $this->db->query($sql); $resql = $this->db->query($sql);
if ($resql) if ($resql) {
{
$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). $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).
$insertdone = true; $insertdone = true;
} else { } else {