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];
565 print
load_fiche_titre($langs->trans(
"InformationOnSourceFile"),
'',
'file-export');
567 print
'<div class="underbanner clearboth"></div>';
568 print
'<div class="fichecenter">';
569 print
'<table width="100%" class="border tableforfield">';
572 print
'<tr><td class="titlefieldcreate">'.$langs->trans(
"SourceFileFormat").
'</td>';
573 print
'<td class="nowraponall">';
574 $text = $objmodelimport->getDriverDescForKey($format);
576 print $form->textwithpicto($objmodelimport->getDriverLabelForKey($format), $text);
577 print
'</td><td style="text-align:right" class="nowrap">';
578 $filename = $langs->transnoentitiesnoconv(
"ExampleOfImportFile").
'_'.$datatoimport.
'.'.$format;
579 print
'<a href="'.DOL_URL_ROOT.
'/imports/emptyexample.php?format='.$format.$param.
'&output=file&file='.urlencode($filename).
'" target="_blank" rel="noopener noreferrer">';
580 print
img_picto(
'',
'download',
'class="paddingright opacitymedium"');
581 print $langs->trans(
"DownloadEmptyExampleShort");
583 print $form->textwithpicto(
'', $langs->trans(
"DownloadEmptyExample").
'.<br>'.$langs->trans(
"StarAreMandatory"));
592 if ($format ==
'xlsx' && !class_exists(
'XMLWriter')) {
593 $langs->load(
"install");
594 print
info_admin($langs->trans(
"ErrorPHPDoesNotSupport",
'php-xml'), 0, 0,
'1',
'error');
600 print
'<form name="userfile" action="'.$_SERVER[
"PHP_SELF"].
'" enctype="multipart/form-data" method="POST">';
601 print
'<input type="hidden" name="token" value="'.newToken().
'">';
602 print
'<input type="hidden" value="'.$step.
'" name="step">';
603 print
'<input type="hidden" value="'.dol_escape_htmltag($format).
'" name="format">';
604 print
'<input type="hidden" value="'.$excludefirstline.
'" name="excludefirstline">';
605 print
'<input type="hidden" value="'.$endatlinenb.
'" name="endatlinenb">';
606 print
'<input type="hidden" value="'.dol_escape_htmltag($separator).
'" name="separator">';
607 print
'<input type="hidden" value="'.dol_escape_htmltag($enclosure).
'" name="enclosure">';
608 print
'<input type="hidden" value="'.dol_escape_htmltag($datatoimport).
'" name="datatoimport">';
610 print
'<span class="opacitymedium">';
611 $s = $langs->trans(
"ChooseFileToImport",
'{s1}');
612 $s = str_replace(
'{s1}',
img_picto(
'',
'next'), $s);
614 print
'</span><br><br>';
619 print
'<div class="marginbottomonly">';
621 $maxmin = $maxfilesizearray[
'maxmin'];
623 print
'<input type="hidden" name="MAX_FILE_SIZE" value="'.($maxmin * 1024).
'">';
625 print
'<input type="file" name="userfile" size="20" maxlength="80"> ';
627 print
'<input type="submit" class="button small" value="'.$langs->trans(
"AddFile").
'"'.$out.
' name="sendit">';
631 $maxphp = @ini_get(
'upload_max_filesize');
632 if (preg_match(
'/k$/i', $maxphp)) {
633 $maxphp = (int) substr($maxphp, 0, -1);
635 if (preg_match(
'/m$/i', $maxphp)) {
636 $maxphp = (int) substr($maxphp, 0, -1) * 1024;
638 if (preg_match(
'/g$/i', $maxphp)) {
639 $maxphp = (int) substr($maxphp, 0, -1) * 1024 * 1024;
641 if (preg_match(
'/t$/i', $maxphp)) {
642 $maxphp = (int) substr($maxphp, 0, -1) * 1024 * 1024 * 1024;
644 $maxphp2 = @ini_get(
'post_max_size');
645 if (preg_match(
'/k$/i', $maxphp2)) {
646 $maxphp2 = (int) substr($maxphp2, 0, -1);
648 if (preg_match(
'/m$/i', $maxphp2)) {
649 $maxphp2 = (int) substr($maxphp2, 0, -1) * 1024;
651 if (preg_match(
'/g$/i', $maxphp2)) {
652 $maxphp2 = (int) substr($maxphp2, 0, -1) * 1024 * 1024;
654 if (preg_match(
'/t$/i', $maxphp2)) {
655 $maxphp2 = (int) substr($maxphp2, 0, -1) * 1024 * 1024 * 1024;
659 $maxphptoshow = $maxphptoshowparam =
'';
661 $maxmin = min($max, $maxphp);
662 $maxphptoshow = $maxphp;
663 $maxphptoshowparam =
'upload_max_filesize';
666 $maxmin = min($max, $maxphp2);
667 if ($maxphp2 < $maxphp) {
668 $maxphptoshow = $maxphp2;
669 $maxphptoshowparam =
'post_max_size';
673 $langs->load(
'other');
675 $out .=
info_admin($langs->trans(
"ThisLimitIsDefinedInSetup", $max, $maxphptoshow), 1);
677 $out .=
' ('.$langs->trans(
"UploadDisabled").
')';
683 $filearray =
dol_dir_list(
$conf->import->dir_temp,
'files', 0,
'',
'',
'name', SORT_DESC);
684 if (count($filearray) > 0) {
685 print
'<div class="div-table-responsive-no-min">';
686 print
'<table class="noborder centpercent" width="100%" cellpadding="4">';
688 $dir =
$conf->import->dir_temp;
692 foreach ($filearray as $key => $val) {
693 $file = $val[
'name'];
697 $file = mb_convert_encoding($file,
'UTF-8',
'ISO-8859-1');
700 if (preg_match(
'/^\./', $file)) {
704 $modulepart =
'import';
705 $urlsource = $_SERVER[
"PHP_SELF"].
'?step='.$step.$param.
'&filetoimport='.urlencode($filetoimport);
706 $relativepath = $file;
708 print
'<tr class="oddeven">';
710 print
img_mime($file,
'',
'pictofixedwidth');
711 print
'<a data-ajax="false" href="'.DOL_URL_ROOT.
'/document.php?modulepart='.$modulepart.
'&file='.urlencode($relativepath).
'&step=3'.$param.
'" target="_blank" rel="noopener noreferrer">';
716 print
'<td style="text-align:right">'.dol_print_size(
dol_filesize($dir.
'/'.$file)).
'</td>';
718 print
'<td style="text-align:right">'.dol_print_date(
dol_filemtime($dir.
'/'.$file),
'dayhour').
'</td>';
720 print
'<td style="text-align:right"><a href="'.$_SERVER[
'PHP_SELF'].
'?action=delete&token='.
newToken().
'&step=3'.$param.
'&urlfile='.urlencode($relativepath);
721 print
'">'.img_delete().
'</a></td>';
723 print
'<td style="text-align:right">';
724 print
'<a href="'.$_SERVER[
'PHP_SELF'].
'?step=4'.$param.
'&filetoimport='.urlencode($relativepath).
'">'.
img_picto($langs->trans(
"NewImport"),
'next',
'class="fa-15"').
'</a>';
738if ($step == 4 && $datatoimport) {
740 $serialized_array_match_file_to_database = isset($_SESSION[
"dol_array_match_file_to_database_select"]) ? $_SESSION[
"dol_array_match_file_to_database_select"] :
'';
741 $fieldsarray = explode(
',', $serialized_array_match_file_to_database);
742 $array_match_file_to_database = array();
743 foreach ($fieldsarray as $elem) {
744 $tabelem = explode(
'=', $elem, 2);
746 $val = (isset($tabelem[1]) ? $tabelem[1] :
'');
748 $array_match_file_to_database[$key] = $val;
757 $list = $objmodelimport->listOfAvailableImportFormat($db);
759 if (empty($separator)) {
760 $separator = (!
getDolGlobalString(
'IMPORT_CSV_SEPARATOR_TO_USE') ?
',' :
$conf->global->IMPORT_CSV_SEPARATOR_TO_USE);
764 if ($model ==
'csv' && strlen($separator) == 1 && !GETPOSTISSET(
'separator')) {
765 '@phan-var-force ImportCsv $obj';
767 $fh = fopen(
$conf->import->dir_temp.
'/'.$filetoimport,
'r');
769 $sline = fgets($fh, 1000000);
771 $nboccurence = substr_count($sline, $separator);
772 $nboccurencea = substr_count($sline,
',');
773 $nboccurenceb = substr_count($sline,
';');
775 if ($nboccurence == 0) {
776 if ($nboccurencea > 2) {
778 } elseif ($nboccurenceb > 2) {
786 $separator_used = str_replace(
'\t',
"\t", $separator);
789 $dir = DOL_DOCUMENT_ROOT.
"/core/modules/import/";
790 $file =
"import_".$model.
".modules.php";
791 $classname =
"Import".ucfirst($model);
792 require_once $dir.$file;
793 $obj =
new $classname($db, $datatoimport);
794 '@phan-var-force ModeleImports $obj';
796 if (!empty($obj->error)) {
797 $langs->load(
"errors");
798 $param =
'&datatoimport='.$datatoimport.
'&format='.$format;
800 header(
"Location: ".$_SERVER[
"PHP_SELF"].
'?step=3'.$param.
'&filetoimport='.urlencode($relativepath));
804 if ($model ==
'csv') {
805 '@phan-var-force ImportCsv $obj';
806 $obj->separator = $separator_used;
807 $obj->enclosure = $enclosure;
810 if ($model ==
'xlsx') {
811 '@phan-var-force ImportXlsx $obj';
812 if (!preg_match(
'/\.xlsx$/i', $filetoimport)) {
813 $langs->load(
"errors");
814 $param =
'&datatoimport='.$datatoimport.
'&format='.$format;
815 setEventMessages($langs->trans(
"ErrorFileMustHaveFormat", $model),
null,
'errors');
816 header(
"Location: ".$_SERVER[
"PHP_SELF"].
'?step=3'.$param.
'&filetoimport='.urlencode($relativepath));
822 $array_match_file_to_database = array();
826 $fieldssource = array();
828 $result = $obj->import_open_file(
$conf->import->dir_temp.
'/'.$filetoimport);
831 $arrayrecord = $obj->import_read_record();
835 foreach ($arrayrecord as $key => $val) {
836 if ($val[
"type"] != -1) {
837 $fieldssource[$i][
'example1'] =
dol_trunc($val[
'val'], 128);
840 $fieldssource[$i][
'example1'] = $langs->trans(
'Empty');
843 $fieldssource[$i][
'imported'] = 0;
845 $obj->import_close_file();
849 $fieldstarget = $objimport->array_import_fields[0];
850 $minpos = min(count($fieldssource), count($fieldstarget));
854 $initialloadofstep4 =
false;
855 if (empty($_SESSION[
'dol_array_match_file_to_database_select'])) {
856 $initialloadofstep4 =
true;
860 if (count($array_match_file_to_database) == 0) {
866 $num = count($fieldssource);
867 while ($pos <= $num) {
868 if ($num >= 1 && $pos <= $num) {
870 foreach ($fieldstarget as $key => $val) {
871 if ($posbis < $pos) {
876 $array_match_file_to_database[$pos] = $key;
883 $array_match_database_to_file = array_flip($array_match_file_to_database);
887 $fieldstarget_tmp = array();
888 $arraykeysfieldtarget = array_keys($fieldstarget);
890 foreach ($fieldstarget as $key => $label) {
891 $isrequired = preg_match(
'/\*$/', $label);
892 if (!empty($isrequired)) {
893 $newlabel = substr($label, 0, -1);
894 $fieldstarget_tmp[$key] = array(
"label" => $newlabel,
"required" =>
true);
896 $fieldstarget_tmp[$key] = array(
"label" => $label,
"required" =>
false);
898 if (!empty($array_match_database_to_file[$key])) {
899 $fieldstarget_tmp[$key][
"imported"] =
true;
900 $fieldstarget_tmp[$key][
"position"] = (int) $array_match_database_to_file[$key] - 1;
902 while (!empty($array_match_database_to_file[$keytoswap])) {
903 if ($position + 1 > $array_match_database_to_file[$keytoswap]) {
904 $keytoswapwith = $array_match_database_to_file[$keytoswap] - 1;
905 $tmp = [$keytoswap => $fieldstarget_tmp[$keytoswap]];
906 unset($fieldstarget_tmp[$keytoswap]);
907 $fieldstarget_tmp =
arrayInsert($fieldstarget_tmp, $keytoswapwith, $tmp);
908 $keytoswapwith = $arraykeysfieldtarget[$array_match_database_to_file[$keytoswap] - 1];
909 $tmp = $fieldstarget_tmp[$keytoswapwith];
910 unset($fieldstarget_tmp[$keytoswapwith]);
911 $fieldstarget_tmp[$keytoswapwith] = $tmp;
912 $keytoswap = $keytoswapwith;
918 $fieldstarget_tmp[$key][
"imported"] =
false;
922 $fieldstarget = $fieldstarget_tmp;
931 $param =
'&format='.$format.
'&datatoimport='.urlencode($datatoimport).
'&filetoimport='.urlencode($filetoimport);
932 if ($excludefirstline) {
933 $param .=
'&excludefirstline='.urlencode($excludefirstline);
936 $param .=
'&endatlinenb='.urlencode($endatlinenb);
939 $param .=
'&separator='.urlencode($separator);
942 $param .=
'&enclosure='.urlencode($enclosure);
945 llxHeader(
'', $langs->trans(
"NewImport"), $help_url);
951 print
'<div class="underbanner clearboth"></div>';
952 print
'<div class="fichecenter">';
954 print
'<table class="centpercent border tableforfield">';
957 print
'<tr><td class="titlefieldcreate">'.$langs->trans(
"Module").
'</td>';
959 $titleofmodule = $objimport->array_import_module[0][
'module']->getName();
961 if (in_array($objimport->array_import_code[0], array(
'produit_supplierprices',
'produit_multiprice',
'produit_languages'))) {
962 $titleofmodule = $langs->trans(
"ProductOrService");
964 print $titleofmodule;
968 print
'<tr><td>'.$langs->trans(
"DatasetToImport").
'</td>';
970 $entity = preg_replace(
'/:.*$/',
'', $objimport->array_import_icon[0]);
971 $entityicon = strtolower(!empty($entitytoicon[$entity]) ? $entitytoicon[$entity] : $entity);
972 print
img_object($objimport->array_import_module[0][
'module']->getName(), $entityicon).
' ';
973 print $objimport->array_import_label[0];
979 print
load_fiche_titre($langs->trans(
"InformationOnSourceFile"),
'',
'file-export');
981 print
'<div class="underbanner clearboth"></div>';
982 print
'<div class="fichecenter">';
983 print
'<table width="100%" class="border tableforfield">';
986 print
'<tr><td class="titlefieldcreate">'.$langs->trans(
"SourceFileFormat").
'</td>';
988 $text = $objmodelimport->getDriverDescForKey($format);
990 print $form->textwithpicto($objmodelimport->getDriverLabelForKey($format), $text);
994 if ($model ==
'csv') {
995 '@phan-var-force ImportCsv $obj';
996 print
'<tr><td>'.$langs->trans(
"CsvOptions").
'</td>';
998 print
'<form method="POST">';
999 print
'<input type="hidden" name="token" value="'.newToken().
'">';
1000 print
'<input type="hidden" value="'.$step.
'" name="step">';
1001 print
'<input type="hidden" value="'.$format.
'" name="format">';
1002 print
'<input type="hidden" value="'.$excludefirstline.
'" name="excludefirstline">';
1003 print
'<input type="hidden" value="'.$endatlinenb.
'" name="endatlinenb">';
1004 print
'<input type="hidden" value="'.$datatoimport.
'" name="datatoimport">';
1005 print
'<input type="hidden" value="'.$filetoimport.
'" name="filetoimport">';
1006 print $langs->trans(
"Separator").
' : ';
1007 print
'<input type="text" class="width25 center" name="separator" value="'.dol_escape_htmltag($separator).
'"/>';
1008 print
' '.$langs->trans(
"Enclosure").
' : ';
1009 print
'<input type="text" class="width25 center" name="enclosure" value="'.dol_escape_htmltag($enclosure).
'"/> ';
1010 print
'<input name="update" type="submit" value="'.$langs->trans(
'Update').
'" class="button smallpaddingimp" />';
1016 print
'<tr><td>'.$langs->trans(
"FileToImport").
'</td>';
1018 $modulepart =
'import';
1019 $relativepath =
GETPOST(
'filetoimport');
1020 print
'<a data-ajax="false" href="'.DOL_URL_ROOT.
'/document.php?modulepart='.$modulepart.
'&file='.urlencode($relativepath).
'&step=4'.$param.
'" target="_blank" rel="noopener noreferrer">';
1021 print
img_mime($file,
'',
'pictofixedwidth');
1022 print $filetoimport;
1023 print
img_picto($langs->trans(
"Download"),
'download',
'class="paddingleft opacitymedium"');
1036 print
'<!-- List of source fields -->'.
"\n";
1037 print
'<form action="'.$_SERVER[
"PHP_SELF"].
'" method="POST">';
1038 print
'<input type="hidden" name="token" value="'.newToken().
'">';
1039 print
'<input type="hidden" name="action" value="select_model">';
1040 print
'<input type="hidden" name="step" value="4">';
1041 print
'<input type="hidden" name="format" value="'.$format.
'">';
1042 print
'<input type="hidden" name="datatoimport" value="'.$datatoimport.
'">';
1043 print
'<input type="hidden" name="filetoimport" value="'.$filetoimport.
'">';
1044 print
'<input type="hidden" name="excludefirstline" value="'.$excludefirstline.
'">';
1045 print
'<input type="hidden" name="endatlinenb" value="'.$endatlinenb.
'">';
1046 print
'<input type="hidden" name="separator" value="'.dol_escape_htmltag($separator).
'">';
1047 print
'<input type="hidden" name="enclosure" value="'.dol_escape_htmltag($enclosure).
'">';
1050 print
'<div class="marginbottomonly">';
1051 print
'<span class="opacitymedium">';
1052 $s = $langs->trans(
"SelectImportFieldsSource",
'{s1}');
1053 $s = str_replace(
'{s1}',
img_picto(
'',
'grip_title',
'', 0, 0, 0,
'',
'', 0), $s);
1056 $htmlother->select_import_model($importmodelid,
'importmodelid', $datatoimport, 1, $user->id);
1057 print
'<input type="submit" class="button small reposition" value="'.$langs->trans(
"Select").
'">';
1062 print
'<div class="div-table-responsive-no-min">';
1063 print
'<table class="noborder centpercent">';
1064 print
'<tr class="liste_titre">';
1065 print
'<td>'.$langs->trans(
"FieldsInSourceFile").
'</td>';
1066 print
'<td>'.$langs->trans(
"FieldsInTargetDatabase").
'</td>';
1071 print
'<tr valign="top"><td width="50%" class="nopaddingleftimp">';
1073 $fieldsplaced = array();
1074 $valforsourcefieldnb = array();
1075 $listofkeys = array();
1076 foreach ($array_match_file_to_database as $key => $val) {
1077 $listofkeys[$key] = 1;
1080 print
"\n<!-- Box left container -->\n";
1081 print
'<div id="left" class="connectedSortable">'.
"\n";
1086 foreach ($fieldssource as $key => $val) {
1089 $listofkeys[$key] = 1;
1090 $fieldsplaced[$key] = 1;
1091 $valforsourcefieldnb[$lefti] = $key;
1101 print
"<!-- End box left container -->\n";
1104 print
'</td><td width="50%" class="nopaddingrightimp">';
1108 $optionsall = array();
1109 foreach ($fieldstarget as $code => $line) {
1110 $tmparray = explode(
'|', $line[
"label"]);
1112 foreach ($tmparray as $tmpkey => $tmpval) {
1113 $labeltoshow .= ($labeltoshow ?
' '.$langs->trans(
'or').
' ' :
'').$langs->transnoentities($tmpval);
1118 $optionsall[$code] = array(
1119 'labelkey' => $line[
'label'],
1120 'labelkeyarray' => $tmparray,
1121 'label' => $labeltoshow,
1122 'required' => (empty($line[
"required"]) ? 0 : 1),
1123 'position' => (!empty($line[
'position']) ? $line[
'position'] : 0),
1131 $mandatoryfieldshavesource =
true;
1144 $modetoautofillmapping =
'session';
1145 if ($initialloadofstep4) {
1146 $modetoautofillmapping =
'guess';
1150 print
'<table class="nobordernopadding centpercent tableimport">';
1151 foreach ($fieldssource as $code => $line) {
1155 print
'<tr style="height:'.$height.
'" class="trimport oddevenimport">';
1157 $entity = (!empty($objimport->array_import_entities[0][$code]) ? $objimport->array_import_entities[0][$code] : $objimport->array_import_icon[0]);
1159 $entityicon = !empty($entitytoicon[$entity]) ? $entitytoicon[$entity] : $entity;
1160 $entitylang = !empty($entitytolang[$entity]) ? $entitytolang[$entity] : $objimport->array_import_label[0];
1162 print
'<td class="nowraponall hideonsmartphone" style="font-weight: normal">=> </td>';
1163 print
'<td class="nowraponall" style="font-weight: normal">';
1165 $selectforline =
'';
1166 $selectforline .=
'<select id="selectorderimport_'.($i + 1).
'" class="targetselectchange minwidth300" name="select_'.($i + 1).
'">';
1167 if (!empty($line[
"imported"])) {
1168 $selectforline .=
'<option value="-1"> </option>';
1170 $selectforline .=
'<option selected="" value="-1"> </option>';
1174 $codeselectedarray = array();
1175 foreach ($optionsall as $tmpcode => $tmpval) {
1177 if (!empty($tmpval[
'picto'])) {
1178 $label .=
img_picto(
'', $tmpval[
'picto'],
'class="pictofixedwidth"');
1180 $label .= $tmpval[
'required'] ?
'<strong>' :
'';
1181 $label .= $tmpval[
'label'];
1182 $label .= $tmpval[
'required'] ?
'*</strong>' :
'';
1184 $tablealias = preg_replace(
'/(\..*)$/i',
'', $tmpcode);
1185 $tablename = !empty($objimport->array_import_tables[0][$tablealias]) ? $objimport->array_import_tables[0][$tablealias] :
"";
1189 $filecolumn = ($i + 1);
1191 if (empty($objimport->array_import_convertvalue[0][$tmpcode])) {
1194 if ($objimport->array_import_convertvalue[0][$tmpcode][
'rule'] ==
'fetchidfromref') {
1195 $htmltext .= $langs->trans(
"DataComeFromIdFoundFromRef", $langs->transnoentitiesnoconv($entitylang)).
'<br>';
1197 if ($objimport->array_import_convertvalue[0][$tmpcode][
'rule'] ==
'fetchidfromcodeid') {
1198 $htmltext .= $langs->trans(
"DataComeFromIdFoundFromCodeId", $langs->transnoentitiesnoconv($objimport->array_import_convertvalue[0][$tmpcode][
'dict'])).
'<br>';
1202 $example = !empty($objimport->array_import_examplevalues[0][$tmpcode]) ? $objimport->array_import_examplevalues[0][$tmpcode] :
"";
1204 if (empty($objimport->array_import_convertvalue[0][$tmpcode])) {
1206 $htmltext .= $langs->trans(
"SourceExample").
': <b>'.str_replace(
'"',
'', $example).
'</b><br>';
1209 if ($objimport->array_import_convertvalue[0][$tmpcode][
'rule'] ==
'fetchidfromref') {
1210 $htmltext .= $langs->trans(
"SourceExample").
': <b>'.$langs->transnoentitiesnoconv(
"ExampleAnyRefFoundIntoElement", $entitylang).($example ?
' ('.$langs->transnoentitiesnoconv(
"Example").
': '.str_replace(
'"',
'', $example).
')' :
'').
'</b><br>';
1211 } elseif ($objimport->array_import_convertvalue[0][$tmpcode][
'rule'] ==
'fetchidfromcodeid') {
1212 $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>';
1213 } elseif ($example) {
1214 $htmltext .= $langs->trans(
"SourceExample").
': <b>'.str_replace(
'"',
'', $example).
'</b><br>';
1218 if (!empty($objimport->array_import_regex[0][$tmpcode])) {
1219 $htmltext .= $langs->trans(
"FormatControlRule").
': <b>'.str_replace(
'"',
'', $objimport->array_import_regex[0][$tmpcode]).
'</b><br>';
1223 $htmltext .= $langs->trans(
"InformationOnTargetTables").
': <b>'.$tablename.
"->".preg_replace(
'/^.*\./',
'', $tmpcode).
"</b>";
1225 $labelhtml = $label.
' '.$form->textwithpicto(
'', $htmltext, 1,
'help',
'', 1);
1227 $selectforline .=
'<option value="'.$tmpcode.
'"';
1228 if ($modetoautofillmapping ==
'orderoftargets') {
1231 $selectforline .=
' selected';
1233 } elseif ($modetoautofillmapping ==
'guess') {
1237 if (preg_match(
'/^(.+)\((.+\..+)\)$/', $line[
'example1'], $regs)) {
1238 $tmpstring1 = $regs[1];
1239 $tmpstring2 = $regs[2];
1241 $tmpstring1 = $line[
'example1'];
1249 foreach ($tmpval[
'labelkeyarray'] as $tmpval2) {
1250 $labeltarget = $langs->transnoentities($tmpval2);
1252 if ($tmpstring1 && ($tmpstring1 == $tmpcode || $tmpstring1 == strtolower($labeltarget)
1253 || $tmpstring1 == strtolower(
dol_string_unaccent($labeltarget)) || $tmpstring1 == strtolower($tmpval2))) {
1254 if (empty($codeselectedarray[$code])) {
1255 $selectforline .=
' selected';
1256 $codeselectedarray[$code] = 1;
1259 } elseif ($tmpstring2 && ($tmpstring2 == $tmpcode || $tmpstring2 == strtolower($labeltarget)
1260 || $tmpstring2 == strtolower(
dol_string_unaccent($labeltarget)) || $tmpstring2 == strtolower($tmpval2))) {
1261 if (empty($codeselectedarray[$code])) {
1262 $selectforline .=
' selected';
1263 $codeselectedarray[$code] = 1;
1268 } elseif ($modetoautofillmapping ==
'session' && !empty($_SESSION[
'dol_array_match_file_to_database_select'])) {
1269 $tmpselectioninsession =
dolExplodeIntoArray($_SESSION[
'dol_array_match_file_to_database_select'],
',',
'=');
1271 if (!empty($tmpselectioninsession[(
string) ($i + 1)]) && $tmpselectioninsession[(
string) ($i + 1)] == $tmpcode) {
1272 $selectforline .=
' selected';
1274 $selectforline .=
' data-debug="'.$tmpcode.
'-'.$code.
'-'.$j.
'-'.(!empty($tmpselectioninsession[(
string) ($i + 1)]) ? $tmpselectioninsession[(string) ($i + 1)] :
"").
'"';
1276 $selectforline .=
' data-html="'.dol_escape_htmltag($labelhtml).
'"';
1277 $selectforline .=
'>';
1278 $selectforline .= $label;
1279 $selectforline .=
'</options>';
1282 $selectforline .=
'</select>';
1283 $selectforline .=
ajax_combobox(
'selectorderimport_'.($i + 1));
1285 print $selectforline;
1290 print
'<td class="nowraponall" style="font-weight:normal; text-align:right">';
1293 $htmltext =
'<b><u>'.$langs->trans(
"FieldSource").
'</u></b><br>';
1295 $htmltext .= $langs->trans(
"DataComeFromFileFieldNb", $filecolumntoshow).
'<br>';
1297 print $form->textwithpicto(
'', $htmltext);
1308 print
'<tr class="liste_titre"><td colspan="2">'.$langs->trans(
"Note").
'</td></tr>';
1309 print
'<tr><td colspan="2"><div id="div-mandatory-target-fields-not-mapped"></div></td></tr>';
1315 if (!empty(
$conf->use_javascript_ajax)) {
1316 print
'<script type="text/javascript">'.
"\n";
1317 print
'var previousselectedvalueimport = "0";'.
"\n";
1318 print
'var previousselectedlabelimport = "0";'.
"\n";
1319 print
'var arrayofselectedvalues = [];'.
"\n";
1320 print
'var arrayoftargetfields = [];'.
"\n";
1321 print
'var arrayoftargetmandatoryfields = [];'.
"\n";
1325 foreach ($fieldstarget as $key => $val) {
1326 print
"arrayoftargetfields[".$tmpi.
"] = '".
dol_escape_js($langs->trans($val[
'label'])).
"'; ";
1327 if ($val[
'required']) {
1328 print
"arrayoftargetmandatoryfields[".$tmpi.
"] = '".
dol_escape_js($key).
"'; ";
1334 print
'$(document).ready(function () {'.
"\n";
1336 print
'setOptionsToDisabled();'.
"\n";
1337 print
'saveSelection();'.
"\n";
1339 print
'$(".targetselectchange").focus(function(){'.
"\n";
1340 print
' previousselectedvalueimport = $(this).val();'.
"\n";
1341 print
' previousselectedlabelimport = $(this).children("option:selected").text();'.
"\n";
1342 print
' console.log("previousselectedvalueimport="+previousselectedvalueimport)'.
"\n";
1349 print
'function setOptionsToDisabled() {'.
"\n";
1350 print
' console.log("Remove the disabled flag everywhere");'.
"\n";
1351 print
' $("select.targetselectchange").not($( this )).find(\'option\').prop("disabled", false);'.
"\n";
1352 print
' arrayofselectedvalues = [];'.
"\n";
1354 print
' $("select.targetselectchange").each(function(){'.
"\n";
1355 print
' id = $(this).attr(\'id\')'.
"\n";
1356 print
' value = $(this).val()'.
"\n";
1357 print
' console.log("a selected value has been found for component "+id+" = "+value);'.
"\n";
1358 print
' arrayofselectedvalues.push(value);'.
"\n";
1361 print
' console.log("List of all selected values arrayofselectedvalues");'.
"\n";
1362 print
' console.log(arrayofselectedvalues);'.
"\n";
1363 print
' console.log("Set the option to disabled for every entry that is currently selected somewhere else (so into arrayofselectedvalues)");'.
"\n";
1365 print
' $.each(arrayofselectedvalues, function(key, value) {'.
"\n";
1366 print
' if (value != -1) {'.
"\n";
1367 print
' console.log("Process key="+key+" value="+value+" to disable.");'.
"\n";
1368 print
' $("select.targetselectchange").find(\'option[value="\'+value+\'"]:not(:selected)\').prop("disabled", true);'.
"\n";
1374 print
'function saveSelection() {'.
"\n";
1376 print
' arrayselectedfields = [];'.
"\n";
1377 print
' arrayselectedfields.push(0);'.
"\n";
1379 print
' $.each( arrayofselectedvalues, function( key, value ) {'.
"\n";
1380 print
' if (value != -1) {'.
"\n";
1381 print
' arrayselectedfields.push(value);'.
"\n";
1382 print
' } else {'.
"\n";
1383 print
' arrayselectedfields.push(0);'.
"\n";
1387 print
" $.ajax({\n";
1388 print
" type: 'POST',\n";
1389 print
" dataType: 'json',\n";
1390 print
" url: '".dol_escape_js($_SERVER[
"PHP_SELF"]).
"?action=saveselectorder&token=".
newToken().
"',\n";
1391 print
" data: 'selectorder='+arrayselectedfields.toString(),\n";
1392 print
" success: function(){\n";
1393 print
" console.log('The selected fields have been saved into '+arrayselectedfields.toString());\n";
1398 print
' console.log("arrayselectedfields");';
1399 print
' console.log(arrayselectedfields);';
1400 print
' console.log("arrayoftargetmandatoryfields");';
1401 print
' console.log(arrayoftargetmandatoryfields);';
1402 print
" listtoshow = '';";
1403 print
" nbelement = arrayoftargetmandatoryfields.length
1404 for (let i = 0; i < nbelement; i++) {
1405 if (arrayoftargetmandatoryfields[i] && ! arrayselectedfields.includes(arrayoftargetmandatoryfields[i])) {
1406 console.log(arrayoftargetmandatoryfields[i]+' not mapped');
1407 listtoshow = listtoshow + (listtoshow ? ', ' : '') + '<b>' + arrayoftargetfields[i] + '*</b>';
1410 console.log(listtoshow);
1412 listtoshow = '".dol_escape_js(
img_warning($langs->trans(
"MandatoryTargetFieldsNotMapped")).
' '.$langs->trans(
"MandatoryTargetFieldsNotMapped")).
": ' + listtoshow;
1413 $('#div-mandatory-target-fields-not-mapped').html(listtoshow);
1415 $('#div-mandatory-target-fields-not-mapped').html('<span class=\"opacitymedium\">".
dol_escape_js($langs->trans(
"AllTargetMandatoryFieldsAreMapped")).
"</span>');
1422 print
'$(".targetselectchange").change(function(){'.
"\n";
1423 print
' setOptionsToDisabled();'.
"\n";
1425 print
' if(previousselectedlabelimport != "" && previousselectedvalueimport != -1) {'.
"\n";
1426 print
' let valuetochange = $(this).val(); '.
"\n";
1427 print
' $(".boxtdunused").each(function(){'.
"\n";
1428 print
' if ($(this).text().includes(valuetochange)){'.
"\n";
1429 print
' arraychild = $(this)[0].childNodes'.
"\n";
1430 print
' arraytexttomodify = arraychild[0].textContent.split(" ")'.
"\n";
1431 print
' arraytexttomodify[1] = previousselectedvalueimport '.
"\n";
1432 print
' textmodified = arraytexttomodify.join(" ") '.
"\n";
1433 print
' arraychild[0].textContent = textmodified'.
"\n";
1434 print
' arraychild[1].innerHTML = previousselectedlabelimport'.
"\n";
1438 print
' $(this).blur()'.
"\n";
1440 print
' saveSelection()'.
"\n";
1444 print
'</script>'.
"\n";
1450 print
'<div class="tabsAction">';
1452 if (count($array_match_file_to_database)) {
1453 if ($mandatoryfieldshavesource) {
1454 print
'<a class="butAction saveorderselect" href="import.php?step=5'.$param.
'&filetoimport='.urlencode($filetoimport).
'">'.$langs->trans(
"NextStep").
'</a>';
1456 print
'<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->transnoentitiesnoconv(
"SomeMandatoryFieldHaveNoSource")).
'">'.$langs->trans(
"NextStep").
'</a>';
1464 if (count($array_match_file_to_database)) {
1466 print
'<!-- Area to add new import profile -->'.
"\n";
1467 print
'<div class="marginbottomonly"><span class="opacitymedium">'.$langs->trans(
"SaveImportModel").
'</span></div>';
1469 print
'<form class="nocellnopadd" action="'.$_SERVER[
"PHP_SELF"].
'" method="post">';
1470 print
'<input type="hidden" name="token" value="'.newToken().
'">';
1471 print
'<input type="hidden" name="action" value="add_import_model">';
1472 print
'<input type="hidden" name="step" value="'.$step.
'">';
1473 print
'<input type="hidden" name="format" value="'.$format.
'">';
1474 print
'<input type="hidden" name="datatoimport" value="'.$datatoimport.
'">';
1475 print
'<input type="hidden" name="filetoimport" value="'.$filetoimport.
'">';
1476 print
'<input type="hidden" name="hexa" value="'.$hexa.
'">';
1477 print
'<input type="hidden" name="excludefirstline" value="'.$excludefirstline.
'">';
1478 print
'<input type="hidden" name="endatlinenb" value="'.$endatlinenb.
'">';
1479 print
'<input type="hidden" name="page_y" value="">';
1480 print
'<input type="hidden" value="'.dol_escape_htmltag($separator).
'" name="separator">';
1481 print
'<input type="hidden" value="'.dol_escape_htmltag($enclosure).
'" name="enclosure">';
1483 print
'<div class="div-table-responsive-no-min">';
1484 print
'<table summary="selectofimportprofil" class="noborder centpercent">';
1485 print
'<tr class="liste_titre">';
1486 print
'<td>'.$langs->trans(
"ImportModelName").
'</td>';
1487 print
'<td>'.$langs->trans(
"Visibility").
'</td>';
1491 $nameofimportprofile = str_replace(
' ',
'-', $langs->trans(
"ImportProfile").
' '.$titleofmodule.
' '.
dol_print_date(
dol_now(
'gmt'),
'dayxcard'));
1493 $nameofimportprofile = $import_name;
1496 print
'<tr class="oddeven">';
1497 print
'<td><input name="import_name" class="minwidth300" value="'.$nameofimportprofile.
'"></td>';
1499 $arrayvisibility = array(
'private' => $langs->trans(
"Private"),
'all' => $langs->trans(
"Everybody"));
1500 print $form->selectarray(
'visibility', $arrayvisibility,
'private');
1502 print
'<td class="right">';
1503 print
'<input type="submit" class="button smallpaddingimp reposition" value="'.$langs->trans(
"SaveImportProfile").
'">';
1507 $sql =
"SELECT rowid, label, fk_user, entity";
1508 $sql .=
" FROM ".MAIN_DB_PREFIX.
"import_model";
1509 $sql .=
" WHERE type = '".$db->escape($datatoimport).
"'";
1511 $sql .=
" AND fk_user IN (0, ".((int) $user->id).
")";
1513 $sql .=
" ORDER BY rowid";
1515 $resql = $db->query($sql);
1517 $num = $db->num_rows($resql);
1519 $tmpuser =
new User($db);
1523 $obj = $db->fetch_object($resql);
1525 print
'<tr class="oddeven"><td>';
1528 print
'<td class="tdoverflowmax150">';
1529 if (empty($obj->fk_user)) {
1530 print $langs->trans(
"Everybody");
1532 $tmpuser->fetch($obj->fk_user);
1533 print $tmpuser->getNomUrl(-1);
1536 print
'<td class="right">';
1537 print
'<a class="reposition" href="'.$_SERVER[
"PHP_SELF"].
'?step='.$step.$param.
'&action=deleteprof&token='.
newToken().
'&id='.$obj->rowid.
'&filetoimport='.urlencode($filetoimport).
'">';
1555if ($step == 5 && $datatoimport) {
1556 $max_execution_time_for_importexport =
getDolGlobalInt(
'IMPORT_MAX_EXECUTION_TIME', 300);
1557 $max_time = @ini_get(
"max_execution_time");
1558 if ($max_time && $max_time < $max_execution_time_for_importexport) {
1559 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.");
1560 @ini_set(
"max_execution_time", $max_execution_time_for_importexport);
1564 $list = $objmodelimport->listOfAvailableImportFormat($db);
1567 $dir = DOL_DOCUMENT_ROOT.
"/core/modules/import/";
1568 $file =
"import_".$model.
".modules.php";
1569 $classname =
"Import".ucfirst($model);
1570 require_once $dir.$file;
1571 $obj =
new $classname($db, $datatoimport);
1572 '@phan-var-force ModeleImports $obj';
1573 if ($model ==
'csv') {
1574 '@phan-var-force ImportCsv $obj';
1575 $obj->separator = $separator_used;
1576 $obj->enclosure = $enclosure;
1580 $fieldssource = array();
1581 $result = $obj->import_open_file(
$conf->import->dir_temp.
'/'.$filetoimport);
1585 $arrayrecord = $obj->import_read_record();
1588 foreach ($arrayrecord as $key => $val) {
1589 $fieldssource[$i][
'example1'] =
dol_trunc($val[
'val'], 24);
1592 $obj->import_close_file();
1595 $nboflines = $obj->import_get_nb_of_lines(
$conf->import->dir_temp.
'/'.$filetoimport);
1597 $param =
'&leftmenu=import&format='.urlencode($format).
'&datatoimport='.urlencode($datatoimport).
'&filetoimport='.urlencode($filetoimport).
'&nboflines='.((int) $nboflines).
'&separator='.urlencode($separator).
'&enclosure='.urlencode($enclosure);
1599 if ($excludefirstline) {
1600 $param .=
'&excludefirstline='.urlencode($excludefirstline);
1603 $param .=
'&endatlinenb='.urlencode($endatlinenb);
1605 if (!empty($updatekeys)) {
1606 $param .=
'&updatekeys[]='.implode(
'&updatekeys[]=', $updatekeys);
1609 llxHeader(
'', $langs->trans(
"NewImport"), $help_url);
1614 print
'<form action="'.$_SERVER[
"PHP_SELF"].
'?'.$param2.
'" method="POST">';
1615 print
'<input type="hidden" name="token" value="'.newToken().
'">';
1616 print
'<input type="hidden" name="step" value="5">';
1617 print
'<input type="hidden" name="action" value="launchsimu">';
1621 print
'<div class="underbanner clearboth"></div>';
1622 print
'<div class="fichecenter">';
1624 print
'<table width="100%" class="border tableforfield">';
1627 print
'<tr><td class="titlefieldcreate">'.$langs->trans(
"Module").
'</td>';
1629 $titleofmodule = $objimport->array_import_module[0][
'module']->getName();
1631 if (in_array($objimport->array_import_code[0], array(
'produit_supplierprices',
'produit_multiprice',
'produit_languages'))) {
1632 $titleofmodule = $langs->trans(
"ProductOrService");
1634 print $titleofmodule;
1638 print
'<tr><td>'.$langs->trans(
"DatasetToImport").
'</td>';
1640 $entity = preg_replace(
'/:.*$/',
'', $objimport->array_import_icon[0]);
1641 $entityicon = strtolower(!empty($entitytoicon[$entity]) ? $entitytoicon[$entity] : $entity);
1642 print
img_object($objimport->array_import_module[0][
'module']->getName(), $entityicon).
' ';
1643 print $objimport->array_import_label[0];
1649 print
load_fiche_titre($langs->trans(
"InformationOnSourceFile"),
'',
'file-export');
1651 print
'<div class="underbanner clearboth"></div>';
1652 print
'<div class="fichecenter">';
1653 print
'<table width="100%" class="border tableforfield">';
1656 print
'<tr><td class="titlefieldcreate">'.$langs->trans(
"SourceFileFormat").
'</td>';
1658 $text = $objmodelimport->getDriverDescForKey($format);
1660 print $form->textwithpicto($objmodelimport->getDriverLabelForKey($format), $text);
1664 if ($model ==
'csv') {
1665 '@phan-var-force ImportCsv $obj';
1666 print
'<tr><td>'.$langs->trans(
"CsvOptions").
'</td>';
1669 print
' '.$langs->trans(
"Enclosure").
' : '.
dol_escape_htmltag($enclosure);
1674 print
'<tr><td>'.$langs->trans(
"FileToImport").
'</td>';
1676 $modulepart =
'import';
1677 $relativepath =
GETPOST(
'filetoimport');
1678 print
'<a data-ajax="false" href="'.DOL_URL_ROOT.
'/document.php?modulepart='.$modulepart.
'&file='.urlencode($relativepath).
'&step=4'.$param.
'" target="_blank" rel="noopener noreferrer">';
1679 print
img_mime($file,
'',
'pictofixedwidth');
1680 print $filetoimport;
1681 print
img_picto($langs->trans(
"Download"),
'download',
'class="paddingleft opacitymedium"');
1687 print $langs->trans(
"NbOfSourceLines");
1694 print $langs->trans(
"ImportFromToLine");
1696 if ($action ==
'launchsimu') {
1697 print
'<input type="number" class="maxwidth50 right" name="excludefirstlinebis" disabled="disabled" value="'.$excludefirstline.
'">';
1698 print
'<input type="hidden" name="excludefirstline" value="'.$excludefirstline.
'">';
1700 print
'<input type="number" class="maxwidth50 right" name="excludefirstline" value="'.$excludefirstline.
'">';
1701 print $form->textwithpicto(
"", $langs->trans(
"SetThisValueTo2ToExcludeFirstLine"));
1704 if ($action ==
'launchsimu') {
1705 print
'<input type="text" class="maxwidth50" name="endatlinenbbis" disabled="disabled" value="'.$endatlinenb.
'">';
1706 print
'<input type="hidden" name="endatlinenb" value="'.$endatlinenb.
'">';
1708 print
'<input type="text" class="maxwidth50" name="endatlinenb" value="'.$endatlinenb.
'">';
1709 print $form->textwithpicto(
"", $langs->trans(
"KeepEmptyToGoToEndOfFile"));
1711 if ($action ==
'launchsimu') {
1712 print
' <a href="'.$_SERVER[
"PHP_SELF"].
'?step=5'.$param.
'">'.$langs->trans(
"Modify").
'</a>';
1714 if ($excludefirstline == 2) {
1715 print $form->textwithpicto(
"", $langs->trans(
"WarningFirstImportedLine", $excludefirstline), 1,
'warning',
"warningexcludefirstline");
1717 $( document ).ready(function() {
1718 $("input[name=\'excludefirstline\']").on("change",function(){
1719 if($(this).val() <= 1){
1720 $(".warningexcludefirstline").hide();
1722 $(".warningexcludefirstline").show();
1732 print $form->textwithpicto($langs->trans(
"KeysToUseForUpdates"), $langs->trans(
"SelectPrimaryColumnsForUpdateAttempt"));
1734 if ($action ==
'launchsimu') {
1735 if (count($updatekeys)) {
1736 print $form->multiselectarray(
'updatekeysbis', $objimport->array_import_updatekeys[0], $updatekeys, 0, 0,
'', 1,
'80%',
'disabled');
1738 print
'<span class="opacitymedium">'.$langs->trans(
"NoUpdateAttempt").
'</span> -';
1740 foreach ($updatekeys as $val) {
1741 print
'<input type="hidden" name="updatekeys[]" value="'.$val.
'">';
1743 print
' <a href="'.$_SERVER[
"PHP_SELF"].
'?step=5'.$param.
'">'.$langs->trans(
"Modify").
'</a>';
1745 if (is_array($objimport->array_import_updatekeys[0]) && count($objimport->array_import_updatekeys[0])) {
1746 print $form->multiselectarray(
'updatekeys', $objimport->array_import_updatekeys[0], $updatekeys, 0, 0,
'', 1,
'80%');
1749 print
'<span class="opacitymedium">'.$langs->trans(
"UpdateNotYetSupportedForThisImport").
'</span>';
1761 print
load_fiche_titre($langs->trans(
"InformationOnTargetTables"),
'',
'file-import');
1763 print
'<div class="underbanner clearboth"></div>';
1764 print
'<div class="fichecenter">';
1766 print
'<table width="100%" class="border tableforfield">';
1769 print
'<tr><td class="titlefieldcreate">';
1770 print $langs->trans(
"TablesTarget");
1772 $listtables = array();
1773 $sort_array_match_file_to_database = $array_match_file_to_database;
1774 foreach ($array_match_file_to_database as $code => $label) {
1776 if ($code > count($fieldssource)) {
1780 $alias = preg_replace(
'/(\..*)$/i',
'', $label);
1781 $listtables[$alias] = $objimport->array_import_tables[0][$alias];
1783 if (count($listtables)) {
1786 foreach ($listtables as $val) {
1805 print $langs->trans(
"Error");
1811 print $langs->trans(
"FieldsTarget").
'</td><td>';
1812 $listfields = array();
1815 $sort_array_match_file_to_database = $array_match_file_to_database;
1816 ksort($sort_array_match_file_to_database);
1818 foreach ($sort_array_match_file_to_database as $code => $label) {
1821 if ($code > count($fieldssource)) {
1825 $alias = preg_replace(
'/(\..*)$/i',
'', $label);
1826 $listfields[$i] =
'<span class="nowrap">'.$langs->trans(
"Column").
' '.
num2Alpha((
int) $code - 1).
' -> '.$label.
'</span>';
1828 print count($listfields) ? (implode(
', ', $listfields)) : $langs->trans(
"Error");
1837 if ($action !=
'launchsimu') {
1839 print
'<br><span class="opacitymedium">';
1840 print $langs->trans(
"NowClickToTestTheImport", $langs->transnoentitiesnoconv(
"RunSimulateImportFile")).
'</span><br>';
1844 print
'<div class="center">';
1845 if ($user->hasRight(
'import',
'run')) {
1846 print
'<input type="submit" class="butAction" value="'.$langs->trans(
"RunSimulateImportFile").
'">';
1848 print
'<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->transnoentitiesnoconv(
"NotEnoughPermissions")).
'">'.$langs->trans(
"RunSimulateImportFile").
'</a>';
1853 $arrayoferrors = array();
1854 $arrayofwarnings = array();
1855 $maxnboferrors = !
getDolGlobalString(
'IMPORT_MAX_NB_OF_ERRORS') ? 50 :
$conf->global->IMPORT_MAX_NB_OF_ERRORS;
1856 $maxnbofwarnings = !
getDolGlobalString(
'IMPORT_MAX_NB_OF_WARNINGS') ? 50 :
$conf->global->IMPORT_MAX_NB_OF_WARNINGS;
1868 $pathfile =
$conf->import->dir_temp.
'/'.$filetoimport;
1869 $result = $obj->import_open_file($pathfile);
1871 global $tablewithentity_cache;
1872 $tablewithentity_cache = array();
1877 while (($sourcelinenb < $nboflines) && !$endoffile) {
1881 $arrayrecord = $obj->import_read_record();
1882 if ($arrayrecord ===
false) {
1883 $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');
1887 if ($excludefirstline && ($sourcelinenb < $excludefirstline)) {
1890 if ($endatlinenb && ($sourcelinenb > $endatlinenb)) {
1894 $parameters = array(
1896 'datatoimport' => $datatoimport,
1898 'arrayrecord' => $arrayrecord,
1899 'array_match_file_to_database' => $array_match_file_to_database,
1900 'objimport' => $objimport,
1901 'fieldssource' => $fieldssource,
1902 'importid' => $importid,
1903 'updatekeys' => $updatekeys,
1904 'arrayoferrors' => &$arrayoferrors,
1905 'arrayofwarnings' => &$arrayofwarnings,
1909 $reshook = $hookmanager->executeHooks(
'ImportInsert', $parameters);
1911 $arrayoferrors[$sourcelinenb][] = [
1912 'lib' => implode(
"<br>", array_merge([$hookmanager->error], $hookmanager->errors))
1916 if (empty($reshook)) {
1918 $result = $obj->import_insert($arrayrecord, $array_match_file_to_database, $objimport, count($fieldssource), $importid, $updatekeys);
1920 if (count($obj->errors)) {
1921 $arrayoferrors[$sourcelinenb] = $obj->errors;
1923 if (count($obj->warnings)) {
1924 $arrayofwarnings[$sourcelinenb] = $obj->warnings;
1926 if (!count($obj->errors) && !count($obj->warnings)) {
1932 $obj->import_close_file();
1934 print $langs->trans(
"ErrorFailedToOpenFile", $pathfile);
1941 if (!empty($objimport->array_import_run_sql_after[0]) && is_array($objimport->array_import_run_sql_after[0])) {
1943 foreach ($objimport->array_import_run_sql_after[0] as $sqlafterimport) {
1945 $resqlafterimport = $db->query($sqlafterimport);
1946 if (!$resqlafterimport) {
1947 $arrayoferrors[
'none'][] = array(
'lib' => $langs->trans(
"Error running final request: ".$sqlafterimport));
1956 if (!count($arrayoferrors) && !count($arrayofwarnings)) {
1958 print
'<div class="info">';
1959 print
'<div class=""><b>'.$langs->trans(
"ResultOfSimulationNoError").
'</b></div>';
1960 print $langs->trans(
"NbInsertSim", empty($obj->nbinsert) ? 0 : $obj->nbinsert).
'<br>';
1961 print $langs->trans(
"NbUpdateSim", empty($obj->nbupdate) ? 0 : $obj->nbupdate).
'<br>';
1966 print
'<div class="warning">';
1967 print $langs->trans(
"NbOfLinesOK", $nbok).
'...<br>';
1974 if (count($arrayoferrors)) {
1975 print
img_error().
' <b>'.$langs->trans(
"ErrorsOnXLines", count($arrayoferrors)).
'</b><br>';
1976 print
'<table width="100%" class="border"><tr><td>';
1977 foreach ($arrayoferrors as $key => $val) {
1979 if ($nboferrors > $maxnboferrors) {
1980 print $langs->trans(
"TooMuchErrors", (count($arrayoferrors) - $nboferrors)).
"<br>";
1984 foreach ($val as $i => $err) {
1985 print
' > '.dol_escape_htmltag($err[
'lib']).
'<br>';
1988 print
'</td></tr></table>';
1994 if (count($arrayofwarnings)) {
1995 print
img_warning().
' <b>'.$langs->trans(
"WarningsOnXLines", count($arrayofwarnings)).
'</b><br>';
1996 print
'<table width="100%" class="border"><tr><td>';
1997 foreach ($arrayofwarnings as $key => $val) {
1999 if ($nbofwarnings > $maxnbofwarnings) {
2000 print $langs->trans(
"TooMuchWarnings", (count($arrayofwarnings) - $nbofwarnings)).
"<br>";
2004 foreach ($val as $i => $err) {
2005 print
' > '.dol_escape_htmltag($err[
'lib']).
'<br>';
2008 print
'</td></tr></table>';
2015 print
'<div class="center">';
2016 print
'<span class="opacitymedium">'.$langs->trans(
"NowClickToRunTheImport", $langs->transnoentitiesnoconv(
"RunImportFile")).
'</span><br>';
2025 print
'<div class="center">';
2026 if ($user->hasRight(
'import',
'run')) {
2027 if (empty($nboferrors)) {
2028 print
'<a class="butAction" href="'.DOL_URL_ROOT.
'/imports/import.php?leftmenu=import&step=6&importid='.$importid.$param.
'">'.$langs->trans(
"RunImportFile").
'</a>';
2032 print
'<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->transnoentitiesnoconv(
"CorrectErrorBeforeRunningImport")).
'">'.$langs->trans(
"RunImportFile").
'</a>';
2035 print
'<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->transnoentitiesnoconv(
"NotEnoughPermissions")).
'">'.$langs->trans(
"RunSimulateImportFile").
'</a>';
2037 print
'<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->transnoentitiesnoconv(
"NotEnoughPermissions")).
'">'.$langs->trans(
"RunImportFile").
'</a>';
2047if ($step == 6 && $datatoimport) {
2048 $max_execution_time_for_importexport =
getDolGlobalInt(
'IMPORT_MAX_EXECUTION_TIME', 300);
2049 $max_time = @ini_get(
"max_execution_time");
2050 if ($max_time && $max_time < $max_execution_time_for_importexport) {
2051 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.");
2052 @ini_set(
"max_execution_time", $max_execution_time_for_importexport);
2056 $list = $objmodelimport->listOfAvailableImportFormat($db);
2057 $importid =
GETPOST(
"importid",
'alphanohtml');
2061 $dir = DOL_DOCUMENT_ROOT.
"/core/modules/import/";
2062 $file =
"import_".$model.
".modules.php";
2063 $classname =
"Import".ucfirst($model);
2064 require_once $dir.$file;
2065 $obj =
new $classname($db, $datatoimport);
2066 '@phan-var-force ModeleImports $obj';
2067 if ($model ==
'csv') {
2068 '@phan-var-force ImportCsv $obj';
2069 $obj->separator = $separator_used;
2070 $obj->enclosure = $enclosure;
2074 $fieldssource = array();
2075 $result = $obj->import_open_file(
$conf->import->dir_temp.
'/'.$filetoimport);
2078 $arrayrecord = $obj->import_read_record();
2081 foreach ($arrayrecord as $key => $val) {
2082 $fieldssource[$i][
'example1'] =
dol_trunc($val[
'val'], 24);
2085 $obj->import_close_file();
2090 $param =
'&format='.$format.
'&datatoimport='.urlencode($datatoimport).
'&filetoimport='.urlencode($filetoimport).
'&nboflines='.((int) $nboflines);
2091 if ($excludefirstline) {
2092 $param .=
'&excludefirstline='.urlencode($excludefirstline);
2095 $param .=
'&endatlinenb='.urlencode($endatlinenb);
2098 $param .=
'&separator='.urlencode($separator);
2101 $param .=
'&enclosure='.urlencode($enclosure);
2104 llxHeader(
'', $langs->trans(
"NewImport"), $help_url);
2110 print
'<div class="underbanner clearboth"></div>';
2111 print
'<div class="fichecenter">';
2113 print
'<table width="100%" class="border">';
2116 print
'<tr><td class="titlefieldcreate">'.$langs->trans(
"Module").
'</td>';
2118 $titleofmodule = $objimport->array_import_module[0][
'module']->getName();
2120 if (in_array($objimport->array_import_code[0], array(
'produit_supplierprices',
'produit_multiprice',
'produit_languages'))) {
2121 $titleofmodule = $langs->trans(
"ProductOrService");
2123 print $titleofmodule;
2127 print
'<tr><td>'.$langs->trans(
"DatasetToImport").
'</td>';
2129 $entity = preg_replace(
'/:.*$/',
'', $objimport->array_import_icon[0]);
2130 $entityicon = strtolower(!empty($entitytoicon[$entity]) ? $entitytoicon[$entity] : $entity);
2131 print
img_object($objimport->array_import_module[0][
'module']->getName(), $entityicon).
' ';
2132 print $objimport->array_import_label[0];
2138 print
load_fiche_titre($langs->trans(
"InformationOnSourceFile"),
'',
'file-export');
2140 print
'<div class="underbanner clearboth"></div>';
2141 print
'<div class="fichecenter">';
2142 print
'<table width="100%" class="border">';
2145 print
'<tr><td class="titlefieldcreate">'.$langs->trans(
"SourceFileFormat").
'</td>';
2147 $text = $objmodelimport->getDriverDescForKey($format);
2149 print $form->textwithpicto($objmodelimport->getDriverLabelForKey($format), $text);
2153 if ($model ==
'csv') {
2154 '@phan-var-force ImportCsv $obj';
2155 print
'<tr><td>'.$langs->trans(
"CsvOptions").
'</td>';
2157 print $langs->trans(
"Separator").
' : ';
2158 print htmlentities($separator);
2159 print
' '.$langs->trans(
"Enclosure").
' : ';
2160 print htmlentities($enclosure);
2165 print
'<tr><td>'.$langs->trans(
"FileToImport").
'</td>';
2167 $modulepart =
'import';
2168 $relativepath =
GETPOST(
'filetoimport');
2169 print
'<a data-ajax="false" href="'.DOL_URL_ROOT.
'/document.php?modulepart='.$modulepart.
'&file='.urlencode($relativepath).
'&step=4'.$param.
'" target="_blank" rel="noopener noreferrer">';
2170 print
img_mime($file,
'',
'pictofixedwidth');
2171 print $filetoimport;
2177 print $langs->trans(
"NbOfSourceLines");
2184 print $langs->trans(
"ImportFromLine");
2186 print
'<input type="text" size="4" name="excludefirstline" disabled="disabled" value="'.$excludefirstline.
'">';
2191 print $langs->trans(
"EndAtLineNb");
2193 print
'<input type="text" size="4" name="endatlinenb" disabled="disabled" value="'.$endatlinenb.
'">';
2201 print
'<b>'.$langs->trans(
"InformationOnTargetTables").
'</b>';
2202 print
'<div class="underbanner clearboth"></div>';
2203 print
'<div class="fichecenter">';
2204 print
'<table class="border centpercent">';
2207 print
'<tr><td width="25%">';
2208 print $langs->trans(
"TablesTarget");
2210 $listtables = array();
2211 foreach ($array_match_file_to_database as $code => $label) {
2213 if ($code > count($fieldssource)) {
2217 $alias = preg_replace(
'/(\..*)$/i',
'', $label);
2218 $listtables[$alias] = $objimport->array_import_tables[0][$alias];
2220 if (count($listtables)) {
2222 foreach ($listtables as $val) {
2241 print $langs->trans(
"Error");
2247 print $langs->trans(
"FieldsTarget").
'</td><td>';
2248 $listfields = array();
2250 $sort_array_match_file_to_database = $array_match_file_to_database;
2251 ksort($sort_array_match_file_to_database);
2253 foreach ($sort_array_match_file_to_database as $code => $label) {
2256 if ($code > count($fieldssource)) {
2260 $alias = preg_replace(
'/(\..*)$/i',
'', $label);
2261 $listfields[$i] = $langs->trans(
"Field").
' '.$code.
'->'.$label;
2263 print count($listfields) ? (implode(
', ', $listfields)) : $langs->trans(
"Error");
2270 $arrayoferrors = array();
2271 $arrayofwarnings = array();
2272 $maxnboferrors = !
getDolGlobalString(
'IMPORT_MAX_NB_OF_ERRORS') ? 50 :
$conf->global->IMPORT_MAX_NB_OF_ERRORS;
2273 $maxnbofwarnings = !
getDolGlobalString(
'IMPORT_MAX_NB_OF_WARNINGS') ? 50 :
$conf->global->IMPORT_MAX_NB_OF_WARNINGS;
2285 $pathfile =
$conf->import->dir_temp.
'/'.$filetoimport;
2286 $result = $obj->import_open_file($pathfile);
2288 global $tablewithentity_cache;
2289 $tablewithentity_cache = array();
2293 while ($sourcelinenb < $nboflines && !$endoffile) {
2295 $arrayrecord = $obj->import_read_record();
2296 if ($arrayrecord ===
false) {
2297 $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');
2301 if ($excludefirstline && ($sourcelinenb < $excludefirstline)) {
2304 if ($endatlinenb && ($sourcelinenb > $endatlinenb)) {
2308 $parameters = array(
2310 'datatoimport' => $datatoimport,
2312 'arrayrecord' => $arrayrecord,
2313 'array_match_file_to_database' => $array_match_file_to_database,
2314 'objimport' => $objimport,
2315 'fieldssource' => $fieldssource,
2316 'importid' => $importid,
2317 'updatekeys' => $updatekeys,
2318 'arrayoferrors' => &$arrayoferrors,
2319 'arrayofwarnings' => &$arrayofwarnings,
2323 $reshook = $hookmanager->executeHooks(
'ImportInsert', $parameters);
2325 $arrayoferrors[$sourcelinenb][] = [
2326 'lib' => implode(
"<br>", array_merge([$hookmanager->error], $hookmanager->errors))
2330 if (empty($reshook)) {
2332 $result = $obj->import_insert($arrayrecord, $array_match_file_to_database, $objimport, count($fieldssource), $importid, $updatekeys);
2334 if (count($obj->errors)) {
2335 $arrayoferrors[$sourcelinenb] = $obj->errors;
2337 if (count($obj->warnings)) {
2338 $arrayofwarnings[$sourcelinenb] = $obj->warnings;
2341 if (!count($obj->errors) && !count($obj->warnings)) {
2346 $reshook = $hookmanager->executeHooks(
'AfterImportInsert', $parameters);
2348 $arrayoferrors[$sourcelinenb][] = [
2349 'lib' => implode(
"<br>", array_merge([$hookmanager->error], $hookmanager->errors))
2354 $obj->import_close_file();
2356 print $langs->trans(
"ErrorFailedToOpenFile", $pathfile);
2359 if (count($arrayoferrors) > 0) {
2366 if (!empty($objimport->array_import_run_sql_after[0]) && is_array($objimport->array_import_run_sql_after[0])) {
2368 foreach ($objimport->array_import_run_sql_after[0] as $sqlafterimport) {
2370 $resqlafterimport = $db->query($sqlafterimport);
2371 if (!$resqlafterimport) {
2372 $arrayoferrors[
'none'][] = array(
'lib' => $langs->trans(
"Error running final request: ".$sqlafterimport));
2390 print
'<div class="info">';
2391 print $langs->trans(
"NbOfLinesImported", $nbok).
'</b><br>';
2392 print $langs->trans(
"NbInsert", empty($obj->nbinsert) ? 0 : $obj->nbinsert).
'<br>';
2393 print $langs->trans(
"NbUpdate", empty($obj->nbupdate) ? 0 : $obj->nbupdate).
'<br>';
2395 print
'<div class="center">';
2396 print $langs->trans(
"FileWasImported", $importid).
'<br>';
2397 print
'<span class="opacitymedium">'.$langs->trans(
"YouCanUseImportIdToFindRecord", $importid).
'</span><br>';
2420 global
$conf, $langs;
2424 if ($key ==
'none') {
2426 print
"\n\n<!-- Box_no-key start-->\n";
2427 print
'<div class="box boximport" style="padding:0;">'.
"\n";
2428 print
'<table summary="boxtable_no-key" class="centpercent nobordernopadding">'.
"\n";
2430 print
"\n\n<!-- Box ".$pos.
" start -->\n";
2431 print
'<div class="box boximport" style="padding: 0;" id="boxto_'.$pos.
'">'.
"\n";
2433 print
'<table summary="boxtable'.$pos.
'" class="nobordernopadding centpercent tableimport">'.
"\n";
2436 if (($pos && $pos > count($fieldssource)) && (!isset($fieldssource[$pos][
"imported"]))) {
2446 } elseif ($key ==
'none') {
2447 print
'<tr style="height:'.$height.
'" class="trimport oddevenimport">';
2448 print
'<td class="nocellnopadd" width="16" style="font-weight: normal">';
2451 print
'<td style="font-weight: normal">';
2457 print
'<tr style="height:'.$height.
'" class="trimport oddevenimport">';
2458 print
'<td class="nocellnopadd" width="16" style="font-weight: normal">';
2461 print
img_picto($langs->trans(
"Column").
' '.
num2Alpha($pos - 1),
'file',
'class="pictofixedwidth"');
2463 if (isset($fieldssource[$pos][
'imported']) && $fieldssource[$pos][
'imported'] ==
false) {
2464 print
'<td class="nowraponall boxtdunused" style="font-weight: normal">';
2466 print
'<td class="nowraponall tdoverflowmax500" style="font-weight: normal">';
2468 print $langs->trans(
"Column").
' '.
num2Alpha($pos - 1).
' (#'.$pos.
')';
2469 if (empty($fieldssource[$pos][
'example1'])) {
2470 $example = $fieldssource[$pos][
'label'];
2472 $example = $fieldssource[$pos][
'example1'];
2476 $example = mb_convert_encoding($example,
'UTF-8',
'ISO-8859-1');
2480 print
'<i class="opacitymedium">'.dol_escape_htmltag($example).
'</i>';
2489 print
"<!-- Box end -->\n\n";
2502 $i = count($fieldssource) + 1;
2505 foreach ($listofkey as $key => $val) {
2506 $maxkey = max($maxkey, $key);
2509 while ($i <= $maxkey) {
2510 if (empty($listofkey[$i])) {
2532 if ($position == count($array)) {
2533 $ret = $array + $insertArray;
2536 foreach ($array as $key => $value) {
2537 if ($position == $i++) {
2538 $ret += $insertArray;
2541 $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.
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.