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 nomarginbottom">';
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 $titleofmodule = $objimport->array_import_module[$key][
'module']->getName();
366 print
'<tr class="oddeven"><td class="tdoverflowmax200" title="'.dolPrintHTML($titleofmodule).
'">';
368 if (in_array($objimport->array_import_code[$key], array(
'produit_supplierprices',
'produit_multiprice',
'produit_languages'))) {
369 $titleofmodule = $langs->trans(
"ProductOrService");
373 $entity = preg_replace(
'/:.*$/',
'', $objimport->array_import_icon[$key]);
374 $entityicon = strtolower(!empty($entitytoicon[$entity]) ? $entitytoicon[$entity] : $entity);
375 $label = $objimport->array_import_label[$key];
376 print
'<div class="twolinesmax-normallineheight minwidth200onall">';
377 print
img_object($objimport->array_import_module[$key][
'module']->getName(), $entityicon,
'class="pictofixedwidth"');
380 print
'</td><td style="text-align: right">';
381 if ($objimport->array_import_perms[$key]) {
382 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>';
384 print $langs->trans(
"NotEnoughPermissions");
389 print
'<tr><td class="oddeven" colspan="3">'.$langs->trans(
"NoImportableData").
'</td></tr>';
399if ($step == 2 && $datatoimport) {
400 $param =
'&datatoimport='.urlencode($datatoimport);
401 if ($excludefirstline) {
402 $param .=
'&excludefirstline='.urlencode($excludefirstline);
405 $param .=
'&endatlinenb='.urlencode($endatlinenb);
408 $param .=
'&separator='.urlencode($separator);
411 $param .=
'&enclosure='.urlencode($enclosure);
414 llxHeader(
'', $langs->trans(
"NewImport"), $help_url);
420 print
'<div class="underbanner clearboth"></div>';
421 print
'<div class="fichecenter">';
423 print
'<table class="border tableforfield centpercent">';
426 print
'<tr><td class="titlefieldcreate">'.$langs->trans(
"Module").
'</td>';
428 $titleofmodule = $objimport->array_import_module[0][
'module']->getName();
430 if (in_array($objimport->array_import_code[0], array(
'produit_supplierprices',
'produit_multiprice',
'produit_languages'))) {
431 $titleofmodule = $langs->trans(
"ProductOrService");
433 print $titleofmodule;
437 print
'<tr><td>'.$langs->trans(
"DatasetToImport").
'</td>';
439 $entity = preg_replace(
'/:.*$/',
'', $objimport->array_import_icon[0]);
440 $entityicon = strtolower(!empty($entitytoicon[$entity]) ? $entitytoicon[$entity] : $entity);
441 print
img_object($objimport->array_import_module[0][
'module']->getName(), $entityicon).
' ';
442 print $objimport->array_import_label[0];
450 print
'<form name="userfile" action="'.$_SERVER[
"PHP_SELF"].
'" enctype="multipart/form-data" METHOD="POST">';
451 print
'<input type="hidden" name="token" value="'.newToken().
'">';
455 print
'<span class="opacitymedium">';
456 $s = $langs->trans(
"ChooseFormatOfFileToImport",
'{s1}');
457 $s = str_replace(
'{s1}',
img_picto(
'',
'next'), $s);
459 print
'</span><br><br>';
463 print
'<div class="div-table-responsive-no-min">';
464 print
'<table class="noborder centpercent" cellpadding="4">';
469 print
'<tr class="liste_titre"><td colspan="5">';
470 print $langs->trans(
"FileMustHaveOneOfFollowingFormat");
472 $list = $objmodelimport->listOfAvailableImportFormat($db);
473 foreach ($list as $key) {
474 print
'<tr class="oddeven">';
475 print
'<td width="16">'.img_picto_common($key, $objmodelimport->getPictoForKey($key)).
'</td>';
476 $htmltext = $objmodelimport->getDriverDescForKey($key);
477 print
'<td>'.$form->textwithpicto($objmodelimport->getDriverLabelForKey($key), $htmltext).
'</td>';
478 print
'<td style="text-align:center">';
479 if (empty($objmodelimport->drivererror[$key])) {
480 $filename = $langs->transnoentitiesnoconv(
"ExampleOfImportFile").
'_'.$datatoimport.
'.'.$key;
481 print
'<a href="'.DOL_URL_ROOT.
'/imports/emptyexample.php?format='.$key.$param.
'&output=file&file='.urlencode($filename).
'" target="_blank" rel="noopener noreferrer">';
482 print
img_picto(
'',
'download',
'class="paddingright opacitymedium"');
483 print $langs->trans(
"DownloadEmptyExampleShort");
485 print $form->textwithpicto(
'', $langs->trans(
"DownloadEmptyExample").
'.<br>'.$langs->trans(
"StarAreMandatory"));
491 print
'<td style="text-align:right">';
492 if (empty($objmodelimport->drivererror[$key])) {
493 print
'<a href="'.DOL_URL_ROOT.
'/imports/import.php?step=3&format='.$key.$param.
'">'.
img_picto($langs->trans(
"SelectFormat"),
'next',
'class="fa-15"').
'</a>';
507if ($step == 3 && $datatoimport) {
508 $param =
'&datatoimport='.urlencode($datatoimport).
'&format='.urlencode($format);
509 if ($excludefirstline) {
510 $param .=
'&excludefirstline='.urlencode($excludefirstline);
513 $param .=
'&endatlinenb='.urlencode($endatlinenb);
516 $param .=
'&separator='.urlencode($separator);
519 $param .=
'&enclosure='.urlencode($enclosure);
522 $list = $objmodelimport->listOfAvailableImportFormat($db);
524 llxHeader(
'', $langs->trans(
"NewImport"), $help_url);
533 if ($action ==
'delete') {
534 print $form->formconfirm($_SERVER[
"PHP_SELF"].
'?urlfile='.urlencode(
GETPOST(
'urlfile')).
'&step=3'.$param, $langs->trans(
'DeleteFile'), $langs->trans(
'ConfirmDeleteFile'),
'confirm_deletefile',
'', 0, 1);
537 print
'<div class="underbanner clearboth"></div>';
538 print
'<div class="fichecenter">';
540 print
'<table class="border tableforfield centpercent">';
543 print
'<tr><td class="titlefieldcreate">'.$langs->trans(
"Module").
'</td>';
545 $titleofmodule = $objimport->array_import_module[0][
'module']->getName();
547 if (in_array($objimport->array_import_code[0], array(
'produit_supplierprices',
'produit_multiprice',
'produit_languages'))) {
548 $titleofmodule = $langs->trans(
"ProductOrService");
550 print $titleofmodule;
554 print
'<tr><td>'.$langs->trans(
"DatasetToImport").
'</td>';
556 $entity = preg_replace(
'/:.*$/',
'', $objimport->array_import_icon[0]);
557 $entityicon = strtolower(!empty($entitytoicon[$entity]) ? $entitytoicon[$entity] : $entity);
558 print
img_object($objimport->array_import_module[0][
'module']->getName(), $entityicon).
' ';
559 print $objimport->array_import_label[0];
567 print
load_fiche_titre($langs->trans(
"InformationOnSourceFile"),
'',
'file-export');
569 print
'<div class="underbanner clearboth"></div>';
570 print
'<div class="fichecenter">';
571 print
'<table width="100%" class="border tableforfield">';
574 print
'<tr><td class="titlefieldcreate">'.$langs->trans(
"SourceFileFormat").
'</td>';
575 print
'<td class="nowraponall">';
576 $text = $objmodelimport->getDriverDescForKey($format);
578 print $form->textwithpicto($objmodelimport->getDriverLabelForKey($format), $text);
579 print
'</td><td style="text-align:right" class="nowrap">';
580 $filename = $langs->transnoentitiesnoconv(
"ExampleOfImportFile").
'_'.$datatoimport.
'.'.$format;
581 print
'<a href="'.DOL_URL_ROOT.
'/imports/emptyexample.php?format='.$format.$param.
'&output=file&file='.urlencode($filename).
'" target="_blank" rel="noopener noreferrer">';
582 print
img_picto(
'',
'download',
'class="paddingright opacitymedium"');
583 print $langs->trans(
"DownloadEmptyExampleShort");
585 print $form->textwithpicto(
'', $langs->trans(
"DownloadEmptyExample").
'.<br>'.$langs->trans(
"StarAreMandatory"));
594 if ($format ==
'xlsx' && !class_exists(
'XMLWriter')) {
595 $langs->load(
"install");
596 print
info_admin($langs->trans(
"ErrorPHPDoesNotSupport",
'php-xml'), 0, 0,
'1',
'error');
602 print
'<form name="userfile" action="'.$_SERVER[
"PHP_SELF"].
'" enctype="multipart/form-data" method="POST">';
603 print
'<input type="hidden" name="token" value="'.newToken().
'">';
604 print
'<input type="hidden" value="'.$step.
'" name="step">';
605 print
'<input type="hidden" value="'.dol_escape_htmltag($format).
'" name="format">';
606 print
'<input type="hidden" value="'.$excludefirstline.
'" name="excludefirstline">';
607 print
'<input type="hidden" value="'.$endatlinenb.
'" name="endatlinenb">';
608 print
'<input type="hidden" value="'.dol_escape_htmltag($separator).
'" name="separator">';
609 print
'<input type="hidden" value="'.dol_escape_htmltag($enclosure).
'" name="enclosure">';
610 print
'<input type="hidden" value="'.dol_escape_htmltag($datatoimport).
'" name="datatoimport">';
612 print
'<span class="opacitymedium">';
613 $s = $langs->trans(
"ChooseFileToImport",
'{s1}');
614 $s = str_replace(
'{s1}',
img_picto(
'',
'next'), $s);
616 print
'</span><br><br>';
621 print
'<div class="marginbottomonly">';
623 $maxmin = $maxfilesizearray[
'maxmin'];
625 print
'<input type="hidden" name="MAX_FILE_SIZE" value="'.($maxmin * 1024).
'">';
627 print
'<input type="file" name="userfile" size="20" maxlength="80"> ';
629 print
'<input type="submit" class="button small" value="'.$langs->trans(
"AddFile").
'"'.$out.
' name="sendit">';
633 $maxphp = @ini_get(
'upload_max_filesize');
634 if (preg_match(
'/k$/i', $maxphp)) {
635 $maxphp = (int) substr($maxphp, 0, -1);
637 if (preg_match(
'/m$/i', $maxphp)) {
638 $maxphp = (int) substr($maxphp, 0, -1) * 1024;
640 if (preg_match(
'/g$/i', $maxphp)) {
641 $maxphp = (int) substr($maxphp, 0, -1) * 1024 * 1024;
643 if (preg_match(
'/t$/i', $maxphp)) {
644 $maxphp = (int) substr($maxphp, 0, -1) * 1024 * 1024 * 1024;
646 $maxphp2 = @ini_get(
'post_max_size');
647 if (preg_match(
'/k$/i', $maxphp2)) {
648 $maxphp2 = (int) substr($maxphp2, 0, -1);
650 if (preg_match(
'/m$/i', $maxphp2)) {
651 $maxphp2 = (int) substr($maxphp2, 0, -1) * 1024;
653 if (preg_match(
'/g$/i', $maxphp2)) {
654 $maxphp2 = (int) substr($maxphp2, 0, -1) * 1024 * 1024;
656 if (preg_match(
'/t$/i', $maxphp2)) {
657 $maxphp2 = (int) substr($maxphp2, 0, -1) * 1024 * 1024 * 1024;
661 $maxphptoshow = $maxphptoshowparam =
'';
663 $maxmin = min($max, $maxphp);
664 $maxphptoshow = $maxphp;
665 $maxphptoshowparam =
'upload_max_filesize';
668 $maxmin = min($max, $maxphp2);
669 if ($maxphp2 < $maxphp) {
670 $maxphptoshow = $maxphp2;
671 $maxphptoshowparam =
'post_max_size';
675 $langs->load(
'other');
677 $out .=
info_admin($langs->trans(
"ThisLimitIsDefinedInSetup", $max, $maxphptoshow), 1);
679 $out .=
' ('.$langs->trans(
"UploadDisabled").
')';
685 $filearray =
dol_dir_list(
$conf->import->dir_temp,
'files', 0,
'',
'',
'name', SORT_DESC);
686 if (count($filearray) > 0) {
687 print
'<div class="div-table-responsive-no-min">';
688 print
'<table class="noborder centpercent" width="100%" cellpadding="4">';
690 $dir =
$conf->import->dir_temp;
694 foreach ($filearray as $key => $val) {
695 $file = $val[
'name'];
699 $file = mb_convert_encoding($file,
'UTF-8',
'ISO-8859-1');
702 if (preg_match(
'/^\./', $file)) {
706 $modulepart =
'import';
707 $urlsource = $_SERVER[
"PHP_SELF"].
'?step='.$step.$param.
'&filetoimport='.urlencode($filetoimport);
708 $relativepath = $file;
710 print
'<tr class="oddeven">';
712 print
img_mime($file,
'',
'pictofixedwidth');
713 print
'<a data-ajax="false" href="'.DOL_URL_ROOT.
'/document.php?modulepart='.$modulepart.
'&file='.urlencode($relativepath).
'&step=3'.$param.
'" target="_blank" rel="noopener noreferrer">';
718 print
'<td style="text-align:right">'.dol_print_size(
dol_filesize($dir.
'/'.$file)).
'</td>';
720 print
'<td style="text-align:right">'.dol_print_date(
dol_filemtime($dir.
'/'.$file),
'dayhour').
'</td>';
722 print
'<td style="text-align:right"><a href="'.$_SERVER[
'PHP_SELF'].
'?action=delete&token='.
newToken().
'&step=3'.$param.
'&urlfile='.urlencode($relativepath);
723 print
'">'.img_delete().
'</a></td>';
725 print
'<td style="text-align:right">';
726 print
'<a href="'.$_SERVER[
'PHP_SELF'].
'?step=4'.$param.
'&filetoimport='.urlencode($relativepath).
'">'.
img_picto($langs->trans(
"NewImport"),
'next',
'class="fa-15"').
'</a>';
740if ($step == 4 && $datatoimport) {
742 $serialized_array_match_file_to_database = isset($_SESSION[
"dol_array_match_file_to_database_select"]) ? $_SESSION[
"dol_array_match_file_to_database_select"] :
'';
743 $fieldsarray = explode(
',', $serialized_array_match_file_to_database);
744 $array_match_file_to_database = array();
745 foreach ($fieldsarray as $elem) {
746 $tabelem = explode(
'=', $elem, 2);
748 $val = (isset($tabelem[1]) ? $tabelem[1] :
'');
750 $array_match_file_to_database[$key] = $val;
759 $list = $objmodelimport->listOfAvailableImportFormat($db);
761 if (empty($separator)) {
762 $separator = (!
getDolGlobalString(
'IMPORT_CSV_SEPARATOR_TO_USE') ?
',' :
$conf->global->IMPORT_CSV_SEPARATOR_TO_USE);
766 if ($model ==
'csv' && strlen($separator) == 1 && !GETPOSTISSET(
'separator')) {
767 '@phan-var-force ImportCsv $obj';
769 $fh = fopen(
$conf->import->dir_temp.
'/'.$filetoimport,
'r');
771 $sline = fgets($fh, 1000000);
773 $nboccurence = substr_count($sline, $separator);
774 $nboccurencea = substr_count($sline,
',');
775 $nboccurenceb = substr_count($sline,
';');
777 if ($nboccurence == 0) {
778 if ($nboccurencea > 2) {
780 } elseif ($nboccurenceb > 2) {
788 $separator_used = str_replace(
'\t',
"\t", $separator);
791 $dir = DOL_DOCUMENT_ROOT.
"/core/modules/import/";
792 $file =
"import_".$model.
".modules.php";
793 $classname =
"Import".ucfirst($model);
794 require_once $dir.$file;
795 $obj =
new $classname($db, $datatoimport);
796 '@phan-var-force ModeleImports $obj';
798 if (!empty($obj->error)) {
799 $langs->load(
"errors");
800 $param =
'&datatoimport='.$datatoimport.
'&format='.$format;
802 header(
"Location: ".$_SERVER[
"PHP_SELF"].
'?step=3'.$param.
'&filetoimport='.urlencode($relativepath));
806 if ($model ==
'csv') {
807 '@phan-var-force ImportCsv $obj';
808 $obj->separator = $separator_used;
809 $obj->enclosure = $enclosure;
812 if ($model ==
'xlsx') {
813 '@phan-var-force ImportXlsx $obj';
814 if (!preg_match(
'/\.xlsx$/i', $filetoimport)) {
815 $langs->load(
"errors");
816 $param =
'&datatoimport='.$datatoimport.
'&format='.$format;
817 setEventMessages($langs->trans(
"ErrorFileMustHaveFormat", $model),
null,
'errors');
818 header(
"Location: ".$_SERVER[
"PHP_SELF"].
'?step=3'.$param.
'&filetoimport='.urlencode($relativepath));
824 $array_match_file_to_database = array();
828 $fieldssource = array();
830 $result = $obj->import_open_file(
$conf->import->dir_temp.
'/'.$filetoimport);
833 $arrayrecord = $obj->import_read_record();
837 foreach ($arrayrecord as $key => $val) {
838 if ($val[
"type"] != -1) {
839 $fieldssource[$i][
'example1'] =
dol_trunc($val[
'val'], 128);
842 $fieldssource[$i][
'example1'] = $langs->trans(
'Empty');
845 $fieldssource[$i][
'imported'] = 0;
847 $obj->import_close_file();
851 $fieldstarget = $objimport->array_import_fields[0];
852 $minpos = min(count($fieldssource), count($fieldstarget));
856 $initialloadofstep4 =
false;
857 if (empty($_SESSION[
'dol_array_match_file_to_database_select'])) {
858 $initialloadofstep4 =
true;
862 if (count($array_match_file_to_database) == 0) {
868 $num = count($fieldssource);
869 while ($pos <= $num) {
870 if ($num >= 1 && $pos <= $num) {
872 foreach ($fieldstarget as $key => $val) {
873 if ($posbis < $pos) {
878 $array_match_file_to_database[$pos] = $key;
885 $array_match_database_to_file = array_flip($array_match_file_to_database);
889 $fieldstarget_tmp = array();
890 $arraykeysfieldtarget = array_keys($fieldstarget);
892 foreach ($fieldstarget as $key => $label) {
893 $isrequired = preg_match(
'/\*$/', $label);
894 if (!empty($isrequired)) {
895 $newlabel = substr($label, 0, -1);
896 $fieldstarget_tmp[$key] = array(
"label" => $newlabel,
"required" =>
true);
898 $fieldstarget_tmp[$key] = array(
"label" => $label,
"required" =>
false);
900 if (!empty($array_match_database_to_file[$key])) {
901 $fieldstarget_tmp[$key][
"imported"] =
true;
902 $fieldstarget_tmp[$key][
"position"] = (int) $array_match_database_to_file[$key] - 1;
904 while (!empty($array_match_database_to_file[$keytoswap])) {
905 if ($position + 1 > $array_match_database_to_file[$keytoswap]) {
906 $keytoswapwith = $array_match_database_to_file[$keytoswap] - 1;
907 $tmp = [$keytoswap => $fieldstarget_tmp[$keytoswap]];
908 unset($fieldstarget_tmp[$keytoswap]);
909 $fieldstarget_tmp =
arrayInsert($fieldstarget_tmp, $keytoswapwith, $tmp);
910 $keytoswapwith = $arraykeysfieldtarget[$array_match_database_to_file[$keytoswap] - 1];
911 $tmp = $fieldstarget_tmp[$keytoswapwith];
912 unset($fieldstarget_tmp[$keytoswapwith]);
913 $fieldstarget_tmp[$keytoswapwith] = $tmp;
914 $keytoswap = $keytoswapwith;
920 $fieldstarget_tmp[$key][
"imported"] =
false;
924 $fieldstarget = $fieldstarget_tmp;
933 $param =
'&format='.$format.
'&datatoimport='.urlencode($datatoimport).
'&filetoimport='.urlencode($filetoimport);
934 if ($excludefirstline) {
935 $param .=
'&excludefirstline='.urlencode($excludefirstline);
938 $param .=
'&endatlinenb='.urlencode($endatlinenb);
941 $param .=
'&separator='.urlencode($separator);
944 $param .=
'&enclosure='.urlencode($enclosure);
947 llxHeader(
'', $langs->trans(
"NewImport"), $help_url);
953 print
'<div class="underbanner clearboth"></div>';
954 print
'<div class="fichecenter">';
956 print
'<table class="centpercent border tableforfield">';
959 print
'<tr><td class="titlefieldcreate">'.$langs->trans(
"Module").
'</td>';
961 $titleofmodule = $objimport->array_import_module[0][
'module']->getName();
963 if (in_array($objimport->array_import_code[0], array(
'produit_supplierprices',
'produit_multiprice',
'produit_languages'))) {
964 $titleofmodule = $langs->trans(
"ProductOrService");
966 print $titleofmodule;
970 print
'<tr><td>'.$langs->trans(
"DatasetToImport").
'</td>';
972 $entity = preg_replace(
'/:.*$/',
'', $objimport->array_import_icon[0]);
973 $entityicon = strtolower(!empty($entitytoicon[$entity]) ? $entitytoicon[$entity] : $entity);
974 print
img_object($objimport->array_import_module[0][
'module']->getName(), $entityicon).
' ';
975 print $objimport->array_import_label[0];
983 print
load_fiche_titre($langs->trans(
"InformationOnSourceFile"),
'',
'file-export');
985 print
'<div class="underbanner clearboth"></div>';
986 print
'<div class="fichecenter">';
987 print
'<table width="100%" class="border tableforfield">';
990 print
'<tr><td class="titlefieldcreate">'.$langs->trans(
"SourceFileFormat").
'</td>';
991 print
'<td class="nowraponall">';
992 $text = $objmodelimport->getDriverDescForKey($format);
994 print $form->textwithpicto($objmodelimport->getDriverLabelForKey($format), $text);
998 if ($model ==
'csv') {
999 '@phan-var-force ImportCsv $obj';
1000 print
'<tr><td>'.$langs->trans(
"CsvOptions").
'</td>';
1002 print
'<form method="POST">';
1003 print
'<input type="hidden" name="token" value="'.newToken().
'">';
1004 print
'<input type="hidden" value="'.$step.
'" name="step">';
1005 print
'<input type="hidden" value="'.$format.
'" name="format">';
1006 print
'<input type="hidden" value="'.$excludefirstline.
'" name="excludefirstline">';
1007 print
'<input type="hidden" value="'.$endatlinenb.
'" name="endatlinenb">';
1008 print
'<input type="hidden" value="'.$datatoimport.
'" name="datatoimport">';
1009 print
'<input type="hidden" value="'.$filetoimport.
'" name="filetoimport">';
1010 print $langs->trans(
"Separator").
' : ';
1011 print
'<input type="text" class="width25 center" name="separator" value="'.dol_escape_htmltag($separator).
'"/>';
1012 print
' '.$langs->trans(
"Enclosure").
' : ';
1013 print
'<input type="text" class="width25 center" name="enclosure" value="'.dol_escape_htmltag($enclosure).
'"/> ';
1014 print
'<input name="update" type="submit" value="'.$langs->trans(
'Update').
'" class="button smallpaddingimp" />';
1020 print
'<tr><td>'.$langs->trans(
"FileToImport").
'</td>';
1022 $modulepart =
'import';
1023 $relativepath =
GETPOST(
'filetoimport');
1024 print
'<a data-ajax="false" href="'.DOL_URL_ROOT.
'/document.php?modulepart='.$modulepart.
'&file='.urlencode($relativepath).
'&step=4'.$param.
'" target="_blank" rel="noopener noreferrer">';
1025 print
img_mime($file,
'',
'pictofixedwidth');
1026 print $filetoimport;
1027 print
img_picto($langs->trans(
"Download"),
'download',
'class="paddingleft opacitymedium"');
1040 print
'<!-- List of source fields -->'.
"\n";
1041 print
'<form action="'.$_SERVER[
"PHP_SELF"].
'" method="POST">';
1042 print
'<input type="hidden" name="token" value="'.newToken().
'">';
1043 print
'<input type="hidden" name="action" value="select_model">';
1044 print
'<input type="hidden" name="step" value="4">';
1045 print
'<input type="hidden" name="format" value="'.$format.
'">';
1046 print
'<input type="hidden" name="datatoimport" value="'.$datatoimport.
'">';
1047 print
'<input type="hidden" name="filetoimport" value="'.$filetoimport.
'">';
1048 print
'<input type="hidden" name="excludefirstline" value="'.$excludefirstline.
'">';
1049 print
'<input type="hidden" name="endatlinenb" value="'.$endatlinenb.
'">';
1050 print
'<input type="hidden" name="separator" value="'.dol_escape_htmltag($separator).
'">';
1051 print
'<input type="hidden" name="enclosure" value="'.dol_escape_htmltag($enclosure).
'">';
1054 print
'<div class="marginbottomonly">';
1055 print
'<span class="opacitymedium">';
1056 $s = $langs->trans(
"SelectImportFieldsSource",
'{s1}');
1057 $s = str_replace(
'{s1}',
img_picto(
'',
'grip_title',
'', 0, 0, 0,
'',
'', 0), $s);
1060 $htmlother->select_import_model($importmodelid,
'importmodelid', $datatoimport, 1, $user->id);
1061 print
'<input type="submit" class="button small reposition" value="'.$langs->trans(
"Select").
'">';
1066 print
'<div class="div-table-responsive-no-min">';
1067 print
'<table class="noborder centpercent">';
1068 print
'<tr class="liste_titre">';
1069 print
'<td>'.$langs->trans(
"FieldsInSourceFile").
'</td>';
1070 print
'<td>'.$langs->trans(
"FieldsInTargetDatabase").
'</td>';
1075 print
'<tr valign="top"><td width="50%" class="nopaddingleftimp">';
1077 $fieldsplaced = array();
1078 $valforsourcefieldnb = array();
1079 $listofkeys = array();
1080 foreach ($array_match_file_to_database as $key => $val) {
1081 $listofkeys[$key] = 1;
1084 print
"\n<!-- Box left container -->\n";
1085 print
'<div id="left" class="connectedSortable">'.
"\n";
1090 foreach ($fieldssource as $key => $val) {
1093 $listofkeys[$key] = 1;
1094 $fieldsplaced[$key] = 1;
1095 $valforsourcefieldnb[$lefti] = $key;
1105 print
"<!-- End box left container -->\n";
1108 print
'</td><td width="50%" class="nopaddingrightimp">';
1112 $optionsall = array();
1113 foreach ($fieldstarget as $code => $line) {
1114 $tmparray = explode(
'|', $line[
"label"]);
1116 foreach ($tmparray as $tmpkey => $tmpval) {
1117 $labeltoshow .= ($labeltoshow ?
' '.$langs->trans(
'or').
' ' :
'').$langs->transnoentities($tmpval);
1122 $optionsall[$code] = array(
1123 'labelkey' => $line[
'label'],
1124 'labelkeyarray' => $tmparray,
1125 'label' => $labeltoshow,
1126 'required' => (empty($line[
"required"]) ? 0 : 1),
1127 'position' => (!empty($line[
'position']) ? $line[
'position'] : 0),
1135 $mandatoryfieldshavesource =
true;
1148 $modetoautofillmapping =
'session';
1149 if ($initialloadofstep4) {
1150 $modetoautofillmapping =
'guess';
1154 print
'<table class="nobordernopadding centpercent tableimport">';
1155 foreach ($fieldssource as $code => $line) {
1159 print
'<tr style="height:'.$height.
'" class="trimport oddevenimport">';
1161 $entity = (!empty($objimport->array_import_entities[0][$code]) ? $objimport->array_import_entities[0][$code] : $objimport->array_import_icon[0]);
1163 $entityicon = !empty($entitytoicon[$entity]) ? $entitytoicon[$entity] : $entity;
1164 $entitylang = !empty($entitytolang[$entity]) ? $entitytolang[$entity] : $objimport->array_import_label[0];
1166 print
'<td class="nowraponall hideonsmartphone" style="font-weight: normal">=> </td>';
1167 print
'<td class="nowraponall" style="font-weight: normal">';
1169 $selectforline =
'';
1170 $selectforline .=
'<select id="selectorderimport_'.($i + 1).
'" class="targetselectchange minwidth300" name="select_'.($i + 1).
'">';
1171 if (!empty($line[
"imported"])) {
1172 $selectforline .=
'<option value="-1"> </option>';
1174 $selectforline .=
'<option selected="" value="-1"> </option>';
1178 $codeselectedarray = array();
1179 foreach ($optionsall as $tmpcode => $tmpval) {
1181 if (!empty($tmpval[
'picto'])) {
1182 $label .=
img_picto(
'', $tmpval[
'picto'],
'class="pictofixedwidth"');
1184 $label .= $tmpval[
'required'] ?
'<strong>' :
'';
1185 $label .= $tmpval[
'label'];
1186 $label .= $tmpval[
'required'] ?
'*</strong>' :
'';
1188 $tablealias = preg_replace(
'/(\..*)$/i',
'', $tmpcode);
1189 $tablename = !empty($objimport->array_import_tables[0][$tablealias]) ? $objimport->array_import_tables[0][$tablealias] :
"";
1193 $filecolumn = ($i + 1);
1195 if (empty($objimport->array_import_convertvalue[0][$tmpcode])) {
1198 if ($objimport->array_import_convertvalue[0][$tmpcode][
'rule'] ==
'fetchidfromref') {
1199 $htmltext .= $langs->trans(
"DataComeFromIdFoundFromRef", $langs->transnoentitiesnoconv($entitylang)).
'<br>';
1201 if ($objimport->array_import_convertvalue[0][$tmpcode][
'rule'] ==
'fetchidfromcodeid') {
1202 $htmltext .= $langs->trans(
"DataComeFromIdFoundFromCodeId", $langs->transnoentitiesnoconv($objimport->array_import_convertvalue[0][$tmpcode][
'dict'])).
'<br>';
1206 $example = !empty($objimport->array_import_examplevalues[0][$tmpcode]) ? $objimport->array_import_examplevalues[0][$tmpcode] :
"";
1208 if (empty($objimport->array_import_convertvalue[0][$tmpcode])) {
1210 $htmltext .= $langs->trans(
"SourceExample").
': <b>'.str_replace(
'"',
'', $example).
'</b><br>';
1213 if ($objimport->array_import_convertvalue[0][$tmpcode][
'rule'] ==
'fetchidfromref') {
1214 $htmltext .= $langs->trans(
"SourceExample").
': <b>'.$langs->transnoentitiesnoconv(
"ExampleAnyRefFoundIntoElement", $entitylang).($example ?
' ('.$langs->transnoentitiesnoconv(
"Example").
': '.str_replace(
'"',
'', $example).
')' :
'').
'</b><br>';
1215 } elseif ($objimport->array_import_convertvalue[0][$tmpcode][
'rule'] ==
'fetchidfromcodeid') {
1216 $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>';
1217 } elseif ($example) {
1218 $htmltext .= $langs->trans(
"SourceExample").
': <b>'.str_replace(
'"',
'', $example).
'</b><br>';
1222 if (!empty($objimport->array_import_regex[0][$tmpcode])) {
1223 $htmltext .= $langs->trans(
"FormatControlRule").
': <b>'.str_replace(
'"',
'', $objimport->array_import_regex[0][$tmpcode]).
'</b><br>';
1227 $htmltext .= $langs->trans(
"InformationOnTargetTables").
': <b>'.$tablename.
"->".preg_replace(
'/^.*\./',
'', $tmpcode).
"</b>";
1229 $labelhtml = $label.
' '.$form->textwithpicto(
'', $htmltext, 1,
'help',
'', 1);
1231 $selectforline .=
'<option value="'.$tmpcode.
'"';
1232 if ($modetoautofillmapping ==
'orderoftargets') {
1235 $selectforline .=
' selected';
1237 } elseif ($modetoautofillmapping ==
'guess') {
1241 if (preg_match(
'/^(.+)\((.+\..+)\)$/', $line[
'example1'], $regs)) {
1242 $tmpstring1 = $regs[1];
1243 $tmpstring2 = $regs[2];
1245 $tmpstring1 = $line[
'example1'];
1253 foreach ($tmpval[
'labelkeyarray'] as $tmpval2) {
1254 $labeltarget = $langs->transnoentities($tmpval2);
1256 if ($tmpstring1 && ($tmpstring1 == $tmpcode || $tmpstring1 == strtolower($labeltarget)
1257 || $tmpstring1 == strtolower(
dol_string_unaccent($labeltarget)) || $tmpstring1 == strtolower($tmpval2))) {
1258 if (empty($codeselectedarray[$code])) {
1259 $selectforline .=
' selected';
1260 $codeselectedarray[$code] = 1;
1263 } elseif ($tmpstring2 && ($tmpstring2 == $tmpcode || $tmpstring2 == strtolower($labeltarget)
1264 || $tmpstring2 == strtolower(
dol_string_unaccent($labeltarget)) || $tmpstring2 == strtolower($tmpval2))) {
1265 if (empty($codeselectedarray[$code])) {
1266 $selectforline .=
' selected';
1267 $codeselectedarray[$code] = 1;
1272 } elseif ($modetoautofillmapping ==
'session' && !empty($_SESSION[
'dol_array_match_file_to_database_select'])) {
1273 $tmpselectioninsession =
dolExplodeIntoArray($_SESSION[
'dol_array_match_file_to_database_select'],
',',
'=');
1275 if (!empty($tmpselectioninsession[(
string) ($i + 1)]) && $tmpselectioninsession[(
string) ($i + 1)] == $tmpcode) {
1276 $selectforline .=
' selected';
1278 $selectforline .=
' data-debug="'.$tmpcode.
'-'.$code.
'-'.$j.
'-'.(!empty($tmpselectioninsession[(
string) ($i + 1)]) ? $tmpselectioninsession[(string) ($i + 1)] :
"").
'"';
1280 $selectforline .=
' data-html="'.dol_escape_htmltag($labelhtml).
'"';
1281 $selectforline .=
'>';
1282 $selectforline .= $label;
1283 $selectforline .=
'</options>';
1286 $selectforline .=
'</select>';
1287 $selectforline .=
ajax_combobox(
'selectorderimport_'.($i + 1));
1289 print $selectforline;
1294 print
'<td class="nowraponall" style="font-weight:normal; text-align:right">';
1297 $htmltext =
'<b><u>'.$langs->trans(
"FieldSource").
'</u></b><br>';
1299 $htmltext .= $langs->trans(
"DataComeFromFileFieldNb", $filecolumntoshow).
'<br>';
1301 print $form->textwithpicto(
'', $htmltext);
1312 print
'<tr class="liste_titre"><td colspan="2">'.$langs->trans(
"Note").
'</td></tr>';
1313 print
'<tr><td colspan="2"><div id="div-mandatory-target-fields-not-mapped"></div></td></tr>';
1319 if (!empty(
$conf->use_javascript_ajax)) {
1320 print
'<script type="text/javascript">'.
"\n";
1321 print
'var previousselectedvalueimport = "0";'.
"\n";
1322 print
'var previousselectedlabelimport = "0";'.
"\n";
1323 print
'var arrayofselectedvalues = [];'.
"\n";
1324 print
'var arrayoftargetfields = [];'.
"\n";
1325 print
'var arrayoftargetmandatoryfields = [];'.
"\n";
1329 foreach ($fieldstarget as $key => $val) {
1330 print
"arrayoftargetfields[".$tmpi.
"] = '".
dol_escape_js($langs->trans($val[
'label'])).
"'; ";
1331 if ($val[
'required']) {
1332 print
"arrayoftargetmandatoryfields[".$tmpi.
"] = '".
dol_escape_js($key).
"'; ";
1338 print
'$(document).ready(function () {'.
"\n";
1340 print
'setOptionsToDisabled();'.
"\n";
1341 print
'saveSelection();'.
"\n";
1343 print
'$(".targetselectchange").focus(function(){'.
"\n";
1344 print
' previousselectedvalueimport = $(this).val();'.
"\n";
1345 print
' previousselectedlabelimport = $(this).children("option:selected").text();'.
"\n";
1346 print
' console.log("previousselectedvalueimport="+previousselectedvalueimport)'.
"\n";
1353 print
'function setOptionsToDisabled() {'.
"\n";
1354 print
' console.log("Remove the disabled flag everywhere");'.
"\n";
1355 print
' $("select.targetselectchange").not($( this )).find(\'option\').prop("disabled", false);'.
"\n";
1356 print
' arrayofselectedvalues = [];'.
"\n";
1358 print
' $("select.targetselectchange").each(function(){'.
"\n";
1359 print
' id = $(this).attr(\'id\')'.
"\n";
1360 print
' value = $(this).val()'.
"\n";
1361 print
' console.log("a selected value has been found for component "+id+" = "+value);'.
"\n";
1362 print
' arrayofselectedvalues.push(value);'.
"\n";
1365 print
' console.log("List of all selected values arrayofselectedvalues");'.
"\n";
1366 print
' console.log(arrayofselectedvalues);'.
"\n";
1367 print
' console.log("Set the option to disabled for every entry that is currently selected somewhere else (so into arrayofselectedvalues)");'.
"\n";
1369 print
' $.each(arrayofselectedvalues, function(key, value) {'.
"\n";
1370 print
' if (value != -1) {'.
"\n";
1371 print
' console.log("Process key="+key+" value="+value+" to disable.");'.
"\n";
1372 print
' $("select.targetselectchange").find(\'option[value="\'+value+\'"]:not(:selected)\').prop("disabled", true);'.
"\n";
1378 print
'function saveSelection() {'.
"\n";
1380 print
' arrayselectedfields = [];'.
"\n";
1381 print
' arrayselectedfields.push(0);'.
"\n";
1383 print
' $.each( arrayofselectedvalues, function( key, value ) {'.
"\n";
1384 print
' if (value != -1) {'.
"\n";
1385 print
' arrayselectedfields.push(value);'.
"\n";
1386 print
' } else {'.
"\n";
1387 print
' arrayselectedfields.push(0);'.
"\n";
1391 print
" $.ajax({\n";
1392 print
" type: 'POST',\n";
1393 print
" dataType: 'json',\n";
1394 print
" url: '".dol_escape_js($_SERVER[
"PHP_SELF"]).
"?action=saveselectorder&token=".
newToken().
"',\n";
1395 print
" data: 'selectorder='+arrayselectedfields.toString(),\n";
1396 print
" success: function(){\n";
1397 print
" console.log('The selected fields have been saved into '+arrayselectedfields.toString());\n";
1402 print
' console.log("arrayselectedfields");';
1403 print
' console.log(arrayselectedfields);';
1404 print
' console.log("arrayoftargetmandatoryfields");';
1405 print
' console.log(arrayoftargetmandatoryfields);';
1406 print
" listtoshow = '';";
1407 print
" nbelement = arrayoftargetmandatoryfields.length
1408 for (let i = 0; i < nbelement; i++) {
1409 if (arrayoftargetmandatoryfields[i] && ! arrayselectedfields.includes(arrayoftargetmandatoryfields[i])) {
1410 console.log(arrayoftargetmandatoryfields[i]+' not mapped');
1411 listtoshow = listtoshow + (listtoshow ? ', ' : '') + '<b>' + arrayoftargetfields[i] + '*</b>';
1414 console.log(listtoshow);
1416 listtoshow = '".dol_escape_js(
img_warning($langs->trans(
"MandatoryTargetFieldsNotMapped")).
' '.$langs->trans(
"MandatoryTargetFieldsNotMapped")).
": ' + listtoshow;
1417 $('#div-mandatory-target-fields-not-mapped').html(listtoshow);
1419 $('#div-mandatory-target-fields-not-mapped').html('<span class=\"opacitymedium\">".
dol_escape_js($langs->trans(
"AllTargetMandatoryFieldsAreMapped")).
"</span>');
1426 print
'$(".targetselectchange").change(function(){'.
"\n";
1427 print
' setOptionsToDisabled();'.
"\n";
1429 print
' if(previousselectedlabelimport != "" && previousselectedvalueimport != -1) {'.
"\n";
1430 print
' let valuetochange = $(this).val(); '.
"\n";
1431 print
' $(".boxtdunused").each(function(){'.
"\n";
1432 print
' if ($(this).text().includes(valuetochange)){'.
"\n";
1433 print
' arraychild = $(this)[0].childNodes'.
"\n";
1434 print
' arraytexttomodify = arraychild[0].textContent.split(" ")'.
"\n";
1435 print
' arraytexttomodify[1] = previousselectedvalueimport '.
"\n";
1436 print
' textmodified = arraytexttomodify.join(" ") '.
"\n";
1437 print
' arraychild[0].textContent = textmodified'.
"\n";
1438 print
' arraychild[1].innerHTML = previousselectedlabelimport'.
"\n";
1442 print
' $(this).blur()'.
"\n";
1444 print
' saveSelection()'.
"\n";
1448 print
'</script>'.
"\n";
1454 print
'<div class="tabsAction">';
1456 if (count($array_match_file_to_database)) {
1457 if ($mandatoryfieldshavesource) {
1458 print
'<a class="butAction saveorderselect" href="import.php?step=5'.$param.
'&filetoimport='.urlencode($filetoimport).
'">'.$langs->trans(
"NextStep").
'</a>';
1460 print
'<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->transnoentitiesnoconv(
"SomeMandatoryFieldHaveNoSource")).
'">'.$langs->trans(
"NextStep").
'</a>';
1468 if (count($array_match_file_to_database)) {
1470 print
'<!-- Area to add new import profile -->'.
"\n";
1471 print
'<div class="marginbottomonly"><span class="opacitymedium">'.$langs->trans(
"SaveImportModel").
'</span></div>';
1473 print
'<form class="nocellnopadd" action="'.$_SERVER[
"PHP_SELF"].
'" method="post">';
1474 print
'<input type="hidden" name="token" value="'.newToken().
'">';
1475 print
'<input type="hidden" name="action" value="add_import_model">';
1476 print
'<input type="hidden" name="step" value="'.$step.
'">';
1477 print
'<input type="hidden" name="format" value="'.$format.
'">';
1478 print
'<input type="hidden" name="datatoimport" value="'.$datatoimport.
'">';
1479 print
'<input type="hidden" name="filetoimport" value="'.$filetoimport.
'">';
1480 print
'<input type="hidden" name="hexa" value="'.$hexa.
'">';
1481 print
'<input type="hidden" name="excludefirstline" value="'.$excludefirstline.
'">';
1482 print
'<input type="hidden" name="endatlinenb" value="'.$endatlinenb.
'">';
1483 print
'<input type="hidden" name="page_y" value="">';
1484 print
'<input type="hidden" value="'.dol_escape_htmltag($separator).
'" name="separator">';
1485 print
'<input type="hidden" value="'.dol_escape_htmltag($enclosure).
'" name="enclosure">';
1487 print
'<div class="div-table-responsive-no-min">';
1488 print
'<table summary="selectofimportprofil" class="noborder centpercent">';
1489 print
'<tr class="liste_titre">';
1490 print
'<td>'.$langs->trans(
"ImportModelName").
'</td>';
1491 print
'<td>'.$langs->trans(
"Visibility").
'</td>';
1495 $nameofimportprofile = str_replace(
' ',
'-', $langs->trans(
"ImportProfile").
' '.$titleofmodule.
' '.
dol_print_date(
dol_now(
'gmt'),
'dayxcard'));
1497 $nameofimportprofile = $import_name;
1500 print
'<tr class="oddeven">';
1501 print
'<td><input name="import_name" class="minwidth300" value="'.$nameofimportprofile.
'"></td>';
1503 $arrayvisibility = array(
'private' => $langs->trans(
"Private"),
'all' => $langs->trans(
"Everybody"));
1504 print $form->selectarray(
'visibility', $arrayvisibility,
'private');
1506 print
'<td class="right">';
1507 print
'<input type="submit" class="button smallpaddingimp reposition" value="'.$langs->trans(
"SaveImportProfile").
'">';
1511 $sql =
"SELECT rowid, label, fk_user, entity";
1512 $sql .=
" FROM ".MAIN_DB_PREFIX.
"import_model";
1513 $sql .=
" WHERE type = '".$db->escape($datatoimport).
"'";
1515 $sql .=
" AND fk_user IN (0, ".((int) $user->id).
")";
1517 $sql .=
" ORDER BY rowid";
1519 $resql = $db->query($sql);
1521 $num = $db->num_rows($resql);
1523 $tmpuser =
new User($db);
1527 $obj = $db->fetch_object($resql);
1529 print
'<tr class="oddeven"><td>';
1532 print
'<td class="tdoverflowmax150">';
1533 if (empty($obj->fk_user)) {
1534 print $langs->trans(
"Everybody");
1536 $tmpuser->fetch($obj->fk_user);
1537 print $tmpuser->getNomUrl(-1);
1540 print
'<td class="right">';
1541 print
'<a class="reposition" href="'.$_SERVER[
"PHP_SELF"].
'?step='.$step.$param.
'&action=deleteprof&token='.
newToken().
'&id='.$obj->rowid.
'&filetoimport='.urlencode($filetoimport).
'">';
1559if ($step == 5 && $datatoimport) {
1560 $max_execution_time_for_importexport =
getDolGlobalInt(
'IMPORT_MAX_EXECUTION_TIME', 300);
1561 $max_time = @ini_get(
"max_execution_time");
1562 if ($max_time && $max_time < $max_execution_time_for_importexport) {
1563 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.");
1564 @ini_set(
"max_execution_time", $max_execution_time_for_importexport);
1568 $list = $objmodelimport->listOfAvailableImportFormat($db);
1571 $dir = DOL_DOCUMENT_ROOT.
"/core/modules/import/";
1572 $file =
"import_".$model.
".modules.php";
1573 $classname =
"Import".ucfirst($model);
1574 require_once $dir.$file;
1575 $obj =
new $classname($db, $datatoimport);
1576 '@phan-var-force ModeleImports $obj';
1577 if ($model ==
'csv') {
1578 '@phan-var-force ImportCsv $obj';
1579 $obj->separator = $separator_used;
1580 $obj->enclosure = $enclosure;
1584 $fieldssource = array();
1585 $result = $obj->import_open_file(
$conf->import->dir_temp.
'/'.$filetoimport);
1589 $arrayrecord = $obj->import_read_record();
1592 foreach ($arrayrecord as $key => $val) {
1593 $fieldssource[$i][
'example1'] =
dol_trunc($val[
'val'], 24);
1596 $obj->import_close_file();
1599 $nboflines = $obj->import_get_nb_of_lines(
$conf->import->dir_temp.
'/'.$filetoimport);
1601 $param =
'&leftmenu=import&format='.urlencode($format).
'&datatoimport='.urlencode($datatoimport).
'&filetoimport='.urlencode($filetoimport).
'&nboflines='.((int) $nboflines).
'&separator='.urlencode($separator).
'&enclosure='.urlencode($enclosure);
1603 if ($excludefirstline) {
1604 $param .=
'&excludefirstline='.urlencode($excludefirstline);
1607 $param .=
'&endatlinenb='.urlencode($endatlinenb);
1609 if (!empty($updatekeys)) {
1610 $param .=
'&updatekeys[]='.implode(
'&updatekeys[]=', $updatekeys);
1613 llxHeader(
'', $langs->trans(
"NewImport"), $help_url);
1618 print
'<form action="'.$_SERVER[
"PHP_SELF"].
'?'.$param2.
'" method="POST">';
1619 print
'<input type="hidden" name="token" value="'.newToken().
'">';
1620 print
'<input type="hidden" name="step" value="5">';
1621 print
'<input type="hidden" name="action" value="launchsimu">';
1625 print
'<div class="underbanner clearboth"></div>';
1626 print
'<div class="fichecenter">';
1628 print
'<table width="100%" class="border tableforfield">';
1631 print
'<tr><td class="titlefieldcreate">'.$langs->trans(
"Module").
'</td>';
1633 $titleofmodule = $objimport->array_import_module[0][
'module']->getName();
1635 if (in_array($objimport->array_import_code[0], array(
'produit_supplierprices',
'produit_multiprice',
'produit_languages'))) {
1636 $titleofmodule = $langs->trans(
"ProductOrService");
1638 print $titleofmodule;
1642 print
'<tr><td>'.$langs->trans(
"DatasetToImport").
'</td>';
1644 $entity = preg_replace(
'/:.*$/',
'', $objimport->array_import_icon[0]);
1645 $entityicon = strtolower(!empty($entitytoicon[$entity]) ? $entitytoicon[$entity] : $entity);
1646 print
img_object($objimport->array_import_module[0][
'module']->getName(), $entityicon).
' ';
1647 print $objimport->array_import_label[0];
1655 print
load_fiche_titre($langs->trans(
"InformationOnSourceFile"),
'',
'file-export');
1657 print
'<div class="underbanner clearboth"></div>';
1658 print
'<div class="fichecenter">';
1659 print
'<table width="100%" class="border tableforfield">';
1662 print
'<tr><td class="titlefieldcreate">'.$langs->trans(
"SourceFileFormat").
'</td>';
1663 print
'<td class="nowraponall">';
1664 $text = $objmodelimport->getDriverDescForKey($format);
1666 print $form->textwithpicto($objmodelimport->getDriverLabelForKey($format), $text);
1670 if ($model ==
'csv') {
1671 '@phan-var-force ImportCsv $obj';
1672 print
'<tr><td>'.$langs->trans(
"CsvOptions").
'</td>';
1675 print
' '.$langs->trans(
"Enclosure").
' : '.
dol_escape_htmltag($enclosure);
1680 print
'<tr><td>'.$langs->trans(
"FileToImport").
'</td>';
1682 $modulepart =
'import';
1683 $relativepath =
GETPOST(
'filetoimport');
1684 print
'<a data-ajax="false" href="'.DOL_URL_ROOT.
'/document.php?modulepart='.$modulepart.
'&file='.urlencode($relativepath).
'&step=4'.$param.
'" target="_blank" rel="noopener noreferrer">';
1685 print
img_mime($file,
'',
'pictofixedwidth');
1686 print $filetoimport;
1687 print
img_picto($langs->trans(
"Download"),
'download',
'class="paddingleft opacitymedium"');
1693 print $langs->trans(
"NbOfSourceLines");
1700 print $langs->trans(
"ImportFromToLine");
1702 if ($action ==
'launchsimu') {
1703 print
'<input type="number" class="maxwidth50 right" name="excludefirstlinebis" disabled="disabled" value="'.$excludefirstline.
'">';
1704 print
'<input type="hidden" name="excludefirstline" value="'.$excludefirstline.
'">';
1706 print
'<input type="number" class="maxwidth50 right" name="excludefirstline" value="'.$excludefirstline.
'">';
1707 print $form->textwithpicto(
"", $langs->trans(
"SetThisValueTo2ToExcludeFirstLine"));
1710 if ($action ==
'launchsimu') {
1711 print
'<input type="text" class="maxwidth50" name="endatlinenbbis" disabled="disabled" value="'.$endatlinenb.
'">';
1712 print
'<input type="hidden" name="endatlinenb" value="'.$endatlinenb.
'">';
1714 print
'<input type="text" class="maxwidth50" name="endatlinenb" value="'.$endatlinenb.
'">';
1715 print $form->textwithpicto(
"", $langs->trans(
"KeepEmptyToGoToEndOfFile"));
1717 if ($action ==
'launchsimu') {
1718 print
' <a href="'.$_SERVER[
"PHP_SELF"].
'?step=5'.$param.
'">'.$langs->trans(
"Modify").
'</a>';
1720 if ($excludefirstline == 2) {
1721 print $form->textwithpicto(
"", $langs->trans(
"WarningFirstImportedLine", $excludefirstline), 1,
'warning',
"warningexcludefirstline");
1723 $( document ).ready(function() {
1724 $("input[name=\'excludefirstline\']").on("change",function(){
1725 if($(this).val() <= 1){
1726 $(".warningexcludefirstline").hide();
1728 $(".warningexcludefirstline").show();
1738 print $form->textwithpicto($langs->trans(
"KeysToUseForUpdates"), $langs->trans(
"SelectPrimaryColumnsForUpdateAttempt"));
1740 if ($action ==
'launchsimu') {
1741 if (count($updatekeys)) {
1742 print $form->multiselectarray(
'updatekeysbis', $objimport->array_import_updatekeys[0], $updatekeys, 0, 0,
'', 1,
'80%',
'disabled');
1744 print
'<span class="opacitymedium">'.$langs->trans(
"NoUpdateAttempt").
'</span> -';
1746 foreach ($updatekeys as $val) {
1747 print
'<input type="hidden" name="updatekeys[]" value="'.$val.
'">';
1749 print
' <a href="'.$_SERVER[
"PHP_SELF"].
'?step=5'.$param.
'">'.$langs->trans(
"Modify").
'</a>';
1751 if (is_array($objimport->array_import_updatekeys[0]) && count($objimport->array_import_updatekeys[0])) {
1752 print $form->multiselectarray(
'updatekeys', $objimport->array_import_updatekeys[0], $updatekeys, 0, 0,
'', 1,
'80%');
1755 print
'<span class="opacitymedium">'.$langs->trans(
"UpdateNotYetSupportedForThisImport").
'</span>';
1768 print
load_fiche_titre($langs->trans(
"InformationOnTargetTables"),
'',
'file-import');
1770 print
'<div class="underbanner clearboth"></div>';
1771 print
'<div class="fichecenter">';
1773 print
'<table width="100%" class="border tableforfield">';
1776 print
'<tr><td class="titlefieldcreate">';
1777 print $langs->trans(
"TablesTarget");
1779 $listtables = array();
1780 $sort_array_match_file_to_database = $array_match_file_to_database;
1781 foreach ($array_match_file_to_database as $code => $label) {
1783 if ($code > count($fieldssource)) {
1787 $alias = preg_replace(
'/(\..*)$/i',
'', $label);
1788 $listtables[$alias] = $objimport->array_import_tables[0][$alias];
1790 if (count($listtables)) {
1793 foreach ($listtables as $val) {
1812 print $langs->trans(
"Error");
1818 print $langs->trans(
"FieldsTarget").
'</td><td>';
1819 $listfields = array();
1822 $sort_array_match_file_to_database = $array_match_file_to_database;
1823 ksort($sort_array_match_file_to_database);
1825 foreach ($sort_array_match_file_to_database as $code => $label) {
1828 if ($code > count($fieldssource)) {
1832 $alias = preg_replace(
'/(\..*)$/i',
'', $label);
1833 $listfields[$i] =
'<span class="nowrap">'.$langs->trans(
"Column").
' '.
num2Alpha((
int) $code - 1).
' -> '.$label.
'</span>';
1835 print count($listfields) ? (implode(
', ', $listfields)) : $langs->trans(
"Error");
1844 if ($action !=
'launchsimu') {
1846 print
'<br><span class="opacitymedium">';
1847 print $langs->trans(
"NowClickToTestTheImport", $langs->transnoentitiesnoconv(
"RunSimulateImportFile")).
'</span><br>';
1851 print
'<div class="center">';
1852 if ($user->hasRight(
'import',
'run')) {
1853 print
'<input type="submit" class="butAction" value="'.$langs->trans(
"RunSimulateImportFile").
'">';
1855 print
'<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->transnoentitiesnoconv(
"NotEnoughPermissions")).
'">'.$langs->trans(
"RunSimulateImportFile").
'</a>';
1860 $arrayoferrors = array();
1861 $arrayofwarnings = array();
1862 $maxnboferrors = !
getDolGlobalString(
'IMPORT_MAX_NB_OF_ERRORS') ? 50 :
$conf->global->IMPORT_MAX_NB_OF_ERRORS;
1863 $maxnbofwarnings = !
getDolGlobalString(
'IMPORT_MAX_NB_OF_WARNINGS') ? 50 :
$conf->global->IMPORT_MAX_NB_OF_WARNINGS;
1875 $pathfile =
$conf->import->dir_temp.
'/'.$filetoimport;
1876 $result = $obj->import_open_file($pathfile);
1878 global $tablewithentity_cache;
1879 $tablewithentity_cache = array();
1884 while (($sourcelinenb < $nboflines) && !$endoffile) {
1888 $arrayrecord = $obj->import_read_record();
1889 if ($arrayrecord ===
false) {
1890 $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');
1894 if ($excludefirstline && ($sourcelinenb < $excludefirstline)) {
1897 if ($endatlinenb && ($sourcelinenb > $endatlinenb)) {
1901 $parameters = array(
1903 'datatoimport' => $datatoimport,
1905 'arrayrecord' => $arrayrecord,
1906 'array_match_file_to_database' => $array_match_file_to_database,
1907 'objimport' => $objimport,
1908 'fieldssource' => $fieldssource,
1909 'importid' => $importid,
1910 'updatekeys' => $updatekeys,
1911 'arrayoferrors' => &$arrayoferrors,
1912 'arrayofwarnings' => &$arrayofwarnings,
1916 $reshook = $hookmanager->executeHooks(
'ImportInsert', $parameters);
1918 $arrayoferrors[$sourcelinenb][] = [
1919 'lib' => implode(
"<br>", array_merge([$hookmanager->error], $hookmanager->errors))
1923 if (empty($reshook)) {
1925 $result = $obj->import_insert($arrayrecord, $array_match_file_to_database, $objimport, count($fieldssource), $importid, $updatekeys);
1927 if (count($obj->errors)) {
1928 $arrayoferrors[$sourcelinenb] = $obj->errors;
1930 if (count($obj->warnings)) {
1931 $arrayofwarnings[$sourcelinenb] = $obj->warnings;
1933 if (!count($obj->errors) && !count($obj->warnings)) {
1938 $reshook = $hookmanager->executeHooks(
'AfterImportInsert', $parameters);
1940 $arrayoferrors[$sourcelinenb][] = [
1941 'lib' => implode(
"<br>", array_merge([$hookmanager->error], $hookmanager->errors))
1946 $obj->import_close_file();
1948 print $langs->trans(
"ErrorFailedToOpenFile", $pathfile);
1955 if (!empty($objimport->array_import_run_sql_after[0]) && is_array($objimport->array_import_run_sql_after[0])) {
1957 foreach ($objimport->array_import_run_sql_after[0] as $sqlafterimport) {
1959 $resqlafterimport = $db->query($sqlafterimport);
1960 if (!$resqlafterimport) {
1961 $arrayoferrors[
'none'][] = array(
'lib' => $langs->trans(
"Error running final request: ".$sqlafterimport));
1970 if (!count($arrayoferrors) && !count($arrayofwarnings)) {
1972 print
'<div class="info">';
1973 print
'<div class=""><b>'.$langs->trans(
"ResultOfSimulationNoError").
'</b></div>';
1974 print $langs->trans(
"NbInsertSim", empty($obj->nbinsert) ? 0 : $obj->nbinsert).
'<br>';
1975 print $langs->trans(
"NbUpdateSim", empty($obj->nbupdate) ? 0 : $obj->nbupdate).
'<br>';
1980 print
'<div class="warning">';
1981 print $langs->trans(
"NbOfLinesOK", $nbok).
'...<br>';
1988 if (count($arrayoferrors)) {
1989 print
img_error().
' <b>'.$langs->trans(
"ErrorsOnXLines", count($arrayoferrors)).
'</b><br>';
1990 print
'<table width="100%" class="border"><tr><td>';
1991 foreach ($arrayoferrors as $key => $val) {
1993 if ($nboferrors > $maxnboferrors) {
1994 print $langs->trans(
"TooMuchErrors", (count($arrayoferrors) - $nboferrors)).
"<br>";
1998 foreach ($val as $i => $err) {
1999 print
' > '.dol_escape_htmltag($err[
'lib']).
'<br>';
2002 print
'</td></tr></table>';
2008 if (count($arrayofwarnings)) {
2009 print
img_warning().
' <b>'.$langs->trans(
"WarningsOnXLines", count($arrayofwarnings)).
'</b><br>';
2010 print
'<table width="100%" class="border"><tr><td>';
2011 foreach ($arrayofwarnings as $key => $val) {
2013 if ($nbofwarnings > $maxnbofwarnings) {
2014 print $langs->trans(
"TooMuchWarnings", (count($arrayofwarnings) - $nbofwarnings)).
"<br>";
2018 foreach ($val as $i => $err) {
2019 print
' > '.dol_escape_htmltag($err[
'lib']).
'<br>';
2022 print
'</td></tr></table>';
2029 print
'<div class="center">';
2030 print
'<span class="opacitymedium">'.$langs->trans(
"NowClickToRunTheImport", $langs->transnoentitiesnoconv(
"RunImportFile")).
'</span><br>';
2039 print
'<div class="center">';
2040 if ($user->hasRight(
'import',
'run')) {
2041 if (empty($nboferrors)) {
2042 print
'<a class="butAction" href="'.DOL_URL_ROOT.
'/imports/import.php?leftmenu=import&step=6&importid='.$importid.$param.
'">'.$langs->trans(
"RunImportFile").
'</a>';
2046 print
'<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->transnoentitiesnoconv(
"CorrectErrorBeforeRunningImport")).
'">'.$langs->trans(
"RunImportFile").
'</a>';
2049 print
'<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->transnoentitiesnoconv(
"NotEnoughPermissions")).
'">'.$langs->trans(
"RunSimulateImportFile").
'</a>';
2051 print
'<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->transnoentitiesnoconv(
"NotEnoughPermissions")).
'">'.$langs->trans(
"RunImportFile").
'</a>';
2061if ($step == 6 && $datatoimport) {
2062 $max_execution_time_for_importexport =
getDolGlobalInt(
'IMPORT_MAX_EXECUTION_TIME', 300);
2063 $max_time = @ini_get(
"max_execution_time");
2064 if ($max_time && $max_time < $max_execution_time_for_importexport) {
2065 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.");
2066 @ini_set(
"max_execution_time", $max_execution_time_for_importexport);
2070 $list = $objmodelimport->listOfAvailableImportFormat($db);
2071 $importid =
GETPOST(
"importid",
'alphanohtml');
2075 $dir = DOL_DOCUMENT_ROOT.
"/core/modules/import/";
2076 $file =
"import_".$model.
".modules.php";
2077 $classname =
"Import".ucfirst($model);
2078 require_once $dir.$file;
2079 $obj =
new $classname($db, $datatoimport);
2080 '@phan-var-force ModeleImports $obj';
2081 if ($model ==
'csv') {
2082 '@phan-var-force ImportCsv $obj';
2083 $obj->separator = $separator_used;
2084 $obj->enclosure = $enclosure;
2088 $fieldssource = array();
2089 $result = $obj->import_open_file(
$conf->import->dir_temp.
'/'.$filetoimport);
2092 $arrayrecord = $obj->import_read_record();
2095 foreach ($arrayrecord as $key => $val) {
2096 $fieldssource[$i][
'example1'] =
dol_trunc($val[
'val'], 24);
2099 $obj->import_close_file();
2104 $param =
'&format='.$format.
'&datatoimport='.urlencode($datatoimport).
'&filetoimport='.urlencode($filetoimport).
'&nboflines='.((int) $nboflines);
2105 if ($excludefirstline) {
2106 $param .=
'&excludefirstline='.urlencode($excludefirstline);
2109 $param .=
'&endatlinenb='.urlencode($endatlinenb);
2112 $param .=
'&separator='.urlencode($separator);
2115 $param .=
'&enclosure='.urlencode($enclosure);
2118 llxHeader(
'', $langs->trans(
"NewImport"), $help_url);
2124 print
'<div class="underbanner clearboth"></div>';
2125 print
'<div class="fichecenter">';
2127 print
'<table width="100%" class="border">';
2130 print
'<tr><td class="titlefieldcreate">'.$langs->trans(
"Module").
'</td>';
2132 $titleofmodule = $objimport->array_import_module[0][
'module']->getName();
2134 if (in_array($objimport->array_import_code[0], array(
'produit_supplierprices',
'produit_multiprice',
'produit_languages'))) {
2135 $titleofmodule = $langs->trans(
"ProductOrService");
2137 print $titleofmodule;
2141 print
'<tr><td>'.$langs->trans(
"DatasetToImport").
'</td>';
2143 $entity = preg_replace(
'/:.*$/',
'', $objimport->array_import_icon[0]);
2144 $entityicon = strtolower(!empty($entitytoicon[$entity]) ? $entitytoicon[$entity] : $entity);
2145 print
img_object($objimport->array_import_module[0][
'module']->getName(), $entityicon).
' ';
2146 print $objimport->array_import_label[0];
2154 print
load_fiche_titre($langs->trans(
"InformationOnSourceFile"),
'',
'file-export');
2156 print
'<div class="underbanner clearboth"></div>';
2157 print
'<div class="fichecenter">';
2158 print
'<table width="100%" class="border tableforfield">';
2161 print
'<tr><td class="titlefieldcreate">'.$langs->trans(
"SourceFileFormat").
'</td>';
2162 print
'<td class="nowraponall">';
2163 $text = $objmodelimport->getDriverDescForKey($format);
2165 print $form->textwithpicto($objmodelimport->getDriverLabelForKey($format), $text);
2169 if ($model ==
'csv') {
2170 '@phan-var-force ImportCsv $obj';
2171 print
'<tr><td>'.$langs->trans(
"CsvOptions").
'</td>';
2173 print $langs->trans(
"Separator").
' : ';
2174 print htmlentities($separator);
2175 print
' '.$langs->trans(
"Enclosure").
' : ';
2176 print htmlentities($enclosure);
2181 print
'<tr><td>'.$langs->trans(
"FileToImport").
'</td>';
2183 $modulepart =
'import';
2184 $relativepath =
GETPOST(
'filetoimport');
2185 print
'<a data-ajax="false" href="'.DOL_URL_ROOT.
'/document.php?modulepart='.$modulepart.
'&file='.urlencode($relativepath).
'&step=4'.$param.
'" target="_blank" rel="noopener noreferrer">';
2186 print
img_mime($file,
'',
'pictofixedwidth');
2187 print $filetoimport;
2193 print $langs->trans(
"NbOfSourceLines");
2200 print $langs->trans(
"ImportFromLine");
2202 print
'<input type="text" size="4" name="excludefirstline" disabled="disabled" value="'.$excludefirstline.
'">';
2207 print $langs->trans(
"EndAtLineNb");
2209 print
'<input type="text" size="4" name="endatlinenb" disabled="disabled" value="'.$endatlinenb.
'">';
2217 print
'<b>'.$langs->trans(
"InformationOnTargetTables").
'</b>';
2218 print
'<div class="underbanner clearboth"></div>';
2219 print
'<div class="fichecenter">';
2220 print
'<table class="border centpercent">';
2223 print
'<tr><td width="25%">';
2224 print $langs->trans(
"TablesTarget");
2226 $listtables = array();
2227 foreach ($array_match_file_to_database as $code => $label) {
2229 if ($code > count($fieldssource)) {
2233 $alias = preg_replace(
'/(\..*)$/i',
'', $label);
2234 $listtables[$alias] = $objimport->array_import_tables[0][$alias];
2236 if (count($listtables)) {
2238 foreach ($listtables as $val) {
2257 print $langs->trans(
"Error");
2263 print $langs->trans(
"FieldsTarget").
'</td><td>';
2264 $listfields = array();
2266 $sort_array_match_file_to_database = $array_match_file_to_database;
2267 ksort($sort_array_match_file_to_database);
2269 foreach ($sort_array_match_file_to_database as $code => $label) {
2272 if ($code > count($fieldssource)) {
2276 $alias = preg_replace(
'/(\..*)$/i',
'', $label);
2277 $listfields[$i] = $langs->trans(
"Field").
' '.$code.
'->'.$label;
2279 print count($listfields) ? (implode(
', ', $listfields)) : $langs->trans(
"Error");
2286 $arrayoferrors = array();
2287 $arrayofwarnings = array();
2288 $maxnboferrors = !
getDolGlobalString(
'IMPORT_MAX_NB_OF_ERRORS') ? 50 :
$conf->global->IMPORT_MAX_NB_OF_ERRORS;
2289 $maxnbofwarnings = !
getDolGlobalString(
'IMPORT_MAX_NB_OF_WARNINGS') ? 50 :
$conf->global->IMPORT_MAX_NB_OF_WARNINGS;
2301 $pathfile =
$conf->import->dir_temp.
'/'.$filetoimport;
2302 $result = $obj->import_open_file($pathfile);
2304 global $tablewithentity_cache;
2305 $tablewithentity_cache = array();
2309 while ($sourcelinenb < $nboflines && !$endoffile) {
2311 $arrayrecord = $obj->import_read_record();
2312 if ($arrayrecord ===
false) {
2313 $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');
2317 if ($excludefirstline && ($sourcelinenb < $excludefirstline)) {
2320 if ($endatlinenb && ($sourcelinenb > $endatlinenb)) {
2324 $parameters = array(
2326 'datatoimport' => $datatoimport,
2328 'arrayrecord' => $arrayrecord,
2329 'array_match_file_to_database' => $array_match_file_to_database,
2330 'objimport' => $objimport,
2331 'fieldssource' => $fieldssource,
2332 'importid' => $importid,
2333 'updatekeys' => $updatekeys,
2334 'arrayoferrors' => &$arrayoferrors,
2335 'arrayofwarnings' => &$arrayofwarnings,
2339 $reshook = $hookmanager->executeHooks(
'ImportInsert', $parameters);
2341 $arrayoferrors[$sourcelinenb][] = [
2342 'lib' => implode(
"<br>", array_merge([$hookmanager->error], $hookmanager->errors))
2346 if (empty($reshook)) {
2348 $result = $obj->import_insert($arrayrecord, $array_match_file_to_database, $objimport, count($fieldssource), $importid, $updatekeys);
2350 if (count($obj->errors)) {
2351 $arrayoferrors[$sourcelinenb] = $obj->errors;
2353 if (count($obj->warnings)) {
2354 $arrayofwarnings[$sourcelinenb] = $obj->warnings;
2357 if (!count($obj->errors) && !count($obj->warnings)) {
2362 $reshook = $hookmanager->executeHooks(
'AfterImportInsert', $parameters);
2364 $arrayoferrors[$sourcelinenb][] = [
2365 'lib' => implode(
"<br>", array_merge([$hookmanager->error], $hookmanager->errors))
2370 $obj->import_close_file();
2372 print $langs->trans(
"ErrorFailedToOpenFile", $pathfile);
2375 if (count($arrayoferrors) > 0) {
2382 if (!empty($objimport->array_import_run_sql_after[0]) && is_array($objimport->array_import_run_sql_after[0])) {
2384 foreach ($objimport->array_import_run_sql_after[0] as $sqlafterimport) {
2386 $resqlafterimport = $db->query($sqlafterimport);
2387 if (!$resqlafterimport) {
2388 $arrayoferrors[
'none'][] = array(
'lib' => $langs->trans(
"Error running final request: ".$sqlafterimport));
2406 print
'<div class="info">';
2407 print $langs->trans(
"NbOfLinesImported", $nbok).
'</b><br>';
2408 print $langs->trans(
"NbInsert", empty($obj->nbinsert) ? 0 : $obj->nbinsert).
'<br>';
2409 print $langs->trans(
"NbUpdate", empty($obj->nbupdate) ? 0 : $obj->nbupdate).
'<br>';
2411 print
'<div class="center">';
2412 print $langs->trans(
"FileWasImported", $importid).
'<br>';
2413 print
'<span class="opacitymedium">'.$langs->trans(
"YouCanUseImportIdToFindRecord", $importid).
'</span><br>';
2436 global
$conf, $langs;
2440 if ($key ==
'none') {
2442 print
"\n\n<!-- Box_no-key start-->\n";
2443 print
'<div class="box boximport" style="padding:0;">'.
"\n";
2444 print
'<table summary="boxtable_no-key" class="centpercent nobordernopadding">'.
"\n";
2446 print
"\n\n<!-- Box ".$pos.
" start -->\n";
2447 print
'<div class="box boximport" style="padding: 0;" id="boxto_'.$pos.
'">'.
"\n";
2449 print
'<table summary="boxtable'.$pos.
'" class="nobordernopadding centpercent tableimport">'.
"\n";
2452 if (($pos && $pos > count($fieldssource)) && (!isset($fieldssource[$pos][
"imported"]))) {
2462 } elseif ($key ==
'none') {
2463 print
'<tr style="height:'.$height.
'" class="trimport oddevenimport">';
2464 print
'<td class="nocellnopadd" width="16" style="font-weight: normal">';
2467 print
'<td style="font-weight: normal">';
2473 print
'<tr style="height:'.$height.
'" class="trimport oddevenimport">';
2474 print
'<td class="nocellnopadd" width="16" style="font-weight: normal">';
2477 print
img_picto($langs->trans(
"Column").
' '.
num2Alpha($pos - 1),
'file',
'class="pictofixedwidth"');
2479 if (isset($fieldssource[$pos][
'imported']) && $fieldssource[$pos][
'imported'] ==
false) {
2480 print
'<td class="nowraponall boxtdunused" style="font-weight: normal">';
2482 print
'<td class="nowraponall tdoverflowmax500" style="font-weight: normal">';
2484 print $langs->trans(
"Column").
' '.
num2Alpha($pos - 1).
' (#'.$pos.
')';
2485 if (empty($fieldssource[$pos][
'example1'])) {
2486 $example = $fieldssource[$pos][
'label'];
2488 $example = $fieldssource[$pos][
'example1'];
2492 $example = mb_convert_encoding($example,
'UTF-8',
'ISO-8859-1');
2496 print
'<i class="opacitymedium">'.dol_escape_htmltag($example).
'</i>';
2505 print
"<!-- Box end -->\n\n";
2518 $i = count($fieldssource) + 1;
2521 foreach ($listofkey as $key => $val) {
2522 $maxkey = max($maxkey, $key);
2525 while ($i <= $maxkey) {
2526 if (empty($listofkey[$i])) {
2548 if ($position == count($array)) {
2549 $ret = $array + $insertArray;
2552 foreach ($array as $key => $value) {
2553 if ($position == $i++) {
2554 $ret += $insertArray;
2557 $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_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.
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.
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.
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.
img_object($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $allowothertags=array())
Show a picto called object_picto (generic function)
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.