29require_once
'../main.inc.php';
37require_once DOL_DOCUMENT_ROOT.
'/core/class/html.formfile.class.php';
38require_once DOL_DOCUMENT_ROOT.
'/core/class/html.formother.class.php';
39require_once DOL_DOCUMENT_ROOT.
'/imports/class/import.class.php';
40require_once DOL_DOCUMENT_ROOT.
'/core/modules/import/modules_import.class.php';
41require_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
42require_once DOL_DOCUMENT_ROOT.
'/core/lib/images.lib.php';
43require_once DOL_DOCUMENT_ROOT.
'/core/lib/import.lib.php';
46$langs->loadLangs(array(
'exports',
'compta',
'errors',
'projects',
'admin'));
49$hookmanager->initHooks(array(
'imports'));
57 'invoice_line' =>
'bill',
59 'order_line' =>
'order',
61 'propal_line' =>
'propal',
62 'intervention' =>
'intervention',
63 'inter_line' =>
'intervention',
65 'member_type' =>
'group',
66 'subscription' =>
'payment',
67 'payment' =>
'payment',
69 'tax_type' =>
'generic',
71 'account' =>
'account',
72 'product' =>
'product',
73 'virtualproduct' =>
'product',
74 'subproduct' =>
'product',
75 'product_supplier_ref' =>
'product',
77 'warehouse' =>
'stock',
79 'stockbatch' =>
'stock',
80 'category' =>
'category',
81 'shipment' =>
'sending',
82 'shipment_line' =>
'sending',
83 'project' =>
'project',
85 'reception' =>
'sending',
86 'reception_line' =>
'sending',
87 'expensereport' =>
'trip',
88 'expensereport_line' =>
'trip',
89 'holiday' =>
'holiday',
90 'contract_line' =>
'contract',
91 'translation' =>
'generic',
99 'company' =>
'Company',
100 'contact' =>
'Contact',
102 'invoice_line' =>
'InvoiceLine',
104 'order_line' =>
'OrderLine',
105 'propal' =>
'Proposal',
106 'propal_line' =>
'ProposalLine',
107 'intervention' =>
'Intervention',
108 'inter_line' =>
'InterLine',
109 'member' =>
'Member',
110 'member_type' =>
'MemberType',
111 'subscription' =>
'Subscription',
112 'tax' =>
'SocialContribution',
113 'tax_type' =>
'DictionarySocialContributions',
114 'account' =>
'BankTransactions',
115 'payment' =>
'Payment',
116 'product' =>
'Product',
117 'virtualproduct' =>
'AssociatedProducts',
118 'subproduct' =>
'SubProduct',
119 'product_supplier_ref' =>
'SupplierPrices',
120 'service' =>
'Service',
122 'movement' =>
'StockMovement',
124 'stockbatch' =>
'StockDetailPerBatch',
125 'warehouse' =>
'Warehouse',
126 'category' =>
'Category',
128 'trip' =>
'TripsAndExpenses',
129 'shipment' =>
'Shipments',
130 'shipment_line' =>
'ShipmentLine',
131 'project' =>
'Projects',
132 'projecttask' =>
'Tasks',
133 'task_time' =>
'TaskTimeSpent',
135 'expensereport' =>
'ExpenseReport',
136 'expensereport_line' =>
'ExpenseReportLine',
137 'holiday' =>
'TitreRequestCP',
138 'contract' =>
'Contract',
139 'contract_line' =>
'ContractLine',
140 'translation' =>
'Translation',
142 'bomline' =>
'BOMLine'
145$datatoimport =
GETPOST(
'datatoimport');
147$filetoimport =
GETPOST(
'filetoimport');
148$action =
GETPOST(
'action',
'alpha');
149$confirm =
GETPOST(
'confirm',
'alpha');
151$import_name =
GETPOST(
'import_name');
154$excludefirstline = (
GETPOST(
'excludefirstline',
'alphanohtml', 3) ?
GETPOST(
'excludefirstline',
'alphanohtml', 3) : 2);
155$endatlinenb = (
GETPOST(
'endatlinenb',
'alphanohtml', 3) ?
GETPOST(
'endatlinenb',
'alphanohtml', 3) :
'');
156$updatekeys = (
GETPOST(
'updatekeys',
'array', 3) ?
GETPOST(
'updatekeys',
'array', 3) : array());
157$importtriggermode =
GETPOST(
'importtriggermode',
'alpha', 3);
158$separator = (
GETPOST(
'separator',
'nohtml') ?
GETPOST(
'separator',
'nohtml', 3) :
'');
159$enclosure = (
GETPOST(
'enclosure',
'nohtml') ?
GETPOST(
'enclosure',
'nohtml') :
'"');
160$charset =
GETPOST(
'charset',
'aZ09');
161$separator_used = str_replace(
'\t',
"\t", $separator);
164if (empty($importtriggermode)) {
165 $importtriggermode =
getDolGlobalString(
'IMPORT_TRIGGER_MODE_DEFAULT',
'strict_line');
167if (!in_array($importtriggermode, array(
'strict_line',
'fast_bulk'),
true)) {
168 $importtriggermode =
'strict_line';
172$objimport->load_arrays($user, ($step == 1 ?
'' : $datatoimport));
174if (empty($updatekeys) && !empty($objimport->array_import_preselected_updatekeys[0])) {
175 $updatekeys = $objimport->array_import_preselected_updatekeys[0];
184if (empty($array_match_file_to_database)) {
185 $serialized_array_match_file_to_database = isset($_SESSION[
"dol_array_match_file_to_database_select"]) ? $_SESSION[
"dol_array_match_file_to_database_select"] :
'';
186 $array_match_file_to_database = array();
187 $fieldsarray = explode(
',', $serialized_array_match_file_to_database);
188 foreach ($fieldsarray as $elem) {
189 $tabelem = explode(
'=', $elem, 2);
191 $val = (isset($tabelem[1]) ? $tabelem[1] :
'');
193 $array_match_file_to_database[$key] = $val;
203if ($action ==
'deleteprof' && $user->hasRight(
'import',
'run')) {
206 $result = $objimport->delete($user);
211if ($action ==
'add_import_model' && $user->hasRight(
'import',
'run')) {
215 foreach ($array_match_file_to_database as $key => $val) {
219 $hexa .= $key.
'='.$val;
222 $objimport->model_name = $import_name;
223 $objimport->datatoimport = $datatoimport;
224 $objimport->hexa = $hexa;
225 $objimport->fk_user = (
GETPOST(
'visibility',
'aZ09') ==
'all' ? 0 : $user->id);
227 $result = $objimport->create($user);
229 setEventMessages($langs->trans(
"ImportModelSaved", $objimport->model_name),
null,
'mesgs');
232 $langs->load(
"errors");
233 if ($objimport->errno ==
'DB_ERROR_RECORD_ALREADY_EXISTS') {
234 setEventMessages($langs->trans(
"ErrorImportDuplicateProfil"),
null,
'errors');
240 setEventMessages($langs->trans(
"ErrorFieldRequired", $langs->transnoentities(
"ImportModelName")),
null,
'errors');
244if ($step == 2 && $datatoimport) {
251 dol_syslog(
"File ".$fullpath.
" was added for import");
253 $langs->load(
"errors");
259 if ($action ==
'confirm_deletefile' && $confirm ==
'yes' && $user->hasRight(
'import',
'run')) {
260 $langs->load(
"other");
262 $param =
'&datatoimport='.urlencode($datatoimport).
'&format='.urlencode($format);
263 if ($excludefirstline) {
264 $param .=
'&excludefirstline='.urlencode($excludefirstline);
267 $param .=
'&endatlinenb='.urlencode($endatlinenb);
277 header(
'Location: '.$_SERVER[
"PHP_SELF"].
'?step='.$step.$param);
282if ($step == 4 && $action ==
'select_model' && $user->hasRight(
'import',
'run')) {
284 $_SESSION[
"dol_array_match_file_to_database"] =
'';
285 $serialized_array_match_file_to_database =
'';
286 $array_match_file_to_database = array();
290 $result = $objimport->fetch($importmodelid);
292 $serialized_array_match_file_to_database = $objimport->hexa;
293 $fieldsarray = explode(
',', $serialized_array_match_file_to_database);
294 foreach ($fieldsarray as $elem) {
295 $tabelem = explode(
'=', $elem);
299 $array_match_file_to_database[$key] = $val;
302 $_SESSION[
"dol_array_match_file_to_database"] = $serialized_array_match_file_to_database;
303 $_SESSION[
'dol_array_match_file_to_database_select'] = $_SESSION[
"dol_array_match_file_to_database"];
306if ($action ==
'saveselectorder' && $user->hasRight(
'import',
'run')) {
308 $serialized_array_match_file_to_database =
'';
310 $selectorder = explode(
",",
GETPOST(
'selectorder'));
311 $fieldtarget = $fieldstarget = $objimport->array_import_fields[0];
312 foreach ($selectorder as $key => $code) {
313 $serialized_array_match_file_to_database .= $key.
'='.$code;
314 $serialized_array_match_file_to_database .=
',';
316 $serialized_array_match_file_to_database = substr($serialized_array_match_file_to_database, 0, -1);
317 dol_syslog(
'dol_array_match_file_to_database_select='.$serialized_array_match_file_to_database);
318 $_SESSION[
"dol_array_match_file_to_database_select"] = $serialized_array_match_file_to_database;
328$help_url =
'EN:Module_Imports_En|FR:Module_Imports|ES:Módulo_Importaciones';
331if ($step == 1 || !$datatoimport) {
333 $serialized_array_match_file_to_database =
'';
334 $array_match_file_to_database = array();
335 $_SESSION[
"dol_array_match_file_to_database"] =
'';
336 $_SESSION[
"dol_array_match_file_to_database_select"] =
'';
339 if ($excludefirstline) {
340 $param .=
'&excludefirstline='.urlencode($excludefirstline);
343 $param .=
'&endatlinenb='.urlencode($endatlinenb);
346 $param .=
'&separator='.urlencode($separator);
349 $param .=
'&enclosure='.urlencode($enclosure);
352 llxHeader(
'', $langs->trans(
"NewImport"), $help_url);
358 print
'<div class="opacitymedium">'.$langs->trans(
"SelectImportDataSet").
'</div>';
362 $nbmodulesnotautoenabled = count(
$conf->modules);
363 $listofmodulesautoenabled = array(
'user',
'agenda',
'fckeditor',
'export',
'import');
364 foreach ($listofmodulesautoenabled as $moduleautoenable) {
365 if (in_array($moduleautoenable,
$conf->modules)) {
366 $nbmodulesnotautoenabled--;
370 if ($user->admin && $nbmodulesnotautoenabled <
getDolGlobalInt(
'MAIN_MIN_NB_ENABLED_MODULE_FOR_WARNING', 1)) {
371 print
info_admin($langs->trans(
"WarningOnlyProfilesOfActivatedModules").
' '.$langs->trans(
"YouCanEnableModulesFrom"));
377 print
'<div class="div-table-responsive-no-min">';
378 print
'<table class="noborder centpercent nomarginbottom">';
379 print
'<tr class="liste_titre">';
380 print
'<td>'.$langs->trans(
"Module").
'</td>';
381 print
'<td>'.$langs->trans(
"ImportableDatas").
'</td>';
382 print
'<td> </td>';
385 if (count($objimport->array_import_module)) {
386 $sortedarrayofmodules =
dol_sort_array($objimport->array_import_module,
'position_of_profile',
'asc', 0, 0, 1);
387 foreach ($sortedarrayofmodules as $key => $value) {
389 $titleofmodule = $objimport->array_import_module[$key][
'module']->getName();
390 print
'<tr class="oddeven"><td class="tdoverflowmax200" title="'.dolPrintHTML($titleofmodule).
'">';
392 if (in_array($objimport->array_import_code[$key], array(
'produit_supplierprices',
'produit_multiprice',
'produit_languages'))) {
393 $titleofmodule = $langs->trans(
"ProductOrService");
397 $entity = preg_replace(
'/:.*$/',
'', $objimport->array_import_icon[$key]);
398 $entityicon = strtolower(!empty($entitytoicon[$entity]) ? $entitytoicon[$entity] : $entity);
399 $label = $objimport->array_import_label[$key];
400 print
'<div class="twolinesmax-normallineheight minwidth200onall">';
401 print
img_object($objimport->array_import_module[$key][
'module']->getName(), $entityicon,
'class="pictofixedwidth"');
404 print
'</td><td style="text-align: right">';
405 if ($objimport->array_import_perms[$key]) {
406 print
'<a href="'.DOL_URL_ROOT.
'/imports/import.php?step=2&datatoimport='.$objimport->array_import_code[$key].$param.
'">'.
img_picto($langs->trans(
"NewImport"),
'next',
'class="fa-15"').
'</a>';
408 print $langs->trans(
"NotEnoughPermissions");
413 print
'<tr><td class="oddeven" colspan="3">'.$langs->trans(
"NoImportableData").
'</td></tr>';
423if ($step == 2 && $datatoimport) {
424 $param =
'&datatoimport='.urlencode($datatoimport);
425 if ($excludefirstline) {
426 $param .=
'&excludefirstline='.urlencode($excludefirstline);
429 $param .=
'&endatlinenb='.urlencode($endatlinenb);
432 $param .=
'&separator='.urlencode($separator);
435 $param .=
'&enclosure='.urlencode($enclosure);
438 $list = $objmodelimport->listOfAvailableImportFormat(
$db);
440 llxHeader(
'', $langs->trans(
"NewImport"), $help_url);
449 if ($action ==
'delete') {
450 print $form->formconfirm($_SERVER[
"PHP_SELF"].
'?urlfile='.urlencode(
GETPOST(
'urlfile')).
'&step=2'.$param, $langs->trans(
'DeleteFile'), $langs->trans(
'ConfirmDeleteFile'),
'confirm_deletefile',
'', 0, 1);
453 print
'<div class="underbanner clearboth"></div>';
454 print
'<div class="fichecenter">';
456 print
'<table class="border tableforfield centpercent">';
459 print
'<tr><td class="titlefieldcreate">'.$langs->trans(
"Module").
'</td>';
461 $titleofmodule = $objimport->array_import_module[0][
'module']->getName();
463 if (in_array($objimport->array_import_code[0], array(
'produit_supplierprices',
'produit_multiprice',
'produit_languages'))) {
464 $titleofmodule = $langs->trans(
"ProductOrService");
466 print $titleofmodule;
470 print
'<tr><td>'.$langs->trans(
"DatasetToImport").
'</td>';
472 $entity = preg_replace(
'/:.*$/',
'', $objimport->array_import_icon[0]);
473 $entityicon = strtolower(!empty($entitytoicon[$entity]) ? $entitytoicon[$entity] : $entity);
474 print
img_object($objimport->array_import_module[0][
'module']->getName(), $entityicon).
' ';
475 print $objimport->array_import_label[0];
505 if ($format ==
'xlsx' && !class_exists(
'XMLWriter')) {
506 $langs->load(
"install");
507 print
info_admin($langs->trans(
"ErrorPHPDoesNotSupport",
'php-xml'), 0, 0,
'1',
'error');
513 print
'<form name="userfile" action="'.$_SERVER[
"PHP_SELF"].
'" enctype="multipart/form-data" method="POST">';
514 print
'<input type="hidden" name="token" value="'.newToken().
'">';
515 print
'<input type="hidden" value="'.$step.
'" name="step">';
516 print
'<input type="hidden" value="'.dol_escape_htmltag($format).
'" name="format">';
517 print
'<input type="hidden" value="'.$excludefirstline.
'" name="excludefirstline">';
518 print
'<input type="hidden" value="'.$endatlinenb.
'" name="endatlinenb">';
519 print
'<input type="hidden" value="'.dol_escape_htmltag($separator).
'" name="separator">';
520 print
'<input type="hidden" value="'.dol_escape_htmltag($enclosure).
'" name="enclosure">';
521 print
'<input type="hidden" value="'.dol_escape_htmltag($datatoimport).
'" name="datatoimport">';
523 print
'<span class="opacitymedium">';
524 $s = $langs->trans(
"ChooseFileToImport",
'{s1}');
525 $s = str_replace(
'{s1}',
img_picto(
'',
'next'), $s);
527 print
'</span><br><br>';
532 print
'<table class="noborder centpercent" cellpadding="4">';
534 print
'<tr class="liste_titre"><td colspan="4">';
535 print $langs->trans(
"FileMustHaveOneOfFollowingFormat").
'...';
537 $list = $objmodelimport->listOfAvailableImportFormat(
$db);
538 foreach ($list as $key) {
539 print
'<tr class="oddeven">';
540 print
'<td width="16">'.img_picto_common($key, $objmodelimport->getPictoForKey($key)).
'</td>';
541 $htmltext = $objmodelimport->getDriverDescForKey($key);
542 print
'<td>'.$form->textwithpicto($objmodelimport->getDriverLabelForKey($key), $htmltext).
'</td>';
543 print
'<td style="text-align:center">';
544 if (empty($objmodelimport->drivererror[$key])) {
545 $filename = $langs->transnoentitiesnoconv(
"ExampleOfImportFile").
'_'.$datatoimport.
'.'.$key;
546 print
'<a href="'.DOL_URL_ROOT.
'/imports/emptyexample.php?format='.$key.$param.
'&output=file&file='.urlencode($filename).
'" target="_blank" rel="noopener noreferrer">';
547 print
img_picto(
'',
'download',
'class="paddingright opacitymedium"');
548 print $langs->trans(
"DownloadEmptyExampleShort");
550 print $form->textwithpicto(
'', $langs->trans(
"DownloadEmptyExample").
'.<br>'.$langs->trans(
"StarAreMandatory"));
564 print
'<div class="marginbottomonly">';
566 $maxmin = $maxfilesizearray[
'maxmin'];
568 print
'<input type="hidden" name="MAX_FILE_SIZE" value="'.($maxmin * 1024).
'">';
570 print
'<input type="file" name="userfile" size="20" maxlength="80"> ';
572 print
'<input type="submit" class="button small" value="'.$langs->trans(
"AddFile").
'"'.$out.
' name="sendit">';
576 $maxphp = @ini_get(
'upload_max_filesize');
577 if (preg_match(
'/k$/i', $maxphp)) {
578 $maxphp = (int) substr($maxphp, 0, -1);
580 if (preg_match(
'/m$/i', $maxphp)) {
581 $maxphp = (int) substr($maxphp, 0, -1) * 1024;
583 if (preg_match(
'/g$/i', $maxphp)) {
584 $maxphp = (int) substr($maxphp, 0, -1) * 1024 * 1024;
586 if (preg_match(
'/t$/i', $maxphp)) {
587 $maxphp = (int) substr($maxphp, 0, -1) * 1024 * 1024 * 1024;
589 $maxphp2 = @ini_get(
'post_max_size');
590 if (preg_match(
'/k$/i', $maxphp2)) {
591 $maxphp2 = (int) substr($maxphp2, 0, -1);
593 if (preg_match(
'/m$/i', $maxphp2)) {
594 $maxphp2 = (int) substr($maxphp2, 0, -1) * 1024;
596 if (preg_match(
'/g$/i', $maxphp2)) {
597 $maxphp2 = (int) substr($maxphp2, 0, -1) * 1024 * 1024;
599 if (preg_match(
'/t$/i', $maxphp2)) {
600 $maxphp2 = (int) substr($maxphp2, 0, -1) * 1024 * 1024 * 1024;
604 $maxphptoshow = $maxphptoshowparam =
'';
606 $maxmin = min($max, $maxphp);
607 $maxphptoshow = $maxphp;
608 $maxphptoshowparam =
'upload_max_filesize';
611 $maxmin = min($max, $maxphp2);
612 if ($maxphp2 < $maxphp) {
613 $maxphptoshow = $maxphp2;
614 $maxphptoshowparam =
'post_max_size';
618 $langs->load(
'other');
620 $out .=
info_admin($langs->trans(
"ThisLimitIsDefinedInSetup", $max, $maxphptoshow), 1);
622 $out .=
' ('.$langs->trans(
"UploadDisabled").
')';
629 $filearray =
dol_dir_list(
$conf->import->dir_temp,
'files', 0,
'',
'',
'name', SORT_DESC);
630 if (count($filearray) > 0) {
631 print
'<div class="div-table-responsive-no-min">';
632 print
'<table class="noborder centpercent" width="100%" cellpadding="4">';
634 $dir =
$conf->import->dir_temp;
638 foreach ($filearray as $key => $val) {
639 $file = $val[
'name'];
643 $file = mb_convert_encoding($file,
'UTF-8',
'ISO-8859-1');
646 if (preg_match(
'/^\./', $file)) {
650 $modulepart =
'import';
651 $urlsource = $_SERVER[
"PHP_SELF"].
'?step='.$step.$param.
'&filetoimport='.urlencode($filetoimport);
652 $relativepath = $file;
654 print
'<tr class="oddeven">';
656 print
img_mime($file,
'',
'pictofixedwidth');
657 print
'<a data-ajax="false" href="'.DOL_URL_ROOT.
'/document.php?modulepart='.$modulepart.
'&file='.urlencode($relativepath).
'&step=2'.$param.
'" target="_blank" rel="noopener noreferrer">';
662 print
'<td style="text-align:right">'.dol_print_size(
dol_filesize($dir.
'/'.$file)).
'</td>';
664 print
'<td style="text-align:right">'.dol_print_date(
dol_filemtime($dir.
'/'.$file),
'dayhour').
'</td>';
666 print
'<td style="text-align:right"><a href="'.$_SERVER[
'PHP_SELF'].
'?action=delete&token='.newToken().
'&step=2'.$param.
'&urlfile='.urlencode($relativepath);
667 print
'">'.img_delete().
'</a></td>';
669 print
'<td style="text-align:right">';
670 print
'<a href="'.$_SERVER[
'PHP_SELF'].
'?step=3'.$param.
'&filetoimport='.urlencode($relativepath).
'">'.
img_picto($langs->trans(
"ImportThisFile"),
'next',
'class="fa-15"').
'</a>';
684if ($step == 3 && $datatoimport) {
686 $serialized_array_match_file_to_database = isset($_SESSION[
"dol_array_match_file_to_database_select"]) ? $_SESSION[
"dol_array_match_file_to_database_select"] :
'';
687 $fieldsarray = explode(
',', $serialized_array_match_file_to_database);
688 $array_match_file_to_database = array();
689 foreach ($fieldsarray as $elem) {
690 $tabelem = explode(
'=', $elem, 2);
692 $val = (isset($tabelem[1]) ? $tabelem[1] :
'');
694 $array_match_file_to_database[$key] = $val;
701 if (empty($format) && !empty($filetoimport)) {
702 $format = pathinfo($filetoimport, PATHINFO_EXTENSION);
708 if ($model ===
'txt') {
712 $list = $objmodelimport->listOfAvailableImportFormat(
$db);
714 if (empty($separator)) {
715 $separator = (!
getDolGlobalString(
'IMPORT_CSV_SEPARATOR_TO_USE') ?
',' :
$conf->global->IMPORT_CSV_SEPARATOR_TO_USE);
719 if ($model ==
'csv' && strlen($separator) == 1 && !GETPOSTISSET(
'separator')) {
720 '@phan-var-force ImportCsv $obj';
722 $fh = fopen(
$conf->import->dir_temp.
'/'.$filetoimport,
'r');
724 $sline = fgets($fh, 1000000);
726 $nboccurence = substr_count($sline, $separator);
727 $nboccurencea = substr_count($sline,
',');
728 $nboccurenceb = substr_count($sline,
';');
730 if ($nboccurence == 0) {
731 if ($nboccurencea > 2) {
733 } elseif ($nboccurenceb > 2) {
741 $separator_used = str_replace(
'\t',
"\t", $separator);
744 $dir = DOL_DOCUMENT_ROOT.
"/core/modules/import/";
745 $file =
"import_".$model.
".modules.php";
746 $classname =
"Import".ucfirst($model);
747 require_once $dir.$file;
748 $obj =
new $classname(
$db, $datatoimport);
749 '@phan-var-force ModeleImports $obj';
751 if (!empty($obj->error)) {
752 $langs->load(
"errors");
753 $param =
'&datatoimport='.$datatoimport.
'&format='.$format;
755 header(
"Location: ".$_SERVER[
"PHP_SELF"].
'?step=2'.$param.
'&filetoimport='.urlencode($relativepath));
759 if ($model ==
'csv') {
760 '@phan-var-force ImportCsv $obj';
761 $obj->separator = $separator_used;
762 $obj->enclosure = $enclosure;
765 if ($model ==
'xlsx') {
766 '@phan-var-force ImportXlsx $obj';
767 if (!preg_match(
'/\.xlsx$/i', $filetoimport)) {
768 $langs->load(
"errors");
769 $param =
'&datatoimport='.$datatoimport.
'&format='.$format;
770 setEventMessages($langs->trans(
"ErrorFileMustHaveFormat", $model),
null,
'errors');
771 header(
"Location: ".$_SERVER[
"PHP_SELF"].
'?step=2'.$param.
'&filetoimport='.urlencode($relativepath));
777 $array_match_file_to_database = array();
781 $fieldssource = array();
783 $result = $obj->import_open_file(
$conf->import->dir_temp.
'/'.$filetoimport);
786 $arrayrecord = $obj->import_read_record();
790 foreach ($arrayrecord as $key => $val) {
791 if ($val[
"type"] != -1) {
792 $fieldssource[$i][
'example1'] =
dol_trunc($val[
'val'], 128);
794 $fieldssource[$i][
'example1'] = $langs->trans(
'Empty');
796 $fieldssource[$i][
'imported'] =
false;
799 $obj->import_close_file();
803 $fieldstarget = $objimport->array_import_fields[0];
804 $minpos = min(count($fieldssource), count($fieldstarget));
808 $initialloadofstep4 =
false;
809 if (empty($_SESSION[
'dol_array_match_file_to_database_select'])) {
810 $initialloadofstep4 =
true;
814 if (count($array_match_file_to_database) == 0) {
820 $num = count($fieldssource);
821 while ($pos <= $num) {
822 if ($num >= 1 && $pos <= $num) {
824 foreach ($fieldstarget as $key => $val) {
825 if ($posbis < $pos) {
830 $array_match_file_to_database[$pos] = $key;
837 $array_match_database_to_file = array_flip($array_match_file_to_database);
841 $fieldstarget_tmp = array();
842 $arraykeysfieldtarget = array_keys($fieldstarget);
844 foreach ($fieldstarget as $key => $label) {
845 $isrequired = preg_match(
'/\*$/', $label);
846 if (!empty($isrequired)) {
847 $newlabel = substr($label, 0, -1);
848 $fieldstarget_tmp[$key] = array(
"label" => (
string) $newlabel,
"required" =>
true);
850 $fieldstarget_tmp[$key] = array(
"label" => (
string) $label,
"required" =>
false);
852 if (!empty($array_match_database_to_file[$key])) {
853 $fieldstarget_tmp[$key][
"imported"] =
true;
854 $fieldstarget_tmp[$key][
"position"] = (int) $array_match_database_to_file[$key] - 1;
856 while (!empty($array_match_database_to_file[$keytoswap])) {
857 if ($position + 1 > $array_match_database_to_file[$keytoswap]) {
858 $keytoswapwith = $array_match_database_to_file[$keytoswap] - 1;
859 $tmp = [$keytoswap => $fieldstarget_tmp[$keytoswap]];
860 unset($fieldstarget_tmp[$keytoswap]);
861 $fieldstarget_tmp =
arrayInsert($fieldstarget_tmp, $keytoswapwith, $tmp);
862 $keytoswapwith = $arraykeysfieldtarget[$array_match_database_to_file[$keytoswap] - 1];
863 $tmp = $fieldstarget_tmp[$keytoswapwith];
864 unset($fieldstarget_tmp[$keytoswapwith]);
865 $fieldstarget_tmp[$keytoswapwith] = $tmp;
866 $keytoswap = $keytoswapwith;
872 $fieldstarget_tmp[$key][
"imported"] =
false;
876 $fieldstarget = $fieldstarget_tmp;
885 $param =
'&format='.$format.
'&datatoimport='.urlencode($datatoimport).
'&filetoimport='.urlencode($filetoimport);
886 if ($excludefirstline) {
887 $param .=
'&excludefirstline='.urlencode($excludefirstline);
890 $param .=
'&endatlinenb='.urlencode($endatlinenb);
893 $param .=
'&separator='.urlencode($separator);
896 $param .=
'&enclosure='.urlencode($enclosure);
899 llxHeader(
'', $langs->trans(
"NewImport"), $help_url);
903 $titleofmodule = $objimport->array_import_module[0][
'module']->getName();
907 print
'<div class="underbanner clearboth"></div>';
908 print
'<div class="fichecenter">';
910 print
'<table class="centpercent border tableforfield">';
913 print
'<tr><td class="titlefieldcreate">'.$langs->trans(
"Module").
'</td>';
916 if (in_array($objimport->array_import_code[0], array(
'produit_supplierprices',
'produit_multiprice',
'produit_languages'))) {
917 $titleofmodule = $langs->trans(
"ProductOrService");
923 print
'<tr><td>'.$langs->trans(
"DatasetToImport").
'</td>';
925 $entity = preg_replace(
'/:.*$/',
'', $objimport->array_import_icon[0]);
926 $entityicon = strtolower(!empty($entitytoicon[$entity]) ? $entitytoicon[$entity] : $entity);
927 print
img_object($objimport->array_import_module[0][
'module']->getName(), $entityicon).
' ';
928 print $objimport->array_import_label[0];
938 print
load_fiche_titre($langs->trans(
"InformationOnSourceFile"),
'',
'file-export');
940 print
'<div class="underbanner clearboth"></div>';
941 print
'<div class="fichecenter">';
942 print
'<table width="100%" class="border tableforfield">';
945 print
'<tr><td class="titlefieldcreate">'.$langs->trans(
"SourceFileFormat").
'</td>';
946 print
'<td class="nowraponall">';
947 $text = $objmodelimport->getDriverDescForKey($format);
949 print $form->textwithpicto($objmodelimport->getDriverLabelForKey($format), $text);
953 if ($model ==
'csv') {
954 '@phan-var-force ImportCsv $obj';
955 print
'<tr><td>'.$langs->trans(
"CsvOptions").
'</td>';
957 print
'<form method="POST">';
958 print
'<input type="hidden" name="token" value="'.newToken().
'">';
959 print
'<input type="hidden" value="'.$step.
'" name="step">';
960 print
'<input type="hidden" value="'.$format.
'" name="format">';
961 print
'<input type="hidden" value="'.$excludefirstline.
'" name="excludefirstline">';
962 print
'<input type="hidden" value="'.$endatlinenb.
'" name="endatlinenb">';
963 print
'<input type="hidden" value="'.$datatoimport.
'" name="datatoimport">';
964 print
'<input type="hidden" value="'.$filetoimport.
'" name="filetoimport">';
965 print $langs->trans(
"Separator").
' : ';
966 print
'<input type="text" class="width25 center" name="separator" value="'.dol_escape_htmltag($separator).
'"/>';
967 print
' '.$langs->trans(
"Enclosure").
' : ';
968 print
'<input type="text" class="width25 center" name="enclosure" value="'.dol_escape_htmltag($enclosure).
'"/> ';
969 print
'<input name="update" type="submit" value="'.$langs->trans(
'Update').
'" class="button smallpaddingimp" />';
975 print
'<tr><td>'.$langs->trans(
"FileToImport").
'</td>';
977 $modulepart =
'import';
978 $relativepath =
GETPOST(
'filetoimport');
979 print
'<a data-ajax="false" href="'.DOL_URL_ROOT.
'/document.php?modulepart='.$modulepart.
'&file='.urlencode($relativepath).
'&step=3'.$param.
'" target="_blank" rel="noopener noreferrer">';
980 print
img_mime($file,
'',
'pictofixedwidth');
982 print
img_picto($langs->trans(
"Download"),
'download',
'class="paddingleft opacitymedium"');
995 print
'<!-- List of source fields -->'.
"\n";
996 print
'<form action="'.$_SERVER[
"PHP_SELF"].
'" method="POST">';
997 print
'<input type="hidden" name="token" value="'.newToken().
'">';
998 print
'<input type="hidden" name="action" value="select_model">';
999 print
'<input type="hidden" name="step" value="3">';
1000 print
'<input type="hidden" name="format" value="'.$format.
'">';
1001 print
'<input type="hidden" name="datatoimport" value="'.$datatoimport.
'">';
1002 print
'<input type="hidden" name="filetoimport" value="'.$filetoimport.
'">';
1003 print
'<input type="hidden" name="excludefirstline" value="'.$excludefirstline.
'">';
1004 print
'<input type="hidden" name="endatlinenb" value="'.$endatlinenb.
'">';
1005 print
'<input type="hidden" name="separator" value="'.dol_escape_htmltag($separator).
'">';
1006 print
'<input type="hidden" name="enclosure" value="'.dol_escape_htmltag($enclosure).
'">';
1009 print
'<div class="marginbottomonly">';
1010 print
'<span class="opacitymedium">';
1011 $s = $langs->trans(
"SelectImportFieldsSource",
'{s1}');
1012 $s = str_replace(
'{s1}',
img_picto(
'',
'grip_title',
'', 0, 0, 0,
'',
'', 0), $s);
1015 $htmlother->select_import_model((
string) $importmodelid,
'importmodelid', $datatoimport, 1, $user->id);
1016 print
'<input type="submit" class="button smallpaddingimp reposition" id="applyprofile" name="applyprofile" value="'.$langs->trans(
"Apply").
'">';
1018 if (!empty(
$conf->use_javascript_ajax)) {
1020 $(document).ready(function() {
1022 $("#applyprofile").hide();
1024 // follow change on list
1025 $("#importmodelid").change(function() {
1026 console.log("We select a new profile");
1027 if ($(this).val() && $(this).val() != "-1") {
1028 $("#applyprofile").show();
1030 $("#applyprofile").hide();
1044 print
'<div class="div-table-responsive-no-min">';
1045 print
'<table class="noborder centpercent">';
1046 print
'<tr class="liste_titre">';
1047 print
'<td>'.$langs->trans(
"FieldsInSourceFile").
'</td>';
1048 print
'<td>'.$langs->trans(
"FieldsInTargetDatabase").
'</td>';
1053 print
'<tr valign="top"><td width="50%" class="nopaddingleftimp">';
1055 $fieldsplaced = array();
1056 $valforsourcefieldnb = array();
1057 $listofkeys = array();
1058 foreach ($array_match_file_to_database as $key => $val) {
1059 $listofkeys[$key] = 1;
1062 print
"\n<!-- Box left container -->\n";
1063 print
'<div id="left" class="connectedSortable">'.
"\n";
1068 foreach ($fieldssource as $key => $val) {
1069 show_elem($fieldssource, $key, (
string) $key);
1070 $listofkeys[$key] = 1;
1071 $fieldsplaced[$key] = 1;
1072 $valforsourcefieldnb[$lefti] = $key;
1082 print
"<!-- End box left container -->\n";
1085 print
'</td><td width="50%" class="nopaddingrightimp">';
1089 $optionsall = array();
1090 foreach ($fieldstarget as $code => $line) {
1091 $tmparray = explode(
'|', $line[
"label"]);
1093 foreach ($tmparray as $tmpkey => $tmpval) {
1094 $labeltoshow .= ($labeltoshow ?
' '.$langs->trans(
'or').
' ' :
'').$langs->transnoentities($tmpval);
1099 $optionsall[$code] = array(
1100 'labelkey' => $line[
'label'],
1101 'labelkeyarray' => $tmparray,
1102 'label' => $labeltoshow,
1103 'required' => (empty($line[
"required"]) ? 0 : 1),
1104 'position' => (!empty($line[
'position']) ? $line[
'position'] : 0),
1112 $mandatoryfieldshavesource =
true;
1125 $modetoautofillmapping =
'session';
1126 if ($initialloadofstep4) {
1127 $modetoautofillmapping =
'guess';
1131 print
'<table class="nobordernopadding centpercent tableimport">';
1132 foreach ($fieldssource as $code => $line) {
1137 print
'<tr style="height:'.$height.
'" class="trimport oddevenimport">';
1139 $entity = (!empty($objimport->array_import_entities[0][$code]) ? $objimport->array_import_entities[0][$code] : $objimport->array_import_icon[0]);
1141 $entityicon = !empty($entitytoicon[$entity]) ? $entitytoicon[$entity] : $entity;
1142 $entitylang = !empty($entitytolang[$entity]) ? $entitytolang[$entity] : $objimport->array_import_label[0];
1144 print
'<td class="nowraponall hideonsmartphone" style="font-weight: normal">=> </td>';
1145 print
'<td class="nowraponall" style="font-weight: normal">';
1147 $selectforline =
'';
1148 $selectforline .=
'<select id="selectorderimport_'.($i + 1).
'" class="targetselectchange minwidth300" name="select_'.($i + 1).
'">';
1149 $selectforline .=
'<option value="-1"> </option>';
1152 $codeselectedarray = array();
1153 foreach ($optionsall as $tmpcode => $tmpval) {
1155 if (!empty($tmpval[
'picto'])) {
1156 $label .=
img_picto(
'', $tmpval[
'picto'],
'class="pictofixedwidth"');
1158 $label .= $tmpval[
'required'] ?
'<strong>' :
'';
1159 $label .= $tmpval[
'label'];
1160 $label .= $tmpval[
'required'] ?
'*</strong>' :
'';
1162 $tablealias = preg_replace(
'/(\..*)$/i',
'', $tmpcode);
1163 $tablename = !empty($objimport->array_import_tables[0][$tablealias]) ? $objimport->array_import_tables[0][$tablealias] :
"";
1167 $filecolumn = ($i + 1);
1169 if (empty($objimport->array_import_convertvalue[0][$tmpcode])) {
1172 if ($objimport->array_import_convertvalue[0][$tmpcode][
'rule'] ==
'fetchidfromref') {
1173 $htmltext .= $langs->trans(
"DataComeFromIdFoundFromRef", $langs->transnoentitiesnoconv($entitylang)).
'<br>';
1175 if ($objimport->array_import_convertvalue[0][$tmpcode][
'rule'] ==
'fetchidfromcodeid') {
1176 $dictlabel = $objimport->array_import_convertvalue[0][$tmpcode][
'dict'] ??
'';
1177 $htmltext .= $langs->trans(
"DataComeFromIdFoundFromCodeId", $langs->transnoentitiesnoconv($dictlabel)).
'<br>';
1181 $example = !empty($objimport->array_import_examplevalues[0][$tmpcode]) ? $objimport->array_import_examplevalues[0][$tmpcode] :
"";
1183 if (empty($objimport->array_import_convertvalue[0][$tmpcode])) {
1185 $htmltext .= $langs->trans(
"SourceExample").
': <b>'.str_replace(
'"',
'', $example).
'</b><br>';
1188 if ($objimport->array_import_convertvalue[0][$tmpcode][
'rule'] ==
'fetchidfromref') {
1189 $htmltext .= $langs->trans(
"SourceExample").
': <b>'.$langs->transnoentitiesnoconv(
"ExampleAnyRefFoundIntoElement", $entitylang).($example ?
' ('.$langs->transnoentitiesnoconv(
"Example").
': '.str_replace(
'"',
'', $example).
')' :
'').
'</b><br>';
1190 } elseif ($objimport->array_import_convertvalue[0][$tmpcode][
'rule'] ==
'fetchidfromcodeid') {
1191 $dictlabel = $objimport->array_import_convertvalue[0][$tmpcode][
'dict'] ??
'';
1192 $htmltext .= $langs->trans(
"SourceExample").
': <b>'.$langs->trans(
"ExampleAnyCodeOrIdFoundIntoDictionary", $langs->transnoentitiesnoconv($dictlabel)).($example ?
' ('.$langs->transnoentitiesnoconv(
"Example").
': '.str_replace(
'"',
'', $example).
')' :
'').
'</b><br>';
1193 } elseif ($example) {
1194 $htmltext .= $langs->trans(
"SourceExample").
': <b>'.str_replace(
'"',
'', $example).
'</b><br>';
1198 if (!empty($objimport->array_import_regex[0][$tmpcode])) {
1199 $htmltext .= $langs->trans(
"FormatControlRule").
': <b>'.str_replace(
'"',
'', $objimport->array_import_regex[0][$tmpcode]).
'</b><br>';
1203 $htmltext .= $langs->trans(
"InformationOnTargetTables").
': <b>'.$tablename.
"->".preg_replace(
'/^.*\./',
'', $tmpcode).
"</b>";
1205 $labelhtml = $label.
' '.$form->textwithpicto(
'', $htmltext, 1,
'help',
'', 1);
1208 $selectforline .=
'<option value="'.$tmpcode.
'"';
1209 if ($modetoautofillmapping ==
'orderoftargets') {
1212 $selectforline .=
' selected';
1214 } elseif ($modetoautofillmapping ==
'guess') {
1218 if (preg_match(
'/^(.+)\((.+\..+)\)$/', $line[
'example1'], $regs)) {
1219 $tmpstring1 = $regs[1];
1220 $tmpstring2 = $regs[2];
1222 $tmpstring1 = $line[
'example1'];
1230 foreach ($tmpval[
'labelkeyarray'] as $tmpval2) {
1231 $labeltarget = $langs->transnoentities($tmpval2);
1233 if ($tmpstring1 && ($tmpstring1 == $tmpcode || $tmpstring1 == strtolower($labeltarget)
1234 || $tmpstring1 == strtolower(
dol_string_unaccent($labeltarget)) || $tmpstring1 == strtolower($tmpval2))) {
1235 if (empty($codeselectedarray[$code])) {
1236 $selectforline .=
' selected';
1237 $codeselectedarray[$code] = 1;
1240 } elseif ($tmpstring2 && ($tmpstring2 == $tmpcode || $tmpstring2 == strtolower($labeltarget)
1241 || $tmpstring2 == strtolower(
dol_string_unaccent($labeltarget)) || $tmpstring2 == strtolower($tmpval2))) {
1242 if (empty($codeselectedarray[$code])) {
1243 $selectforline .=
' selected';
1244 $codeselectedarray[$code] = 1;
1249 } elseif ($modetoautofillmapping ==
'session' && !empty($_SESSION[
'dol_array_match_file_to_database_select'])) {
1250 $tmpselectioninsession =
dolExplodeIntoArray($_SESSION[
'dol_array_match_file_to_database_select'],
',',
'=');
1252 if (!empty($tmpselectioninsession[(
string) ($i + 1)]) && $tmpselectioninsession[(
string) ($i + 1)] == $tmpcode) {
1253 $selectforline .=
' selected';
1255 $selectforline .=
' data-debug="'.$tmpcode.
'-'.$code.
'-'.$j.
'-'.(!empty($tmpselectioninsession[(
string) ($i + 1)]) ? $tmpselectioninsession[(
string) ($i + 1)] :
"").
'"';
1257 $selectforline .=
' data-html="'.dol_escape_htmltag($labelhtml).
'"';
1258 $selectforline .=
'>';
1259 $selectforline .= $label;
1260 $selectforline .=
'</options>';
1263 $selectforline .=
'</select>';
1264 $selectforline .=
ajax_combobox(
'selectorderimport_'.($i + 1));
1266 print $selectforline;
1271 print
'<td class="nowraponall" style="font-weight:normal; text-align:right">';
1274 $htmltext =
'<b><u>'.$langs->trans(
"FieldSource").
'</u></b><br>';
1276 $htmltext .= $langs->trans(
"DataComeFromFileFieldNb", $filecolumntoshow).
'<br>';
1278 print $form->textwithpicto(
'', $htmltext);
1289 print
'<tr class="liste_titre"><td colspan="2">'.$langs->trans(
"Note").
'</td></tr>';
1290 print
'<tr><td colspan="2"><div id="div-mandatory-target-fields-not-mapped"></div></td></tr>';
1296 if (!empty(
$conf->use_javascript_ajax)) {
1297 print
'<script type="text/javascript">'.
"\n";
1298 print
'var previousselectedvalueimport = "0";'.
"\n";
1299 print
'var previousselectedlabelimport = "0";'.
"\n";
1300 print
'var arrayofselectedvalues = [];'.
"\n";
1301 print
'var arrayoftargetfields = [];'.
"\n";
1302 print
'var arrayoftargetmandatoryfields = [];'.
"\n";
1306 foreach ($fieldstarget as $key => $val) {
1307 print
"arrayoftargetfields[".$tmpi.
"] = '".
dol_escape_js($langs->trans($val[
'label'])).
"'; ";
1308 if ($val[
'required']) {
1309 print
"arrayoftargetmandatoryfields[".$tmpi.
"] = '".
dol_escape_js($key).
"'; ";
1315 print
'$(document).ready(function () {'.
"\n";
1317 print
'setOptionsToDisabled();'.
"\n";
1318 print
'saveSelection();'.
"\n";
1320 print
'$(".targetselectchange").focus(function(){'.
"\n";
1321 print
' previousselectedvalueimport = $(this).val();'.
"\n";
1322 print
' previousselectedlabelimport = $(this).children("option:selected").text();'.
"\n";
1323 print
' console.log("previousselectedvalueimport="+previousselectedvalueimport)'.
"\n";
1330 print
'function setOptionsToDisabled() {'.
"\n";
1331 print
' console.log("Remove the disabled flag everywhere");'.
"\n";
1332 print
' $("select.targetselectchange").not($( this )).find(\'option\').prop("disabled", false);'.
"\n";
1333 print
' arrayofselectedvalues = [];'.
"\n";
1335 print
' $("select.targetselectchange").each(function(){'.
"\n";
1336 print
' id = $(this).attr(\'id\')'.
"\n";
1337 print
' value = $(this).val()'.
"\n";
1338 print
' console.log("a selected value has been found for component "+id+" = "+value);'.
"\n";
1339 print
' arrayofselectedvalues.push(value);'.
"\n";
1342 print
' console.log("List of all selected values arrayofselectedvalues");'.
"\n";
1343 print
' console.log(arrayofselectedvalues);'.
"\n";
1344 print
' console.log("Set the option to disabled for every entry that is currently selected somewhere else (so into arrayofselectedvalues)");'.
"\n";
1346 print
' $.each(arrayofselectedvalues, function(key, value) {'.
"\n";
1347 print
' if (value != -1) {'.
"\n";
1348 print
' console.log("Process key="+key+" value="+value+" to disable.");'.
"\n";
1349 print
' $("select.targetselectchange").find(\'option[value="\'+value+\'"]:not(:selected)\').prop("disabled", true);'.
"\n";
1355 print
'function saveSelection() {'.
"\n";
1357 print
' arrayselectedfields = [];'.
"\n";
1358 print
' arrayselectedfields.push(0);'.
"\n";
1360 print
' $.each( arrayofselectedvalues, function( key, value ) {'.
"\n";
1361 print
' if (value != -1) {'.
"\n";
1362 print
' arrayselectedfields.push(value);'.
"\n";
1363 print
' } else {'.
"\n";
1364 print
' arrayselectedfields.push(0);'.
"\n";
1368 print
" $.ajax({\n";
1369 print
" type: 'POST',\n";
1370 print
" dataType: 'json',\n";
1371 print
" url: '".dol_escape_js($_SERVER[
"PHP_SELF"]).
"?action=saveselectorder&token=".newToken().
"',\n";
1372 print
" data: 'selectorder='+arrayselectedfields.toString(),\n";
1373 print
" success: function(){\n";
1374 print
" console.log('The selected fields have been saved into '+arrayselectedfields.toString());\n";
1379 print
' console.log("arrayselectedfields");';
1380 print
' console.log(arrayselectedfields);';
1381 print
' console.log("arrayoftargetmandatoryfields");';
1382 print
' console.log(arrayoftargetmandatoryfields);';
1383 print
" listtoshow = '';";
1384 print
" nbelement = arrayoftargetmandatoryfields.length
1385 for (let i = 0; i < nbelement; i++) {
1386 if (arrayoftargetmandatoryfields[i] && ! arrayselectedfields.includes(arrayoftargetmandatoryfields[i])) {
1387 console.log(arrayoftargetmandatoryfields[i]+' not mapped');
1388 listtoshow = listtoshow + (listtoshow ? ', ' : '') + '<b>' + arrayoftargetfields[i] + '*</b>';
1391 console.log(listtoshow);
1393 listtoshow = '".dol_escape_js(
img_warning($langs->trans(
"MandatoryTargetFieldsNotMapped")).
' '.$langs->trans(
"MandatoryTargetFieldsNotMapped")).
": ' + listtoshow;
1394 $('#div-mandatory-target-fields-not-mapped').html(listtoshow);
1396 $('#div-mandatory-target-fields-not-mapped').html('<span class=\"opacitymedium\">".
dol_escape_js($langs->trans(
"AllTargetMandatoryFieldsAreMapped")).
"</span>');
1403 print
'$(".targetselectchange").change(function(){'.
"\n";
1404 print
' setOptionsToDisabled();'.
"\n";
1406 print
' if(previousselectedlabelimport != "" && previousselectedvalueimport != -1) {'.
"\n";
1407 print
' let valuetochange = $(this).val(); '.
"\n";
1408 print
' $(".boxtdunused").each(function(){'.
"\n";
1409 print
' if ($(this).text().includes(valuetochange)){'.
"\n";
1410 print
' arraychild = $(this)[0].childNodes'.
"\n";
1411 print
' arraytexttomodify = arraychild[0].textContent.split(" ")'.
"\n";
1412 print
' arraytexttomodify[1] = previousselectedvalueimport '.
"\n";
1413 print
' textmodified = arraytexttomodify.join(" ") '.
"\n";
1414 print
' arraychild[0].textContent = textmodified'.
"\n";
1415 print
' arraychild[1].innerHTML = previousselectedlabelimport'.
"\n";
1419 print
' $(this).blur()'.
"\n";
1421 print
' saveSelection()'.
"\n";
1425 print
'</script>'.
"\n";
1431 print
'<div class="tabsAction">';
1433 if (count($array_match_file_to_database)) {
1434 if ($mandatoryfieldshavesource) {
1435 print
'<a class="butAction saveorderselect" href="import.php?step=4'.$param.
'&filetoimport='.urlencode($filetoimport).
'">'.$langs->trans(
"NextStep").
'</a>';
1437 print
'<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->transnoentitiesnoconv(
"SomeMandatoryFieldHaveNoSource")).
'">'.$langs->trans(
"NextStep").
'</a>';
1445 if (count($array_match_file_to_database)) {
1447 print
'<!-- Area to add new import profile -->'.
"\n";
1448 print
'<div class="marginbottomonly"><span class="opacitymedium">'.$langs->trans(
"SaveImportModel").
'</span></div>';
1450 print
'<form class="nocellnopadd" action="'.$_SERVER[
"PHP_SELF"].
'" method="post">';
1451 print
'<input type="hidden" name="token" value="'.newToken().
'">';
1452 print
'<input type="hidden" name="action" value="add_import_model">';
1453 print
'<input type="hidden" name="step" value="'.$step.
'">';
1454 print
'<input type="hidden" name="format" value="'.$format.
'">';
1455 print
'<input type="hidden" name="datatoimport" value="'.$datatoimport.
'">';
1456 print
'<input type="hidden" name="filetoimport" value="'.$filetoimport.
'">';
1457 print
'<input type="hidden" name="hexa" value="'.$hexa.
'">';
1458 print
'<input type="hidden" name="excludefirstline" value="'.$excludefirstline.
'">';
1459 print
'<input type="hidden" name="endatlinenb" value="'.$endatlinenb.
'">';
1460 print
'<input type="hidden" name="page_y" value="">';
1461 print
'<input type="hidden" value="'.dol_escape_htmltag($separator).
'" name="separator">';
1462 print
'<input type="hidden" value="'.dol_escape_htmltag($enclosure).
'" name="enclosure">';
1464 print
'<div class="div-table-responsive-no-min">';
1465 print
'<table summary="selectofimportprofil" class="noborder centpercent">';
1466 print
'<tr class="liste_titre">';
1467 print
'<td>'.$langs->trans(
"ImportModelName").
'</td>';
1468 print
'<td>'.$langs->trans(
"Visibility").
'</td>';
1472 $nameofimportprofile = str_replace(
' ',
'-', $langs->trans(
"ImportProfile").
' '.$titleofmodule.
' '.
dol_print_date(
dol_now(
'gmt'),
'dayxcard'));
1474 $nameofimportprofile = $import_name;
1477 print
'<tr class="oddeven">';
1478 print
'<td><input name="import_name" class="minwidth300" value="'.$nameofimportprofile.
'"></td>';
1480 $arrayvisibility = array(
'private' => $langs->trans(
"Private"),
'all' => $langs->trans(
"Everybody"));
1481 print $form->selectarray(
'visibility', $arrayvisibility,
'private');
1483 print
'<td class="right">';
1484 print
'<input type="submit" class="button smallpaddingimp reposition" value="'.$langs->trans(
"SaveImportProfile").
'">';
1488 $sql =
"SELECT rowid, label, fk_user, entity";
1489 $sql .=
" FROM ".MAIN_DB_PREFIX.
"import_model";
1490 $sql .=
" WHERE type = '".$db->escape($datatoimport).
"'";
1492 $sql .=
" AND fk_user IN (0, ".((int) $user->id).
")";
1494 $sql .=
" ORDER BY rowid";
1496 $resql =
$db->query($sql);
1498 $num =
$db->num_rows($resql);
1504 $obj =
$db->fetch_object($resql);
1506 print
'<tr class="oddeven"><td>';
1509 print
'<td class="tdoverflowmax150">';
1510 if (empty($obj->fk_user)) {
1511 print $langs->trans(
"Everybody");
1513 $tmpuser->fetch($obj->fk_user);
1514 print $tmpuser->getNomUrl(-1);
1517 print
'<td class="right">';
1518 print
'<a class="reposition" href="'.$_SERVER[
"PHP_SELF"].
'?step='.$step.$param.
'&action=deleteprof&token='.newToken().
'&id='.$obj->rowid.
'&filetoimport='.urlencode($filetoimport).
'">';
1536if ($step == 4 && $datatoimport) {
1537 $max_execution_time_for_importexport =
getDolGlobalInt(
'IMPORT_MAX_EXECUTION_TIME', 300);
1538 $max_time = @ini_get(
"max_execution_time");
1539 if ($max_time && $max_time < $max_execution_time_for_importexport) {
1540 dol_syslog(
"max_execution_time=".$max_time.
" is lower than max_execution_time_for_importexport=".$max_execution_time_for_importexport.
". We try to increase it dynamically.");
1541 @ini_set(
"max_execution_time", $max_execution_time_for_importexport);
1547 if ($model ===
'txt') {
1551 $list = $objmodelimport->listOfAvailableImportFormat(
$db);
1554 $dir = DOL_DOCUMENT_ROOT.
"/core/modules/import/";
1555 $file =
"import_".$model.
".modules.php";
1556 $classname =
"Import".ucfirst($model);
1557 require_once $dir.$file;
1558 $obj =
new $classname(
$db, $datatoimport);
1559 '@phan-var-force ModeleImports $obj';
1560 $obj->importtriggermode = $importtriggermode;
1561 $obj->importissimulation = 1;
1562 if ($model ==
'csv') {
1563 '@phan-var-force ImportCsv $obj';
1564 $obj->separator = $separator_used;
1565 $obj->enclosure = $enclosure;
1569 $fieldssource = array();
1570 $result = $obj->import_open_file(
$conf->import->dir_temp.
'/'.$filetoimport);
1574 $arrayrecord = $obj->import_read_record();
1577 foreach ($arrayrecord as $key => $val) {
1578 $fieldssource[$i][
'example1'] =
dol_trunc($val[
'val'], 24);
1581 $obj->import_close_file();
1584 $nboflines = $obj->import_get_nb_of_lines(
$conf->import->dir_temp.
'/'.$filetoimport);
1586 $param =
'&leftmenu=import&format='.urlencode($format).
'&datatoimport='.urlencode($datatoimport).
'&filetoimport='.urlencode($filetoimport).
'&nboflines='.((int) $nboflines).
'&separator='.urlencode($separator).
'&enclosure='.urlencode($enclosure).
'&importtriggermode='.urlencode($importtriggermode);
1588 if ($excludefirstline) {
1589 $param .=
'&excludefirstline='.urlencode($excludefirstline);
1592 $param .=
'&endatlinenb='.urlencode($endatlinenb);
1594 if (!empty($updatekeys)) {
1595 $param .=
'&updatekeys[]='.implode(
'&updatekeys[]=', $updatekeys);
1598 llxHeader(
'', $langs->trans(
"NewImport"), $help_url);
1603 print
'<form action="'.$_SERVER[
"PHP_SELF"].
'?'.$param2.
'" method="POST">';
1604 print
'<input type="hidden" name="token" value="'.newToken().
'">';
1605 print
'<input type="hidden" name="step" value="4">';
1606 print
'<input type="hidden" name="action" value="launchsimu">';
1607 print
'<input type="hidden" name="importtriggermode" value="'.dol_escape_htmltag($importtriggermode).
'">';
1611 print
'<div class="underbanner clearboth"></div>';
1612 print
'<div class="fichecenter">';
1614 print
'<table width="100%" class="border tableforfield">';
1617 print
'<tr><td class="titlefieldcreate">'.$langs->trans(
"Module").
'</td>';
1619 $titleofmodule = $objimport->array_import_module[0][
'module']->getName();
1621 if (in_array($objimport->array_import_code[0], array(
'produit_supplierprices',
'produit_multiprice',
'produit_languages'))) {
1622 $titleofmodule = $langs->trans(
"ProductOrService");
1624 print $titleofmodule;
1628 print
'<tr><td>'.$langs->trans(
"DatasetToImport").
'</td>';
1630 $entity = preg_replace(
'/:.*$/',
'', $objimport->array_import_icon[0]);
1631 $entityicon = strtolower(!empty($entitytoicon[$entity]) ? $entitytoicon[$entity] : $entity);
1632 print
img_object($objimport->array_import_module[0][
'module']->getName(), $entityicon).
' ';
1633 print $objimport->array_import_label[0];
1641 print
load_fiche_titre($langs->trans(
"InformationOnSourceFile"),
'',
'file-export');
1643 print
'<div class="underbanner clearboth"></div>';
1644 print
'<div class="fichecenter">';
1645 print
'<table width="100%" class="border tableforfield">';
1648 print
'<tr><td class="titlefieldcreate">'.$langs->trans(
"SourceFileFormat").
'</td>';
1649 print
'<td class="nowraponall">';
1650 $text = $objmodelimport->getDriverDescForKey($format);
1652 print $form->textwithpicto($objmodelimport->getDriverLabelForKey($format), $text);
1656 if ($model ==
'csv') {
1657 '@phan-var-force ImportCsv $obj';
1658 print
'<tr><td>'.$langs->trans(
"CsvOptions").
'</td>';
1661 print
' '.$langs->trans(
"Enclosure").
' : '.
dol_escape_htmltag($enclosure);
1666 print
'<tr><td>'.$langs->trans(
"FileToImport").
'</td>';
1668 $modulepart =
'import';
1669 $relativepath =
GETPOST(
'filetoimport');
1670 print
'<a data-ajax="false" href="'.DOL_URL_ROOT.
'/document.php?modulepart='.urlencode($modulepart).
'&file='.urlencode($relativepath).
'&step=4'.$param.
'" target="_blank" rel="noopener noreferrer">';
1671 print
img_mime($file,
'',
'pictofixedwidth');
1672 print $filetoimport;
1673 print
img_picto($langs->trans(
"Download"),
'download',
'class="paddingleft opacitymedium"');
1679 print $langs->trans(
"NbOfSourceLines");
1686 print $langs->trans(
"ImportFromToLine");
1688 if ($action ==
'launchsimu') {
1689 print
'<input type="number" min="1" class="maxwidth50 right valignmiddle" name="excludefirstlinebis" disabled="disabled" value="'.$excludefirstline.
'">';
1690 print
'<input type="hidden" name="excludefirstline" value="'.$excludefirstline.
'">';
1692 print
'<input type="number" min="1" class="maxwidth50 right valignmiddle" name="excludefirstline" value="'.$excludefirstline.
'">';
1693 print $form->textwithpicto(
"", $langs->trans(
"SetThisValueTo2ToExcludeFirstLine"));
1696 if ($action ==
'launchsimu') {
1697 print
'<input type="text" class="maxwidth50 valignmiddle" name="endatlinenbbis" disabled="disabled" value="'.$endatlinenb.
'">';
1698 print
'<input type="hidden" name="endatlinenb" value="'.$endatlinenb.
'">';
1700 print
'<input type="text" class="maxwidth50 valignmiddle" name="endatlinenb" value="'.$endatlinenb.
'">';
1701 print $form->textwithpicto(
"", $langs->trans(
"KeepEmptyToGoToEndOfFile"));
1703 if ($action ==
'launchsimu') {
1704 print
' <a href="'.$_SERVER[
"PHP_SELF"].
'?step=4'.$param.
'" class="editfielda">';
1706 print
img_picto($langs->trans(
"Modify"),
'edit');
1709 if ($excludefirstline == 2) {
1710 print $form->textwithpicto(
"", $langs->trans(
"WarningFirstImportedLine", $excludefirstline), 1,
'warning',
"warningexcludefirstline valignmiddle");
1712 $( document ).ready(function() {
1713 $("input[name=\'excludefirstline\']").on("change",function(){
1714 if($(this).val() <= 1){
1715 $(".warningexcludefirstline").hide();
1717 $(".warningexcludefirstline").show();
1727 print $form->textwithpicto($langs->trans(
"KeysToUseForUpdates"), $langs->trans(
"SelectPrimaryColumnsForUpdateAttempt"));
1729 if ($action ==
'launchsimu') {
1730 if (count($updatekeys)) {
1731 print $form->multiselectarray(
'updatekeysbis', $objimport->array_import_updatekeys[0], $updatekeys, 0, 0,
'', 1,
'80%',
'disabled');
1733 print
'<span class="opacitymedium">'.$langs->trans(
"NoUpdateAttempt").
'</span>';
1735 foreach ($updatekeys as $val) {
1736 print
'<input type="hidden" name="updatekeys[]" value="'.$val.
'">';
1738 print
' <a href="'.$_SERVER[
"PHP_SELF"].
'?step=4'.$param.
'" class="editfielda">';
1740 print
img_picto($langs->trans(
"Modify"),
'edit');
1743 if (is_array($objimport->array_import_updatekeys[0]) && count($objimport->array_import_updatekeys[0])) {
1744 print $form->multiselectarray(
'updatekeys', $objimport->array_import_updatekeys[0], $updatekeys, 0, 0,
'', 1,
'80%');
1747 print
'<span class="opacitymedium">'.$langs->trans(
"UpdateNotYetSupportedForThisImport").
'</span>';
1760 print
load_fiche_titre($langs->trans(
"InformationOnTargetTables"),
'',
'file-import');
1762 print
'<div class="underbanner clearboth"></div>';
1763 print
'<div class="fichecenter">';
1765 print
'<table class="centpercent border tableforfield">';
1768 print
'<tr><td class="titlefieldcreate">';
1769 print $langs->trans(
"TablesTarget");
1771 $listtables = array();
1772 $sort_array_match_file_to_database = $array_match_file_to_database;
1773 foreach ($array_match_file_to_database as $code => $label) {
1775 if ($code > count($fieldssource)) {
1779 $alias = preg_replace(
'/(\..*)$/i',
'', $label);
1780 $listtables[$alias] = $objimport->array_import_tables[0][$alias];
1782 if (count($listtables)) {
1785 foreach ($listtables as $val) {
1804 print $langs->trans(
"Error");
1810 print $langs->trans(
"FieldsTarget").
'</td><td class="small">';
1811 $listfields = array();
1814 $sort_array_match_file_to_database = $array_match_file_to_database;
1815 ksort($sort_array_match_file_to_database);
1817 foreach ($sort_array_match_file_to_database as $code => $label) {
1820 if ($code > count($fieldssource)) {
1824 $alias = preg_replace(
'/(\..*)$/i',
'', $label);
1825 $listfields[$i] =
'<span class="nowrap">'.$langs->trans(
"Column").
' '.
num2Alpha((
int) $code - 1).
' -> '.$label.
'</span>';
1827 print count($listfields) ? (implode(
', ', $listfields)) : $langs->trans(
"Error");
1832 print $form->textwithpicto($langs->trans(
"ImportTriggerModeLabel"), $langs->trans(
"ImportTriggerModeHint"));
1834 $triggerModeChoices = array(
1835 'strict_line' => $langs->trans(
"ImportTriggerModeStrictLine"),
1836 'fast_bulk' => $langs->trans(
"ImportTriggerModeFastBulk"),
1838 if ($action ==
'launchsimu') {
1839 print
dol_escape_htmltag($triggerModeChoices[$importtriggermode] ?? $importtriggermode);
1840 print
'<input type="hidden" name="importtriggermode" value="'.dol_escape_htmltag($importtriggermode).
'">';
1841 print
' <a href="'.$_SERVER[
"PHP_SELF"].
'?step=4'.$param.
'" class="editfielda">';
1843 print
img_picto($langs->trans(
"Modify"),
'edit');
1846 print $form->selectarray(
'importtriggermode', $triggerModeChoices, $importtriggermode, 0);
1848 if ($importtriggermode ===
'fast_bulk') {
1849 print
'<br><span class="warning">';
1850 print $langs->trans(
"ImportTriggerModeFastBulkWarning");
1861 if ($action !=
'launchsimu') {
1864 print
'<div class="neutral">';
1865 print $langs->trans(
"NowClickToTestTheImport", $langs->transnoentitiesnoconv(
"RunSimulateImportFile")).
'<br>';
1869 print
'<div class="center">';
1870 if ($user->hasRight(
'import',
'run')) {
1871 print
'<input type="submit" class="butAction" value="'.$langs->trans(
"RunSimulateImportFile").
'">';
1873 print
'<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->transnoentitiesnoconv(
"NotEnoughPermissions")).
'">'.$langs->trans(
"RunSimulateImportFile").
'</a>';
1878 print
'<div class="warning">';
1879 print
'<b>'.$langs->trans(
"ImportTriggerModeSimulationWarningTitle").
'</b><br>';
1880 print $langs->trans(
"ImportTriggerModeSimulationWarning");
1884 $arrayoferrors = array();
1885 $arrayofwarnings = array();
1899 $pathfile =
$conf->import->dir_temp.
'/'.$filetoimport;
1900 $result = $obj->import_open_file($pathfile);
1902 global $tablewithentity_cache;
1903 $tablewithentity_cache = array();
1908 while (($sourcelinenb < $nboflines) && !$endoffile) {
1912 $arrayrecord = $obj->import_read_record();
1913 if ($arrayrecord ===
false) {
1914 $arrayofwarnings[$sourcelinenb][0] = array(
'lib' => $langs->trans(
'ErrorFileLinesReachEOF', $nboflines, $sourcelinenb),
'type' =>
'EOF_RECORD_ON_SEVERAL_LINES');
1918 if ($excludefirstline && ($sourcelinenb < $excludefirstline)) {
1921 if ($endatlinenb && ($sourcelinenb > $endatlinenb)) {
1925 $parameters = array(
1927 'datatoimport' => $datatoimport,
1929 'arrayrecord' => $arrayrecord,
1930 'array_match_file_to_database' => $array_match_file_to_database,
1931 'objimport' => $objimport,
1932 'fieldssource' => $fieldssource,
1933 'importid' => $importid,
1934 'updatekeys' => $updatekeys,
1935 'importtriggermode' => $importtriggermode,
1936 'arrayoferrors' => &$arrayoferrors,
1937 'arrayofwarnings' => &$arrayofwarnings,
1941 $reshook = $hookmanager->executeHooks(
'ImportInsert', $parameters);
1943 $arrayoferrors[$sourcelinenb][] = [
1944 'lib' => implode(
"<br>", array_merge([$hookmanager->error], $hookmanager->errors))
1948 if (empty($reshook)) {
1950 $result = $obj->import_insert($arrayrecord, $array_match_file_to_database, $objimport, count($fieldssource), $importid, $updatekeys);
1952 if (count($obj->errors)) {
1953 $arrayoferrors[$sourcelinenb] = $obj->errors;
1955 if (count($obj->warnings)) {
1956 $arrayofwarnings[$sourcelinenb] = $obj->warnings;
1958 if (!count($obj->errors) && !count($obj->warnings)) {
1963 $reshook = $hookmanager->executeHooks(
'AfterImportInsert', $parameters);
1965 $arrayoferrors[$sourcelinenb][] = [
1966 'lib' => implode(
"<br>", array_merge([$hookmanager->error], $hookmanager->errors))
1971 $obj->import_close_file();
1973 print $langs->trans(
"ErrorFailedToOpenFile", $pathfile);
1980 if (!empty($objimport->array_import_run_sql_after[0]) && is_array($objimport->array_import_run_sql_after[0])) {
1982 foreach ($objimport->array_import_run_sql_after[0] as $sqlafterimport) {
1984 $resqlafterimport =
$db->query($sqlafterimport);
1985 if (!$resqlafterimport) {
1986 $arrayoferrors[
'none'][] = array(
'lib' => $langs->trans(
"Error running final request: ".$sqlafterimport));
1995 if (!count($arrayoferrors) && !count($arrayofwarnings)) {
1997 print
'<div class="info">';
1998 print
'<div class=""><b>'.$langs->trans(
"ResultOfSimulationNoError").
'</b></div>';
1999 print $langs->trans(
"NbInsertSim", empty($obj->nbinsert) ? 0 : $obj->nbinsert).
'<br>';
2000 print $langs->trans(
"NbUpdateSim", empty($obj->nbupdate) ? 0 : $obj->nbupdate).
'<br>';
2005 print
'<div class="warning">';
2006 print $langs->trans(
"NbOfLinesOK", $nbok).
'...<br>';
2013 if (count($arrayoferrors)) {
2014 print
img_error().
' <b>'.$langs->trans(
"ErrorsOnXLines", count($arrayoferrors)).
'</b><br>';
2015 print
'<table width="100%" class="border"><tr><td>';
2016 foreach ($arrayoferrors as $key => $val) {
2018 if ($nboferrors > $maxnboferrors) {
2019 print $langs->trans(
"TooMuchErrors", (count($arrayoferrors) - $nboferrors)).
"<br>";
2023 foreach ($val as $i => $err) {
2024 print
' > '.dol_escape_htmltag($err[
'lib']).
'<br>';
2027 print
'</td></tr></table>';
2033 if (count($arrayofwarnings)) {
2034 print
img_warning().
' <b>'.$langs->trans(
"WarningsOnXLines", count($arrayofwarnings)).
'</b><br>';
2035 print
'<table width="100%" class="border"><tr><td>';
2036 foreach ($arrayofwarnings as $key => $val) {
2038 if ($nbofwarnings > $maxnbofwarnings) {
2039 print $langs->trans(
"TooMuchWarnings", (count($arrayofwarnings) - $nbofwarnings)).
"<br>";
2043 foreach ($val as $i => $err) {
2044 print
' > '.dol_escape_htmltag($err[
'lib']).
'<br>';
2047 print
'</td></tr></table>';
2054 print
'<div class="center">';
2055 print
'<span class="opacitymedium">'.$langs->trans(
"NowClickToRunTheImport", $langs->transnoentitiesnoconv(
"RunImportFile")).
'</span><br>';
2064 print
'<div class="center">';
2065 if ($user->hasRight(
'import',
'run')) {
2066 if (empty($nboferrors)) {
2067 print
'<a class="butAction" href="'.DOL_URL_ROOT.
'/imports/import.php?leftmenu=import&step=5&importid='.$importid.$param.
'">'.$langs->trans(
"RunImportFile").
'</a>';
2071 print
'<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->transnoentitiesnoconv(
"CorrectErrorBeforeRunningImport")).
'">'.$langs->trans(
"RunImportFile").
'</a>';
2074 print
'<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->transnoentitiesnoconv(
"NotEnoughPermissions")).
'">'.$langs->trans(
"RunSimulateImportFile").
'</a>';
2076 print
'<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->transnoentitiesnoconv(
"NotEnoughPermissions")).
'">'.$langs->trans(
"RunImportFile").
'</a>';
2086if ($step == 5 && $datatoimport) {
2087 $max_execution_time_for_importexport =
getDolGlobalInt(
'IMPORT_MAX_EXECUTION_TIME', 300);
2088 $max_time = @ini_get(
"max_execution_time");
2089 if ($max_time && $max_time < $max_execution_time_for_importexport) {
2090 dol_syslog(
"max_execution_time=".$max_time.
" is lower than max_execution_time_for_importexport=".$max_execution_time_for_importexport.
". We try to increase it dynamically.");
2091 @ini_set(
"max_execution_time", $max_execution_time_for_importexport);
2097 if ($model ===
'txt') {
2101 $list = $objmodelimport->listOfAvailableImportFormat(
$db);
2102 $importid =
GETPOST(
"importid",
'alphanohtml');
2106 $dir = DOL_DOCUMENT_ROOT.
"/core/modules/import/";
2107 $file =
"import_".$model.
".modules.php";
2108 $classname =
"Import".ucfirst($model);
2109 require_once $dir.$file;
2110 $obj =
new $classname(
$db, $datatoimport);
2111 '@phan-var-force ModeleImports $obj';
2112 $obj->importtriggermode = $importtriggermode;
2113 $obj->importissimulation = 0;
2114 if ($model ==
'csv') {
2115 '@phan-var-force ImportCsv $obj';
2116 $obj->separator = $separator_used;
2117 $obj->enclosure = $enclosure;
2121 $fieldssource = array();
2122 $result = $obj->import_open_file(
$conf->import->dir_temp.
'/'.$filetoimport);
2125 $arrayrecord = $obj->import_read_record();
2128 foreach ($arrayrecord as $key => $val) {
2129 $fieldssource[$i][
'example1'] =
dol_trunc($val[
'val'], 24);
2132 $obj->import_close_file();
2137 $param =
'&format='.$format.
'&datatoimport='.urlencode($datatoimport).
'&filetoimport='.urlencode($filetoimport).
'&nboflines='.((int) $nboflines).
'&importtriggermode='.urlencode($importtriggermode);
2138 if ($excludefirstline) {
2139 $param .=
'&excludefirstline='.urlencode($excludefirstline);
2142 $param .=
'&endatlinenb='.urlencode($endatlinenb);
2145 $param .=
'&separator='.urlencode($separator);
2148 $param .=
'&enclosure='.urlencode($enclosure);
2151 llxHeader(
'', $langs->trans(
"NewImport"), $help_url);
2157 print
'<div class="underbanner clearboth"></div>';
2158 print
'<div class="fichecenter">';
2160 print
'<table width="100%" class="border">';
2163 print
'<tr><td class="titlefieldcreate">'.$langs->trans(
"Module").
'</td>';
2165 $titleofmodule = $objimport->array_import_module[0][
'module']->getName();
2167 if (in_array($objimport->array_import_code[0], array(
'produit_supplierprices',
'produit_multiprice',
'produit_languages'))) {
2168 $titleofmodule = $langs->trans(
"ProductOrService");
2170 print $titleofmodule;
2174 print
'<tr><td>'.$langs->trans(
"DatasetToImport").
'</td>';
2176 $entity = preg_replace(
'/:.*$/',
'', $objimport->array_import_icon[0]);
2177 $entityicon = strtolower(!empty($entitytoicon[$entity]) ? $entitytoicon[$entity] : $entity);
2178 print
img_object($objimport->array_import_module[0][
'module']->getName(), $entityicon).
' ';
2179 print $objimport->array_import_label[0];
2187 print
load_fiche_titre($langs->trans(
"InformationOnSourceFile"),
'',
'file-export');
2189 print
'<div class="underbanner clearboth"></div>';
2190 print
'<div class="fichecenter">';
2191 print
'<table width="100%" class="border tableforfield">';
2194 print
'<tr><td class="titlefieldcreate">'.$langs->trans(
"SourceFileFormat").
'</td>';
2195 print
'<td class="nowraponall">';
2196 $text = $objmodelimport->getDriverDescForKey($format);
2198 print $form->textwithpicto($objmodelimport->getDriverLabelForKey($format), $text);
2202 if ($model ==
'csv') {
2203 '@phan-var-force ImportCsv $obj';
2204 print
'<tr><td>'.$langs->trans(
"CsvOptions").
'</td>';
2206 print $langs->trans(
"Separator").
' : ';
2207 print htmlentities($separator);
2208 print
' '.$langs->trans(
"Enclosure").
' : ';
2209 print htmlentities($enclosure);
2214 print
'<tr><td>'.$langs->trans(
"FileToImport").
'</td>';
2216 $modulepart =
'import';
2217 $relativepath =
GETPOST(
'filetoimport');
2218 print
'<a data-ajax="false" href="'.DOL_URL_ROOT.
'/document.php?modulepart='.$modulepart.
'&file='.urlencode($relativepath).
'&step=4'.$param.
'" target="_blank" rel="noopener noreferrer">';
2219 print
img_mime($file,
'',
'pictofixedwidth');
2220 print $filetoimport;
2226 print $langs->trans(
"NbOfSourceLines");
2233 print $langs->trans(
"ImportFromLine");
2235 print
'<input type="text" size="4" name="excludefirstline" disabled="disabled" value="'.$excludefirstline.
'">';
2240 print $langs->trans(
"EndAtLineNb");
2242 print
'<input type="text" size="4" name="endatlinenb" disabled="disabled" value="'.$endatlinenb.
'">';
2247 print $langs->trans(
"ImportTriggerModeLabel");
2249 if ($importtriggermode ===
'fast_bulk') {
2250 print $langs->trans(
"ImportTriggerModeSummaryFast");
2252 print $langs->trans(
"ImportTriggerModeSummaryStrict");
2254 print
'<br><span class="opacitymedium">';
2255 print $langs->trans(
"ImportTriggerModeSummaryHint");
2264 print
'<b>'.$langs->trans(
"InformationOnTargetTables").
'</b>';
2265 print
'<div class="underbanner clearboth"></div>';
2266 print
'<div class="fichecenter">';
2267 print
'<table class="border centpercent">';
2270 print
'<tr><td width="25%">';
2271 print $langs->trans(
"TablesTarget");
2273 $listtables = array();
2274 foreach ($array_match_file_to_database as $code => $label) {
2276 if ($code > count($fieldssource)) {
2280 $alias = preg_replace(
'/(\..*)$/i',
'', $label);
2281 $listtables[$alias] = $objimport->array_import_tables[0][$alias];
2283 if (count($listtables)) {
2285 foreach ($listtables as $val) {
2304 print $langs->trans(
"Error");
2310 print $langs->trans(
"FieldsTarget").
'</td><td>';
2311 $listfields = array();
2313 $sort_array_match_file_to_database = $array_match_file_to_database;
2314 ksort($sort_array_match_file_to_database);
2316 foreach ($sort_array_match_file_to_database as $code => $label) {
2319 if ($code > count($fieldssource)) {
2323 $alias = preg_replace(
'/(\..*)$/i',
'', $label);
2324 $listfields[$i] = $langs->trans(
"Field").
' '.$code.
'->'.$label;
2326 print count($listfields) ? (implode(
', ', $listfields)) : $langs->trans(
"Error");
2333 $arrayoferrors = array();
2334 $arrayofwarnings = array();
2335 $maxnboferrors = !
getDolGlobalString(
'IMPORT_MAX_NB_OF_ERRORS') ? 50 :
$conf->global->IMPORT_MAX_NB_OF_ERRORS;
2336 $maxnbofwarnings = !
getDolGlobalString(
'IMPORT_MAX_NB_OF_WARNINGS') ? 50 :
$conf->global->IMPORT_MAX_NB_OF_WARNINGS;
2348 $pathfile =
$conf->import->dir_temp.
'/'.$filetoimport;
2349 $result = $obj->import_open_file($pathfile);
2351 global $tablewithentity_cache;
2352 $tablewithentity_cache = array();
2356 while ($sourcelinenb < $nboflines && !$endoffile) {
2358 $arrayrecord = $obj->import_read_record();
2359 if ($arrayrecord ===
false) {
2360 $arrayofwarnings[$sourcelinenb][0] = array(
'lib' => $langs->trans(
'ErrorFileLinesReachEOF', $nboflines, $sourcelinenb),
'type' =>
'EOF_RECORD_ON_SEVERAL_LINES');
2364 if ($excludefirstline && ($sourcelinenb < $excludefirstline)) {
2367 if ($endatlinenb && ($sourcelinenb > $endatlinenb)) {
2371 $parameters = array(
2373 'datatoimport' => $datatoimport,
2375 'arrayrecord' => $arrayrecord,
2376 'array_match_file_to_database' => $array_match_file_to_database,
2377 'objimport' => $objimport,
2378 'fieldssource' => $fieldssource,
2379 'importid' => $importid,
2380 'updatekeys' => $updatekeys,
2381 'importtriggermode' => $importtriggermode,
2382 'arrayoferrors' => &$arrayoferrors,
2383 'arrayofwarnings' => &$arrayofwarnings,
2387 $reshook = $hookmanager->executeHooks(
'ImportInsert', $parameters);
2389 $arrayoferrors[$sourcelinenb][] = [
2390 'lib' => implode(
"<br>", array_merge([$hookmanager->error], $hookmanager->errors))
2394 if (empty($reshook)) {
2396 $result = $obj->import_insert($arrayrecord, $array_match_file_to_database, $objimport, count($fieldssource), $importid, $updatekeys);
2398 if (count($obj->errors)) {
2399 $arrayoferrors[$sourcelinenb] = $obj->errors;
2401 if (count($obj->warnings)) {
2402 $arrayofwarnings[$sourcelinenb] = $obj->warnings;
2405 if (!count($obj->errors) && !count($obj->warnings)) {
2410 $reshook = $hookmanager->executeHooks(
'AfterImportInsert', $parameters);
2412 $arrayoferrors[$sourcelinenb][] = [
2413 'lib' => implode(
"<br>", array_merge([$hookmanager->error], $hookmanager->errors))
2418 $obj->import_close_file();
2420 print $langs->trans(
"ErrorFailedToOpenFile", $pathfile);
2423 if (count($arrayoferrors) > 0) {
2430 if (!empty($objimport->array_import_run_sql_after[0]) && is_array($objimport->array_import_run_sql_after[0])) {
2432 foreach ($objimport->array_import_run_sql_after[0] as $sqlafterimport) {
2434 $resqlafterimport =
$db->query($sqlafterimport);
2435 if (!$resqlafterimport) {
2436 $arrayoferrors[
'none'][] = array(
'lib' => $langs->trans(
"Error running final request: ".$sqlafterimport));
2442 if (!$error && $importtriggermode ===
'fast_bulk') {
2443 $resbulktrigger = $obj->runImportBulkTrigger($importid, $user, $langs,
$conf);
2444 if ($resbulktrigger < 0) {
2445 $arrayoferrors[
'none'][] = array(
'lib' => $langs->trans(
"ErrorFailedTriggerCall"),
'type' =>
'TRIGGER');
2446 if (!empty($obj->errors) && is_array($obj->errors)) {
2447 foreach ($obj->errors as $tmperror) {
2448 $lib = (is_array($tmperror) ? ($tmperror[
'lib'] ??
'') : $tmperror);
2450 $arrayoferrors[
'none'][] = array(
'lib' => $lib,
'type' =>
'TRIGGER');
2467 if ($importtriggermode ===
'fast_bulk') {
2468 print
'<div class="warning">';
2469 print
'<b>'.$langs->trans(
"ImportTriggerModeFastBulkFinalWarningTitle").
'</b><br>';
2470 print $langs->trans(
"ImportTriggerModeFastBulkFinalWarning");
2477 print
'<div class="info">';
2478 print $langs->trans(
"NbOfLinesImported", $nbok).
'</b><br>';
2479 print $langs->trans(
"NbInsert", empty($obj->nbinsert) ? 0 : $obj->nbinsert).
'<br>';
2480 print $langs->trans(
"NbUpdate", empty($obj->nbupdate) ? 0 : $obj->nbupdate).
'<br>';
2482 print
'<div class="center">';
2483 print $langs->trans(
"FileWasImported", $importid).
'<br>';
2484 print
'<span class="opacitymedium">'.$langs->trans(
"YouCanUseImportIdToFindRecord", $importid).
'</span><br>';
2507 global
$conf, $langs;
2511 if ($key ==
'none') {
2513 print
"\n\n<!-- Box_no-key start-->\n";
2514 print
'<div class="box boximport" style="padding:0;">'.
"\n";
2515 print
'<table summary="boxtable_no-key" class="centpercent nobordernopadding">'.
"\n";
2517 print
"\n\n<!-- Box ".$pos.
" start -->\n";
2518 print
'<div class="box boximport" style="padding: 0;" id="boxto_'.$pos.
'">'.
"\n";
2520 print
'<table summary="boxtable'.$pos.
'" class="nobordernopadding centpercent tableimport">'.
"\n";
2523 if (($pos && $pos > count($fieldssource)) && (!isset($fieldssource[$pos][
"imported"]))) {
2533 } elseif ($key ==
'none') {
2534 print
'<tr style="height:'.$height.
'" class="trimport oddevenimport">';
2535 print
'<td class="nocellnopadd" width="16" style="font-weight: normal">';
2538 print
'<td style="font-weight: normal">';
2544 print
'<tr style="height:'.$height.
'" class="trimport oddevenimport">';
2545 print
'<td class="nocellnopadd" width="16" style="font-weight: normal">';
2548 print
img_picto($langs->trans(
"Column").
' '.
num2Alpha($pos - 1),
'file',
'class="pictofixedwidth marginleftonly"');
2550 if (isset($fieldssource[$pos][
'imported']) && $fieldssource[$pos][
'imported'] ==
false) {
2551 print
'<td class="nowraponall boxtdunused" style="font-weight: normal">';
2553 print
'<td class="nowraponall tdoverflowmax500" style="font-weight: normal">';
2555 print $langs->trans(
"Column").
' '.
num2Alpha($pos - 1).
' (#'.$pos.
')';
2556 if (empty($fieldssource[$pos][
'example1'])) {
2557 $example = $fieldssource[$pos][
'label'];
2559 $example = $fieldssource[$pos][
'example1'];
2563 $example = mb_convert_encoding($example,
'UTF-8',
'ISO-8859-1');
2567 print
'<i class="opacitymedium">'.dol_escape_htmltag($example).
'</i>';
2576 print
"<!-- Box end -->\n\n";
2589 $i = count($fieldssource) + 1;
2592 foreach ($listofkey as $key => $val) {
2593 $maxkey = max($maxkey, $key);
2596 while ($i <= $maxkey) {
2597 if (empty($listofkey[$i])) {
2619 if ($position == count($array)) {
2620 $ret = $array + $insertArray;
2623 foreach ($array as $key => $value) {
2624 if ($position == $i++) {
2625 $ret += $insertArray;
2628 $ret[$key] = $value;
ajax_combobox($htmlname, $events=array(), $minLengthToAutocomplete=0, $forcefocus=0, $widthTypeOfAutocomplete='resolve', $idforemptyvalue='-1', $morecss='')
Convert a html select field into an ajax combobox.
llxFooter($comment='', $zone='private', $disabledoutputofmessages=0)
Empty footer.
if(!defined('NOREQUIRESOC')) if(!defined( 'NOREQUIRETRAN')) if(!defined('NOTOKENRENEWAL')) if(!defined( 'NOREQUIREMENU')) if(!defined('NOREQUIREHTML')) if(!defined( 'NOREQUIREAJAX')) llxHeader($head='', $title='', $help_url='', $target='', $disablejs=0, $disablehead=0, $arrayofjs='', $arrayofcss='', $morequerystring='', $morecssonbody='', $replacemainareaby='', $disablenofollow=0, $disablenoindex=0)
Empty header.
Parent class for import file readers.
Class to manage Dolibarr users.
dol_filemtime($pathoffile)
Return time of a file.
dol_filesize($pathoffile)
Return size of a file.
dol_delete_file($file, $disableglob=0, $nophperrors=0, $nohook=0, $object=null, $allowdotdot=false, $indexdatabase=1, $nolog=0)
Remove a file or several files with a mask.
dol_count_nb_of_line($file)
Count number of lines in a file.
dol_dir_list($utf8_path, $types="all", $recursive=0, $filter="", $excludefilter=null, $sortcriteria="name", $sortorder=SORT_ASC, $mode=0, $nohook=0, $relativename="", $donotfollowsymlinks=0, $nbsecondsold=0)
Scan a directory and return a list of files/directories.
dol_move_uploaded_file($src_file, $dest_file, $allowoverwrite, $disablevirusscan=0, $uploaderrorcode=0, $nohook=0, $keyforsourcefile='addedfile', $upload_dir='', $mode=0)
Check validity of a file upload from an GUI page, and move it to its final destination.
dol_now($mode='gmt')
Return date for now.
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='', $noduplicate=0, $attop=0)
Set event messages in dol_events session object.
dolExplodeIntoArray($string, $delimiter=';', $kv='=')
Split a string with 2 keys into key array.
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2, $allowothertags=array())
Show picto whatever it's its name (generic function)
img_warning($titlealt='default', $moreatt='', $morecss='pictowarning')
Show warning logo.
info_admin($text, $infoonimgalt=0, $nodiv=0, $admin='1', $morecss='hideonsmartphone', $textfordropdown='', $picto='', $textonpictotooltip='')
Show information in HTML for admin users or standard users.
img_delete($titlealt='default', $other='class="pictodelete"', $morecss='')
Show delete logo.
GETPOSTINT($paramname, $method=0)
Return the value of a $_GET or $_POST supervariable, converted into integer.
dolPrintHTML($s, $allowiframe=0, $moreallowedtags=array())
Return a string (that can be on several lines) ready to be output on a HTML page.
dol_get_fiche_head($links=array(), $active='', $title='', $notab=0, $picto='', $pictoisfullpath=0, $morehtmlright='', $morecss='', $limittoshow=0, $moretabssuffix='', $dragdropfile=0, $morecssdiv='')
Show tabs of a record.
dol_string_nohtmltag($stringtoclean, $removelinefeed=1, $pagecodeto='UTF-8', $strip_tags=0, $removedoublespaces=1)
Clean a string from all HTML tags and entities.
dol_get_fiche_end($notab=0)
Return tab footer of a card.
img_object($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $allowothertags=array())
Show a picto called object_picto (generic function)
dol_sanitizeFileName($str, $newstr='_', $unaccent=1, $includequotes=0, $allowdash=0)
Clean a string to use it as a file name.
img_mime($file, $titlealt='', $morecss='')
Show MIME img of a file.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
dol_escape_js($stringtoescape, $mode=0, $noescapebackslashn=0)
Returns text escaped for inclusion into JavaScript code.
dol_sort_array(&$array, $index, $order='asc', $natsort=0, $case_sensitive=0, $keepindex=0)
Advanced sort array by the value of a given key, which produces ascending (default) or descending out...
dol_string_unaccent($str)
Clean a string from all accent characters to be used as ref, login or by dol_sanitizeFileName.
num2Alpha($n)
Return a numeric value into an Excel like column number.
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0)
Return value of a param into GET or POST supervariable.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false, $decorate=0)
Output date in a string format according to outputlangs (or langs if not defined).
img_error($titlealt='default')
Show error logo.
dol_print_error($db=null, $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
load_fiche_titre($title, $morehtmlright='', $picto='generic', $pictoisfullpath=0, $id='', $morecssontable='', $morehtmlcenter='', $morecssonpicto='widthpictotitle')
Load a title with picto.
dol_trunc($string, $size=40, $trunc='right', $stringencoding='UTF-8', $nodot=0, $display=0)
Truncate a string to a particular length adding '…' if string larger than length.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
utf8_check($str)
Check if a string is in UTF8.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
dol_mkdir($dir, $dataroot='', $newmask='')
Creation of a directory (this can create recursive subdir)
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags='', $escapeonlyhtmltags=0, $cleanalsojavascript=0)
Returns text escaped for inclusion in HTML alt or title or value tags, or into values of HTML input f...
import_prepare_head($param, $maxstep=0)
Function to return list of tabs for import pages.
show_elem($fieldssource, $pos, $key)
Function to put the movable box of a source field.
getnewkey(&$fieldssource, &$listofkey)
Return not used field number.
arrayInsert($array, $position, $insertArray)
Return array with element inserted in it at position $position.
print $langs trans("Show") . '< td style="' . $timeColor . '" align="center"> s</td > badge status0 badge status4 badge status3 Error badge status8< td align="center">< span class="badge ' . $badge . '"></span ></td >< td align="center">< a href="#" class="button button-small" onclick="openLogModal(this)" data-req="' . dol_escape_htmltag($reqSafe) . '" data-res="' . dol_escape_htmltag($resSafe) . '" data-err="' . dol_escape_htmltag($errSafe) . '">< span class="fa fa-search-plus"></span ></a ></td ></tr >< tr >< td colspan="' . $colspan . '" class="opacitymedium"></td ></tr ></table ></div ></form > logModal none logModal none s a JSON string
buildzip.php
getMaxFileSizeArray()
Return the max allowed for file upload.
restrictedArea(User $user, $features, $object=0, $tableandshare='', $feature2='', $dbt_keyfield='fk_soc', $dbt_select='rowid', $isdraft=0, $mode=0)
Check permissions of a user to show a page and an object.