29require_once
'../main.inc.php';
30require_once DOL_DOCUMENT_ROOT.
'/core/class/html.formfile.class.php';
31require_once DOL_DOCUMENT_ROOT.
'/core/class/html.formother.class.php';
32require_once DOL_DOCUMENT_ROOT.
'/imports/class/import.class.php';
33require_once DOL_DOCUMENT_ROOT.
'/core/modules/import/modules_import.php';
34require_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
35require_once DOL_DOCUMENT_ROOT.
'/core/lib/images.lib.php';
36require_once DOL_DOCUMENT_ROOT.
'/core/lib/import.lib.php';
47$langs->loadLangs(array(
'exports',
'compta',
'errors',
'projects',
'admin'));
50$hookmanager->initHooks(array(
'imports'));
58 'invoice_line' =>
'bill',
60 'order_line' =>
'order',
62 'propal_line' =>
'propal',
63 'intervention' =>
'intervention',
64 'inter_line' =>
'intervention',
66 'member_type' =>
'group',
67 'subscription' =>
'payment',
68 'payment' =>
'payment',
70 'tax_type' =>
'generic',
72 'account' =>
'account',
73 'product' =>
'product',
74 'virtualproduct' =>
'product',
75 'subproduct' =>
'product',
76 'product_supplier_ref' =>
'product',
78 'warehouse' =>
'stock',
80 'stockbatch' =>
'stock',
81 'category' =>
'category',
82 'shipment' =>
'sending',
83 'shipment_line' =>
'sending',
84 'reception' =>
'sending',
85 'reception_line' =>
'sending',
86 'expensereport' =>
'trip',
87 'expensereport_line' =>
'trip',
88 'holiday' =>
'holiday',
89 'contract_line' =>
'contract',
90 'translation' =>
'generic',
98 'company' =>
'Company',
99 'contact' =>
'Contact',
101 'invoice_line' =>
'InvoiceLine',
103 'order_line' =>
'OrderLine',
104 'propal' =>
'Proposal',
105 'propal_line' =>
'ProposalLine',
106 'intervention' =>
'Intervention',
107 'inter_line' =>
'InterLine',
108 'member' =>
'Member',
109 'member_type' =>
'MemberType',
110 'subscription' =>
'Subscription',
111 'tax' =>
'SocialContribution',
112 'tax_type' =>
'DictionarySocialContributions',
113 'account' =>
'BankTransactions',
114 'payment' =>
'Payment',
115 'product' =>
'Product',
116 'virtualproduct' =>
'AssociatedProducts',
117 'subproduct' =>
'SubProduct',
118 'product_supplier_ref' =>
'SupplierPrices',
119 'service' =>
'Service',
121 'movement' =>
'StockMovement',
123 'stockbatch' =>
'StockDetailPerBatch',
124 'warehouse' =>
'Warehouse',
125 'category' =>
'Category',
127 'trip' =>
'TripsAndExpenses',
128 'shipment' =>
'Shipments',
129 'shipment_line' =>
'ShipmentLine',
130 'project' =>
'Projects',
131 'projecttask' =>
'Tasks',
132 'task_time' =>
'TaskTimeSpent',
134 'expensereport' =>
'ExpenseReport',
135 'expensereport_line' =>
'ExpenseReportLine',
136 'holiday' =>
'TitreRequestCP',
137 'contract' =>
'Contract',
138 'contract_line' =>
'ContractLine',
139 'translation' =>
'Translation',
141 'bomline' =>
'BOMLine'
144$datatoimport =
GETPOST(
'datatoimport');
146$filetoimport =
GETPOST(
'filetoimport');
147$action =
GETPOST(
'action',
'alpha');
148$confirm =
GETPOST(
'confirm',
'alpha');
150$import_name =
GETPOST(
'import_name');
153$excludefirstline = (
GETPOST(
'excludefirstline') ?
GETPOST(
'excludefirstline') : 2);
154$endatlinenb = (
GETPOST(
'endatlinenb') ?
GETPOST(
'endatlinenb') :
'');
155$updatekeys = (
GETPOST(
'updatekeys',
'array') ?
GETPOST(
'updatekeys',
'array') : array());
156$separator = (
GETPOST(
'separator',
'nohtml') ?
GETPOST(
'separator',
'nohtml', 3) :
'');
157$enclosure = (
GETPOST(
'enclosure',
'nohtml') ?
GETPOST(
'enclosure',
'nohtml') :
'"');
158$charset =
GETPOST(
'charset',
'aZ09');
159$separator_used = str_replace(
'\t',
"\t", $separator);
162$objimport =
new Import($db);
163$objimport->load_arrays($user, ($step == 1 ?
'' : $datatoimport));
165if (empty($updatekeys) && !empty($objimport->array_import_preselected_updatekeys[0])) {
166 $updatekeys = $objimport->array_import_preselected_updatekeys[0];
171$form =
new Form($db);
176if (empty($array_match_file_to_database)) {
177 $serialized_array_match_file_to_database = isset($_SESSION[
"dol_array_match_file_to_database_select"]) ? $_SESSION[
"dol_array_match_file_to_database_select"] :
'';
178 $array_match_file_to_database = array();
179 $fieldsarray = explode(
',', $serialized_array_match_file_to_database);
180 foreach ($fieldsarray as $elem) {
181 $tabelem = explode(
'=', $elem, 2);
183 $val = (isset($tabelem[1]) ? $tabelem[1] :
'');
185 $array_match_file_to_database[$key] = $val;
195if ($action ==
'deleteprof' && $user->hasRight(
'import',
'run')) {
198 $result = $objimport->delete($user);
203if ($action ==
'add_import_model' && $user->hasRight(
'import',
'run')) {
207 foreach ($array_match_file_to_database as $key => $val) {
211 $hexa .= $key.
'='.$val;
214 $objimport->model_name = $import_name;
215 $objimport->datatoimport = $datatoimport;
216 $objimport->hexa = $hexa;
217 $objimport->fk_user = (
GETPOST(
'visibility',
'aZ09') ==
'all' ? 0 : $user->id);
219 $result = $objimport->create($user);
221 setEventMessages($langs->trans(
"ImportModelSaved", $objimport->model_name),
null,
'mesgs');
224 $langs->load(
"errors");
225 if ($objimport->errno ==
'DB_ERROR_RECORD_ALREADY_EXISTS') {
226 setEventMessages($langs->trans(
"ErrorImportDuplicateProfil"),
null,
'errors');
232 setEventMessages($langs->trans(
"ErrorFieldRequired", $langs->transnoentities(
"ImportModelName")),
null,
'errors');
236if ($step == 3 && $datatoimport) {
241 $fullpath =
$conf->import->dir_temp.
"/".$nowyearmonth.
'-'.$_FILES[
'userfile'][
'name'];
243 dol_syslog(
"File ".$fullpath.
" was added for import");
245 $langs->load(
"errors");
251 if ($action ==
'confirm_deletefile' && $confirm ==
'yes') {
252 $langs->load(
"other");
254 $param =
'&datatoimport='.urlencode($datatoimport).
'&format='.urlencode($format);
255 if ($excludefirstline) {
256 $param .=
'&excludefirstline='.urlencode($excludefirstline);
259 $param .=
'&endatlinenb='.urlencode($endatlinenb);
269 header(
'Location: '.$_SERVER[
"PHP_SELF"].
'?step='.$step.$param);
274if ($step == 4 && $action ==
'select_model' && $user->hasRight(
'import',
'run')) {
276 $_SESSION[
"dol_array_match_file_to_database"] =
'';
277 $serialized_array_match_file_to_database =
'';
278 $array_match_file_to_database = array();
282 $result = $objimport->fetch($importmodelid);
284 $serialized_array_match_file_to_database = $objimport->hexa;
285 $fieldsarray = explode(
',', $serialized_array_match_file_to_database);
286 foreach ($fieldsarray as $elem) {
287 $tabelem = explode(
'=', $elem);
291 $array_match_file_to_database[$key] = $val;
294 $_SESSION[
"dol_array_match_file_to_database"] = $serialized_array_match_file_to_database;
295 $_SESSION[
'dol_array_match_file_to_database_select'] = $_SESSION[
"dol_array_match_file_to_database"];
298if ($action ==
'saveselectorder' && $user->hasRight(
'import',
'run')) {
300 $serialized_array_match_file_to_database =
'';
302 $selectorder = explode(
",",
GETPOST(
'selectorder'));
303 $fieldtarget = $fieldstarget = $objimport->array_import_fields[0];
304 foreach ($selectorder as $key => $code) {
305 $serialized_array_match_file_to_database .= $key.
'='.$code;
306 $serialized_array_match_file_to_database .=
',';
308 $serialized_array_match_file_to_database = substr($serialized_array_match_file_to_database, 0, -1);
309 dol_syslog(
'dol_array_match_file_to_database_select='.$serialized_array_match_file_to_database);
310 $_SESSION[
"dol_array_match_file_to_database_select"] = $serialized_array_match_file_to_database;
320$help_url =
'EN:Module_Imports_En|FR:Module_Imports|ES:Módulo_Importaciones';
323if ($step == 1 || !$datatoimport) {
325 $serialized_array_match_file_to_database =
'';
326 $array_match_file_to_database = array();
327 $_SESSION[
"dol_array_match_file_to_database"] =
'';
328 $_SESSION[
"dol_array_match_file_to_database_select"] =
'';
331 if ($excludefirstline) {
332 $param .=
'&excludefirstline='.urlencode($excludefirstline);
335 $param .=
'&endatlinenb='.urlencode($endatlinenb);
338 $param .=
'&separator='.urlencode($separator);
341 $param .=
'&enclosure='.urlencode($enclosure);
344 llxHeader(
'', $langs->trans(
"NewImport"), $help_url);
350 print
'<div class="opacitymedium">'.$langs->trans(
"SelectImportDataSet").
'</div><br>';
353 print
'<div class="div-table-responsive-no-min">';
354 print
'<table class="noborder centpercent">';
355 print
'<tr class="liste_titre">';
356 print
'<td>'.$langs->trans(
"Module").
'</td>';
357 print
'<td>'.$langs->trans(
"ImportableDatas").
'</td>';
358 print
'<td> </td>';
361 if (count($objimport->array_import_module)) {
362 $sortedarrayofmodules =
dol_sort_array($objimport->array_import_module,
'position_of_profile',
'asc', 0, 0, 1);
363 foreach ($sortedarrayofmodules as $key => $value) {
365 print
'<tr class="oddeven"><td>';
366 $titleofmodule = $objimport->array_import_module[$key][
'module']->getName();
368 if (in_array($objimport->array_import_code[$key], array(
'produit_supplierprices',
'produit_multiprice',
'produit_languages'))) {
369 $titleofmodule = $langs->trans(
"ProductOrService");
371 print $titleofmodule;
373 $entity = preg_replace(
'/:.*$/',
'', $objimport->array_import_icon[$key]);
374 $entityicon = strtolower(!empty($entitytoicon[$entity]) ? $entitytoicon[$entity] : $entity);
375 print
img_object($objimport->array_import_module[$key][
'module']->getName(), $entityicon).
' ';
376 print $objimport->array_import_label[$key];
377 print
'</td><td style="text-align: right">';
378 if ($objimport->array_import_perms[$key]) {
379 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>';
381 print $langs->trans(
"NotEnoughPermissions");
386 print
'<tr><td class="oddeven" colspan="3">'.$langs->trans(
"NoImportableData").
'</td></tr>';
396if ($step == 2 && $datatoimport) {
397 $param =
'&datatoimport='.urlencode($datatoimport);
398 if ($excludefirstline) {
399 $param .=
'&excludefirstline='.urlencode($excludefirstline);
402 $param .=
'&endatlinenb='.urlencode($endatlinenb);
405 $param .=
'&separator='.urlencode($separator);
408 $param .=
'&enclosure='.urlencode($enclosure);
411 llxHeader(
'', $langs->trans(
"NewImport"), $help_url);
417 print
'<div class="underbanner clearboth"></div>';
418 print
'<div class="fichecenter">';
420 print
'<table class="border tableforfield centpercent">';
423 print
'<tr><td class="titlefieldcreate">'.$langs->trans(
"Module").
'</td>';
425 $titleofmodule = $objimport->array_import_module[0][
'module']->getName();
427 if (in_array($objimport->array_import_code[0], array(
'produit_supplierprices',
'produit_multiprice',
'produit_languages'))) {
428 $titleofmodule = $langs->trans(
"ProductOrService");
430 print $titleofmodule;
434 print
'<tr><td>'.$langs->trans(
"DatasetToImport").
'</td>';
436 $entity = preg_replace(
'/:.*$/',
'', $objimport->array_import_icon[0]);
437 $entityicon = strtolower(!empty($entitytoicon[$entity]) ? $entitytoicon[$entity] : $entity);
438 print
img_object($objimport->array_import_module[0][
'module']->getName(), $entityicon).
' ';
439 print $objimport->array_import_label[0];
447 print
'<form name="userfile" action="'.$_SERVER[
"PHP_SELF"].
'" enctype="multipart/form-data" METHOD="POST">';
448 print
'<input type="hidden" name="token" value="'.newToken().
'">';
452 print
'<span class="opacitymedium">';
453 $s = $langs->trans(
"ChooseFormatOfFileToImport",
'{s1}');
454 $s = str_replace(
'{s1}',
img_picto(
'',
'next'), $s);
456 print
'</span><br><br>';
460 print
'<div class="div-table-responsive-no-min">';
461 print
'<table class="noborder centpercent" cellpadding="4">';
466 print
'<tr class="liste_titre"><td colspan="5">';
467 print $langs->trans(
"FileMustHaveOneOfFollowingFormat");
469 $list = $objmodelimport->listOfAvailableImportFormat($db);
470 foreach ($list as $key) {
471 print
'<tr class="oddeven">';
472 print
'<td width="16">'.img_picto_common($key, $objmodelimport->getPictoForKey($key)).
'</td>';
473 $htmltext = $objmodelimport->getDriverDescForKey($key);
474 print
'<td>'.$form->textwithpicto($objmodelimport->getDriverLabelForKey($key), $htmltext).
'</td>';
475 print
'<td style="text-align:center">';
476 if (empty($objmodelimport->drivererror[$key])) {
477 $filename = $langs->transnoentitiesnoconv(
"ExampleOfImportFile").
'_'.$datatoimport.
'.'.$key;
478 print
'<a href="'.DOL_URL_ROOT.
'/imports/emptyexample.php?format='.$key.$param.
'&output=file&file='.urlencode($filename).
'" target="_blank" rel="noopener noreferrer">';
479 print
img_picto(
'',
'download',
'class="paddingright opacitymedium"');
480 print $langs->trans(
"DownloadEmptyExampleShort");
482 print $form->textwithpicto(
'', $langs->trans(
"DownloadEmptyExample").
'.<br>'.$langs->trans(
"StarAreMandatory"));
488 print
'<td style="text-align:right">';
489 if (empty($objmodelimport->drivererror[$key])) {
490 print
'<a href="'.DOL_URL_ROOT.
'/imports/import.php?step=3&format='.$key.$param.
'">'.
img_picto($langs->trans(
"SelectFormat"),
'next',
'class="fa-15"').
'</a>';
504if ($step == 3 && $datatoimport) {
505 $param =
'&datatoimport='.urlencode($datatoimport).
'&format='.urlencode($format);
506 if ($excludefirstline) {
507 $param .=
'&excludefirstline='.urlencode($excludefirstline);
510 $param .=
'&endatlinenb='.urlencode($endatlinenb);
513 $param .=
'&separator='.urlencode($separator);
516 $param .=
'&enclosure='.urlencode($enclosure);
519 $list = $objmodelimport->listOfAvailableImportFormat($db);
521 llxHeader(
'', $langs->trans(
"NewImport"), $help_url);
530 if ($action ==
'delete') {
531 print $form->formconfirm($_SERVER[
"PHP_SELF"].
'?urlfile='.urlencode(
GETPOST(
'urlfile')).
'&step=3'.$param, $langs->trans(
'DeleteFile'), $langs->trans(
'ConfirmDeleteFile'),
'confirm_deletefile',
'', 0, 1);
534 print
'<div class="underbanner clearboth"></div>';
535 print
'<div class="fichecenter">';
537 print
'<table class="border tableforfield centpercent">';
540 print
'<tr><td class="titlefieldcreate">'.$langs->trans(
"Module").
'</td>';
542 $titleofmodule = $objimport->array_import_module[0][
'module']->getName();
544 if (in_array($objimport->array_import_code[0], array(
'produit_supplierprices',
'produit_multiprice',
'produit_languages'))) {
545 $titleofmodule = $langs->trans(
"ProductOrService");
547 print $titleofmodule;
551 print
'<tr><td>'.$langs->trans(
"DatasetToImport").
'</td>';
553 $entity = preg_replace(
'/:.*$/',
'', $objimport->array_import_icon[0]);
554 $entityicon = strtolower(!empty($entitytoicon[$entity]) ? $entitytoicon[$entity] : $entity);
555 print
img_object($objimport->array_import_module[0][
'module']->getName(), $entityicon).
' ';
556 print $objimport->array_import_label[0];
562 print
load_fiche_titre($langs->trans(
"InformationOnSourceFile"),
'',
'file-export');
564 print
'<div class="underbanner clearboth"></div>';
565 print
'<div class="fichecenter">';
566 print
'<table width="100%" class="border tableforfield">';
569 print
'<tr><td class="titlefieldcreate">'.$langs->trans(
"SourceFileFormat").
'</td>';
570 print
'<td class="nowraponall">';
571 $text = $objmodelimport->getDriverDescForKey($format);
573 print $form->textwithpicto($objmodelimport->getDriverLabelForKey($format), $text);
574 print
'</td><td style="text-align:right" class="nowrap">';
575 $filename = $langs->transnoentitiesnoconv(
"ExampleOfImportFile").
'_'.$datatoimport.
'.'.$format;
576 print
'<a href="'.DOL_URL_ROOT.
'/imports/emptyexample.php?format='.$format.$param.
'&output=file&file='.urlencode($filename).
'" target="_blank" rel="noopener noreferrer">';
577 print
img_picto(
'',
'download',
'class="paddingright opacitymedium"');
578 print $langs->trans(
"DownloadEmptyExampleShort");
580 print $form->textwithpicto(
'', $langs->trans(
"DownloadEmptyExample").
'.<br>'.$langs->trans(
"StarAreMandatory"));
589 if ($format ==
'xlsx' && !class_exists(
'XMLWriter')) {
590 $langs->load(
"install");
591 print
info_admin($langs->trans(
"ErrorPHPDoesNotSupport",
'php-xml'), 0, 0,
'1',
'error');
597 print
'<form name="userfile" action="'.$_SERVER[
"PHP_SELF"].
'" enctype="multipart/form-data" method="POST">';
598 print
'<input type="hidden" name="token" value="'.newToken().
'">';
599 print
'<input type="hidden" value="'.$step.
'" name="step">';
600 print
'<input type="hidden" value="'.dol_escape_htmltag($format).
'" name="format">';
601 print
'<input type="hidden" value="'.$excludefirstline.
'" name="excludefirstline">';
602 print
'<input type="hidden" value="'.$endatlinenb.
'" name="endatlinenb">';
603 print
'<input type="hidden" value="'.dol_escape_htmltag($separator).
'" name="separator">';
604 print
'<input type="hidden" value="'.dol_escape_htmltag($enclosure).
'" name="enclosure">';
605 print
'<input type="hidden" value="'.dol_escape_htmltag($datatoimport).
'" name="datatoimport">';
607 print
'<span class="opacitymedium">';
608 $s = $langs->trans(
"ChooseFileToImport",
'{s1}');
609 $s = str_replace(
'{s1}',
img_picto(
'',
'next'), $s);
611 print
'</span><br><br>';
616 print
'<div class="marginbottomonly">';
618 $maxmin = $maxfilesizearray[
'maxmin'];
620 print
'<input type="hidden" name="MAX_FILE_SIZE" value="'.($maxmin * 1024).
'">';
622 print
'<input type="file" name="userfile" size="20" maxlength="80"> ';
624 print
'<input type="submit" class="button small" value="'.$langs->trans(
"AddFile").
'"'.$out.
' name="sendit">';
628 $maxphp = @ini_get(
'upload_max_filesize');
629 if (preg_match(
'/k$/i', $maxphp)) {
630 $maxphp = (int) substr($maxphp, 0, -1);
632 if (preg_match(
'/m$/i', $maxphp)) {
633 $maxphp = (int) substr($maxphp, 0, -1) * 1024;
635 if (preg_match(
'/g$/i', $maxphp)) {
636 $maxphp = (int) substr($maxphp, 0, -1) * 1024 * 1024;
638 if (preg_match(
'/t$/i', $maxphp)) {
639 $maxphp = (int) substr($maxphp, 0, -1) * 1024 * 1024 * 1024;
641 $maxphp2 = @ini_get(
'post_max_size');
642 if (preg_match(
'/k$/i', $maxphp2)) {
643 $maxphp2 = (int) substr($maxphp2, 0, -1);
645 if (preg_match(
'/m$/i', $maxphp2)) {
646 $maxphp2 = (int) substr($maxphp2, 0, -1) * 1024;
648 if (preg_match(
'/g$/i', $maxphp2)) {
649 $maxphp2 = (int) substr($maxphp2, 0, -1) * 1024 * 1024;
651 if (preg_match(
'/t$/i', $maxphp2)) {
652 $maxphp2 = (int) substr($maxphp2, 0, -1) * 1024 * 1024 * 1024;
656 $maxphptoshow = $maxphptoshowparam =
'';
658 $maxmin = min($max, $maxphp);
659 $maxphptoshow = $maxphp;
660 $maxphptoshowparam =
'upload_max_filesize';
663 $maxmin = min($max, $maxphp2);
664 if ($maxphp2 < $maxphp) {
665 $maxphptoshow = $maxphp2;
666 $maxphptoshowparam =
'post_max_size';
670 $langs->load(
'other');
672 $out .=
info_admin($langs->trans(
"ThisLimitIsDefinedInSetup", $max, $maxphptoshow), 1);
674 $out .=
' ('.$langs->trans(
"UploadDisabled").
')';
680 $filearray =
dol_dir_list(
$conf->import->dir_temp,
'files', 0,
'',
'',
'name', SORT_DESC);
681 if (count($filearray) > 0) {
682 print
'<div class="div-table-responsive-no-min">';
683 print
'<table class="noborder centpercent" width="100%" cellpadding="4">';
685 $dir =
$conf->import->dir_temp;
689 foreach ($filearray as $key => $val) {
690 $file = $val[
'name'];
694 $file = mb_convert_encoding($file,
'UTF-8',
'ISO-8859-1');
697 if (preg_match(
'/^\./', $file)) {
701 $modulepart =
'import';
702 $urlsource = $_SERVER[
"PHP_SELF"].
'?step='.$step.$param.
'&filetoimport='.urlencode($filetoimport);
703 $relativepath = $file;
705 print
'<tr class="oddeven">';
707 print
img_mime($file,
'',
'pictofixedwidth');
708 print
'<a data-ajax="false" href="'.DOL_URL_ROOT.
'/document.php?modulepart='.$modulepart.
'&file='.urlencode($relativepath).
'&step=3'.$param.
'" target="_blank" rel="noopener noreferrer">';
713 print
'<td style="text-align:right">'.dol_print_size(
dol_filesize($dir.
'/'.$file)).
'</td>';
715 print
'<td style="text-align:right">'.dol_print_date(
dol_filemtime($dir.
'/'.$file),
'dayhour').
'</td>';
717 print
'<td style="text-align:right"><a href="'.$_SERVER[
'PHP_SELF'].
'?action=delete&token='.
newToken().
'&step=3'.$param.
'&urlfile='.urlencode($relativepath);
718 print
'">'.img_delete().
'</a></td>';
720 print
'<td style="text-align:right">';
721 print
'<a href="'.$_SERVER[
'PHP_SELF'].
'?step=4'.$param.
'&filetoimport='.urlencode($relativepath).
'">'.
img_picto($langs->trans(
"NewImport"),
'next',
'class="fa-15"').
'</a>';
735if ($step == 4 && $datatoimport) {
737 $serialized_array_match_file_to_database = isset($_SESSION[
"dol_array_match_file_to_database_select"]) ? $_SESSION[
"dol_array_match_file_to_database_select"] :
'';
738 $fieldsarray = explode(
',', $serialized_array_match_file_to_database);
739 $array_match_file_to_database = array();
740 foreach ($fieldsarray as $elem) {
741 $tabelem = explode(
'=', $elem, 2);
743 $val = (isset($tabelem[1]) ? $tabelem[1] :
'');
745 $array_match_file_to_database[$key] = $val;
754 $list = $objmodelimport->listOfAvailableImportFormat($db);
756 if (empty($separator)) {
757 $separator = (!
getDolGlobalString(
'IMPORT_CSV_SEPARATOR_TO_USE') ?
',' :
$conf->global->IMPORT_CSV_SEPARATOR_TO_USE);
761 if ($model ==
'csv' && strlen($separator) == 1 && !GETPOSTISSET(
'separator')) {
762 '@phan-var-force ImportCsv $obj';
764 $fh = fopen(
$conf->import->dir_temp.
'/'.$filetoimport,
'r');
766 $sline = fgets($fh, 1000000);
768 $nboccurence = substr_count($sline, $separator);
769 $nboccurencea = substr_count($sline,
',');
770 $nboccurenceb = substr_count($sline,
';');
772 if ($nboccurence == 0) {
773 if ($nboccurencea > 2) {
775 } elseif ($nboccurenceb > 2) {
783 $separator_used = str_replace(
'\t',
"\t", $separator);
786 $dir = DOL_DOCUMENT_ROOT.
"/core/modules/import/";
787 $file =
"import_".$model.
".modules.php";
788 $classname =
"Import".ucfirst($model);
789 require_once $dir.$file;
790 $obj =
new $classname($db, $datatoimport);
791 '@phan-var-force ModeleImports $obj';
793 if (!empty($obj->error)) {
794 $langs->load(
"errors");
795 $param =
'&datatoimport='.$datatoimport.
'&format='.$format;
797 header(
"Location: ".$_SERVER[
"PHP_SELF"].
'?step=3'.$param.
'&filetoimport='.urlencode($relativepath));
801 if ($model ==
'csv') {
802 '@phan-var-force ImportCsv $obj';
803 $obj->separator = $separator_used;
804 $obj->enclosure = $enclosure;
807 if ($model ==
'xlsx') {
808 '@phan-var-force ImportXlsx $obj';
809 if (!preg_match(
'/\.xlsx$/i', $filetoimport)) {
810 $langs->load(
"errors");
811 $param =
'&datatoimport='.$datatoimport.
'&format='.$format;
812 setEventMessages($langs->trans(
"ErrorFileMustHaveFormat", $model),
null,
'errors');
813 header(
"Location: ".$_SERVER[
"PHP_SELF"].
'?step=3'.$param.
'&filetoimport='.urlencode($relativepath));
819 $array_match_file_to_database = array();
823 $fieldssource = array();
825 $result = $obj->import_open_file(
$conf->import->dir_temp.
'/'.$filetoimport);
828 $arrayrecord = $obj->import_read_record();
832 foreach ($arrayrecord as $key => $val) {
833 if ($val[
"type"] != -1) {
834 $fieldssource[$i][
'example1'] =
dol_trunc($val[
'val'], 128);
837 $fieldssource[$i][
'example1'] = $langs->trans(
'Empty');
840 $fieldssource[$i][
'imported'] = 0;
842 $obj->import_close_file();
846 $fieldstarget = $objimport->array_import_fields[0];
847 $minpos = min(count($fieldssource), count($fieldstarget));
851 $initialloadofstep4 =
false;
852 if (empty($_SESSION[
'dol_array_match_file_to_database_select'])) {
853 $initialloadofstep4 =
true;
857 if (count($array_match_file_to_database) == 0) {
863 $num = count($fieldssource);
864 while ($pos <= $num) {
865 if ($num >= 1 && $pos <= $num) {
867 foreach ($fieldstarget as $key => $val) {
868 if ($posbis < $pos) {
873 $array_match_file_to_database[$pos] = $key;
880 $array_match_database_to_file = array_flip($array_match_file_to_database);
884 $fieldstarget_tmp = array();
885 $arraykeysfieldtarget = array_keys($fieldstarget);
887 foreach ($fieldstarget as $key => $label) {
888 $isrequired = preg_match(
'/\*$/', $label);
889 if (!empty($isrequired)) {
890 $newlabel = substr($label, 0, -1);
891 $fieldstarget_tmp[$key] = array(
"label" => $newlabel,
"required" =>
true);
893 $fieldstarget_tmp[$key] = array(
"label" => $label,
"required" =>
false);
895 if (!empty($array_match_database_to_file[$key])) {
896 $fieldstarget_tmp[$key][
"imported"] =
true;
897 $fieldstarget_tmp[$key][
"position"] = (int) $array_match_database_to_file[$key] - 1;
899 while (!empty($array_match_database_to_file[$keytoswap])) {
900 if ($position + 1 > $array_match_database_to_file[$keytoswap]) {
901 $keytoswapwith = $array_match_database_to_file[$keytoswap] - 1;
902 $tmp = [$keytoswap => $fieldstarget_tmp[$keytoswap]];
903 unset($fieldstarget_tmp[$keytoswap]);
904 $fieldstarget_tmp =
arrayInsert($fieldstarget_tmp, $keytoswapwith, $tmp);
905 $keytoswapwith = $arraykeysfieldtarget[$array_match_database_to_file[$keytoswap] - 1];
906 $tmp = $fieldstarget_tmp[$keytoswapwith];
907 unset($fieldstarget_tmp[$keytoswapwith]);
908 $fieldstarget_tmp[$keytoswapwith] = $tmp;
909 $keytoswap = $keytoswapwith;
915 $fieldstarget_tmp[$key][
"imported"] =
false;
919 $fieldstarget = $fieldstarget_tmp;
928 $param =
'&format='.$format.
'&datatoimport='.urlencode($datatoimport).
'&filetoimport='.urlencode($filetoimport);
929 if ($excludefirstline) {
930 $param .=
'&excludefirstline='.urlencode($excludefirstline);
933 $param .=
'&endatlinenb='.urlencode($endatlinenb);
936 $param .=
'&separator='.urlencode($separator);
939 $param .=
'&enclosure='.urlencode($enclosure);
942 llxHeader(
'', $langs->trans(
"NewImport"), $help_url);
948 print
'<div class="underbanner clearboth"></div>';
949 print
'<div class="fichecenter">';
951 print
'<table class="centpercent border tableforfield">';
954 print
'<tr><td class="titlefieldcreate">'.$langs->trans(
"Module").
'</td>';
956 $titleofmodule = $objimport->array_import_module[0][
'module']->getName();
958 if (in_array($objimport->array_import_code[0], array(
'produit_supplierprices',
'produit_multiprice',
'produit_languages'))) {
959 $titleofmodule = $langs->trans(
"ProductOrService");
961 print $titleofmodule;
965 print
'<tr><td>'.$langs->trans(
"DatasetToImport").
'</td>';
967 $entity = preg_replace(
'/:.*$/',
'', $objimport->array_import_icon[0]);
968 $entityicon = strtolower(!empty($entitytoicon[$entity]) ? $entitytoicon[$entity] : $entity);
969 print
img_object($objimport->array_import_module[0][
'module']->getName(), $entityicon).
' ';
970 print $objimport->array_import_label[0];
976 print
load_fiche_titre($langs->trans(
"InformationOnSourceFile"),
'',
'file-export');
978 print
'<div class="underbanner clearboth"></div>';
979 print
'<div class="fichecenter">';
980 print
'<table width="100%" class="border tableforfield">';
983 print
'<tr><td class="titlefieldcreate">'.$langs->trans(
"SourceFileFormat").
'</td>';
985 $text = $objmodelimport->getDriverDescForKey($format);
987 print $form->textwithpicto($objmodelimport->getDriverLabelForKey($format), $text);
991 if ($model ==
'csv') {
992 '@phan-var-force ImportCsv $obj';
993 print
'<tr><td>'.$langs->trans(
"CsvOptions").
'</td>';
995 print
'<form method="POST">';
996 print
'<input type="hidden" name="token" value="'.newToken().
'">';
997 print
'<input type="hidden" value="'.$step.
'" name="step">';
998 print
'<input type="hidden" value="'.$format.
'" name="format">';
999 print
'<input type="hidden" value="'.$excludefirstline.
'" name="excludefirstline">';
1000 print
'<input type="hidden" value="'.$endatlinenb.
'" name="endatlinenb">';
1001 print
'<input type="hidden" value="'.$datatoimport.
'" name="datatoimport">';
1002 print
'<input type="hidden" value="'.$filetoimport.
'" name="filetoimport">';
1003 print $langs->trans(
"Separator").
' : ';
1004 print
'<input type="text" class="width25 center" name="separator" value="'.dol_escape_htmltag($separator).
'"/>';
1005 print
' '.$langs->trans(
"Enclosure").
' : ';
1006 print
'<input type="text" class="width25 center" name="enclosure" value="'.dol_escape_htmltag($enclosure).
'"/> ';
1007 print
'<input name="update" type="submit" value="'.$langs->trans(
'Update').
'" class="button smallpaddingimp" />';
1013 print
'<tr><td>'.$langs->trans(
"FileToImport").
'</td>';
1015 $modulepart =
'import';
1016 $relativepath =
GETPOST(
'filetoimport');
1017 print
'<a data-ajax="false" href="'.DOL_URL_ROOT.
'/document.php?modulepart='.$modulepart.
'&file='.urlencode($relativepath).
'&step=4'.$param.
'" target="_blank" rel="noopener noreferrer">';
1018 print
img_mime($file,
'',
'pictofixedwidth');
1019 print $filetoimport;
1020 print
img_picto($langs->trans(
"Download"),
'download',
'class="paddingleft opacitymedium"');
1033 print
'<!-- List of source fields -->'.
"\n";
1034 print
'<form action="'.$_SERVER[
"PHP_SELF"].
'" method="POST">';
1035 print
'<input type="hidden" name="token" value="'.newToken().
'">';
1036 print
'<input type="hidden" name="action" value="select_model">';
1037 print
'<input type="hidden" name="step" value="4">';
1038 print
'<input type="hidden" name="format" value="'.$format.
'">';
1039 print
'<input type="hidden" name="datatoimport" value="'.$datatoimport.
'">';
1040 print
'<input type="hidden" name="filetoimport" value="'.$filetoimport.
'">';
1041 print
'<input type="hidden" name="excludefirstline" value="'.$excludefirstline.
'">';
1042 print
'<input type="hidden" name="endatlinenb" value="'.$endatlinenb.
'">';
1043 print
'<input type="hidden" name="separator" value="'.dol_escape_htmltag($separator).
'">';
1044 print
'<input type="hidden" name="enclosure" value="'.dol_escape_htmltag($enclosure).
'">';
1047 print
'<div class="marginbottomonly">';
1048 print
'<span class="opacitymedium">';
1049 $s = $langs->trans(
"SelectImportFieldsSource",
'{s1}');
1050 $s = str_replace(
'{s1}',
img_picto(
'',
'grip_title',
'', 0, 0, 0,
'',
'', 0), $s);
1053 $htmlother->select_import_model($importmodelid,
'importmodelid', $datatoimport, 1, $user->id);
1054 print
'<input type="submit" class="button small reposition" value="'.$langs->trans(
"Select").
'">';
1059 print
'<div class="div-table-responsive-no-min">';
1060 print
'<table class="noborder centpercent">';
1061 print
'<tr class="liste_titre">';
1062 print
'<td>'.$langs->trans(
"FieldsInSourceFile").
'</td>';
1063 print
'<td>'.$langs->trans(
"FieldsInTargetDatabase").
'</td>';
1068 print
'<tr valign="top"><td width="50%" class="nopaddingleftimp">';
1070 $fieldsplaced = array();
1071 $valforsourcefieldnb = array();
1072 $listofkeys = array();
1073 foreach ($array_match_file_to_database as $key => $val) {
1074 $listofkeys[$key] = 1;
1077 print
"\n<!-- Box left container -->\n";
1078 print
'<div id="left" class="connectedSortable">'.
"\n";
1083 foreach ($fieldssource as $key => $val) {
1086 $listofkeys[$key] = 1;
1087 $fieldsplaced[$key] = 1;
1088 $valforsourcefieldnb[$lefti] = $key;
1098 print
"<!-- End box left container -->\n";
1101 print
'</td><td width="50%" class="nopaddingrightimp">';
1105 $optionsall = array();
1106 foreach ($fieldstarget as $code => $line) {
1107 $tmparray = explode(
'|', $line[
"label"]);
1109 foreach ($tmparray as $tmpkey => $tmpval) {
1110 $labeltoshow .= ($labeltoshow ?
' '.$langs->trans(
'or').
' ' :
'').$langs->transnoentities($tmpval);
1115 $optionsall[$code] = array(
1116 'labelkey' => $line[
'label'],
1117 'labelkeyarray' => $tmparray,
1118 'label' => $labeltoshow,
1119 'required' => (empty($line[
"required"]) ? 0 : 1),
1120 'position' => (!empty($line[
'position']) ? $line[
'position'] : 0),
1128 $mandatoryfieldshavesource =
true;
1141 $modetoautofillmapping =
'session';
1142 if ($initialloadofstep4) {
1143 $modetoautofillmapping =
'guess';
1147 print
'<table class="nobordernopadding centpercent tableimport">';
1148 foreach ($fieldssource as $code => $line) {
1152 print
'<tr style="height:'.$height.
'" class="trimport oddevenimport">';
1154 $entity = (!empty($objimport->array_import_entities[0][$code]) ? $objimport->array_import_entities[0][$code] : $objimport->array_import_icon[0]);
1156 $entityicon = !empty($entitytoicon[$entity]) ? $entitytoicon[$entity] : $entity;
1157 $entitylang = !empty($entitytolang[$entity]) ? $entitytolang[$entity] : $objimport->array_import_label[0];
1159 print
'<td class="nowraponall hideonsmartphone" style="font-weight: normal">=> </td>';
1160 print
'<td class="nowraponall" style="font-weight: normal">';
1162 $selectforline =
'';
1163 $selectforline .=
'<select id="selectorderimport_'.($i + 1).
'" class="targetselectchange minwidth300" name="select_'.($i + 1).
'">';
1164 if (!empty($line[
"imported"])) {
1165 $selectforline .=
'<option value="-1"> </option>';
1167 $selectforline .=
'<option selected="" value="-1"> </option>';
1171 $codeselectedarray = array();
1172 foreach ($optionsall as $tmpcode => $tmpval) {
1174 if (!empty($tmpval[
'picto'])) {
1175 $label .=
img_picto(
'', $tmpval[
'picto'],
'class="pictofixedwidth"');
1177 $label .= $tmpval[
'required'] ?
'<strong>' :
'';
1178 $label .= $tmpval[
'label'];
1179 $label .= $tmpval[
'required'] ?
'*</strong>' :
'';
1181 $tablealias = preg_replace(
'/(\..*)$/i',
'', $tmpcode);
1182 $tablename = !empty($objimport->array_import_tables[0][$tablealias]) ? $objimport->array_import_tables[0][$tablealias] :
"";
1186 $filecolumn = ($i + 1);
1188 if (empty($objimport->array_import_convertvalue[0][$tmpcode])) {
1191 if ($objimport->array_import_convertvalue[0][$tmpcode][
'rule'] ==
'fetchidfromref') {
1192 $htmltext .= $langs->trans(
"DataComeFromIdFoundFromRef", $langs->transnoentitiesnoconv($entitylang)).
'<br>';
1194 if ($objimport->array_import_convertvalue[0][$tmpcode][
'rule'] ==
'fetchidfromcodeid') {
1195 $htmltext .= $langs->trans(
"DataComeFromIdFoundFromCodeId", $langs->transnoentitiesnoconv($objimport->array_import_convertvalue[0][$tmpcode][
'dict'])).
'<br>';
1199 $example = !empty($objimport->array_import_examplevalues[0][$tmpcode]) ? $objimport->array_import_examplevalues[0][$tmpcode] :
"";
1201 if (empty($objimport->array_import_convertvalue[0][$tmpcode])) {
1203 $htmltext .= $langs->trans(
"SourceExample").
': <b>'.str_replace(
'"',
'', $example).
'</b><br>';
1206 if ($objimport->array_import_convertvalue[0][$tmpcode][
'rule'] ==
'fetchidfromref') {
1207 $htmltext .= $langs->trans(
"SourceExample").
': <b>'.$langs->transnoentitiesnoconv(
"ExampleAnyRefFoundIntoElement", $entitylang).($example ?
' ('.$langs->transnoentitiesnoconv(
"Example").
': '.str_replace(
'"',
'', $example).
')' :
'').
'</b><br>';
1208 } elseif ($objimport->array_import_convertvalue[0][$tmpcode][
'rule'] ==
'fetchidfromcodeid') {
1209 $htmltext .= $langs->trans(
"SourceExample").
': <b>'.$langs->trans(
"ExampleAnyCodeOrIdFoundIntoDictionary", $langs->transnoentitiesnoconv($objimport->array_import_convertvalue[0][$tmpcode][
'dict'])).($example ?
' ('.$langs->transnoentitiesnoconv(
"Example").
': '.str_replace(
'"',
'', $example).
')' :
'').
'</b><br>';
1210 } elseif ($example) {
1211 $htmltext .= $langs->trans(
"SourceExample").
': <b>'.str_replace(
'"',
'', $example).
'</b><br>';
1215 if (!empty($objimport->array_import_regex[0][$tmpcode])) {
1216 $htmltext .= $langs->trans(
"FormatControlRule").
': <b>'.str_replace(
'"',
'', $objimport->array_import_regex[0][$tmpcode]).
'</b><br>';
1220 $htmltext .= $langs->trans(
"InformationOnTargetTables").
': <b>'.$tablename.
"->".preg_replace(
'/^.*\./',
'', $tmpcode).
"</b>";
1222 $labelhtml = $label.
' '.$form->textwithpicto(
'', $htmltext, 1,
'help',
'', 1);
1224 $selectforline .=
'<option value="'.$tmpcode.
'"';
1225 if ($modetoautofillmapping ==
'orderoftargets') {
1228 $selectforline .=
' selected';
1230 } elseif ($modetoautofillmapping ==
'guess') {
1234 if (preg_match(
'/^(.+)\((.+\..+)\)$/', $line[
'example1'], $regs)) {
1235 $tmpstring1 = $regs[1];
1236 $tmpstring2 = $regs[2];
1238 $tmpstring1 = $line[
'example1'];
1246 foreach ($tmpval[
'labelkeyarray'] as $tmpval2) {
1247 $labeltarget = $langs->transnoentities($tmpval2);
1249 if ($tmpstring1 && ($tmpstring1 == $tmpcode || $tmpstring1 == strtolower($labeltarget)
1250 || $tmpstring1 == strtolower(
dol_string_unaccent($labeltarget)) || $tmpstring1 == strtolower($tmpval2))) {
1251 if (empty($codeselectedarray[$code])) {
1252 $selectforline .=
' selected';
1253 $codeselectedarray[$code] = 1;
1256 } elseif ($tmpstring2 && ($tmpstring2 == $tmpcode || $tmpstring2 == strtolower($labeltarget)
1257 || $tmpstring2 == strtolower(
dol_string_unaccent($labeltarget)) || $tmpstring2 == strtolower($tmpval2))) {
1258 if (empty($codeselectedarray[$code])) {
1259 $selectforline .=
' selected';
1260 $codeselectedarray[$code] = 1;
1265 } elseif ($modetoautofillmapping ==
'session' && !empty($_SESSION[
'dol_array_match_file_to_database_select'])) {
1266 $tmpselectioninsession =
dolExplodeIntoArray($_SESSION[
'dol_array_match_file_to_database_select'],
',',
'=');
1268 if (!empty($tmpselectioninsession[(
string) ($i + 1)]) && $tmpselectioninsession[(
string) ($i + 1)] == $tmpcode) {
1269 $selectforline .=
' selected';
1271 $selectforline .=
' data-debug="'.$tmpcode.
'-'.$code.
'-'.$j.
'-'.(!empty($tmpselectioninsession[(
string) ($i + 1)]) ? $tmpselectioninsession[(string) ($i + 1)] :
"").
'"';
1273 $selectforline .=
' data-html="'.dol_escape_htmltag($labelhtml).
'"';
1274 $selectforline .=
'>';
1275 $selectforline .= $label;
1276 $selectforline .=
'</options>';
1279 $selectforline .=
'</select>';
1280 $selectforline .=
ajax_combobox(
'selectorderimport_'.($i + 1));
1282 print $selectforline;
1287 print
'<td class="nowraponall" style="font-weight:normal; text-align:right">';
1290 $htmltext =
'<b><u>'.$langs->trans(
"FieldSource").
'</u></b><br>';
1292 $htmltext .= $langs->trans(
"DataComeFromFileFieldNb", $filecolumntoshow).
'<br>';
1294 print $form->textwithpicto(
'', $htmltext);
1305 print
'<tr class="liste_titre"><td colspan="2">'.$langs->trans(
"Note").
'</td></tr>';
1306 print
'<tr><td colspan="2"><div id="div-mandatory-target-fields-not-mapped"></div></td></tr>';
1312 if (!empty(
$conf->use_javascript_ajax)) {
1313 print
'<script type="text/javascript">'.
"\n";
1314 print
'var previousselectedvalueimport = "0";'.
"\n";
1315 print
'var previousselectedlabelimport = "0";'.
"\n";
1316 print
'var arrayofselectedvalues = [];'.
"\n";
1317 print
'var arrayoftargetfields = [];'.
"\n";
1318 print
'var arrayoftargetmandatoryfields = [];'.
"\n";
1322 foreach ($fieldstarget as $key => $val) {
1323 print
"arrayoftargetfields[".$tmpi.
"] = '".
dol_escape_js($langs->trans($val[
'label'])).
"'; ";
1324 if ($val[
'required']) {
1325 print
"arrayoftargetmandatoryfields[".$tmpi.
"] = '".
dol_escape_js($key).
"'; ";
1331 print
'$(document).ready(function () {'.
"\n";
1333 print
'setOptionsToDisabled();'.
"\n";
1334 print
'saveSelection();'.
"\n";
1336 print
'$(".targetselectchange").focus(function(){'.
"\n";
1337 print
' previousselectedvalueimport = $(this).val();'.
"\n";
1338 print
' previousselectedlabelimport = $(this).children("option:selected").text();'.
"\n";
1339 print
' console.log("previousselectedvalueimport="+previousselectedvalueimport)'.
"\n";
1346 print
'function setOptionsToDisabled() {'.
"\n";
1347 print
' console.log("Remove the disabled flag everywhere");'.
"\n";
1348 print
' $("select.targetselectchange").not($( this )).find(\'option\').prop("disabled", false);'.
"\n";
1349 print
' arrayofselectedvalues = [];'.
"\n";
1351 print
' $("select.targetselectchange").each(function(){'.
"\n";
1352 print
' id = $(this).attr(\'id\')'.
"\n";
1353 print
' value = $(this).val()'.
"\n";
1354 print
' console.log("a selected value has been found for component "+id+" = "+value);'.
"\n";
1355 print
' arrayofselectedvalues.push(value);'.
"\n";
1358 print
' console.log("List of all selected values arrayofselectedvalues");'.
"\n";
1359 print
' console.log(arrayofselectedvalues);'.
"\n";
1360 print
' console.log("Set the option to disabled for every entry that is currently selected somewhere else (so into arrayofselectedvalues)");'.
"\n";
1362 print
' $.each(arrayofselectedvalues, function(key, value) {'.
"\n";
1363 print
' if (value != -1) {'.
"\n";
1364 print
' console.log("Process key="+key+" value="+value+" to disable.");'.
"\n";
1365 print
' $("select.targetselectchange").find(\'option[value="\'+value+\'"]:not(:selected)\').prop("disabled", true);'.
"\n";
1371 print
'function saveSelection() {'.
"\n";
1373 print
' arrayselectedfields = [];'.
"\n";
1374 print
' arrayselectedfields.push(0);'.
"\n";
1376 print
' $.each( arrayofselectedvalues, function( key, value ) {'.
"\n";
1377 print
' if (value != -1) {'.
"\n";
1378 print
' arrayselectedfields.push(value);'.
"\n";
1379 print
' } else {'.
"\n";
1380 print
' arrayselectedfields.push(0);'.
"\n";
1384 print
" $.ajax({\n";
1385 print
" type: 'POST',\n";
1386 print
" dataType: 'json',\n";
1387 print
" url: '".dol_escape_js($_SERVER[
"PHP_SELF"]).
"?action=saveselectorder&token=".
newToken().
"',\n";
1388 print
" data: 'selectorder='+arrayselectedfields.toString(),\n";
1389 print
" success: function(){\n";
1390 print
" console.log('The selected fields have been saved into '+arrayselectedfields.toString());\n";
1395 print
' console.log("arrayselectedfields");';
1396 print
' console.log(arrayselectedfields);';
1397 print
' console.log("arrayoftargetmandatoryfields");';
1398 print
' console.log(arrayoftargetmandatoryfields);';
1399 print
" listtoshow = '';";
1400 print
" nbelement = arrayoftargetmandatoryfields.length
1401 for (let i = 0; i < nbelement; i++) {
1402 if (arrayoftargetmandatoryfields[i] && ! arrayselectedfields.includes(arrayoftargetmandatoryfields[i])) {
1403 console.log(arrayoftargetmandatoryfields[i]+' not mapped');
1404 listtoshow = listtoshow + (listtoshow ? ', ' : '') + '<b>' + arrayoftargetfields[i] + '*</b>';
1407 console.log(listtoshow);
1409 listtoshow = '".dol_escape_js(
img_warning($langs->trans(
"MandatoryTargetFieldsNotMapped")).
' '.$langs->trans(
"MandatoryTargetFieldsNotMapped")).
": ' + listtoshow;
1410 $('#div-mandatory-target-fields-not-mapped').html(listtoshow);
1412 $('#div-mandatory-target-fields-not-mapped').html('<span class=\"opacitymedium\">".
dol_escape_js($langs->trans(
"AllTargetMandatoryFieldsAreMapped")).
"</span>');
1419 print
'$(".targetselectchange").change(function(){'.
"\n";
1420 print
' setOptionsToDisabled();'.
"\n";
1422 print
' if(previousselectedlabelimport != "" && previousselectedvalueimport != -1) {'.
"\n";
1423 print
' let valuetochange = $(this).val(); '.
"\n";
1424 print
' $(".boxtdunused").each(function(){'.
"\n";
1425 print
' if ($(this).text().includes(valuetochange)){'.
"\n";
1426 print
' arraychild = $(this)[0].childNodes'.
"\n";
1427 print
' arraytexttomodify = arraychild[0].textContent.split(" ")'.
"\n";
1428 print
' arraytexttomodify[1] = previousselectedvalueimport '.
"\n";
1429 print
' textmodified = arraytexttomodify.join(" ") '.
"\n";
1430 print
' arraychild[0].textContent = textmodified'.
"\n";
1431 print
' arraychild[1].innerHTML = previousselectedlabelimport'.
"\n";
1435 print
' $(this).blur()'.
"\n";
1437 print
' saveSelection()'.
"\n";
1441 print
'</script>'.
"\n";
1447 print
'<div class="tabsAction">';
1449 if (count($array_match_file_to_database)) {
1450 if ($mandatoryfieldshavesource) {
1451 print
'<a class="butAction saveorderselect" href="import.php?step=5'.$param.
'&filetoimport='.urlencode($filetoimport).
'">'.$langs->trans(
"NextStep").
'</a>';
1453 print
'<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->transnoentitiesnoconv(
"SomeMandatoryFieldHaveNoSource")).
'">'.$langs->trans(
"NextStep").
'</a>';
1461 if (count($array_match_file_to_database)) {
1463 print
'<!-- Area to add new import profile -->'.
"\n";
1464 print
'<div class="marginbottomonly"><span class="opacitymedium">'.$langs->trans(
"SaveImportModel").
'</span></div>';
1466 print
'<form class="nocellnopadd" action="'.$_SERVER[
"PHP_SELF"].
'" method="post">';
1467 print
'<input type="hidden" name="token" value="'.newToken().
'">';
1468 print
'<input type="hidden" name="action" value="add_import_model">';
1469 print
'<input type="hidden" name="step" value="'.$step.
'">';
1470 print
'<input type="hidden" name="format" value="'.$format.
'">';
1471 print
'<input type="hidden" name="datatoimport" value="'.$datatoimport.
'">';
1472 print
'<input type="hidden" name="filetoimport" value="'.$filetoimport.
'">';
1473 print
'<input type="hidden" name="hexa" value="'.$hexa.
'">';
1474 print
'<input type="hidden" name="excludefirstline" value="'.$excludefirstline.
'">';
1475 print
'<input type="hidden" name="endatlinenb" value="'.$endatlinenb.
'">';
1476 print
'<input type="hidden" name="page_y" value="">';
1477 print
'<input type="hidden" value="'.dol_escape_htmltag($separator).
'" name="separator">';
1478 print
'<input type="hidden" value="'.dol_escape_htmltag($enclosure).
'" name="enclosure">';
1480 print
'<div class="div-table-responsive-no-min">';
1481 print
'<table summary="selectofimportprofil" class="noborder centpercent">';
1482 print
'<tr class="liste_titre">';
1483 print
'<td>'.$langs->trans(
"ImportModelName").
'</td>';
1484 print
'<td>'.$langs->trans(
"Visibility").
'</td>';
1488 $nameofimportprofile = str_replace(
' ',
'-', $langs->trans(
"ImportProfile").
' '.$titleofmodule.
' '.
dol_print_date(
dol_now(
'gmt'),
'dayxcard'));
1490 $nameofimportprofile = $import_name;
1493 print
'<tr class="oddeven">';
1494 print
'<td><input name="import_name" class="minwidth300" value="'.$nameofimportprofile.
'"></td>';
1496 $arrayvisibility = array(
'private' => $langs->trans(
"Private"),
'all' => $langs->trans(
"Everybody"));
1497 print $form->selectarray(
'visibility', $arrayvisibility,
'private');
1499 print
'<td class="right">';
1500 print
'<input type="submit" class="button smallpaddingimp reposition" value="'.$langs->trans(
"SaveImportProfile").
'">';
1504 $sql =
"SELECT rowid, label, fk_user, entity";
1505 $sql .=
" FROM ".MAIN_DB_PREFIX.
"import_model";
1506 $sql .=
" WHERE type = '".$db->escape($datatoimport).
"'";
1508 $sql .=
" AND fk_user IN (0, ".((int) $user->id).
")";
1510 $sql .=
" ORDER BY rowid";
1512 $resql = $db->query($sql);
1514 $num = $db->num_rows($resql);
1516 $tmpuser =
new User($db);
1520 $obj = $db->fetch_object($resql);
1522 print
'<tr class="oddeven"><td>';
1525 print
'<td class="tdoverflowmax150">';
1526 if (empty($obj->fk_user)) {
1527 print $langs->trans(
"Everybody");
1529 $tmpuser->fetch($obj->fk_user);
1530 print $tmpuser->getNomUrl(-1);
1533 print
'<td class="right">';
1534 print
'<a class="reposition" href="'.$_SERVER[
"PHP_SELF"].
'?step='.$step.$param.
'&action=deleteprof&token='.
newToken().
'&id='.$obj->rowid.
'&filetoimport='.urlencode($filetoimport).
'">';
1552if ($step == 5 && $datatoimport) {
1553 $max_execution_time_for_importexport =
getDolGlobalInt(
'IMPORT_MAX_EXECUTION_TIME', 300);
1554 $max_time = @ini_get(
"max_execution_time");
1555 if ($max_time && $max_time < $max_execution_time_for_importexport) {
1556 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.");
1557 @ini_set(
"max_execution_time", $max_execution_time_for_importexport);
1561 $list = $objmodelimport->listOfAvailableImportFormat($db);
1564 $dir = DOL_DOCUMENT_ROOT.
"/core/modules/import/";
1565 $file =
"import_".$model.
".modules.php";
1566 $classname =
"Import".ucfirst($model);
1567 require_once $dir.$file;
1568 $obj =
new $classname($db, $datatoimport);
1569 '@phan-var-force ModeleImports $obj';
1570 if ($model ==
'csv') {
1571 '@phan-var-force ImportCsv $obj';
1572 $obj->separator = $separator_used;
1573 $obj->enclosure = $enclosure;
1577 $fieldssource = array();
1578 $result = $obj->import_open_file(
$conf->import->dir_temp.
'/'.$filetoimport);
1582 $arrayrecord = $obj->import_read_record();
1585 foreach ($arrayrecord as $key => $val) {
1586 $fieldssource[$i][
'example1'] =
dol_trunc($val[
'val'], 24);
1589 $obj->import_close_file();
1592 $nboflines = $obj->import_get_nb_of_lines(
$conf->import->dir_temp.
'/'.$filetoimport);
1594 $param =
'&leftmenu=import&format='.urlencode($format).
'&datatoimport='.urlencode($datatoimport).
'&filetoimport='.urlencode($filetoimport).
'&nboflines='.((int) $nboflines).
'&separator='.urlencode($separator).
'&enclosure='.urlencode($enclosure);
1596 if ($excludefirstline) {
1597 $param .=
'&excludefirstline='.urlencode($excludefirstline);
1600 $param .=
'&endatlinenb='.urlencode($endatlinenb);
1602 if (!empty($updatekeys)) {
1603 $param .=
'&updatekeys[]='.implode(
'&updatekeys[]=', $updatekeys);
1606 llxHeader(
'', $langs->trans(
"NewImport"), $help_url);
1611 print
'<form action="'.$_SERVER[
"PHP_SELF"].
'?'.$param2.
'" method="POST">';
1612 print
'<input type="hidden" name="token" value="'.newToken().
'">';
1613 print
'<input type="hidden" name="step" value="5">';
1614 print
'<input type="hidden" name="action" value="launchsimu">';
1618 print
'<div class="underbanner clearboth"></div>';
1619 print
'<div class="fichecenter">';
1621 print
'<table width="100%" class="border tableforfield">';
1624 print
'<tr><td class="titlefieldcreate">'.$langs->trans(
"Module").
'</td>';
1626 $titleofmodule = $objimport->array_import_module[0][
'module']->getName();
1628 if (in_array($objimport->array_import_code[0], array(
'produit_supplierprices',
'produit_multiprice',
'produit_languages'))) {
1629 $titleofmodule = $langs->trans(
"ProductOrService");
1631 print $titleofmodule;
1635 print
'<tr><td>'.$langs->trans(
"DatasetToImport").
'</td>';
1637 $entity = preg_replace(
'/:.*$/',
'', $objimport->array_import_icon[0]);
1638 $entityicon = strtolower(!empty($entitytoicon[$entity]) ? $entitytoicon[$entity] : $entity);
1639 print
img_object($objimport->array_import_module[0][
'module']->getName(), $entityicon).
' ';
1640 print $objimport->array_import_label[0];
1646 print
load_fiche_titre($langs->trans(
"InformationOnSourceFile"),
'',
'file-export');
1648 print
'<div class="underbanner clearboth"></div>';
1649 print
'<div class="fichecenter">';
1650 print
'<table width="100%" class="border tableforfield">';
1653 print
'<tr><td class="titlefieldcreate">'.$langs->trans(
"SourceFileFormat").
'</td>';
1655 $text = $objmodelimport->getDriverDescForKey($format);
1657 print $form->textwithpicto($objmodelimport->getDriverLabelForKey($format), $text);
1661 if ($model ==
'csv') {
1662 '@phan-var-force ImportCsv $obj';
1663 print
'<tr><td>'.$langs->trans(
"CsvOptions").
'</td>';
1666 print
' '.$langs->trans(
"Enclosure").
' : '.
dol_escape_htmltag($enclosure);
1671 print
'<tr><td>'.$langs->trans(
"FileToImport").
'</td>';
1673 $modulepart =
'import';
1674 $relativepath =
GETPOST(
'filetoimport');
1675 print
'<a data-ajax="false" href="'.DOL_URL_ROOT.
'/document.php?modulepart='.$modulepart.
'&file='.urlencode($relativepath).
'&step=4'.$param.
'" target="_blank" rel="noopener noreferrer">';
1676 print
img_mime($file,
'',
'pictofixedwidth');
1677 print $filetoimport;
1678 print
img_picto($langs->trans(
"Download"),
'download',
'class="paddingleft opacitymedium"');
1684 print $langs->trans(
"NbOfSourceLines");
1691 print $langs->trans(
"ImportFromToLine");
1693 if ($action ==
'launchsimu') {
1694 print
'<input type="number" class="maxwidth50 right" name="excludefirstlinebis" disabled="disabled" value="'.$excludefirstline.
'">';
1695 print
'<input type="hidden" name="excludefirstline" value="'.$excludefirstline.
'">';
1697 print
'<input type="number" class="maxwidth50 right" name="excludefirstline" value="'.$excludefirstline.
'">';
1698 print $form->textwithpicto(
"", $langs->trans(
"SetThisValueTo2ToExcludeFirstLine"));
1701 if ($action ==
'launchsimu') {
1702 print
'<input type="text" class="maxwidth50" name="endatlinenbbis" disabled="disabled" value="'.$endatlinenb.
'">';
1703 print
'<input type="hidden" name="endatlinenb" value="'.$endatlinenb.
'">';
1705 print
'<input type="text" class="maxwidth50" name="endatlinenb" value="'.$endatlinenb.
'">';
1706 print $form->textwithpicto(
"", $langs->trans(
"KeepEmptyToGoToEndOfFile"));
1708 if ($action ==
'launchsimu') {
1709 print
' <a href="'.$_SERVER[
"PHP_SELF"].
'?step=5'.$param.
'">'.$langs->trans(
"Modify").
'</a>';
1711 if ($excludefirstline == 2) {
1712 print $form->textwithpicto(
"", $langs->trans(
"WarningFirstImportedLine", $excludefirstline), 1,
'warning',
"warningexcludefirstline");
1714 $( document ).ready(function() {
1715 $("input[name=\'excludefirstline\']").on("change",function(){
1716 if($(this).val() <= 1){
1717 $(".warningexcludefirstline").hide();
1719 $(".warningexcludefirstline").show();
1729 print $form->textwithpicto($langs->trans(
"KeysToUseForUpdates"), $langs->trans(
"SelectPrimaryColumnsForUpdateAttempt"));
1731 if ($action ==
'launchsimu') {
1732 if (count($updatekeys)) {
1733 print $form->multiselectarray(
'updatekeysbis', $objimport->array_import_updatekeys[0], $updatekeys, 0, 0,
'', 1,
'80%',
'disabled');
1735 print
'<span class="opacitymedium">'.$langs->trans(
"NoUpdateAttempt").
'</span> -';
1737 foreach ($updatekeys as $val) {
1738 print
'<input type="hidden" name="updatekeys[]" value="'.$val.
'">';
1740 print
' <a href="'.$_SERVER[
"PHP_SELF"].
'?step=5'.$param.
'">'.$langs->trans(
"Modify").
'</a>';
1742 if (is_array($objimport->array_import_updatekeys[0]) && count($objimport->array_import_updatekeys[0])) {
1743 print $form->multiselectarray(
'updatekeys', $objimport->array_import_updatekeys[0], $updatekeys, 0, 0,
'', 1,
'80%');
1746 print
'<span class="opacitymedium">'.$langs->trans(
"UpdateNotYetSupportedForThisImport").
'</span>';
1758 print
load_fiche_titre($langs->trans(
"InformationOnTargetTables"),
'',
'file-import');
1760 print
'<div class="underbanner clearboth"></div>';
1761 print
'<div class="fichecenter">';
1763 print
'<table width="100%" class="border tableforfield">';
1766 print
'<tr><td class="titlefieldcreate">';
1767 print $langs->trans(
"TablesTarget");
1769 $listtables = array();
1770 $sort_array_match_file_to_database = $array_match_file_to_database;
1771 foreach ($array_match_file_to_database as $code => $label) {
1773 if ($code > count($fieldssource)) {
1777 $alias = preg_replace(
'/(\..*)$/i',
'', $label);
1778 $listtables[$alias] = $objimport->array_import_tables[0][$alias];
1780 if (count($listtables)) {
1783 foreach ($listtables as $val) {
1802 print $langs->trans(
"Error");
1808 print $langs->trans(
"FieldsTarget").
'</td><td>';
1809 $listfields = array();
1812 $sort_array_match_file_to_database = $array_match_file_to_database;
1813 ksort($sort_array_match_file_to_database);
1815 foreach ($sort_array_match_file_to_database as $code => $label) {
1818 if ($code > count($fieldssource)) {
1822 $alias = preg_replace(
'/(\..*)$/i',
'', $label);
1823 $listfields[$i] =
'<span class="nowrap">'.$langs->trans(
"Column").
' '.
num2Alpha((
int) $code - 1).
' -> '.$label.
'</span>';
1825 print count($listfields) ? (implode(
', ', $listfields)) : $langs->trans(
"Error");
1834 if ($action !=
'launchsimu') {
1836 print
'<br><span class="opacitymedium">';
1837 print $langs->trans(
"NowClickToTestTheImport", $langs->transnoentitiesnoconv(
"RunSimulateImportFile")).
'</span><br>';
1841 print
'<div class="center">';
1842 if ($user->hasRight(
'import',
'run')) {
1843 print
'<input type="submit" class="butAction" value="'.$langs->trans(
"RunSimulateImportFile").
'">';
1845 print
'<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->transnoentitiesnoconv(
"NotEnoughPermissions")).
'">'.$langs->trans(
"RunSimulateImportFile").
'</a>';
1850 $arrayoferrors = array();
1851 $arrayofwarnings = array();
1852 $maxnboferrors = !
getDolGlobalString(
'IMPORT_MAX_NB_OF_ERRORS') ? 50 :
$conf->global->IMPORT_MAX_NB_OF_ERRORS;
1853 $maxnbofwarnings = !
getDolGlobalString(
'IMPORT_MAX_NB_OF_WARNINGS') ? 50 :
$conf->global->IMPORT_MAX_NB_OF_WARNINGS;
1865 $pathfile =
$conf->import->dir_temp.
'/'.$filetoimport;
1866 $result = $obj->import_open_file($pathfile);
1868 global $tablewithentity_cache;
1869 $tablewithentity_cache = array();
1874 while (($sourcelinenb < $nboflines) && !$endoffile) {
1878 $arrayrecord = $obj->import_read_record();
1879 if ($arrayrecord ===
false) {
1880 $arrayofwarnings[$sourcelinenb][0] = array(
'lib' =>
'File has '.$nboflines.
' lines. However we reach the end of file or an empty line at record '.$sourcelinenb.
'. This may occurs when some records are split onto several lines and not correctly delimited by the "Char delimiter", or if there is line with no data on all fields.',
'type' =>
'EOF_RECORD_ON_SEVERAL_LINES');
1884 if ($excludefirstline && ($sourcelinenb < $excludefirstline)) {
1887 if ($endatlinenb && ($sourcelinenb > $endatlinenb)) {
1891 $parameters = array(
1893 'datatoimport' => $datatoimport,
1895 'arrayrecord' => $arrayrecord,
1896 'array_match_file_to_database' => $array_match_file_to_database,
1897 'objimport' => $objimport,
1898 'fieldssource' => $fieldssource,
1899 'importid' => $importid,
1900 'updatekeys' => $updatekeys,
1901 'arrayoferrors' => &$arrayoferrors,
1902 'arrayofwarnings' => &$arrayofwarnings,
1906 $reshook = $hookmanager->executeHooks(
'ImportInsert', $parameters);
1908 $arrayoferrors[$sourcelinenb][] = [
1909 'lib' => implode(
"<br>", array_merge([$hookmanager->error], $hookmanager->errors))
1913 if (empty($reshook)) {
1915 $result = $obj->import_insert($arrayrecord, $array_match_file_to_database, $objimport, count($fieldssource), $importid, $updatekeys);
1917 if (count($obj->errors)) {
1918 $arrayoferrors[$sourcelinenb] = $obj->errors;
1920 if (count($obj->warnings)) {
1921 $arrayofwarnings[$sourcelinenb] = $obj->warnings;
1923 if (!count($obj->errors) && !count($obj->warnings)) {
1929 $obj->import_close_file();
1931 print $langs->trans(
"ErrorFailedToOpenFile", $pathfile);
1938 if (!empty($objimport->array_import_run_sql_after[0]) && is_array($objimport->array_import_run_sql_after[0])) {
1940 foreach ($objimport->array_import_run_sql_after[0] as $sqlafterimport) {
1942 $resqlafterimport = $db->query($sqlafterimport);
1943 if (!$resqlafterimport) {
1944 $arrayoferrors[
'none'][] = array(
'lib' => $langs->trans(
"Error running final request: ".$sqlafterimport));
1953 if (!count($arrayoferrors) && !count($arrayofwarnings)) {
1955 print
'<div class="info">';
1956 print
'<div class=""><b>'.$langs->trans(
"ResultOfSimulationNoError").
'</b></div>';
1957 print $langs->trans(
"NbInsertSim", empty($obj->nbinsert) ? 0 : $obj->nbinsert).
'<br>';
1958 print $langs->trans(
"NbUpdateSim", empty($obj->nbupdate) ? 0 : $obj->nbupdate).
'<br>';
1963 print
'<div class="warning">';
1964 print $langs->trans(
"NbOfLinesOK", $nbok).
'...<br>';
1971 if (count($arrayoferrors)) {
1972 print
img_error().
' <b>'.$langs->trans(
"ErrorsOnXLines", count($arrayoferrors)).
'</b><br>';
1973 print
'<table width="100%" class="border"><tr><td>';
1974 foreach ($arrayoferrors as $key => $val) {
1976 if ($nboferrors > $maxnboferrors) {
1977 print $langs->trans(
"TooMuchErrors", (count($arrayoferrors) - $nboferrors)).
"<br>";
1981 foreach ($val as $i => $err) {
1982 print
' > '.dol_escape_htmltag($err[
'lib']).
'<br>';
1985 print
'</td></tr></table>';
1991 if (count($arrayofwarnings)) {
1992 print
img_warning().
' <b>'.$langs->trans(
"WarningsOnXLines", count($arrayofwarnings)).
'</b><br>';
1993 print
'<table width="100%" class="border"><tr><td>';
1994 foreach ($arrayofwarnings as $key => $val) {
1996 if ($nbofwarnings > $maxnbofwarnings) {
1997 print $langs->trans(
"TooMuchWarnings", (count($arrayofwarnings) - $nbofwarnings)).
"<br>";
2001 foreach ($val as $i => $err) {
2002 print
' > '.dol_escape_htmltag($err[
'lib']).
'<br>';
2005 print
'</td></tr></table>';
2012 print
'<div class="center">';
2013 print
'<span class="opacitymedium">'.$langs->trans(
"NowClickToRunTheImport", $langs->transnoentitiesnoconv(
"RunImportFile")).
'</span><br>';
2022 print
'<div class="center">';
2023 if ($user->hasRight(
'import',
'run')) {
2024 if (empty($nboferrors)) {
2025 print
'<a class="butAction" href="'.DOL_URL_ROOT.
'/imports/import.php?leftmenu=import&step=6&importid='.$importid.$param.
'">'.$langs->trans(
"RunImportFile").
'</a>';
2029 print
'<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->transnoentitiesnoconv(
"CorrectErrorBeforeRunningImport")).
'">'.$langs->trans(
"RunImportFile").
'</a>';
2032 print
'<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->transnoentitiesnoconv(
"NotEnoughPermissions")).
'">'.$langs->trans(
"RunSimulateImportFile").
'</a>';
2034 print
'<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->transnoentitiesnoconv(
"NotEnoughPermissions")).
'">'.$langs->trans(
"RunImportFile").
'</a>';
2044if ($step == 6 && $datatoimport) {
2045 $max_execution_time_for_importexport =
getDolGlobalInt(
'IMPORT_MAX_EXECUTION_TIME', 300);
2046 $max_time = @ini_get(
"max_execution_time");
2047 if ($max_time && $max_time < $max_execution_time_for_importexport) {
2048 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.");
2049 @ini_set(
"max_execution_time", $max_execution_time_for_importexport);
2053 $list = $objmodelimport->listOfAvailableImportFormat($db);
2054 $importid =
GETPOST(
"importid",
'alphanohtml');
2058 $dir = DOL_DOCUMENT_ROOT.
"/core/modules/import/";
2059 $file =
"import_".$model.
".modules.php";
2060 $classname =
"Import".ucfirst($model);
2061 require_once $dir.$file;
2062 $obj =
new $classname($db, $datatoimport);
2063 '@phan-var-force ModeleImports $obj';
2064 if ($model ==
'csv') {
2065 '@phan-var-force ImportCsv $obj';
2066 $obj->separator = $separator_used;
2067 $obj->enclosure = $enclosure;
2071 $fieldssource = array();
2072 $result = $obj->import_open_file(
$conf->import->dir_temp.
'/'.$filetoimport);
2075 $arrayrecord = $obj->import_read_record();
2078 foreach ($arrayrecord as $key => $val) {
2079 $fieldssource[$i][
'example1'] =
dol_trunc($val[
'val'], 24);
2082 $obj->import_close_file();
2087 $param =
'&format='.$format.
'&datatoimport='.urlencode($datatoimport).
'&filetoimport='.urlencode($filetoimport).
'&nboflines='.((int) $nboflines);
2088 if ($excludefirstline) {
2089 $param .=
'&excludefirstline='.urlencode($excludefirstline);
2092 $param .=
'&endatlinenb='.urlencode($endatlinenb);
2095 $param .=
'&separator='.urlencode($separator);
2098 $param .=
'&enclosure='.urlencode($enclosure);
2101 llxHeader(
'', $langs->trans(
"NewImport"), $help_url);
2107 print
'<div class="underbanner clearboth"></div>';
2108 print
'<div class="fichecenter">';
2110 print
'<table width="100%" class="border">';
2113 print
'<tr><td class="titlefieldcreate">'.$langs->trans(
"Module").
'</td>';
2115 $titleofmodule = $objimport->array_import_module[0][
'module']->getName();
2117 if (in_array($objimport->array_import_code[0], array(
'produit_supplierprices',
'produit_multiprice',
'produit_languages'))) {
2118 $titleofmodule = $langs->trans(
"ProductOrService");
2120 print $titleofmodule;
2124 print
'<tr><td>'.$langs->trans(
"DatasetToImport").
'</td>';
2126 $entity = preg_replace(
'/:.*$/',
'', $objimport->array_import_icon[0]);
2127 $entityicon = strtolower(!empty($entitytoicon[$entity]) ? $entitytoicon[$entity] : $entity);
2128 print
img_object($objimport->array_import_module[0][
'module']->getName(), $entityicon).
' ';
2129 print $objimport->array_import_label[0];
2135 print
load_fiche_titre($langs->trans(
"InformationOnSourceFile"),
'',
'file-export');
2137 print
'<div class="underbanner clearboth"></div>';
2138 print
'<div class="fichecenter">';
2139 print
'<table width="100%" class="border">';
2142 print
'<tr><td class="titlefieldcreate">'.$langs->trans(
"SourceFileFormat").
'</td>';
2144 $text = $objmodelimport->getDriverDescForKey($format);
2146 print $form->textwithpicto($objmodelimport->getDriverLabelForKey($format), $text);
2150 if ($model ==
'csv') {
2151 '@phan-var-force ImportCsv $obj';
2152 print
'<tr><td>'.$langs->trans(
"CsvOptions").
'</td>';
2154 print $langs->trans(
"Separator").
' : ';
2155 print htmlentities($separator);
2156 print
' '.$langs->trans(
"Enclosure").
' : ';
2157 print htmlentities($enclosure);
2162 print
'<tr><td>'.$langs->trans(
"FileToImport").
'</td>';
2164 $modulepart =
'import';
2165 $relativepath =
GETPOST(
'filetoimport');
2166 print
'<a data-ajax="false" href="'.DOL_URL_ROOT.
'/document.php?modulepart='.$modulepart.
'&file='.urlencode($relativepath).
'&step=4'.$param.
'" target="_blank" rel="noopener noreferrer">';
2167 print
img_mime($file,
'',
'pictofixedwidth');
2168 print $filetoimport;
2174 print $langs->trans(
"NbOfSourceLines");
2181 print $langs->trans(
"ImportFromLine");
2183 print
'<input type="text" size="4" name="excludefirstline" disabled="disabled" value="'.$excludefirstline.
'">';
2188 print $langs->trans(
"EndAtLineNb");
2190 print
'<input type="text" size="4" name="endatlinenb" disabled="disabled" value="'.$endatlinenb.
'">';
2198 print
'<b>'.$langs->trans(
"InformationOnTargetTables").
'</b>';
2199 print
'<div class="underbanner clearboth"></div>';
2200 print
'<div class="fichecenter">';
2201 print
'<table class="border centpercent">';
2204 print
'<tr><td width="25%">';
2205 print $langs->trans(
"TablesTarget");
2207 $listtables = array();
2208 foreach ($array_match_file_to_database as $code => $label) {
2210 if ($code > count($fieldssource)) {
2214 $alias = preg_replace(
'/(\..*)$/i',
'', $label);
2215 $listtables[$alias] = $objimport->array_import_tables[0][$alias];
2217 if (count($listtables)) {
2219 foreach ($listtables as $val) {
2238 print $langs->trans(
"Error");
2244 print $langs->trans(
"FieldsTarget").
'</td><td>';
2245 $listfields = array();
2247 $sort_array_match_file_to_database = $array_match_file_to_database;
2248 ksort($sort_array_match_file_to_database);
2250 foreach ($sort_array_match_file_to_database as $code => $label) {
2253 if ($code > count($fieldssource)) {
2257 $alias = preg_replace(
'/(\..*)$/i',
'', $label);
2258 $listfields[$i] = $langs->trans(
"Field").
' '.$code.
'->'.$label;
2260 print count($listfields) ? (implode(
', ', $listfields)) : $langs->trans(
"Error");
2267 $arrayoferrors = array();
2268 $arrayofwarnings = array();
2269 $maxnboferrors = !
getDolGlobalString(
'IMPORT_MAX_NB_OF_ERRORS') ? 50 :
$conf->global->IMPORT_MAX_NB_OF_ERRORS;
2270 $maxnbofwarnings = !
getDolGlobalString(
'IMPORT_MAX_NB_OF_WARNINGS') ? 50 :
$conf->global->IMPORT_MAX_NB_OF_WARNINGS;
2282 $pathfile =
$conf->import->dir_temp.
'/'.$filetoimport;
2283 $result = $obj->import_open_file($pathfile);
2285 global $tablewithentity_cache;
2286 $tablewithentity_cache = array();
2290 while ($sourcelinenb < $nboflines && !$endoffile) {
2292 $arrayrecord = $obj->import_read_record();
2293 if ($arrayrecord ===
false) {
2294 $arrayofwarnings[$sourcelinenb][0] = array(
'lib' =>
'File has '.$nboflines.
' lines. However we reach the end of file or an empty line at record '.$sourcelinenb.
'. This may occurs when some records are split onto several lines and not correctly delimited by the "Char delimiter", or if there is line with no data on all fields.',
'type' =>
'EOF_RECORD_ON_SEVERAL_LINES');
2298 if ($excludefirstline && ($sourcelinenb < $excludefirstline)) {
2301 if ($endatlinenb && ($sourcelinenb > $endatlinenb)) {
2305 $parameters = array(
2307 'datatoimport' => $datatoimport,
2309 'arrayrecord' => $arrayrecord,
2310 'array_match_file_to_database' => $array_match_file_to_database,
2311 'objimport' => $objimport,
2312 'fieldssource' => $fieldssource,
2313 'importid' => $importid,
2314 'updatekeys' => $updatekeys,
2315 'arrayoferrors' => &$arrayoferrors,
2316 'arrayofwarnings' => &$arrayofwarnings,
2320 $reshook = $hookmanager->executeHooks(
'ImportInsert', $parameters);
2322 $arrayoferrors[$sourcelinenb][] = [
2323 'lib' => implode(
"<br>", array_merge([$hookmanager->error], $hookmanager->errors))
2327 if (empty($reshook)) {
2329 $result = $obj->import_insert($arrayrecord, $array_match_file_to_database, $objimport, count($fieldssource), $importid, $updatekeys);
2331 if (count($obj->errors)) {
2332 $arrayoferrors[$sourcelinenb] = $obj->errors;
2334 if (count($obj->warnings)) {
2335 $arrayofwarnings[$sourcelinenb] = $obj->warnings;
2338 if (!count($obj->errors) && !count($obj->warnings)) {
2343 $reshook = $hookmanager->executeHooks(
'AfterImportInsert', $parameters);
2345 $arrayoferrors[$sourcelinenb][] = [
2346 'lib' => implode(
"<br>", array_merge([$hookmanager->error], $hookmanager->errors))
2351 $obj->import_close_file();
2353 print $langs->trans(
"ErrorFailedToOpenFile", $pathfile);
2356 if (count($arrayoferrors) > 0) {
2363 if (!empty($objimport->array_import_run_sql_after[0]) && is_array($objimport->array_import_run_sql_after[0])) {
2365 foreach ($objimport->array_import_run_sql_after[0] as $sqlafterimport) {
2367 $resqlafterimport = $db->query($sqlafterimport);
2368 if (!$resqlafterimport) {
2369 $arrayoferrors[
'none'][] = array(
'lib' => $langs->trans(
"Error running final request: ".$sqlafterimport));
2387 print
'<div class="info">';
2388 print $langs->trans(
"NbOfLinesImported", $nbok).
'</b><br>';
2389 print $langs->trans(
"NbInsert", empty($obj->nbinsert) ? 0 : $obj->nbinsert).
'<br>';
2390 print $langs->trans(
"NbUpdate", empty($obj->nbupdate) ? 0 : $obj->nbupdate).
'<br>';
2392 print
'<div class="center">';
2393 print $langs->trans(
"FileWasImported", $importid).
'<br>';
2394 print
'<span class="opacitymedium">'.$langs->trans(
"YouCanUseImportIdToFindRecord", $importid).
'</span><br>';
2417 global
$conf, $langs;
2421 if ($key ==
'none') {
2423 print
"\n\n<!-- Box_no-key start-->\n";
2424 print
'<div class="box boximport" style="padding:0;">'.
"\n";
2425 print
'<table summary="boxtable_no-key" class="centpercent nobordernopadding">'.
"\n";
2427 print
"\n\n<!-- Box ".$pos.
" start -->\n";
2428 print
'<div class="box boximport" style="padding: 0;" id="boxto_'.$pos.
'">'.
"\n";
2430 print
'<table summary="boxtable'.$pos.
'" class="nobordernopadding centpercent tableimport">'.
"\n";
2433 if (($pos && $pos > count($fieldssource)) && (!isset($fieldssource[$pos][
"imported"]))) {
2443 } elseif ($key ==
'none') {
2444 print
'<tr style="height:'.$height.
'" class="trimport oddevenimport">';
2445 print
'<td class="nocellnopadd" width="16" style="font-weight: normal">';
2448 print
'<td style="font-weight: normal">';
2454 print
'<tr style="height:'.$height.
'" class="trimport oddevenimport">';
2455 print
'<td class="nocellnopadd" width="16" style="font-weight: normal">';
2458 print
img_picto($langs->trans(
"Column").
' '.
num2Alpha($pos - 1),
'file',
'class="pictofixedwidth"');
2460 if (isset($fieldssource[$pos][
'imported']) && $fieldssource[$pos][
'imported'] ==
false) {
2461 print
'<td class="nowraponall boxtdunused" style="font-weight: normal">';
2463 print
'<td class="nowraponall tdoverflowmax500" style="font-weight: normal">';
2465 print $langs->trans(
"Column").
' '.
num2Alpha($pos - 1).
' (#'.$pos.
')';
2466 if (empty($fieldssource[$pos][
'example1'])) {
2467 $example = $fieldssource[$pos][
'label'];
2469 $example = $fieldssource[$pos][
'example1'];
2473 $example = mb_convert_encoding($example,
'UTF-8',
'ISO-8859-1');
2477 print
'<i class="opacitymedium">'.dol_escape_htmltag($example).
'</i>';
2486 print
"<!-- Box end -->\n\n";
2499 $i = count($fieldssource) + 1;
2502 foreach ($listofkey as $key => $val) {
2503 $maxkey = max($maxkey, $key);
2506 while ($i <= $maxkey) {
2507 if (empty($listofkey[$i])) {
2529 if ($position == count($array)) {
2530 $ret = $array + $insertArray;
2533 foreach ($array as $key => $value) {
2534 if ($position == $i++) {
2535 $ret += $insertArray;
2538 $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.
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_move_uploaded_file($src_file, $dest_file, $allowoverwrite, $disablevirusscan=0, $uploaderrorcode=0, $nohook=0, $varfiles='addedfile', $upload_dir='')
Check validity of a file upload from an GUI page, and move it to its final destination.
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.
load_fiche_titre($title, $morehtmlright='', $picto='generic', $pictoisfullpath=0, $id='', $morecssontable='', $morehtmlcenter='')
Load a title with picto.
img_object($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0)
Show a picto called object_picto (generic function)
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_warning($titlealt='default', $moreatt='', $morecss='pictowarning')
Show warning logo.
img_delete($titlealt='default', $other='class="pictodelete"', $morecss='')
Show delete logo.
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2)
Show picto whatever it's its name (generic function)
GETPOSTINT($paramname, $method=0)
Return the value of a $_GET or $_POST supervariable, converted into integer.
dol_get_fiche_head($links=array(), $active='', $title='', $notab=0, $picto='', $pictoisfullpath=0, $morehtmlright='', $morecss='', $limittoshow=0, $moretabssuffix='', $dragdropfile=0)
Show tabs of a record.
dolPrintHTML($s, $allowiframe=0)
Return a string (that can be on several lines) ready to be output on a HTML page.
dol_get_fiche_end($notab=0)
Return tab footer of a card.
dol_now($mode='auto')
Return date for now.
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_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
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...
newToken()
Return the value of token currently saved into session with name 'newtoken'.
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.
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...
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.
info_admin($text, $infoonimgalt=0, $nodiv=0, $admin='1', $morecss='hideonsmartphone', $textfordropdown='', $picto='')
Show information in HTML for admin users or standard users.
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.
global $conf
The following vars must be defined: $type2label $form $conf, $lang, The following vars may also be de...
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.