29require_once
'../main.inc.php';
37require_once DOL_DOCUMENT_ROOT.
'/core/class/html.formfile.class.php';
38require_once DOL_DOCUMENT_ROOT.
'/core/class/html.formother.class.php';
39require_once DOL_DOCUMENT_ROOT.
'/imports/class/import.class.php';
40require_once DOL_DOCUMENT_ROOT.
'/core/modules/import/modules_import.php';
41require_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
42require_once DOL_DOCUMENT_ROOT.
'/core/lib/images.lib.php';
43require_once DOL_DOCUMENT_ROOT.
'/core/lib/import.lib.php';
46$langs->loadLangs(array(
'exports',
'compta',
'errors',
'projects',
'admin',
'products',
'margins'));
49$hookmanager->initHooks(array(
'imports'));
57 'invoice_line' =>
'bill',
59 'order_line' =>
'order',
61 'propal_line' =>
'propal',
62 'intervention' =>
'intervention',
63 'inter_line' =>
'intervention',
65 'member_type' =>
'group',
66 'subscription' =>
'payment',
67 'payment' =>
'payment',
69 'tax_type' =>
'generic',
71 'account' =>
'account',
72 'product' =>
'product',
73 'virtualproduct' =>
'product',
74 'subproduct' =>
'product',
75 'product_supplier_ref' =>
'product',
77 'warehouse' =>
'stock',
79 'stockbatch' =>
'stock',
80 'category' =>
'category',
81 'shipment' =>
'sending',
82 'shipment_line' =>
'sending',
83 'project' =>
'project',
85 'reception' =>
'sending',
86 'reception_line' =>
'sending',
87 'expensereport' =>
'trip',
88 'expensereport_line' =>
'trip',
89 'holiday' =>
'holiday',
90 'contract_line' =>
'contract',
91 'translation' =>
'generic',
99 'company' =>
'Company',
100 'contact' =>
'Contact',
102 'invoice_line' =>
'InvoiceLine',
104 'order_line' =>
'OrderLine',
105 'propal' =>
'Proposal',
106 'propal_line' =>
'ProposalLine',
107 'intervention' =>
'Intervention',
108 'inter_line' =>
'InterLine',
109 'member' =>
'Member',
110 'member_type' =>
'MemberType',
111 'subscription' =>
'Subscription',
112 'tax' =>
'SocialContribution',
113 'tax_type' =>
'DictionarySocialContributions',
114 'account' =>
'BankTransactions',
115 'payment' =>
'Payment',
116 'product' =>
'Product',
117 'virtualproduct' =>
'AssociatedProducts',
118 'subproduct' =>
'SubProduct',
119 'product_supplier_ref' =>
'SupplierPrices',
120 'service' =>
'Service',
122 'movement' =>
'StockMovement',
124 'stockbatch' =>
'StockDetailPerBatch',
125 'warehouse' =>
'Warehouse',
126 'category' =>
'Category',
128 'trip' =>
'TripsAndExpenses',
129 'shipment' =>
'Shipments',
130 'shipment_line' =>
'ShipmentLine',
131 'project' =>
'Projects',
132 'projecttask' =>
'Tasks',
133 'task_time' =>
'TaskTimeSpent',
135 'expensereport' =>
'ExpenseReport',
136 'expensereport_line' =>
'ExpenseReportLine',
137 'holiday' =>
'TitreRequestCP',
138 'contract' =>
'Contract',
139 'contract_line' =>
'ContractLine',
140 'translation' =>
'Translation',
142 'bomline' =>
'BOMLine'
145$datatoimport =
GETPOST(
'datatoimport');
147$filetoimport =
GETPOST(
'filetoimport');
148$action =
GETPOST(
'action',
'alpha');
149$confirm =
GETPOST(
'confirm',
'alpha');
151$import_name =
GETPOST(
'import_name');
154$excludefirstline = (
GETPOST(
'excludefirstline') ?
GETPOST(
'excludefirstline') : 2);
155$endatlinenb = (
GETPOST(
'endatlinenb') ?
GETPOST(
'endatlinenb') :
'');
156$updatekeys = (
GETPOST(
'updatekeys',
'array') ?
GETPOST(
'updatekeys',
'array') : array());
157$separator = (
GETPOST(
'separator',
'nohtml') ?
GETPOST(
'separator',
'nohtml', 3) :
'');
158$enclosure = (
GETPOST(
'enclosure',
'nohtml') ?
GETPOST(
'enclosure',
'nohtml') :
'"');
159$charset =
GETPOST(
'charset',
'aZ09');
160$separator_used = str_replace(
'\t',
"\t", $separator);
163$objimport =
new Import($db);
164$objimport->load_arrays($user, ($step == 1 ?
'' : $datatoimport));
166if (empty($updatekeys) && !empty($objimport->array_import_preselected_updatekeys[0])) {
167 $updatekeys = $objimport->array_import_preselected_updatekeys[0];
172$form =
new Form($db);
177if (empty($array_match_file_to_database)) {
178 $serialized_array_match_file_to_database = isset($_SESSION[
"dol_array_match_file_to_database_select"]) ? $_SESSION[
"dol_array_match_file_to_database_select"] :
'';
179 $array_match_file_to_database = array();
180 $fieldsarray = explode(
',', $serialized_array_match_file_to_database);
181 foreach ($fieldsarray as $elem) {
182 $tabelem = explode(
'=', $elem, 2);
184 $val = (isset($tabelem[1]) ? $tabelem[1] :
'');
186 $array_match_file_to_database[$key] = $val;
196if ($action ==
'deleteprof' && $user->hasRight(
'import',
'run')) {
199 $result = $objimport->delete($user);
204if ($action ==
'add_import_model' && $user->hasRight(
'import',
'run')) {
208 foreach ($array_match_file_to_database as $key => $val) {
212 $hexa .= $key.
'='.$val;
215 $objimport->model_name = $import_name;
216 $objimport->datatoimport = $datatoimport;
217 $objimport->hexa = $hexa;
218 $objimport->fk_user = (
GETPOST(
'visibility',
'aZ09') ==
'all' ? 0 : $user->id);
220 $result = $objimport->create($user);
222 setEventMessages($langs->trans(
"ImportModelSaved", $objimport->model_name),
null,
'mesgs');
225 $langs->load(
"errors");
226 if ($objimport->errno ==
'DB_ERROR_RECORD_ALREADY_EXISTS') {
227 setEventMessages($langs->trans(
"ErrorImportDuplicateProfil"),
null,
'errors');
233 setEventMessages($langs->trans(
"ErrorFieldRequired", $langs->transnoentities(
"ImportModelName")),
null,
'errors');
237if ($step == 3 && $datatoimport) {
245 if (is_numeric($resultupload) && $resultupload > 0) {
246 dol_syslog(
"File ".$fullpath.
" was added for import");
248 $langs->load(
"errors");
254 if ($action ==
'confirm_deletefile' && $confirm ==
'yes' && $user->hasRight(
'import',
'run')) {
255 $langs->load(
"other");
257 $param =
'&datatoimport='.urlencode($datatoimport).
'&format='.urlencode($format);
258 if ($excludefirstline) {
259 $param .=
'&excludefirstline='.urlencode($excludefirstline);
262 $param .=
'&endatlinenb='.urlencode($endatlinenb);
265 $file = $conf->import->dir_temp.
'/'.
GETPOST(
'urlfile');
272 header(
'Location: '.$_SERVER[
"PHP_SELF"].
'?step='.$step.$param);
277if ($step == 4 && $action ==
'select_model' && $user->hasRight(
'import',
'run')) {
279 $_SESSION[
"dol_array_match_file_to_database"] =
'';
280 $serialized_array_match_file_to_database =
'';
281 $array_match_file_to_database = array();
285 $result = $objimport->fetch($importmodelid);
287 $serialized_array_match_file_to_database = $objimport->hexa;
288 $fieldsarray = explode(
',', $serialized_array_match_file_to_database);
289 foreach ($fieldsarray as $elem) {
290 $tabelem = explode(
'=', $elem);
294 $array_match_file_to_database[$key] = $val;
297 $_SESSION[
"dol_array_match_file_to_database"] = $serialized_array_match_file_to_database;
298 $_SESSION[
'dol_array_match_file_to_database_select'] = $_SESSION[
"dol_array_match_file_to_database"];
301if ($action ==
'saveselectorder' && $user->hasRight(
'import',
'run')) {
303 $serialized_array_match_file_to_database =
'';
305 $selectorder = explode(
",",
GETPOST(
'selectorder'));
306 $fieldtarget = $fieldstarget = $objimport->array_import_fields[0];
307 foreach ($selectorder as $key => $code) {
308 $serialized_array_match_file_to_database .= $key.
'='.$code;
309 $serialized_array_match_file_to_database .=
',';
311 $serialized_array_match_file_to_database = substr($serialized_array_match_file_to_database, 0, -1);
312 dol_syslog(
'dol_array_match_file_to_database_select='.$serialized_array_match_file_to_database);
313 $_SESSION[
"dol_array_match_file_to_database_select"] = $serialized_array_match_file_to_database;
323$help_url =
'EN:Module_Imports_En|FR:Module_Imports|ES:Módulo_Importaciones';
326if ($step == 1 || !$datatoimport) {
328 $serialized_array_match_file_to_database =
'';
329 $array_match_file_to_database = array();
330 $_SESSION[
"dol_array_match_file_to_database"] =
'';
331 $_SESSION[
"dol_array_match_file_to_database_select"] =
'';
334 if ($excludefirstline) {
335 $param .=
'&excludefirstline='.urlencode($excludefirstline);
338 $param .=
'&endatlinenb='.urlencode($endatlinenb);
341 $param .=
'&separator='.urlencode($separator);
344 $param .=
'&enclosure='.urlencode($enclosure);
347 llxHeader(
'', $langs->trans(
"NewImport"), $help_url);
353 print
'<div class="opacitymedium">'.$langs->trans(
"SelectImportDataSet").
'</div>';
357 $nbmodulesnotautoenabled = count($conf->modules);
358 $listofmodulesautoenabled = array(
'user',
'agenda',
'fckeditor',
'export',
'import');
359 foreach ($listofmodulesautoenabled as $moduleautoenable) {
360 if (in_array($moduleautoenable, $conf->modules)) {
361 $nbmodulesnotautoenabled--;
365 if ($user->admin && $nbmodulesnotautoenabled <
getDolGlobalInt(
'MAIN_MIN_NB_ENABLED_MODULE_FOR_WARNING', 1)) {
366 print
info_admin($langs->trans(
"WarningOnlyProfilesOfActivatedModules").
' '.$langs->trans(
"YouCanEnableModulesFrom"));
372 print
'<div class="div-table-responsive-no-min">';
373 print
'<table class="noborder centpercent nomarginbottom">';
374 print
'<tr class="liste_titre">';
375 print
'<td>'.$langs->trans(
"Module").
'</td>';
376 print
'<td>'.$langs->trans(
"ImportableDatas").
'</td>';
377 print
'<td> </td>';
380 if (count($objimport->array_import_module)) {
381 $sortedarrayofmodules =
dol_sort_array($objimport->array_import_module,
'position_of_profile',
'asc', 0, 0, 1);
382 foreach ($sortedarrayofmodules as $key => $value) {
384 $titleofmodule = $objimport->array_import_module[$key][
'module']->getName();
385 print
'<tr class="oddeven"><td class="tdoverflowmax200" title="'.dolPrintHTML($titleofmodule).
'">';
387 if (in_array($objimport->array_import_code[$key], array(
'produit_supplierprices',
'produit_multiprice',
'produit_languages'))) {
388 $titleofmodule = $langs->trans(
"ProductOrService");
392 $entity = preg_replace(
'/:.*$/',
'', $objimport->array_import_icon[$key]);
393 $entityicon = strtolower(!empty($entitytoicon[$entity]) ? $entitytoicon[$entity] : $entity);
394 $label = $objimport->array_import_label[$key];
395 print
'<div class="twolinesmax-normallineheight minwidth200onall">';
396 print
img_object($objimport->array_import_module[$key][
'module']->getName(), $entityicon,
'class="pictofixedwidth"');
399 print
'</td><td style="text-align: right">';
400 if ($objimport->array_import_perms[$key]) {
401 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>';
403 print $langs->trans(
"NotEnoughPermissions");
408 print
'<tr><td class="oddeven" colspan="3">'.$langs->trans(
"NoImportableData").
'</td></tr>';
418if ($step == 2 && $datatoimport) {
419 $param =
'&datatoimport='.urlencode($datatoimport);
420 if ($excludefirstline) {
421 $param .=
'&excludefirstline='.urlencode($excludefirstline);
424 $param .=
'&endatlinenb='.urlencode($endatlinenb);
427 $param .=
'&separator='.urlencode($separator);
430 $param .=
'&enclosure='.urlencode($enclosure);
433 llxHeader(
'', $langs->trans(
"NewImport"), $help_url);
439 print
'<div class="underbanner clearboth"></div>';
440 print
'<div class="fichecenter">';
442 print
'<table class="border tableforfield centpercent">';
445 print
'<tr><td class="titlefieldcreate">'.$langs->trans(
"Module").
'</td>';
447 $titleofmodule = $objimport->array_import_module[0][
'module']->getName();
449 if (in_array($objimport->array_import_code[0], array(
'produit_supplierprices',
'produit_multiprice',
'produit_languages'))) {
450 $titleofmodule = $langs->trans(
"ProductOrService");
452 print $titleofmodule;
456 print
'<tr><td>'.$langs->trans(
"DatasetToImport").
'</td>';
458 $entity = preg_replace(
'/:.*$/',
'', $objimport->array_import_icon[0]);
459 $entityicon = strtolower(!empty($entitytoicon[$entity]) ? $entitytoicon[$entity] : $entity);
460 print
img_object($objimport->array_import_module[0][
'module']->getName(), $entityicon).
' ';
461 print $objimport->array_import_label[0];
469 print
'<form name="userfile" action="'.$_SERVER[
"PHP_SELF"].
'" enctype="multipart/form-data" METHOD="POST">';
470 print
'<input type="hidden" name="token" value="'.newToken().
'">';
474 print
'<span class="opacitymedium">';
475 $s = $langs->trans(
"ChooseFormatOfFileToImport",
'{s1}');
476 $s = str_replace(
'{s1}',
img_picto(
'',
'next'), $s);
478 print
'</span><br><br>';
482 print
'<div class="div-table-responsive-no-min">';
483 print
'<table class="noborder centpercent" cellpadding="4">';
488 print
'<tr class="liste_titre"><td colspan="5">';
489 print $langs->trans(
"FileMustHaveOneOfFollowingFormat");
491 $list = $objmodelimport->listOfAvailableImportFormat($db);
492 foreach ($list as $key) {
493 print
'<tr class="oddeven">';
494 print
'<td width="16">'.img_picto_common($key, $objmodelimport->getPictoForKey($key)).
'</td>';
495 $htmltext = $objmodelimport->getDriverDescForKey($key);
496 print
'<td>'.$form->textwithpicto($objmodelimport->getDriverLabelForKey($key), $htmltext).
'</td>';
497 print
'<td style="text-align:center">';
498 if (empty($objmodelimport->drivererror[$key])) {
499 $filename = $langs->transnoentitiesnoconv(
"ExampleOfImportFile").
'_'.$datatoimport.
'.'.$key;
500 print
'<a href="'.DOL_URL_ROOT.
'/imports/emptyexample.php?format='.$key.$param.
'&output=file&file='.urlencode($filename).
'" target="_blank" rel="noopener noreferrer">';
501 print
img_picto(
'',
'download',
'class="paddingright opacitymedium"');
502 print $langs->trans(
"DownloadEmptyExampleShort");
504 print $form->textwithpicto(
'', $langs->trans(
"DownloadEmptyExample").
'.<br>'.$langs->trans(
"StarAreMandatory"));
510 print
'<td style="text-align:right">';
511 if (empty($objmodelimport->drivererror[$key])) {
512 print
'<a href="'.DOL_URL_ROOT.
'/imports/import.php?step=3&format='.$key.$param.
'">'.
img_picto($langs->trans(
"SelectFormat"),
'next',
'class="fa-15"').
'</a>';
526if ($step == 3 && $datatoimport) {
527 $param =
'&datatoimport='.urlencode($datatoimport).
'&format='.urlencode($format);
528 if ($excludefirstline) {
529 $param .=
'&excludefirstline='.urlencode($excludefirstline);
532 $param .=
'&endatlinenb='.urlencode($endatlinenb);
535 $param .=
'&separator='.urlencode($separator);
538 $param .=
'&enclosure='.urlencode($enclosure);
541 $list = $objmodelimport->listOfAvailableImportFormat($db);
543 llxHeader(
'', $langs->trans(
"NewImport"), $help_url);
552 if ($action ==
'delete') {
553 print $form->formconfirm($_SERVER[
"PHP_SELF"].
'?urlfile='.urlencode(
GETPOST(
'urlfile')).
'&step=3'.$param, $langs->trans(
'DeleteFile'), $langs->trans(
'ConfirmDeleteFile'),
'confirm_deletefile',
'', 0, 1);
556 print
'<div class="underbanner clearboth"></div>';
557 print
'<div class="fichecenter">';
559 print
'<table class="border tableforfield centpercent">';
562 print
'<tr><td class="titlefieldcreate">'.$langs->trans(
"Module").
'</td>';
564 $titleofmodule = $objimport->array_import_module[0][
'module']->getName();
566 if (in_array($objimport->array_import_code[0], array(
'produit_supplierprices',
'produit_multiprice',
'produit_languages'))) {
567 $titleofmodule = $langs->trans(
"ProductOrService");
569 print $titleofmodule;
573 print
'<tr><td>'.$langs->trans(
"DatasetToImport").
'</td>';
575 $entity = preg_replace(
'/:.*$/',
'', $objimport->array_import_icon[0]);
576 $entityicon = strtolower(!empty($entitytoicon[$entity]) ? $entitytoicon[$entity] : $entity);
577 print
img_object($objimport->array_import_module[0][
'module']->getName(), $entityicon).
' ';
578 print $objimport->array_import_label[0];
586 print
load_fiche_titre($langs->trans(
"InformationOnSourceFile"),
'',
'file-export');
588 print
'<div class="underbanner clearboth"></div>';
589 print
'<div class="fichecenter">';
590 print
'<table width="100%" class="border tableforfield">';
593 print
'<tr><td class="titlefieldcreate">'.$langs->trans(
"SourceFileFormat").
'</td>';
594 print
'<td class="nowraponall">';
595 $text = $objmodelimport->getDriverDescForKey($format);
597 print $form->textwithpicto($objmodelimport->getDriverLabelForKey($format), $text);
598 print
'</td><td style="text-align:right" class="nowrap">';
599 $filename = $langs->transnoentitiesnoconv(
"ExampleOfImportFile").
'_'.$datatoimport.
'.'.$format;
600 print
'<a href="'.DOL_URL_ROOT.
'/imports/emptyexample.php?format='.$format.$param.
'&output=file&file='.urlencode($filename).
'" target="_blank" rel="noopener noreferrer">';
601 print
img_picto(
'',
'download',
'class="paddingright opacitymedium"');
602 print $langs->trans(
"DownloadEmptyExampleShort");
604 print $form->textwithpicto(
'', $langs->trans(
"DownloadEmptyExample").
'.<br>'.$langs->trans(
"StarAreMandatory"));
613 if ($format ==
'xlsx' && !class_exists(
'XMLWriter')) {
614 $langs->load(
"install");
615 print
info_admin($langs->trans(
"ErrorPHPDoesNotSupport",
'php-xml'), 0, 0,
'1',
'error');
621 print
'<form name="userfile" action="'.$_SERVER[
"PHP_SELF"].
'" enctype="multipart/form-data" method="POST">';
622 print
'<input type="hidden" name="token" value="'.newToken().
'">';
623 print
'<input type="hidden" value="'.$step.
'" name="step">';
624 print
'<input type="hidden" value="'.dol_escape_htmltag($format).
'" name="format">';
625 print
'<input type="hidden" value="'.$excludefirstline.
'" name="excludefirstline">';
626 print
'<input type="hidden" value="'.$endatlinenb.
'" name="endatlinenb">';
627 print
'<input type="hidden" value="'.dol_escape_htmltag($separator).
'" name="separator">';
628 print
'<input type="hidden" value="'.dol_escape_htmltag($enclosure).
'" name="enclosure">';
629 print
'<input type="hidden" value="'.dol_escape_htmltag($datatoimport).
'" name="datatoimport">';
631 print
'<span class="opacitymedium">';
632 $s = $langs->trans(
"ChooseFileToImport",
'{s1}');
633 $s = str_replace(
'{s1}',
img_picto(
'',
'next'), $s);
635 print
'</span><br><br>';
640 print
'<div class="marginbottomonly">';
642 $maxmin = $maxfilesizearray[
'maxmin'];
644 print
'<input type="hidden" name="MAX_FILE_SIZE" value="'.($maxmin * 1024).
'">';
646 print
'<input type="file" name="userfile" size="20" maxlength="80"> ';
648 print
'<input type="submit" class="button small" value="'.$langs->trans(
"AddFile").
'"'.$out.
' name="sendit">';
652 $maxphp = @ini_get(
'upload_max_filesize');
653 if (preg_match(
'/k$/i', $maxphp)) {
654 $maxphp = (int) substr($maxphp, 0, -1);
656 if (preg_match(
'/m$/i', $maxphp)) {
657 $maxphp = (int) substr($maxphp, 0, -1) * 1024;
659 if (preg_match(
'/g$/i', $maxphp)) {
660 $maxphp = (int) substr($maxphp, 0, -1) * 1024 * 1024;
662 if (preg_match(
'/t$/i', $maxphp)) {
663 $maxphp = (int) substr($maxphp, 0, -1) * 1024 * 1024 * 1024;
665 $maxphp2 = @ini_get(
'post_max_size');
666 if (preg_match(
'/k$/i', $maxphp2)) {
667 $maxphp2 = (int) substr($maxphp2, 0, -1);
669 if (preg_match(
'/m$/i', $maxphp2)) {
670 $maxphp2 = (int) substr($maxphp2, 0, -1) * 1024;
672 if (preg_match(
'/g$/i', $maxphp2)) {
673 $maxphp2 = (int) substr($maxphp2, 0, -1) * 1024 * 1024;
675 if (preg_match(
'/t$/i', $maxphp2)) {
676 $maxphp2 = (int) substr($maxphp2, 0, -1) * 1024 * 1024 * 1024;
680 $maxphptoshow = $maxphptoshowparam =
'';
682 $maxmin = min($max, $maxphp);
683 $maxphptoshow = $maxphp;
684 $maxphptoshowparam =
'upload_max_filesize';
687 $maxmin = min($max, $maxphp2);
688 if ($maxphp2 < $maxphp) {
689 $maxphptoshow = $maxphp2;
690 $maxphptoshowparam =
'post_max_size';
694 $langs->load(
'other');
696 $out .=
info_admin($langs->trans(
"ThisLimitIsDefinedInSetup", $max, $maxphptoshow), 1);
698 $out .=
' ('.$langs->trans(
"UploadDisabled").
')';
704 $filearray =
dol_dir_list($conf->import->dir_temp,
'files', 0,
'',
'',
'name', SORT_DESC);
705 if (count($filearray) > 0) {
706 print
'<div class="div-table-responsive-no-min">';
707 print
'<table class="noborder centpercent" width="100%" cellpadding="4">';
709 $dir = $conf->import->dir_temp;
713 foreach ($filearray as $key => $val) {
714 $file = $val[
'name'];
718 $file = mb_convert_encoding($file,
'UTF-8',
'ISO-8859-1');
721 if (preg_match(
'/^\./', $file)) {
725 $modulepart =
'import';
726 $urlsource = $_SERVER[
"PHP_SELF"].
'?step='.$step.$param.
'&filetoimport='.urlencode($filetoimport);
727 $relativepath = $file;
729 print
'<tr class="oddeven">';
731 print
img_mime($file,
'',
'pictofixedwidth');
732 print
'<a data-ajax="false" href="'.DOL_URL_ROOT.
'/document.php?modulepart='.$modulepart.
'&file='.urlencode($relativepath).
'&step=3'.$param.
'" target="_blank" rel="noopener noreferrer">';
737 print
'<td style="text-align:right">'.dol_print_size(
dol_filesize($dir.
'/'.$file)).
'</td>';
739 print
'<td style="text-align:right">'.dol_print_date(
dol_filemtime($dir.
'/'.$file),
'dayhour').
'</td>';
741 print
'<td style="text-align:right"><a href="'.$_SERVER[
'PHP_SELF'].
'?action=delete&token='.
newToken().
'&step=3'.$param.
'&urlfile='.urlencode($relativepath);
742 print
'">'.img_delete().
'</a></td>';
744 print
'<td style="text-align:right">';
745 print
'<a href="'.$_SERVER[
'PHP_SELF'].
'?step=4'.$param.
'&filetoimport='.urlencode($relativepath).
'">'.
img_picto($langs->trans(
"NewImport"),
'next',
'class="fa-15"').
'</a>';
759if ($step == 4 && $datatoimport) {
761 $serialized_array_match_file_to_database = isset($_SESSION[
"dol_array_match_file_to_database_select"]) ? $_SESSION[
"dol_array_match_file_to_database_select"] :
'';
762 $fieldsarray = explode(
',', $serialized_array_match_file_to_database);
763 $array_match_file_to_database = array();
764 foreach ($fieldsarray as $elem) {
765 $tabelem = explode(
'=', $elem, 2);
767 $val = (isset($tabelem[1]) ? $tabelem[1] :
'');
769 $array_match_file_to_database[$key] = $val;
778 $list = $objmodelimport->listOfAvailableImportFormat($db);
780 if (empty($separator)) {
781 $separator = (!
getDolGlobalString(
'IMPORT_CSV_SEPARATOR_TO_USE') ?
',' : $conf->global->IMPORT_CSV_SEPARATOR_TO_USE);
785 if ($model ==
'csv' && strlen($separator) == 1 && !GETPOSTISSET(
'separator')) {
786 '@phan-var-force ImportCsv $obj';
788 $fh = fopen($conf->import->dir_temp.
'/'.$filetoimport,
'r');
790 $sline = fgets($fh, 1000000);
792 $nboccurence = substr_count($sline, $separator);
793 $nboccurencea = substr_count($sline,
',');
794 $nboccurenceb = substr_count($sline,
';');
796 if ($nboccurence == 0) {
797 if ($nboccurencea > 2) {
799 } elseif ($nboccurenceb > 2) {
807 $separator_used = str_replace(
'\t',
"\t", $separator);
810 $dir = DOL_DOCUMENT_ROOT.
"/core/modules/import/";
811 $file =
"import_".$model.
".modules.php";
812 $classname =
"Import".ucfirst($model);
813 require_once $dir.$file;
814 $obj =
new $classname($db, $datatoimport);
815 '@phan-var-force ModeleImports $obj';
817 if (!empty($obj->error)) {
818 $langs->load(
"errors");
819 $param =
'&datatoimport='.$datatoimport.
'&format='.$format;
821 header(
"Location: ".$_SERVER[
"PHP_SELF"].
'?step=3'.$param.
'&filetoimport='.urlencode($relativepath));
825 if ($model ==
'csv') {
826 '@phan-var-force ImportCsv $obj';
827 $obj->separator = $separator_used;
828 $obj->enclosure = $enclosure;
831 if ($model ==
'xlsx') {
832 '@phan-var-force ImportXlsx $obj';
833 if (!preg_match(
'/\.xlsx$/i', $filetoimport)) {
834 $langs->load(
"errors");
835 $param =
'&datatoimport='.$datatoimport.
'&format='.$format;
836 setEventMessages($langs->trans(
"ErrorFileMustHaveFormat", $model),
null,
'errors');
837 header(
"Location: ".$_SERVER[
"PHP_SELF"].
'?step=3'.$param.
'&filetoimport='.urlencode($relativepath));
843 $array_match_file_to_database = array();
847 $fieldssource = array();
849 $result = $obj->import_open_file($conf->import->dir_temp.
'/'.$filetoimport);
852 $arrayrecord = $obj->import_read_record();
856 foreach ($arrayrecord as $key => $val) {
857 if ($val[
"type"] != -1) {
858 $fieldssource[$i][
'example1'] =
dol_trunc($val[
'val'], 128);
860 $fieldssource[$i][
'example1'] = $langs->trans(
'Empty');
862 $fieldssource[$i][
'imported'] =
false;
865 $obj->import_close_file();
869 $fieldstarget = $objimport->array_import_fields[0];
870 $minpos = min(count($fieldssource), count($fieldstarget));
874 $initialloadofstep4 =
false;
875 if (empty($_SESSION[
'dol_array_match_file_to_database_select'])) {
876 $initialloadofstep4 =
true;
880 if (count($array_match_file_to_database) == 0) {
886 $num = count($fieldssource);
887 while ($pos <= $num) {
888 if ($num >= 1 && $pos <= $num) {
890 foreach ($fieldstarget as $key => $val) {
891 if ($posbis < $pos) {
896 $array_match_file_to_database[$pos] = $key;
903 $array_match_database_to_file = array_flip($array_match_file_to_database);
907 $fieldstarget_tmp = array();
908 $arraykeysfieldtarget = array_keys($fieldstarget);
910 foreach ($fieldstarget as $key => $label) {
911 $isrequired = preg_match(
'/\*$/', $label);
912 if (!empty($isrequired)) {
913 $newlabel = substr($label, 0, -1);
914 $fieldstarget_tmp[$key] = array(
"label" => $newlabel,
"required" =>
true);
916 $fieldstarget_tmp[$key] = array(
"label" => $label,
"required" =>
false);
918 if (!empty($array_match_database_to_file[$key])) {
919 $fieldstarget_tmp[$key][
"imported"] =
true;
920 $fieldstarget_tmp[$key][
"position"] = (int) $array_match_database_to_file[$key] - 1;
922 while (!empty($array_match_database_to_file[$keytoswap])) {
923 if ($position + 1 > $array_match_database_to_file[$keytoswap]) {
924 $keytoswapwith = $array_match_database_to_file[$keytoswap] - 1;
925 $tmp = [$keytoswap => $fieldstarget_tmp[$keytoswap]];
926 unset($fieldstarget_tmp[$keytoswap]);
927 $fieldstarget_tmp =
arrayInsert($fieldstarget_tmp, $keytoswapwith, $tmp);
928 $keytoswapwith = $arraykeysfieldtarget[$array_match_database_to_file[$keytoswap] - 1];
929 $tmp = $fieldstarget_tmp[$keytoswapwith];
930 unset($fieldstarget_tmp[$keytoswapwith]);
931 $fieldstarget_tmp[$keytoswapwith] = $tmp;
932 $keytoswap = $keytoswapwith;
938 $fieldstarget_tmp[$key][
"imported"] =
false;
942 $fieldstarget = $fieldstarget_tmp;
951 $param =
'&format='.$format.
'&datatoimport='.urlencode($datatoimport).
'&filetoimport='.urlencode($filetoimport);
952 if ($excludefirstline) {
953 $param .=
'&excludefirstline='.urlencode($excludefirstline);
956 $param .=
'&endatlinenb='.urlencode($endatlinenb);
959 $param .=
'&separator='.urlencode($separator);
962 $param .=
'&enclosure='.urlencode($enclosure);
965 llxHeader(
'', $langs->trans(
"NewImport"), $help_url);
971 print
'<div class="underbanner clearboth"></div>';
972 print
'<div class="fichecenter">';
974 print
'<table class="centpercent border tableforfield">';
977 print
'<tr><td class="titlefieldcreate">'.$langs->trans(
"Module").
'</td>';
979 $titleofmodule = $objimport->array_import_module[0][
'module']->getName();
981 if (in_array($objimport->array_import_code[0], array(
'produit_supplierprices',
'produit_multiprice',
'produit_languages'))) {
982 $titleofmodule = $langs->trans(
"ProductOrService");
984 print $titleofmodule;
988 print
'<tr><td>'.$langs->trans(
"DatasetToImport").
'</td>';
990 $entity = preg_replace(
'/:.*$/',
'', $objimport->array_import_icon[0]);
991 $entityicon = strtolower(!empty($entitytoicon[$entity]) ? $entitytoicon[$entity] : $entity);
992 print
img_object($objimport->array_import_module[0][
'module']->getName(), $entityicon).
' ';
993 print $objimport->array_import_label[0];
1001 print
load_fiche_titre($langs->trans(
"InformationOnSourceFile"),
'',
'file-export');
1003 print
'<div class="underbanner clearboth"></div>';
1004 print
'<div class="fichecenter">';
1005 print
'<table width="100%" class="border tableforfield">';
1008 print
'<tr><td class="titlefieldcreate">'.$langs->trans(
"SourceFileFormat").
'</td>';
1009 print
'<td class="nowraponall">';
1010 $text = $objmodelimport->getDriverDescForKey($format);
1012 print $form->textwithpicto($objmodelimport->getDriverLabelForKey($format), $text);
1016 if ($model ==
'csv') {
1017 '@phan-var-force ImportCsv $obj';
1018 print
'<tr><td>'.$langs->trans(
"CsvOptions").
'</td>';
1020 print
'<form method="POST">';
1021 print
'<input type="hidden" name="token" value="'.newToken().
'">';
1022 print
'<input type="hidden" value="'.$step.
'" name="step">';
1023 print
'<input type="hidden" value="'.$format.
'" name="format">';
1024 print
'<input type="hidden" value="'.$excludefirstline.
'" name="excludefirstline">';
1025 print
'<input type="hidden" value="'.$endatlinenb.
'" name="endatlinenb">';
1026 print
'<input type="hidden" value="'.$datatoimport.
'" name="datatoimport">';
1027 print
'<input type="hidden" value="'.$filetoimport.
'" name="filetoimport">';
1028 print $langs->trans(
"Separator").
' : ';
1029 print
'<input type="text" class="width25 center" name="separator" value="'.dol_escape_htmltag($separator).
'"/>';
1030 print
' '.$langs->trans(
"Enclosure").
' : ';
1031 print
'<input type="text" class="width25 center" name="enclosure" value="'.dol_escape_htmltag($enclosure).
'"/> ';
1032 print
'<input name="update" type="submit" value="'.$langs->trans(
'Update').
'" class="button smallpaddingimp" />';
1038 print
'<tr><td>'.$langs->trans(
"FileToImport").
'</td>';
1040 $modulepart =
'import';
1041 $relativepath =
GETPOST(
'filetoimport');
1042 print
'<a data-ajax="false" href="'.DOL_URL_ROOT.
'/document.php?modulepart='.$modulepart.
'&file='.urlencode($relativepath).
'&step=4'.$param.
'" target="_blank" rel="noopener noreferrer">';
1043 print
img_mime($file,
'',
'pictofixedwidth');
1044 print $filetoimport;
1045 print
img_picto($langs->trans(
"Download"),
'download',
'class="paddingleft opacitymedium"');
1058 print
'<!-- List of source fields -->'.
"\n";
1059 print
'<form action="'.$_SERVER[
"PHP_SELF"].
'" method="POST">';
1060 print
'<input type="hidden" name="token" value="'.newToken().
'">';
1061 print
'<input type="hidden" name="action" value="select_model">';
1062 print
'<input type="hidden" name="step" value="4">';
1063 print
'<input type="hidden" name="format" value="'.$format.
'">';
1064 print
'<input type="hidden" name="datatoimport" value="'.$datatoimport.
'">';
1065 print
'<input type="hidden" name="filetoimport" value="'.$filetoimport.
'">';
1066 print
'<input type="hidden" name="excludefirstline" value="'.$excludefirstline.
'">';
1067 print
'<input type="hidden" name="endatlinenb" value="'.$endatlinenb.
'">';
1068 print
'<input type="hidden" name="separator" value="'.dol_escape_htmltag($separator).
'">';
1069 print
'<input type="hidden" name="enclosure" value="'.dol_escape_htmltag($enclosure).
'">';
1072 print
'<div class="marginbottomonly">';
1073 print
'<span class="opacitymedium">';
1074 $s = $langs->trans(
"SelectImportFieldsSource",
'{s1}');
1075 $s = str_replace(
'{s1}',
img_picto(
'',
'grip_title',
'', 0, 0, 0,
'',
'', 0), $s);
1078 $htmlother->select_import_model((
string) $importmodelid,
'importmodelid', $datatoimport, 1, $user->id);
1079 print
'<input type="submit" class="button smallpaddingimp reposition" value="'.$langs->trans(
"Select").
'">';
1084 print
'<div class="div-table-responsive-no-min">';
1085 print
'<table class="noborder centpercent">';
1086 print
'<tr class="liste_titre">';
1087 print
'<td>'.$langs->trans(
"FieldsInSourceFile").
'</td>';
1088 print
'<td>'.$langs->trans(
"FieldsInTargetDatabase").
'</td>';
1093 print
'<tr valign="top"><td width="50%" class="nopaddingleftimp">';
1095 $fieldsplaced = array();
1096 $valforsourcefieldnb = array();
1097 $listofkeys = array();
1098 foreach ($array_match_file_to_database as $key => $val) {
1099 $listofkeys[$key] = 1;
1102 print
"\n<!-- Box left container -->\n";
1103 print
'<div id="left" class="connectedSortable">'.
"\n";
1108 foreach ($fieldssource as $key => $val) {
1109 show_elem($fieldssource, $key, (
string) $key);
1110 $listofkeys[$key] = 1;
1111 $fieldsplaced[$key] = 1;
1112 $valforsourcefieldnb[$lefti] = $key;
1122 print
"<!-- End box left container -->\n";
1125 print
'</td><td width="50%" class="nopaddingrightimp">';
1129 $optionsall = array();
1130 foreach ($fieldstarget as $code => $line) {
1131 $tmparray = explode(
'|', $line[
"label"]);
1133 foreach ($tmparray as $tmpkey => $tmpval) {
1134 $labeltoshow .= ($labeltoshow ?
' '.$langs->trans(
'or').
' ' :
'').$langs->transnoentities($tmpval);
1139 $optionsall[$code] = array(
1140 'labelkey' => $line[
'label'],
1141 'labelkeyarray' => $tmparray,
1142 'label' => $labeltoshow,
1143 'required' => (empty($line[
"required"]) ? 0 : 1),
1144 'position' => (!empty($line[
'position']) ? $line[
'position'] : 0),
1152 $mandatoryfieldshavesource =
true;
1165 $modetoautofillmapping =
'session';
1166 if ($initialloadofstep4) {
1167 $modetoautofillmapping =
'guess';
1171 print
'<table class="nobordernopadding centpercent tableimport">';
1172 foreach ($fieldssource as $code => $line) {
1177 print
'<tr style="height:'.$height.
'" class="trimport oddevenimport">';
1179 $entity = (!empty($objimport->array_import_entities[0][$code]) ? $objimport->array_import_entities[0][$code] : $objimport->array_import_icon[0]);
1181 $entityicon = !empty($entitytoicon[$entity]) ? $entitytoicon[$entity] : $entity;
1182 $entitylang = !empty($entitytolang[$entity]) ? $entitytolang[$entity] : $objimport->array_import_label[0];
1184 print
'<td class="nowraponall hideonsmartphone" style="font-weight: normal">=> </td>';
1185 print
'<td class="nowraponall" style="font-weight: normal">';
1187 $selectforline =
'';
1188 $selectforline .=
'<select id="selectorderimport_'.($i + 1).
'" class="targetselectchange minwidth300" name="select_'.($i + 1).
'">';
1189 $selectforline .=
'<option value="-1"> </option>';
1192 $codeselectedarray = array();
1193 foreach ($optionsall as $tmpcode => $tmpval) {
1195 if (!empty($tmpval[
'picto'])) {
1196 $label .=
img_picto(
'', $tmpval[
'picto'],
'class="pictofixedwidth"');
1198 $label .= $tmpval[
'required'] ?
'<strong>' :
'';
1199 $label .= $tmpval[
'label'];
1200 $label .= $tmpval[
'required'] ?
'*</strong>' :
'';
1202 $tablealias = preg_replace(
'/(\..*)$/i',
'', $tmpcode);
1203 $tablename = !empty($objimport->array_import_tables[0][$tablealias]) ? $objimport->array_import_tables[0][$tablealias] :
"";
1207 $filecolumn = ($i + 1);
1209 if (empty($objimport->array_import_convertvalue[0][$tmpcode])) {
1212 if ($objimport->array_import_convertvalue[0][$tmpcode][
'rule'] ==
'fetchidfromref') {
1213 $htmltext .= $langs->trans(
"DataComeFromIdFoundFromRef", $langs->transnoentitiesnoconv($entitylang)).
'<br>';
1215 if ($objimport->array_import_convertvalue[0][$tmpcode][
'rule'] ==
'fetchidfromcodeid') {
1216 $dictlabel = $objimport->array_import_convertvalue[0][$tmpcode][
'dict'] ??
'';
1217 $htmltext .= $langs->trans(
"DataComeFromIdFoundFromCodeId", $langs->transnoentitiesnoconv($dictlabel)).
'<br>';
1221 $example = !empty($objimport->array_import_examplevalues[0][$tmpcode]) ? $objimport->array_import_examplevalues[0][$tmpcode] :
"";
1223 if (empty($objimport->array_import_convertvalue[0][$tmpcode])) {
1225 $htmltext .= $langs->trans(
"SourceExample").
': <b>'.str_replace(
'"',
'', $example).
'</b><br>';
1228 if ($objimport->array_import_convertvalue[0][$tmpcode][
'rule'] ==
'fetchidfromref') {
1229 $htmltext .= $langs->trans(
"SourceExample").
': <b>'.$langs->transnoentitiesnoconv(
"ExampleAnyRefFoundIntoElement", $entitylang).($example ?
' ('.$langs->transnoentitiesnoconv(
"Example").
': '.str_replace(
'"',
'', $example).
')' :
'').
'</b><br>';
1230 } elseif ($objimport->array_import_convertvalue[0][$tmpcode][
'rule'] ==
'fetchidfromcodeid') {
1231 $dictlabel = $objimport->array_import_convertvalue[0][$tmpcode][
'dict'] ??
'';
1232 $htmltext .= $langs->trans(
"SourceExample").
': <b>'.$langs->trans(
"ExampleAnyCodeOrIdFoundIntoDictionary", $langs->transnoentitiesnoconv($dictlabel)).($example ?
' ('.$langs->transnoentitiesnoconv(
"Example").
': '.str_replace(
'"',
'', $example).
')' :
'').
'</b><br>';
1233 } elseif ($example) {
1234 $htmltext .= $langs->trans(
"SourceExample").
': <b>'.str_replace(
'"',
'', $example).
'</b><br>';
1238 if (!empty($objimport->array_import_regex[0][$tmpcode])) {
1239 $htmltext .= $langs->trans(
"FormatControlRule").
': <b>'.str_replace(
'"',
'', $objimport->array_import_regex[0][$tmpcode]).
'</b><br>';
1243 $htmltext .= $langs->trans(
"InformationOnTargetTables").
': <b>'.$tablename.
"->".preg_replace(
'/^.*\./',
'', $tmpcode).
"</b>";
1245 $labelhtml = $label.
' '.$form->textwithpicto(
'', $htmltext, 1,
'help',
'', 1);
1248 $selectforline .=
'<option value="'.$tmpcode.
'"';
1249 if ($modetoautofillmapping ==
'orderoftargets') {
1252 $selectforline .=
' selected';
1254 } elseif ($modetoautofillmapping ==
'guess') {
1258 if (preg_match(
'/^(.+)\((.+\..+)\)$/', $line[
'example1'], $regs)) {
1259 $tmpstring1 = $regs[1];
1260 $tmpstring2 = $regs[2];
1262 $tmpstring1 = $line[
'example1'];
1270 foreach ($tmpval[
'labelkeyarray'] as $tmpval2) {
1271 $labeltarget = $langs->transnoentities($tmpval2);
1273 if ($tmpstring1 && ($tmpstring1 == $tmpcode || $tmpstring1 == strtolower($labeltarget)
1274 || $tmpstring1 == strtolower(
dol_string_unaccent($labeltarget)) || $tmpstring1 == strtolower($tmpval2))) {
1275 if (empty($codeselectedarray[$code])) {
1276 $selectforline .=
' selected';
1277 $codeselectedarray[$code] = 1;
1280 } elseif ($tmpstring2 && ($tmpstring2 == $tmpcode || $tmpstring2 == strtolower($labeltarget)
1281 || $tmpstring2 == strtolower(
dol_string_unaccent($labeltarget)) || $tmpstring2 == strtolower($tmpval2))) {
1282 if (empty($codeselectedarray[$code])) {
1283 $selectforline .=
' selected';
1284 $codeselectedarray[$code] = 1;
1289 } elseif ($modetoautofillmapping ==
'session' && !empty($_SESSION[
'dol_array_match_file_to_database_select'])) {
1290 $tmpselectioninsession =
dolExplodeIntoArray($_SESSION[
'dol_array_match_file_to_database_select'],
',',
'=');
1292 if (!empty($tmpselectioninsession[(
string) ($i + 1)]) && $tmpselectioninsession[(
string) ($i + 1)] == $tmpcode) {
1293 $selectforline .=
' selected';
1295 $selectforline .=
' data-debug="'.$tmpcode.
'-'.$code.
'-'.$j.
'-'.(!empty($tmpselectioninsession[(
string) ($i + 1)]) ? $tmpselectioninsession[(string) ($i + 1)] :
"").
'"';
1297 $selectforline .=
' data-html="'.dol_escape_htmltag($labelhtml).
'"';
1298 $selectforline .=
'>';
1299 $selectforline .= $label;
1300 $selectforline .=
'</options>';
1303 $selectforline .=
'</select>';
1304 $selectforline .=
ajax_combobox(
'selectorderimport_'.($i + 1));
1306 print $selectforline;
1311 print
'<td class="nowraponall" style="font-weight:normal; text-align:right">';
1314 $htmltext =
'<b><u>'.$langs->trans(
"FieldSource").
'</u></b><br>';
1316 $htmltext .= $langs->trans(
"DataComeFromFileFieldNb", $filecolumntoshow).
'<br>';
1318 print $form->textwithpicto(
'', $htmltext);
1329 print
'<tr class="liste_titre"><td colspan="2">'.$langs->trans(
"Note").
'</td></tr>';
1330 print
'<tr><td colspan="2"><div id="div-mandatory-target-fields-not-mapped"></div></td></tr>';
1336 if (!empty($conf->use_javascript_ajax)) {
1337 print
'<script type="text/javascript">'.
"\n";
1338 print
'var previousselectedvalueimport = "0";'.
"\n";
1339 print
'var previousselectedlabelimport = "0";'.
"\n";
1340 print
'var arrayofselectedvalues = [];'.
"\n";
1341 print
'var arrayoftargetfields = [];'.
"\n";
1342 print
'var arrayoftargetmandatoryfields = [];'.
"\n";
1346 foreach ($fieldstarget as $key => $val) {
1347 print
"arrayoftargetfields[".$tmpi.
"] = '".
dol_escape_js($langs->trans($val[
'label'])).
"'; ";
1348 if ($val[
'required']) {
1349 print
"arrayoftargetmandatoryfields[".$tmpi.
"] = '".
dol_escape_js($key).
"'; ";
1355 print
'$(document).ready(function () {'.
"\n";
1357 print
'setOptionsToDisabled();'.
"\n";
1358 print
'saveSelection();'.
"\n";
1360 print
'$(".targetselectchange").focus(function(){'.
"\n";
1361 print
' previousselectedvalueimport = $(this).val();'.
"\n";
1362 print
' previousselectedlabelimport = $(this).children("option:selected").text();'.
"\n";
1363 print
' console.log("previousselectedvalueimport="+previousselectedvalueimport)'.
"\n";
1370 print
'function setOptionsToDisabled() {'.
"\n";
1371 print
' console.log("Remove the disabled flag everywhere");'.
"\n";
1372 print
' $("select.targetselectchange").not($( this )).find(\'option\').prop("disabled", false);'.
"\n";
1373 print
' arrayofselectedvalues = [];'.
"\n";
1375 print
' $("select.targetselectchange").each(function(){'.
"\n";
1376 print
' id = $(this).attr(\'id\')'.
"\n";
1377 print
' value = $(this).val()'.
"\n";
1378 print
' console.log("a selected value has been found for component "+id+" = "+value);'.
"\n";
1379 print
' arrayofselectedvalues.push(value);'.
"\n";
1382 print
' console.log("List of all selected values arrayofselectedvalues");'.
"\n";
1383 print
' console.log(arrayofselectedvalues);'.
"\n";
1384 print
' console.log("Set the option to disabled for every entry that is currently selected somewhere else (so into arrayofselectedvalues)");'.
"\n";
1386 print
' $.each(arrayofselectedvalues, function(key, value) {'.
"\n";
1387 print
' if (value != -1) {'.
"\n";
1388 print
' console.log("Process key="+key+" value="+value+" to disable.");'.
"\n";
1389 print
' $("select.targetselectchange").find(\'option[value="\'+value+\'"]:not(:selected)\').prop("disabled", true);'.
"\n";
1395 print
'function saveSelection() {'.
"\n";
1397 print
' arrayselectedfields = [];'.
"\n";
1398 print
' arrayselectedfields.push(0);'.
"\n";
1400 print
' $.each( arrayofselectedvalues, function( key, value ) {'.
"\n";
1401 print
' if (value != -1) {'.
"\n";
1402 print
' arrayselectedfields.push(value);'.
"\n";
1403 print
' } else {'.
"\n";
1404 print
' arrayselectedfields.push(0);'.
"\n";
1408 print
" $.ajax({\n";
1409 print
" type: 'POST',\n";
1410 print
" dataType: 'json',\n";
1411 print
" url: '".dol_escape_js($_SERVER[
"PHP_SELF"]).
"?action=saveselectorder&token=".
newToken().
"',\n";
1412 print
" data: 'selectorder='+arrayselectedfields.toString(),\n";
1413 print
" success: function(){\n";
1414 print
" console.log('The selected fields have been saved into '+arrayselectedfields.toString());\n";
1419 print
' console.log("arrayselectedfields");';
1420 print
' console.log(arrayselectedfields);';
1421 print
' console.log("arrayoftargetmandatoryfields");';
1422 print
' console.log(arrayoftargetmandatoryfields);';
1423 print
" listtoshow = '';";
1424 print
" nbelement = arrayoftargetmandatoryfields.length
1425 for (let i = 0; i < nbelement; i++) {
1426 if (arrayoftargetmandatoryfields[i] && ! arrayselectedfields.includes(arrayoftargetmandatoryfields[i])) {
1427 console.log(arrayoftargetmandatoryfields[i]+' not mapped');
1428 listtoshow = listtoshow + (listtoshow ? ', ' : '') + '<b>' + arrayoftargetfields[i] + '*</b>';
1431 console.log(listtoshow);
1433 listtoshow = '".dol_escape_js(
img_warning($langs->trans(
"MandatoryTargetFieldsNotMapped")).
' '.$langs->trans(
"MandatoryTargetFieldsNotMapped")).
": ' + listtoshow;
1434 $('#div-mandatory-target-fields-not-mapped').html(listtoshow);
1436 $('#div-mandatory-target-fields-not-mapped').html('<span class=\"opacitymedium\">".
dol_escape_js($langs->trans(
"AllTargetMandatoryFieldsAreMapped")).
"</span>');
1443 print
'$(".targetselectchange").change(function(){'.
"\n";
1444 print
' setOptionsToDisabled();'.
"\n";
1446 print
' if(previousselectedlabelimport != "" && previousselectedvalueimport != -1) {'.
"\n";
1447 print
' let valuetochange = $(this).val(); '.
"\n";
1448 print
' $(".boxtdunused").each(function(){'.
"\n";
1449 print
' if ($(this).text().includes(valuetochange)){'.
"\n";
1450 print
' arraychild = $(this)[0].childNodes'.
"\n";
1451 print
' arraytexttomodify = arraychild[0].textContent.split(" ")'.
"\n";
1452 print
' arraytexttomodify[1] = previousselectedvalueimport '.
"\n";
1453 print
' textmodified = arraytexttomodify.join(" ") '.
"\n";
1454 print
' arraychild[0].textContent = textmodified'.
"\n";
1455 print
' arraychild[1].innerHTML = previousselectedlabelimport'.
"\n";
1459 print
' $(this).blur()'.
"\n";
1461 print
' saveSelection()'.
"\n";
1465 print
'</script>'.
"\n";
1471 print
'<div class="tabsAction">';
1473 if (count($array_match_file_to_database)) {
1474 if ($mandatoryfieldshavesource) {
1475 print
'<a class="butAction saveorderselect" href="import.php?step=5'.$param.
'&filetoimport='.urlencode($filetoimport).
'">'.$langs->trans(
"NextStep").
'</a>';
1477 print
'<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->transnoentitiesnoconv(
"SomeMandatoryFieldHaveNoSource")).
'">'.$langs->trans(
"NextStep").
'</a>';
1485 if (count($array_match_file_to_database)) {
1487 print
'<!-- Area to add new import profile -->'.
"\n";
1488 print
'<div class="marginbottomonly"><span class="opacitymedium">'.$langs->trans(
"SaveImportModel").
'</span></div>';
1490 print
'<form class="nocellnopadd" action="'.$_SERVER[
"PHP_SELF"].
'" method="post">';
1491 print
'<input type="hidden" name="token" value="'.newToken().
'">';
1492 print
'<input type="hidden" name="action" value="add_import_model">';
1493 print
'<input type="hidden" name="step" value="'.$step.
'">';
1494 print
'<input type="hidden" name="format" value="'.$format.
'">';
1495 print
'<input type="hidden" name="datatoimport" value="'.$datatoimport.
'">';
1496 print
'<input type="hidden" name="filetoimport" value="'.$filetoimport.
'">';
1497 print
'<input type="hidden" name="hexa" value="'.$hexa.
'">';
1498 print
'<input type="hidden" name="excludefirstline" value="'.$excludefirstline.
'">';
1499 print
'<input type="hidden" name="endatlinenb" value="'.$endatlinenb.
'">';
1500 print
'<input type="hidden" name="page_y" value="">';
1501 print
'<input type="hidden" value="'.dol_escape_htmltag($separator).
'" name="separator">';
1502 print
'<input type="hidden" value="'.dol_escape_htmltag($enclosure).
'" name="enclosure">';
1504 print
'<div class="div-table-responsive-no-min">';
1505 print
'<table summary="selectofimportprofil" class="noborder centpercent">';
1506 print
'<tr class="liste_titre">';
1507 print
'<td>'.$langs->trans(
"ImportModelName").
'</td>';
1508 print
'<td>'.$langs->trans(
"Visibility").
'</td>';
1512 $nameofimportprofile = str_replace(
' ',
'-', $langs->trans(
"ImportProfile").
' '.$titleofmodule.
' '.
dol_print_date(
dol_now(
'gmt'),
'dayxcard'));
1514 $nameofimportprofile = $import_name;
1517 print
'<tr class="oddeven">';
1518 print
'<td><input name="import_name" class="minwidth300" value="'.$nameofimportprofile.
'"></td>';
1520 $arrayvisibility = array(
'private' => $langs->trans(
"Private"),
'all' => $langs->trans(
"Everybody"));
1521 print $form->selectarray(
'visibility', $arrayvisibility,
'private');
1523 print
'<td class="right">';
1524 print
'<input type="submit" class="button smallpaddingimp reposition" value="'.$langs->trans(
"SaveImportProfile").
'">';
1528 $sql =
"SELECT rowid, label, fk_user, entity";
1529 $sql .=
" FROM ".MAIN_DB_PREFIX.
"import_model";
1530 $sql .=
" WHERE type = '".$db->escape($datatoimport).
"'";
1532 $sql .=
" AND fk_user IN (0, ".((int) $user->id).
")";
1534 $sql .=
" ORDER BY rowid";
1536 $resql = $db->query($sql);
1538 $num = $db->num_rows($resql);
1540 $tmpuser =
new User($db);
1544 $obj = $db->fetch_object($resql);
1546 print
'<tr class="oddeven"><td>';
1549 print
'<td class="tdoverflowmax150">';
1550 if (empty($obj->fk_user)) {
1551 print $langs->trans(
"Everybody");
1553 $tmpuser->fetch($obj->fk_user);
1554 print $tmpuser->getNomUrl(-1);
1557 print
'<td class="right">';
1558 print
'<a class="reposition" href="'.$_SERVER[
"PHP_SELF"].
'?step='.$step.$param.
'&action=deleteprof&token='.
newToken().
'&id='.$obj->rowid.
'&filetoimport='.urlencode($filetoimport).
'">';
1576if ($step == 5 && $datatoimport) {
1577 $max_execution_time_for_importexport =
getDolGlobalInt(
'IMPORT_MAX_EXECUTION_TIME', 300);
1578 $max_time = @ini_get(
"max_execution_time");
1579 if ($max_time && $max_time < $max_execution_time_for_importexport) {
1580 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.");
1581 @ini_set(
"max_execution_time", $max_execution_time_for_importexport);
1585 $list = $objmodelimport->listOfAvailableImportFormat($db);
1588 $dir = DOL_DOCUMENT_ROOT.
"/core/modules/import/";
1589 $file =
"import_".$model.
".modules.php";
1590 $classname =
"Import".ucfirst($model);
1591 require_once $dir.$file;
1592 $obj =
new $classname($db, $datatoimport);
1593 '@phan-var-force ModeleImports $obj';
1594 if ($model ==
'csv') {
1595 '@phan-var-force ImportCsv $obj';
1596 $obj->separator = $separator_used;
1597 $obj->enclosure = $enclosure;
1601 $fieldssource = array();
1602 $result = $obj->import_open_file($conf->import->dir_temp.
'/'.$filetoimport);
1606 $arrayrecord = $obj->import_read_record();
1609 foreach ($arrayrecord as $key => $val) {
1610 $fieldssource[$i][
'example1'] =
dol_trunc($val[
'val'], 24);
1613 $obj->import_close_file();
1616 $nboflines = $obj->import_get_nb_of_lines($conf->import->dir_temp.
'/'.$filetoimport);
1618 $param =
'&leftmenu=import&format='.urlencode($format).
'&datatoimport='.urlencode($datatoimport).
'&filetoimport='.urlencode($filetoimport).
'&nboflines='.((int) $nboflines).
'&separator='.urlencode($separator).
'&enclosure='.urlencode($enclosure);
1620 if ($excludefirstline) {
1621 $param .=
'&excludefirstline='.urlencode($excludefirstline);
1624 $param .=
'&endatlinenb='.urlencode($endatlinenb);
1626 if (!empty($updatekeys)) {
1627 $param .=
'&updatekeys[]='.implode(
'&updatekeys[]=', $updatekeys);
1630 llxHeader(
'', $langs->trans(
"NewImport"), $help_url);
1635 print
'<form action="'.$_SERVER[
"PHP_SELF"].
'?'.$param2.
'" method="POST">';
1636 print
'<input type="hidden" name="token" value="'.newToken().
'">';
1637 print
'<input type="hidden" name="step" value="5">';
1638 print
'<input type="hidden" name="action" value="launchsimu">';
1642 print
'<div class="underbanner clearboth"></div>';
1643 print
'<div class="fichecenter">';
1645 print
'<table width="100%" class="border tableforfield">';
1648 print
'<tr><td class="titlefieldcreate">'.$langs->trans(
"Module").
'</td>';
1650 $titleofmodule = $objimport->array_import_module[0][
'module']->getName();
1652 if (in_array($objimport->array_import_code[0], array(
'produit_supplierprices',
'produit_multiprice',
'produit_languages'))) {
1653 $titleofmodule = $langs->trans(
"ProductOrService");
1655 print $titleofmodule;
1659 print
'<tr><td>'.$langs->trans(
"DatasetToImport").
'</td>';
1661 $entity = preg_replace(
'/:.*$/',
'', $objimport->array_import_icon[0]);
1662 $entityicon = strtolower(!empty($entitytoicon[$entity]) ? $entitytoicon[$entity] : $entity);
1663 print
img_object($objimport->array_import_module[0][
'module']->getName(), $entityicon).
' ';
1664 print $objimport->array_import_label[0];
1672 print
load_fiche_titre($langs->trans(
"InformationOnSourceFile"),
'',
'file-export');
1674 print
'<div class="underbanner clearboth"></div>';
1675 print
'<div class="fichecenter">';
1676 print
'<table width="100%" class="border tableforfield">';
1679 print
'<tr><td class="titlefieldcreate">'.$langs->trans(
"SourceFileFormat").
'</td>';
1680 print
'<td class="nowraponall">';
1681 $text = $objmodelimport->getDriverDescForKey($format);
1683 print $form->textwithpicto($objmodelimport->getDriverLabelForKey($format), $text);
1687 if ($model ==
'csv') {
1688 '@phan-var-force ImportCsv $obj';
1689 print
'<tr><td>'.$langs->trans(
"CsvOptions").
'</td>';
1692 print
' '.$langs->trans(
"Enclosure").
' : '.
dol_escape_htmltag($enclosure);
1697 print
'<tr><td>'.$langs->trans(
"FileToImport").
'</td>';
1699 $modulepart =
'import';
1700 $relativepath =
GETPOST(
'filetoimport');
1701 print
'<a data-ajax="false" href="'.DOL_URL_ROOT.
'/document.php?modulepart='.urlencode($modulepart).
'&file='.urlencode($relativepath).
'&step=4'.$param.
'" target="_blank" rel="noopener noreferrer">';
1702 print
img_mime($file,
'',
'pictofixedwidth');
1703 print $filetoimport;
1704 print
img_picto($langs->trans(
"Download"),
'download',
'class="paddingleft opacitymedium"');
1710 print $langs->trans(
"NbOfSourceLines");
1717 print $langs->trans(
"ImportFromToLine");
1719 if ($action ==
'launchsimu') {
1720 print
'<input type="number" class="maxwidth50 right" name="excludefirstlinebis" disabled="disabled" value="'.$excludefirstline.
'">';
1721 print
'<input type="hidden" name="excludefirstline" value="'.$excludefirstline.
'">';
1723 print
'<input type="number" class="maxwidth50 right" name="excludefirstline" value="'.$excludefirstline.
'">';
1724 print $form->textwithpicto(
"", $langs->trans(
"SetThisValueTo2ToExcludeFirstLine"));
1727 if ($action ==
'launchsimu') {
1728 print
'<input type="text" class="maxwidth50" name="endatlinenbbis" disabled="disabled" value="'.$endatlinenb.
'">';
1729 print
'<input type="hidden" name="endatlinenb" value="'.$endatlinenb.
'">';
1731 print
'<input type="text" class="maxwidth50" name="endatlinenb" value="'.$endatlinenb.
'">';
1732 print $form->textwithpicto(
"", $langs->trans(
"KeepEmptyToGoToEndOfFile"));
1734 if ($action ==
'launchsimu') {
1735 print
' <a href="'.$_SERVER[
"PHP_SELF"].
'?step=5'.$param.
'">'.$langs->trans(
"Modify").
'</a>';
1737 if ($excludefirstline == 2) {
1738 print $form->textwithpicto(
"", $langs->trans(
"WarningFirstImportedLine", $excludefirstline), 1,
'warning',
"warningexcludefirstline");
1740 $( document ).ready(function() {
1741 $("input[name=\'excludefirstline\']").on("change",function(){
1742 if($(this).val() <= 1){
1743 $(".warningexcludefirstline").hide();
1745 $(".warningexcludefirstline").show();
1755 print $form->textwithpicto($langs->trans(
"KeysToUseForUpdates"), $langs->trans(
"SelectPrimaryColumnsForUpdateAttempt"));
1757 if ($action ==
'launchsimu') {
1758 if (count($updatekeys)) {
1759 print $form->multiselectarray(
'updatekeysbis', $objimport->array_import_updatekeys[0], $updatekeys, 0, 0,
'', 1,
'80%',
'disabled');
1761 print
'<span class="opacitymedium">'.$langs->trans(
"NoUpdateAttempt").
'</span> -';
1763 foreach ($updatekeys as $val) {
1764 print
'<input type="hidden" name="updatekeys[]" value="'.$val.
'">';
1766 print
' <a href="'.$_SERVER[
"PHP_SELF"].
'?step=5'.$param.
'">'.$langs->trans(
"Modify").
'</a>';
1768 if (is_array($objimport->array_import_updatekeys[0]) && count($objimport->array_import_updatekeys[0])) {
1769 print $form->multiselectarray(
'updatekeys', $objimport->array_import_updatekeys[0], $updatekeys, 0, 0,
'', 1,
'80%');
1772 print
'<span class="opacitymedium">'.$langs->trans(
"UpdateNotYetSupportedForThisImport").
'</span>';
1785 print
load_fiche_titre($langs->trans(
"InformationOnTargetTables"),
'',
'file-import');
1787 print
'<div class="underbanner clearboth"></div>';
1788 print
'<div class="fichecenter">';
1790 print
'<table class="centpercent border tableforfield">';
1793 print
'<tr><td class="titlefieldcreate">';
1794 print $langs->trans(
"TablesTarget");
1796 $listtables = array();
1797 $sort_array_match_file_to_database = $array_match_file_to_database;
1798 foreach ($array_match_file_to_database as $code => $label) {
1800 if ($code > count($fieldssource)) {
1804 $alias = preg_replace(
'/(\..*)$/i',
'', $label);
1805 $listtables[$alias] = $objimport->array_import_tables[0][$alias];
1807 if (count($listtables)) {
1810 foreach ($listtables as $val) {
1829 print $langs->trans(
"Error");
1835 print $langs->trans(
"FieldsTarget").
'</td><td class="small">';
1836 $listfields = array();
1839 $sort_array_match_file_to_database = $array_match_file_to_database;
1840 ksort($sort_array_match_file_to_database);
1842 foreach ($sort_array_match_file_to_database as $code => $label) {
1845 if ($code > count($fieldssource)) {
1849 $alias = preg_replace(
'/(\..*)$/i',
'', $label);
1850 $listfields[$i] =
'<span class="nowrap">'.$langs->trans(
"Column").
' '.
num2Alpha((
int) $code - 1).
' -> '.$label.
'</span>';
1852 print count($listfields) ? (implode(
', ', $listfields)) : $langs->trans(
"Error");
1861 if ($action !=
'launchsimu') {
1863 print
'<br><span class="opacitymedium">';
1864 print $langs->trans(
"NowClickToTestTheImport", $langs->transnoentitiesnoconv(
"RunSimulateImportFile")).
'</span><br>';
1868 print
'<div class="center">';
1869 if ($user->hasRight(
'import',
'run')) {
1870 print
'<input type="submit" class="butAction" value="'.$langs->trans(
"RunSimulateImportFile").
'">';
1872 print
'<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->transnoentitiesnoconv(
"NotEnoughPermissions")).
'">'.$langs->trans(
"RunSimulateImportFile").
'</a>';
1877 $arrayoferrors = array();
1878 $arrayofwarnings = array();
1892 $pathfile = $conf->import->dir_temp.
'/'.$filetoimport;
1893 $result = $obj->import_open_file($pathfile);
1895 global $tablewithentity_cache;
1896 $tablewithentity_cache = array();
1901 while (($sourcelinenb < $nboflines) && !$endoffile) {
1905 $arrayrecord = $obj->import_read_record();
1906 if ($arrayrecord ===
false) {
1907 $arrayofwarnings[$sourcelinenb][0] = array(
'lib' => $langs->trans(
'ErrorFileLinesReachEOF', $nboflines, $sourcelinenb),
'type' =>
'EOF_RECORD_ON_SEVERAL_LINES');
1911 if ($excludefirstline && ($sourcelinenb < $excludefirstline)) {
1914 if ($endatlinenb && ($sourcelinenb > $endatlinenb)) {
1918 $parameters = array(
1920 'datatoimport' => $datatoimport,
1922 'arrayrecord' => $arrayrecord,
1923 'array_match_file_to_database' => $array_match_file_to_database,
1924 'objimport' => $objimport,
1925 'fieldssource' => $fieldssource,
1926 'importid' => $importid,
1927 'updatekeys' => $updatekeys,
1928 'arrayoferrors' => &$arrayoferrors,
1929 'arrayofwarnings' => &$arrayofwarnings,
1933 $reshook = $hookmanager->executeHooks(
'ImportInsert', $parameters);
1935 $arrayoferrors[$sourcelinenb][] = [
1936 'lib' => implode(
"<br>", array_merge([$hookmanager->error], $hookmanager->errors))
1940 if (empty($reshook)) {
1942 $result = $obj->import_insert($arrayrecord, $array_match_file_to_database, $objimport, count($fieldssource), $importid, $updatekeys);
1944 if (count($obj->errors)) {
1945 $arrayoferrors[$sourcelinenb] = $obj->errors;
1947 if (count($obj->warnings)) {
1948 $arrayofwarnings[$sourcelinenb] = $obj->warnings;
1950 if (!count($obj->errors) && !count($obj->warnings)) {
1955 $reshook = $hookmanager->executeHooks(
'AfterImportInsert', $parameters);
1957 $arrayoferrors[$sourcelinenb][] = [
1958 'lib' => implode(
"<br>", array_merge([$hookmanager->error], $hookmanager->errors))
1963 $obj->import_close_file();
1965 print $langs->trans(
"ErrorFailedToOpenFile", $pathfile);
1972 if (!empty($objimport->array_import_run_sql_after[0]) && is_array($objimport->array_import_run_sql_after[0])) {
1974 foreach ($objimport->array_import_run_sql_after[0] as $sqlafterimport) {
1976 $resqlafterimport = $db->query($sqlafterimport);
1977 if (!$resqlafterimport) {
1978 $arrayoferrors[
'none'][] = array(
'lib' => $langs->trans(
"Error running final request: ".$sqlafterimport));
1987 if (!count($arrayoferrors) && !count($arrayofwarnings)) {
1989 print
'<div class="info">';
1990 print
'<div class=""><b>'.$langs->trans(
"ResultOfSimulationNoError").
'</b></div>';
1991 print $langs->trans(
"NbInsertSim", empty($obj->nbinsert) ? 0 : $obj->nbinsert).
'<br>';
1992 print $langs->trans(
"NbUpdateSim", empty($obj->nbupdate) ? 0 : $obj->nbupdate).
'<br>';
1997 print
'<div class="warning">';
1998 print $langs->trans(
"NbOfLinesOK", $nbok).
'...<br>';
2005 if (count($arrayoferrors)) {
2006 print
img_error().
' <b>'.$langs->trans(
"ErrorsOnXLines", count($arrayoferrors)).
'</b><br>';
2007 print
'<table width="100%" class="border"><tr><td>';
2008 foreach ($arrayoferrors as $key => $val) {
2010 if ($nboferrors > $maxnboferrors) {
2011 print $langs->trans(
"TooMuchErrors", (count($arrayoferrors) - $nboferrors)).
"<br>";
2015 foreach ($val as $i => $err) {
2016 print
' > '.dol_escape_htmltag($err[
'lib']).
'<br>';
2019 print
'</td></tr></table>';
2025 if (count($arrayofwarnings)) {
2026 print
img_warning().
' <b>'.$langs->trans(
"WarningsOnXLines", count($arrayofwarnings)).
'</b><br>';
2027 print
'<table width="100%" class="border"><tr><td>';
2028 foreach ($arrayofwarnings as $key => $val) {
2030 if ($nbofwarnings > $maxnbofwarnings) {
2031 print $langs->trans(
"TooMuchWarnings", (count($arrayofwarnings) - $nbofwarnings)).
"<br>";
2035 foreach ($val as $i => $err) {
2036 print
' > '.dol_escape_htmltag($err[
'lib']).
'<br>';
2039 print
'</td></tr></table>';
2046 print
'<div class="center">';
2047 print
'<span class="opacitymedium">'.$langs->trans(
"NowClickToRunTheImport", $langs->transnoentitiesnoconv(
"RunImportFile")).
'</span><br>';
2056 print
'<div class="center">';
2057 if ($user->hasRight(
'import',
'run')) {
2058 if (empty($nboferrors)) {
2059 print
'<a class="butAction" href="'.DOL_URL_ROOT.
'/imports/import.php?leftmenu=import&step=6&importid='.$importid.$param.
'">'.$langs->trans(
"RunImportFile").
'</a>';
2063 print
'<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->transnoentitiesnoconv(
"CorrectErrorBeforeRunningImport")).
'">'.$langs->trans(
"RunImportFile").
'</a>';
2066 print
'<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->transnoentitiesnoconv(
"NotEnoughPermissions")).
'">'.$langs->trans(
"RunSimulateImportFile").
'</a>';
2068 print
'<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->transnoentitiesnoconv(
"NotEnoughPermissions")).
'">'.$langs->trans(
"RunImportFile").
'</a>';
2078if ($step == 6 && $datatoimport) {
2079 $max_execution_time_for_importexport =
getDolGlobalInt(
'IMPORT_MAX_EXECUTION_TIME', 300);
2080 $max_time = @ini_get(
"max_execution_time");
2081 if ($max_time && $max_time < $max_execution_time_for_importexport) {
2082 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.");
2083 @ini_set(
"max_execution_time", $max_execution_time_for_importexport);
2087 $list = $objmodelimport->listOfAvailableImportFormat($db);
2088 $importid =
GETPOST(
"importid",
'alphanohtml');
2092 $dir = DOL_DOCUMENT_ROOT.
"/core/modules/import/";
2093 $file =
"import_".$model.
".modules.php";
2094 $classname =
"Import".ucfirst($model);
2095 require_once $dir.$file;
2096 $obj =
new $classname($db, $datatoimport);
2097 '@phan-var-force ModeleImports $obj';
2098 if ($model ==
'csv') {
2099 '@phan-var-force ImportCsv $obj';
2100 $obj->separator = $separator_used;
2101 $obj->enclosure = $enclosure;
2105 $fieldssource = array();
2106 $result = $obj->import_open_file($conf->import->dir_temp.
'/'.$filetoimport);
2109 $arrayrecord = $obj->import_read_record();
2112 foreach ($arrayrecord as $key => $val) {
2113 $fieldssource[$i][
'example1'] =
dol_trunc($val[
'val'], 24);
2116 $obj->import_close_file();
2121 $param =
'&format='.$format.
'&datatoimport='.urlencode($datatoimport).
'&filetoimport='.urlencode($filetoimport).
'&nboflines='.((int) $nboflines);
2122 if ($excludefirstline) {
2123 $param .=
'&excludefirstline='.urlencode($excludefirstline);
2126 $param .=
'&endatlinenb='.urlencode($endatlinenb);
2129 $param .=
'&separator='.urlencode($separator);
2132 $param .=
'&enclosure='.urlencode($enclosure);
2135 llxHeader(
'', $langs->trans(
"NewImport"), $help_url);
2141 print
'<div class="underbanner clearboth"></div>';
2142 print
'<div class="fichecenter">';
2144 print
'<table width="100%" class="border">';
2147 print
'<tr><td class="titlefieldcreate">'.$langs->trans(
"Module").
'</td>';
2149 $titleofmodule = $objimport->array_import_module[0][
'module']->getName();
2151 if (in_array($objimport->array_import_code[0], array(
'produit_supplierprices',
'produit_multiprice',
'produit_languages'))) {
2152 $titleofmodule = $langs->trans(
"ProductOrService");
2154 print $titleofmodule;
2158 print
'<tr><td>'.$langs->trans(
"DatasetToImport").
'</td>';
2160 $entity = preg_replace(
'/:.*$/',
'', $objimport->array_import_icon[0]);
2161 $entityicon = strtolower(!empty($entitytoicon[$entity]) ? $entitytoicon[$entity] : $entity);
2162 print
img_object($objimport->array_import_module[0][
'module']->getName(), $entityicon).
' ';
2163 print $objimport->array_import_label[0];
2171 print
load_fiche_titre($langs->trans(
"InformationOnSourceFile"),
'',
'file-export');
2173 print
'<div class="underbanner clearboth"></div>';
2174 print
'<div class="fichecenter">';
2175 print
'<table width="100%" class="border tableforfield">';
2178 print
'<tr><td class="titlefieldcreate">'.$langs->trans(
"SourceFileFormat").
'</td>';
2179 print
'<td class="nowraponall">';
2180 $text = $objmodelimport->getDriverDescForKey($format);
2182 print $form->textwithpicto($objmodelimport->getDriverLabelForKey($format), $text);
2186 if ($model ==
'csv') {
2187 '@phan-var-force ImportCsv $obj';
2188 print
'<tr><td>'.$langs->trans(
"CsvOptions").
'</td>';
2190 print $langs->trans(
"Separator").
' : ';
2191 print htmlentities($separator);
2192 print
' '.$langs->trans(
"Enclosure").
' : ';
2193 print htmlentities($enclosure);
2198 print
'<tr><td>'.$langs->trans(
"FileToImport").
'</td>';
2200 $modulepart =
'import';
2201 $relativepath =
GETPOST(
'filetoimport');
2202 print
'<a data-ajax="false" href="'.DOL_URL_ROOT.
'/document.php?modulepart='.$modulepart.
'&file='.urlencode($relativepath).
'&step=4'.$param.
'" target="_blank" rel="noopener noreferrer">';
2203 print
img_mime($file,
'',
'pictofixedwidth');
2204 print $filetoimport;
2210 print $langs->trans(
"NbOfSourceLines");
2217 print $langs->trans(
"ImportFromLine");
2219 print
'<input type="text" size="4" name="excludefirstline" disabled="disabled" value="'.$excludefirstline.
'">';
2224 print $langs->trans(
"EndAtLineNb");
2226 print
'<input type="text" size="4" name="endatlinenb" disabled="disabled" value="'.$endatlinenb.
'">';
2234 print
'<b>'.$langs->trans(
"InformationOnTargetTables").
'</b>';
2235 print
'<div class="underbanner clearboth"></div>';
2236 print
'<div class="fichecenter">';
2237 print
'<table class="border centpercent">';
2240 print
'<tr><td width="25%">';
2241 print $langs->trans(
"TablesTarget");
2243 $listtables = array();
2244 foreach ($array_match_file_to_database as $code => $label) {
2246 if ($code > count($fieldssource)) {
2250 $alias = preg_replace(
'/(\..*)$/i',
'', $label);
2251 $listtables[$alias] = $objimport->array_import_tables[0][$alias];
2253 if (count($listtables)) {
2255 foreach ($listtables as $val) {
2274 print $langs->trans(
"Error");
2280 print $langs->trans(
"FieldsTarget").
'</td><td>';
2281 $listfields = array();
2283 $sort_array_match_file_to_database = $array_match_file_to_database;
2284 ksort($sort_array_match_file_to_database);
2286 foreach ($sort_array_match_file_to_database as $code => $label) {
2289 if ($code > count($fieldssource)) {
2293 $alias = preg_replace(
'/(\..*)$/i',
'', $label);
2294 $listfields[$i] = $langs->trans(
"Field").
' '.$code.
'->'.$label;
2296 print count($listfields) ? (implode(
', ', $listfields)) : $langs->trans(
"Error");
2303 $arrayoferrors = array();
2304 $arrayofwarnings = array();
2305 $maxnboferrors = !
getDolGlobalString(
'IMPORT_MAX_NB_OF_ERRORS') ? 50 : $conf->global->IMPORT_MAX_NB_OF_ERRORS;
2306 $maxnbofwarnings = !
getDolGlobalString(
'IMPORT_MAX_NB_OF_WARNINGS') ? 50 : $conf->global->IMPORT_MAX_NB_OF_WARNINGS;
2318 $pathfile = $conf->import->dir_temp.
'/'.$filetoimport;
2319 $result = $obj->import_open_file($pathfile);
2321 global $tablewithentity_cache;
2322 $tablewithentity_cache = array();
2326 while ($sourcelinenb < $nboflines && !$endoffile) {
2328 $arrayrecord = $obj->import_read_record();
2329 if ($arrayrecord ===
false) {
2330 $arrayofwarnings[$sourcelinenb][0] = array(
'lib' => $langs->trans(
'ErrorFileLinesReachEOF', $nboflines, $sourcelinenb),
'type' =>
'EOF_RECORD_ON_SEVERAL_LINES');
2334 if ($excludefirstline && ($sourcelinenb < $excludefirstline)) {
2337 if ($endatlinenb && ($sourcelinenb > $endatlinenb)) {
2341 $parameters = array(
2343 'datatoimport' => $datatoimport,
2345 'arrayrecord' => $arrayrecord,
2346 'array_match_file_to_database' => $array_match_file_to_database,
2347 'objimport' => $objimport,
2348 'fieldssource' => $fieldssource,
2349 'importid' => $importid,
2350 'updatekeys' => $updatekeys,
2351 'arrayoferrors' => &$arrayoferrors,
2352 'arrayofwarnings' => &$arrayofwarnings,
2356 $reshook = $hookmanager->executeHooks(
'ImportInsert', $parameters);
2358 $arrayoferrors[$sourcelinenb][] = [
2359 'lib' => implode(
"<br>", array_merge([$hookmanager->error], $hookmanager->errors))
2363 if (empty($reshook)) {
2365 $result = $obj->import_insert($arrayrecord, $array_match_file_to_database, $objimport, count($fieldssource), $importid, $updatekeys);
2367 if (count($obj->errors)) {
2368 $arrayoferrors[$sourcelinenb] = $obj->errors;
2370 if (count($obj->warnings)) {
2371 $arrayofwarnings[$sourcelinenb] = $obj->warnings;
2374 if (!count($obj->errors) && !count($obj->warnings)) {
2379 $reshook = $hookmanager->executeHooks(
'AfterImportInsert', $parameters);
2381 $arrayoferrors[$sourcelinenb][] = [
2382 'lib' => implode(
"<br>", array_merge([$hookmanager->error], $hookmanager->errors))
2387 $obj->import_close_file();
2389 print $langs->trans(
"ErrorFailedToOpenFile", $pathfile);
2392 if (count($arrayoferrors) > 0) {
2399 if (!empty($objimport->array_import_run_sql_after[0]) && is_array($objimport->array_import_run_sql_after[0])) {
2401 foreach ($objimport->array_import_run_sql_after[0] as $sqlafterimport) {
2403 $resqlafterimport = $db->query($sqlafterimport);
2404 if (!$resqlafterimport) {
2405 $arrayoferrors[
'none'][] = array(
'lib' => $langs->trans(
"Error running final request: ".$sqlafterimport));
2423 print
'<div class="info">';
2424 print $langs->trans(
"NbOfLinesImported", $nbok).
'</b><br>';
2425 print $langs->trans(
"NbInsert", empty($obj->nbinsert) ? 0 : $obj->nbinsert).
'<br>';
2426 print $langs->trans(
"NbUpdate", empty($obj->nbupdate) ? 0 : $obj->nbupdate).
'<br>';
2428 print
'<div class="center">';
2429 print $langs->trans(
"FileWasImported", $importid).
'<br>';
2430 print
'<span class="opacitymedium">'.$langs->trans(
"YouCanUseImportIdToFindRecord", $importid).
'</span><br>';
2453 global $conf, $langs;
2457 if ($key ==
'none') {
2459 print
"\n\n<!-- Box_no-key start-->\n";
2460 print
'<div class="box boximport" style="padding:0;">'.
"\n";
2461 print
'<table summary="boxtable_no-key" class="centpercent nobordernopadding">'.
"\n";
2463 print
"\n\n<!-- Box ".$pos.
" start -->\n";
2464 print
'<div class="box boximport" style="padding: 0;" id="boxto_'.$pos.
'">'.
"\n";
2466 print
'<table summary="boxtable'.$pos.
'" class="nobordernopadding centpercent tableimport">'.
"\n";
2469 if (($pos && $pos > count($fieldssource)) && (!isset($fieldssource[$pos][
"imported"]))) {
2479 } elseif ($key ==
'none') {
2480 print
'<tr style="height:'.$height.
'" class="trimport oddevenimport">';
2481 print
'<td class="nocellnopadd" width="16" style="font-weight: normal">';
2484 print
'<td style="font-weight: normal">';
2490 print
'<tr style="height:'.$height.
'" class="trimport oddevenimport">';
2491 print
'<td class="nocellnopadd" width="16" style="font-weight: normal">';
2494 print
img_picto($langs->trans(
"Column").
' '.
num2Alpha($pos - 1),
'file',
'class="pictofixedwidth marginleftonly"');
2496 if (isset($fieldssource[$pos][
'imported']) && $fieldssource[$pos][
'imported'] ==
false) {
2497 print
'<td class="nowraponall boxtdunused" style="font-weight: normal">';
2499 print
'<td class="nowraponall tdoverflowmax500" style="font-weight: normal">';
2501 print $langs->trans(
"Column").
' '.
num2Alpha($pos - 1).
' (#'.$pos.
')';
2502 if (empty($fieldssource[$pos][
'example1'])) {
2503 $example = $fieldssource[$pos][
'label'];
2505 $example = $fieldssource[$pos][
'example1'];
2509 $example = mb_convert_encoding($example,
'UTF-8',
'ISO-8859-1');
2513 print
'<i class="opacitymedium">'.dol_escape_htmltag($example).
'</i>';
2522 print
"<!-- Box end -->\n\n";
2535 $i = count($fieldssource) + 1;
2538 foreach ($listofkey as $key => $val) {
2539 $maxkey = max($maxkey, $key);
2542 while ($i <= $maxkey) {
2543 if (empty($listofkey[$i])) {
2565 if ($position == count($array)) {
2566 $ret = $array + $insertArray;
2569 foreach ($array as $key => $value) {
2570 if ($position == $i++) {
2571 $ret += $insertArray;
2574 $ret[$key] = $value;
ajax_combobox($htmlname, $events=array(), $minLengthToAutocomplete=0, $forcefocus=0, $widthTypeOfAutocomplete='resolve', $idforemptyvalue='-1', $morecss='')
Convert a html select field into an ajax combobox.
llxFooter($comment='', $zone='private', $disabledoutputofmessages=0)
Empty footer.
if(!defined('NOREQUIRESOC')) if(!defined( 'NOREQUIRETRAN')) if(!defined('NOTOKENRENEWAL')) if(!defined( 'NOREQUIREMENU')) if(!defined('NOREQUIREHTML')) if(!defined( 'NOREQUIREAJAX')) llxHeader($head='', $title='', $help_url='', $target='', $disablejs=0, $disablehead=0, $arrayofjs='', $arrayofcss='', $morequerystring='', $morecssonbody='', $replacemainareaby='', $disablenofollow=0, $disablenoindex=0)
Empty header.
Parent class for import file readers.
Class to manage Dolibarr users.
dol_filemtime($pathoffile)
Return time of a file.
dol_filesize($pathoffile)
Return size of a file.
dol_delete_file($file, $disableglob=0, $nophperrors=0, $nohook=0, $object=null, $allowdotdot=false, $indexdatabase=1, $nolog=0)
Remove a file or several files with a mask.
dol_count_nb_of_line($file)
Count number of lines in a file.
dol_dir_list($utf8_path, $types="all", $recursive=0, $filter="", $excludefilter=null, $sortcriteria="name", $sortorder=SORT_ASC, $mode=0, $nohook=0, $relativename="", $donotfollowsymlinks=0, $nbsecondsold=0)
Scan a directory and return a list of files/directories.
dol_move_uploaded_file($src_file, $dest_file, $allowoverwrite, $disablevirusscan=0, $uploaderrorcode=0, $nohook=0, $keyforsourcefile='addedfile', $upload_dir='', $mode=0)
Check validity of a file upload from an GUI page, and move it to its final destination.
dol_now($mode='gmt')
Return date for now.
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='', $noduplicate=0, $attop=0)
Set event messages in dol_events session object.
dolExplodeIntoArray($string, $delimiter=';', $kv='=')
Split a string with 2 keys into key array.
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2, $allowothertags=array())
Show picto whatever it's its name (generic function)
img_warning($titlealt='default', $moreatt='', $morecss='pictowarning')
Show warning logo.
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, $morecssdiv='')
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_string_nohtmltag($stringtoclean, $removelinefeed=1, $pagecodeto='UTF-8', $strip_tags=0, $removedoublespaces=1)
Clean a string from all HTML tags and entities.
dol_get_fiche_end($notab=0)
Return tab footer of a card.
img_object($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $allowothertags=array())
Show a picto called object_picto (generic function)
dol_sanitizeFileName($str, $newstr='_', $unaccent=1, $includequotes=0, $allowdash=0)
Clean a string to use it as a file name.
img_mime($file, $titlealt='', $morecss='')
Show MIME img of a file.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
dol_escape_js($stringtoescape, $mode=0, $noescapebackslashn=0)
Returns text escaped for inclusion into javascript code.
dol_sort_array(&$array, $index, $order='asc', $natsort=0, $case_sensitive=0, $keepindex=0)
Advanced sort array by the value of a given key, which produces ascending (default) or descending out...
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.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false, $decorate=0)
Output date in a string format according to outputlangs (or langs if not defined).
img_error($titlealt='default')
Show error logo.
dol_print_error($db=null, $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
load_fiche_titre($title, $morehtmlright='', $picto='generic', $pictoisfullpath=0, $id='', $morecssontable='', $morehtmlcenter='', $morecssonpicto='widthpictotitle')
Load a title with picto.
dol_trunc($string, $size=40, $trunc='right', $stringencoding='UTF-8', $nodot=0, $display=0)
Truncate a string to a particular length adding '…' if string larger than length.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
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.
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.