29require_once
'../main.inc.php';
37require_once DOL_DOCUMENT_ROOT.
'/core/class/html.formfile.class.php';
38require_once DOL_DOCUMENT_ROOT.
'/core/class/html.formother.class.php';
39require_once DOL_DOCUMENT_ROOT.
'/imports/class/import.class.php';
40require_once DOL_DOCUMENT_ROOT.
'/core/modules/import/modules_import.class.php';
41require_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
42require_once DOL_DOCUMENT_ROOT.
'/core/lib/images.lib.php';
43require_once DOL_DOCUMENT_ROOT.
'/core/lib/import.lib.php';
46$langs->loadLangs(array(
'exports',
'compta',
'errors',
'projects',
'admin',
'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',
'alphanohtml', 3) ?
GETPOST(
'excludefirstline',
'alphanohtml', 3) : 2);
155$endatlinenb = (
GETPOST(
'endatlinenb',
'alphanohtml', 3) ?
GETPOST(
'endatlinenb',
'alphanohtml', 3) :
'');
156$updatekeys = (
GETPOST(
'updatekeys',
'array', 3) ?
GETPOST(
'updatekeys',
'array', 3) : array());
157$importtriggermode =
GETPOST(
'importtriggermode',
'alpha', 3);
158$separator = (
GETPOST(
'separator',
'nohtml') ?
GETPOST(
'separator',
'nohtml', 3) :
'');
159$enclosure = (
GETPOST(
'enclosure',
'nohtml') ?
GETPOST(
'enclosure',
'nohtml') :
'"');
160$charset =
GETPOST(
'charset',
'aZ09');
161$separator_used = str_replace(
'\t',
"\t", $separator);
164if (empty($importtriggermode)) {
165 $importtriggermode =
getDolGlobalString(
'IMPORT_TRIGGER_MODE_DEFAULT',
'strict_line');
167if (!in_array($importtriggermode, array(
'strict_line',
'fast_bulk'),
true)) {
168 $importtriggermode =
'strict_line';
172$objimport->load_arrays($user, ($step == 1 ?
'' : $datatoimport));
174if (empty($updatekeys) && !empty($objimport->array_import_preselected_updatekeys[0])) {
175 $updatekeys = $objimport->array_import_preselected_updatekeys[0];
184if (empty($array_match_file_to_database)) {
185 $serialized_array_match_file_to_database = isset($_SESSION[
"dol_array_match_file_to_database_select"]) ? $_SESSION[
"dol_array_match_file_to_database_select"] :
'';
186 $array_match_file_to_database = array();
187 $fieldsarray = explode(
',', $serialized_array_match_file_to_database);
188 foreach ($fieldsarray as $elem) {
189 $tabelem = explode(
'=', $elem, 2);
191 $val = (isset($tabelem[1]) ? $tabelem[1] :
'');
193 $array_match_file_to_database[$key] = $val;
203if ($action ==
'deleteprof' && $user->hasRight(
'import',
'run')) {
206 $result = $objimport->delete($user);
211if ($action ==
'add_import_model' && $user->hasRight(
'import',
'run')) {
215 foreach ($array_match_file_to_database as $key => $val) {
219 $hexa .= $key.
'='.$val;
222 $objimport->model_name = $import_name;
223 $objimport->datatoimport = $datatoimport;
224 $objimport->hexa = $hexa;
225 $objimport->fk_user = (
GETPOST(
'visibility',
'aZ09') ==
'all' ? 0 : $user->id);
227 $result = $objimport->create($user);
229 setEventMessages($langs->trans(
"ImportModelSaved", $objimport->model_name),
null,
'mesgs');
232 $langs->load(
"errors");
233 if ($objimport->errno ==
'DB_ERROR_RECORD_ALREADY_EXISTS') {
234 setEventMessages($langs->trans(
"ErrorImportDuplicateProfil"),
null,
'errors');
240 setEventMessages($langs->trans(
"ErrorFieldRequired", $langs->transnoentities(
"ImportModelName")),
null,
'errors');
244if ($step == 2 && $datatoimport) {
252 if (is_numeric($resultupload) && $resultupload > 0) {
253 dol_syslog(
"File ".$fullpath.
" was added for import");
255 $langs->load(
"errors");
261 if ($action ==
'confirm_deletefile' && $confirm ==
'yes' && $user->hasRight(
'import',
'run')) {
262 $langs->load(
"other");
264 $param =
'&datatoimport='.urlencode($datatoimport).
'&format='.urlencode($format);
265 if ($excludefirstline) {
266 $param .=
'&excludefirstline='.urlencode($excludefirstline);
269 $param .=
'&endatlinenb='.urlencode($endatlinenb);
279 header(
'Location: '.$_SERVER[
"PHP_SELF"].
'?step='.$step.$param);
284if ($step == 4 && $action ==
'select_model' && $user->hasRight(
'import',
'run')) {
286 $_SESSION[
"dol_array_match_file_to_database"] =
'';
287 $serialized_array_match_file_to_database =
'';
288 $array_match_file_to_database = array();
292 $result = $objimport->fetch($importmodelid);
294 $serialized_array_match_file_to_database = $objimport->hexa;
295 $fieldsarray = explode(
',', $serialized_array_match_file_to_database);
296 foreach ($fieldsarray as $elem) {
297 $tabelem = explode(
'=', $elem);
301 $array_match_file_to_database[$key] = $val;
304 $_SESSION[
"dol_array_match_file_to_database"] = $serialized_array_match_file_to_database;
305 $_SESSION[
'dol_array_match_file_to_database_select'] = $_SESSION[
"dol_array_match_file_to_database"];
308if ($action ==
'saveselectorder' && $user->hasRight(
'import',
'run')) {
310 $serialized_array_match_file_to_database =
'';
312 $selectorder = explode(
",",
GETPOST(
'selectorder'));
313 $fieldtarget = $fieldstarget = $objimport->array_import_fields[0];
314 foreach ($selectorder as $key => $code) {
315 $serialized_array_match_file_to_database .= $key.
'='.$code;
316 $serialized_array_match_file_to_database .=
',';
318 $serialized_array_match_file_to_database = substr($serialized_array_match_file_to_database, 0, -1);
319 dol_syslog(
'dol_array_match_file_to_database_select='.$serialized_array_match_file_to_database);
320 $_SESSION[
"dol_array_match_file_to_database_select"] = $serialized_array_match_file_to_database;
330$help_url =
'EN:Module_Imports_En|FR:Module_Imports|ES:Módulo_Importaciones';
333if ($step == 1 || !$datatoimport) {
335 $serialized_array_match_file_to_database =
'';
336 $array_match_file_to_database = array();
337 $_SESSION[
"dol_array_match_file_to_database"] =
'';
338 $_SESSION[
"dol_array_match_file_to_database_select"] =
'';
341 if ($excludefirstline) {
342 $param .=
'&excludefirstline='.urlencode($excludefirstline);
345 $param .=
'&endatlinenb='.urlencode($endatlinenb);
348 $param .=
'&separator='.urlencode($separator);
351 $param .=
'&enclosure='.urlencode($enclosure);
354 llxHeader(
'', $langs->trans(
"NewImport"), $help_url);
360 print
'<div class="opacitymedium">'.$langs->trans(
"SelectImportDataSet").
'</div>';
364 $nbmodulesnotautoenabled = count(
$conf->modules);
365 $listofmodulesautoenabled = array(
'user',
'agenda',
'fckeditor',
'export',
'import');
366 foreach ($listofmodulesautoenabled as $moduleautoenable) {
367 if (in_array($moduleautoenable,
$conf->modules)) {
368 $nbmodulesnotautoenabled--;
372 if ($user->admin && $nbmodulesnotautoenabled <
getDolGlobalInt(
'MAIN_MIN_NB_ENABLED_MODULE_FOR_WARNING', 1)) {
373 print
info_admin($langs->trans(
"WarningOnlyProfilesOfActivatedModules").
' '.$langs->trans(
"YouCanEnableModulesFrom"));
379 print
'<div class="div-table-responsive-no-min">';
380 print
'<table class="noborder centpercent nomarginbottom">';
381 print
'<tr class="liste_titre">';
382 print
'<td>'.$langs->trans(
"Module").
'</td>';
383 print
'<td>'.$langs->trans(
"ImportableDatas").
'</td>';
384 print
'<td> </td>';
387 if (count($objimport->array_import_module)) {
388 $sortedarrayofmodules =
dol_sort_array($objimport->array_import_module,
'position_of_profile',
'asc', 0, 0, 1);
389 foreach ($sortedarrayofmodules as $key => $value) {
391 $titleofmodule = $objimport->array_import_module[$key][
'module']->getName();
392 print
'<tr class="oddeven"><td class="tdoverflowmax200" title="'.dolPrintHTML($titleofmodule).
'">';
394 if (in_array($objimport->array_import_code[$key], array(
'produit_supplierprices',
'produit_multiprice',
'produit_languages'))) {
395 $titleofmodule = $langs->trans(
"ProductOrService");
399 $entity = preg_replace(
'/:.*$/',
'', $objimport->array_import_icon[$key]);
400 $entityicon = strtolower(!empty($entitytoicon[$entity]) ? $entitytoicon[$entity] : $entity);
401 $label = $objimport->array_import_label[$key];
402 print
'<div class="twolinesmax-normallineheight minwidth200onall">';
403 print
img_object($objimport->array_import_module[$key][
'module']->getName(), $entityicon,
'class="pictofixedwidth"');
406 print
'</td><td style="text-align: right">';
407 if ($objimport->array_import_perms[$key]) {
408 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>';
410 print $langs->trans(
"NotEnoughPermissions");
415 print
'<tr><td class="oddeven" colspan="3">'.$langs->trans(
"NoImportableData").
'</td></tr>';
425if ($step == 2 && $datatoimport) {
426 $param =
'&datatoimport='.urlencode($datatoimport);
427 if ($excludefirstline) {
428 $param .=
'&excludefirstline='.urlencode($excludefirstline);
431 $param .=
'&endatlinenb='.urlencode($endatlinenb);
434 $param .=
'&separator='.urlencode($separator);
437 $param .=
'&enclosure='.urlencode($enclosure);
440 $list = $objmodelimport->listOfAvailableImportFormat(
$db);
442 llxHeader(
'', $langs->trans(
"NewImport"), $help_url);
451 if ($action ==
'delete') {
452 print $form->formconfirm($_SERVER[
"PHP_SELF"].
'?urlfile='.urlencode(
GETPOST(
'urlfile')).
'&step=2'.$param, $langs->trans(
'DeleteFile'), $langs->trans(
'ConfirmDeleteFile'),
'confirm_deletefile',
'', 0, 1);
455 print
'<div class="underbanner clearboth"></div>';
456 print
'<div class="fichecenter">';
458 print
'<table class="border tableforfield centpercent">';
461 print
'<tr><td class="titlefieldcreate">'.$langs->trans(
"Module").
'</td>';
463 $titleofmodule = $objimport->array_import_module[0][
'module']->getName();
465 if (in_array($objimport->array_import_code[0], array(
'produit_supplierprices',
'produit_multiprice',
'produit_languages'))) {
466 $titleofmodule = $langs->trans(
"ProductOrService");
468 print $titleofmodule;
472 print
'<tr><td>'.$langs->trans(
"DatasetToImport").
'</td>';
474 $entity = preg_replace(
'/:.*$/',
'', $objimport->array_import_icon[0]);
475 $entityicon = strtolower(!empty($entitytoicon[$entity]) ? $entitytoicon[$entity] : $entity);
476 print
img_object($objimport->array_import_module[0][
'module']->getName(), $entityicon).
' ';
477 print $objimport->array_import_label[0];
507 if ($format ==
'xlsx' && !class_exists(
'XMLWriter')) {
508 $langs->load(
"install");
509 print
info_admin($langs->trans(
"ErrorPHPDoesNotSupport",
'php-xml'), 0, 0,
'1',
'error');
515 print
'<form name="userfile" action="'.$_SERVER[
"PHP_SELF"].
'" enctype="multipart/form-data" method="POST">';
516 print
'<input type="hidden" name="token" value="'.newToken().
'">';
517 print
'<input type="hidden" value="'.$step.
'" name="step">';
518 print
'<input type="hidden" value="'.dol_escape_htmltag($format).
'" name="format">';
519 print
'<input type="hidden" value="'.$excludefirstline.
'" name="excludefirstline">';
520 print
'<input type="hidden" value="'.$endatlinenb.
'" name="endatlinenb">';
521 print
'<input type="hidden" value="'.dol_escape_htmltag($separator).
'" name="separator">';
522 print
'<input type="hidden" value="'.dol_escape_htmltag($enclosure).
'" name="enclosure">';
523 print
'<input type="hidden" value="'.dol_escape_htmltag($datatoimport).
'" name="datatoimport">';
525 print
'<span class="opacitymedium">';
526 $s = $langs->trans(
"ChooseFileToImport",
'{s1}');
527 $s = str_replace(
'{s1}',
img_picto(
'',
'next'), $s);
529 print
'</span><br><br>';
534 print
'<table class="noborder centpercent" cellpadding="4">';
536 print
'<tr class="liste_titre"><td colspan="4">';
537 print $langs->trans(
"FileMustHaveOneOfFollowingFormat").
'...';
539 $list = $objmodelimport->listOfAvailableImportFormat(
$db);
540 foreach ($list as $key) {
541 print
'<tr class="oddeven">';
542 print
'<td width="16">'.img_picto_common($key, $objmodelimport->getPictoForKey($key)).
'</td>';
543 $htmltext = $objmodelimport->getDriverDescForKey($key);
544 print
'<td>'.$form->textwithpicto($objmodelimport->getDriverLabelForKey($key), $htmltext).
'</td>';
545 print
'<td style="text-align:center">';
546 if (empty($objmodelimport->drivererror[$key])) {
547 $filename = $langs->transnoentitiesnoconv(
"ExampleOfImportFile").
'_'.$datatoimport.
'.'.$key;
548 print
'<a href="'.DOL_URL_ROOT.
'/imports/emptyexample.php?format='.$key.$param.
'&output=file&file='.urlencode($filename).
'" target="_blank" rel="noopener noreferrer">';
549 print
img_picto(
'',
'download',
'class="paddingright opacitymedium"');
550 print $langs->trans(
"DownloadEmptyExampleShort");
552 print $form->textwithpicto(
'', $langs->trans(
"DownloadEmptyExample").
'.<br>'.$langs->trans(
"StarAreMandatory"));
566 print
'<div class="marginbottomonly">';
568 $maxmin = $maxfilesizearray[
'maxmin'];
570 print
'<input type="hidden" name="MAX_FILE_SIZE" value="'.($maxmin * 1024).
'">';
572 print
'<input type="file" name="userfile" size="20" maxlength="80"> ';
574 print
'<input type="submit" class="button small" value="'.$langs->trans(
"AddFile").
'"'.$out.
' name="sendit">';
578 $maxphp = @ini_get(
'upload_max_filesize');
579 if (preg_match(
'/k$/i', $maxphp)) {
580 $maxphp = (int) substr($maxphp, 0, -1);
582 if (preg_match(
'/m$/i', $maxphp)) {
583 $maxphp = (int) substr($maxphp, 0, -1) * 1024;
585 if (preg_match(
'/g$/i', $maxphp)) {
586 $maxphp = (int) substr($maxphp, 0, -1) * 1024 * 1024;
588 if (preg_match(
'/t$/i', $maxphp)) {
589 $maxphp = (int) substr($maxphp, 0, -1) * 1024 * 1024 * 1024;
591 $maxphp2 = @ini_get(
'post_max_size');
592 if (preg_match(
'/k$/i', $maxphp2)) {
593 $maxphp2 = (int) substr($maxphp2, 0, -1);
595 if (preg_match(
'/m$/i', $maxphp2)) {
596 $maxphp2 = (int) substr($maxphp2, 0, -1) * 1024;
598 if (preg_match(
'/g$/i', $maxphp2)) {
599 $maxphp2 = (int) substr($maxphp2, 0, -1) * 1024 * 1024;
601 if (preg_match(
'/t$/i', $maxphp2)) {
602 $maxphp2 = (int) substr($maxphp2, 0, -1) * 1024 * 1024 * 1024;
606 $maxphptoshow = $maxphptoshowparam =
'';
608 $maxmin = min($max, $maxphp);
609 $maxphptoshow = $maxphp;
610 $maxphptoshowparam =
'upload_max_filesize';
613 $maxmin = min($max, $maxphp2);
614 if ($maxphp2 < $maxphp) {
615 $maxphptoshow = $maxphp2;
616 $maxphptoshowparam =
'post_max_size';
620 $langs->load(
'other');
622 $out .=
info_admin($langs->trans(
"ThisLimitIsDefinedInSetup", $max, $maxphptoshow), 1);
624 $out .=
' ('.$langs->trans(
"UploadDisabled").
')';
631 $filearray =
dol_dir_list(
$conf->import->dir_temp,
'files', 0,
'',
'',
'name', SORT_DESC);
632 if (count($filearray) > 0) {
633 print
'<div class="div-table-responsive-no-min">';
634 print
'<table class="noborder centpercent" width="100%" cellpadding="4">';
636 $dir =
$conf->import->dir_temp;
640 foreach ($filearray as $key => $val) {
641 $file = $val[
'name'];
645 $file = mb_convert_encoding($file,
'UTF-8',
'ISO-8859-1');
648 if (preg_match(
'/^\./', $file)) {
652 $modulepart =
'import';
653 $urlsource = $_SERVER[
"PHP_SELF"].
'?step='.$step.$param.
'&filetoimport='.urlencode($filetoimport);
654 $relativepath = $file;
656 print
'<tr class="oddeven">';
658 print
img_mime($file,
'',
'pictofixedwidth');
659 print
'<a data-ajax="false" href="'.DOL_URL_ROOT.
'/document.php?modulepart='.$modulepart.
'&file='.urlencode($relativepath).
'&step=2'.$param.
'" target="_blank" rel="noopener noreferrer">';
664 print
'<td style="text-align:right">'.dol_print_size(
dol_filesize($dir.
'/'.$file)).
'</td>';
666 print
'<td style="text-align:right">'.dol_print_date(
dol_filemtime($dir.
'/'.$file),
'dayhour').
'</td>';
668 print
'<td style="text-align:right"><a href="'.$_SERVER[
'PHP_SELF'].
'?action=delete&token='.
newToken().
'&step=2'.$param.
'&urlfile='.urlencode($relativepath);
669 print
'">'.img_delete().
'</a></td>';
671 print
'<td style="text-align:right">';
672 print
'<a href="'.$_SERVER[
'PHP_SELF'].
'?step=3'.$param.
'&filetoimport='.urlencode($relativepath).
'">'.
img_picto($langs->trans(
"ImportThisFile"),
'next',
'class="fa-15"').
'</a>';
686if ($step == 3 && $datatoimport) {
688 $serialized_array_match_file_to_database = isset($_SESSION[
"dol_array_match_file_to_database_select"]) ? $_SESSION[
"dol_array_match_file_to_database_select"] :
'';
689 $fieldsarray = explode(
',', $serialized_array_match_file_to_database);
690 $array_match_file_to_database = array();
691 foreach ($fieldsarray as $elem) {
692 $tabelem = explode(
'=', $elem, 2);
694 $val = (isset($tabelem[1]) ? $tabelem[1] :
'');
696 $array_match_file_to_database[$key] = $val;
703 if (empty($format) && !empty($filetoimport)) {
704 $format = pathinfo($filetoimport, PATHINFO_EXTENSION);
710 if ($model ===
'txt') {
714 $list = $objmodelimport->listOfAvailableImportFormat(
$db);
716 if (empty($separator)) {
717 $separator = (!
getDolGlobalString(
'IMPORT_CSV_SEPARATOR_TO_USE') ?
',' :
$conf->global->IMPORT_CSV_SEPARATOR_TO_USE);
721 if ($model ==
'csv' && strlen($separator) == 1 && !
GETPOSTISSET(
'separator')) {
722 '@phan-var-force ImportCsv $obj';
724 $fh = fopen(
$conf->import->dir_temp.
'/'.$filetoimport,
'r');
726 $sline = fgets($fh, 1000000);
728 $nboccurence = substr_count($sline, $separator);
729 $nboccurencea = substr_count($sline,
',');
730 $nboccurenceb = substr_count($sline,
';');
732 if ($nboccurence == 0) {
733 if ($nboccurencea > 2) {
735 } elseif ($nboccurenceb > 2) {
743 $separator_used = str_replace(
'\t',
"\t", $separator);
746 $dir = DOL_DOCUMENT_ROOT.
"/core/modules/import/";
747 $file =
"import_".$model.
".modules.php";
748 $classname =
"Import".ucfirst($model);
749 require_once $dir.$file;
750 $obj =
new $classname(
$db, $datatoimport);
751 '@phan-var-force ModeleImports $obj';
753 if (!empty($obj->error)) {
754 $langs->load(
"errors");
755 $param =
'&datatoimport='.$datatoimport.
'&format='.$format;
757 header(
"Location: ".$_SERVER[
"PHP_SELF"].
'?step=2'.$param.
'&filetoimport='.urlencode($relativepath));
761 if ($model ==
'csv') {
762 '@phan-var-force ImportCsv $obj';
763 $obj->separator = $separator_used;
764 $obj->enclosure = $enclosure;
767 if ($model ==
'xlsx') {
768 '@phan-var-force ImportXlsx $obj';
769 if (!preg_match(
'/\.xlsx$/i', $filetoimport)) {
770 $langs->load(
"errors");
771 $param =
'&datatoimport='.$datatoimport.
'&format='.$format;
772 setEventMessages($langs->trans(
"ErrorFileMustHaveFormat", $model),
null,
'errors');
773 header(
"Location: ".$_SERVER[
"PHP_SELF"].
'?step=2'.$param.
'&filetoimport='.urlencode($relativepath));
779 $array_match_file_to_database = array();
783 $fieldssource = array();
785 $result = $obj->import_open_file(
$conf->import->dir_temp.
'/'.$filetoimport);
788 $arrayrecord = $obj->import_read_record();
792 foreach ($arrayrecord as $key => $val) {
793 if ($val[
"type"] != -1) {
794 $fieldssource[$i][
'example1'] =
dol_trunc($val[
'val'], 128);
796 $fieldssource[$i][
'example1'] = $langs->trans(
'Empty');
798 $fieldssource[$i][
'imported'] =
false;
801 $obj->import_close_file();
805 $fieldstarget = $objimport->array_import_fields[0];
806 $minpos = min(count($fieldssource), count($fieldstarget));
810 $initialloadofstep4 =
false;
811 if (empty($_SESSION[
'dol_array_match_file_to_database_select'])) {
812 $initialloadofstep4 =
true;
816 if (count($array_match_file_to_database) == 0) {
822 $num = count($fieldssource);
823 while ($pos <= $num) {
824 if ($num >= 1 && $pos <= $num) {
826 foreach ($fieldstarget as $key => $val) {
827 if ($posbis < $pos) {
832 $array_match_file_to_database[$pos] = $key;
839 $array_match_database_to_file = array_flip($array_match_file_to_database);
843 $fieldstarget_tmp = array();
844 $arraykeysfieldtarget = array_keys($fieldstarget);
846 foreach ($fieldstarget as $key => $label) {
847 $isrequired = preg_match(
'/\*$/', $label);
848 if (!empty($isrequired)) {
849 $newlabel = substr($label, 0, -1);
850 $fieldstarget_tmp[$key] = array(
"label" => (
string) $newlabel,
"required" =>
true);
852 $fieldstarget_tmp[$key] = array(
"label" => (
string) $label,
"required" =>
false);
854 if (!empty($array_match_database_to_file[$key])) {
855 $fieldstarget_tmp[$key][
"imported"] =
true;
856 $fieldstarget_tmp[$key][
"position"] = (int) $array_match_database_to_file[$key] - 1;
858 while (!empty($array_match_database_to_file[$keytoswap])) {
859 if ($position + 1 > $array_match_database_to_file[$keytoswap]) {
860 $keytoswapwith = $array_match_database_to_file[$keytoswap] - 1;
861 $tmp = [$keytoswap => $fieldstarget_tmp[$keytoswap]];
862 unset($fieldstarget_tmp[$keytoswap]);
863 $fieldstarget_tmp =
arrayInsert($fieldstarget_tmp, $keytoswapwith, $tmp);
864 $keytoswapwith = $arraykeysfieldtarget[$array_match_database_to_file[$keytoswap] - 1];
865 $tmp = $fieldstarget_tmp[$keytoswapwith];
866 unset($fieldstarget_tmp[$keytoswapwith]);
867 $fieldstarget_tmp[$keytoswapwith] = $tmp;
868 $keytoswap = $keytoswapwith;
874 $fieldstarget_tmp[$key][
"imported"] =
false;
878 $fieldstarget = $fieldstarget_tmp;
887 $param =
'&format='.$format.
'&datatoimport='.urlencode($datatoimport).
'&filetoimport='.urlencode($filetoimport);
888 if ($excludefirstline) {
889 $param .=
'&excludefirstline='.urlencode($excludefirstline);
892 $param .=
'&endatlinenb='.urlencode($endatlinenb);
895 $param .=
'&separator='.urlencode($separator);
898 $param .=
'&enclosure='.urlencode($enclosure);
901 llxHeader(
'', $langs->trans(
"NewImport"), $help_url);
905 $titleofmodule = $objimport->array_import_module[0][
'module']->getName();
909 print
'<div class="underbanner clearboth"></div>';
910 print
'<div class="fichecenter">';
912 print
'<table class="centpercent border tableforfield">';
915 print
'<tr><td class="titlefieldcreate">'.$langs->trans(
"Module").
'</td>';
918 if (in_array($objimport->array_import_code[0], array(
'produit_supplierprices',
'produit_multiprice',
'produit_languages'))) {
919 $titleofmodule = $langs->trans(
"ProductOrService");
925 print
'<tr><td>'.$langs->trans(
"DatasetToImport").
'</td>';
927 $entity = preg_replace(
'/:.*$/',
'', $objimport->array_import_icon[0]);
928 $entityicon = strtolower(!empty($entitytoicon[$entity]) ? $entitytoicon[$entity] : $entity);
929 print
img_object($objimport->array_import_module[0][
'module']->getName(), $entityicon).
' ';
930 print $objimport->array_import_label[0];
940 print
load_fiche_titre($langs->trans(
"InformationOnSourceFile"),
'',
'file-export');
942 print
'<div class="underbanner clearboth"></div>';
943 print
'<div class="fichecenter">';
944 print
'<table width="100%" class="border tableforfield">';
947 print
'<tr><td class="titlefieldcreate">'.$langs->trans(
"SourceFileFormat").
'</td>';
948 print
'<td class="nowraponall">';
949 $text = $objmodelimport->getDriverDescForKey($format);
951 print $form->textwithpicto($objmodelimport->getDriverLabelForKey($format), $text);
955 if ($model ==
'csv') {
956 '@phan-var-force ImportCsv $obj';
957 print
'<tr><td>'.$langs->trans(
"CsvOptions").
'</td>';
959 print
'<form method="POST">';
960 print
'<input type="hidden" name="token" value="'.newToken().
'">';
961 print
'<input type="hidden" value="'.$step.
'" name="step">';
962 print
'<input type="hidden" value="'.$format.
'" name="format">';
963 print
'<input type="hidden" value="'.$excludefirstline.
'" name="excludefirstline">';
964 print
'<input type="hidden" value="'.$endatlinenb.
'" name="endatlinenb">';
965 print
'<input type="hidden" value="'.$datatoimport.
'" name="datatoimport">';
966 print
'<input type="hidden" value="'.$filetoimport.
'" name="filetoimport">';
967 print $langs->trans(
"Separator").
' : ';
968 print
'<input type="text" class="width25 center" name="separator" value="'.dol_escape_htmltag($separator).
'"/>';
969 print
' '.$langs->trans(
"Enclosure").
' : ';
970 print
'<input type="text" class="width25 center" name="enclosure" value="'.dol_escape_htmltag($enclosure).
'"/> ';
971 print
'<input name="update" type="submit" value="'.$langs->trans(
'Update').
'" class="button smallpaddingimp" />';
977 print
'<tr><td>'.$langs->trans(
"FileToImport").
'</td>';
979 $modulepart =
'import';
980 $relativepath =
GETPOST(
'filetoimport');
981 print
'<a data-ajax="false" href="'.DOL_URL_ROOT.
'/document.php?modulepart='.$modulepart.
'&file='.urlencode($relativepath).
'&step=3'.$param.
'" target="_blank" rel="noopener noreferrer">';
982 print
img_mime($file,
'',
'pictofixedwidth');
984 print
img_picto($langs->trans(
"Download"),
'download',
'class="paddingleft opacitymedium"');
997 print
'<!-- List of source fields -->'.
"\n";
998 print
'<form action="'.$_SERVER[
"PHP_SELF"].
'" method="POST">';
999 print
'<input type="hidden" name="token" value="'.newToken().
'">';
1000 print
'<input type="hidden" name="action" value="select_model">';
1001 print
'<input type="hidden" name="step" value="3">';
1002 print
'<input type="hidden" name="format" value="'.$format.
'">';
1003 print
'<input type="hidden" name="datatoimport" value="'.$datatoimport.
'">';
1004 print
'<input type="hidden" name="filetoimport" value="'.$filetoimport.
'">';
1005 print
'<input type="hidden" name="excludefirstline" value="'.$excludefirstline.
'">';
1006 print
'<input type="hidden" name="endatlinenb" value="'.$endatlinenb.
'">';
1007 print
'<input type="hidden" name="separator" value="'.dol_escape_htmltag($separator).
'">';
1008 print
'<input type="hidden" name="enclosure" value="'.dol_escape_htmltag($enclosure).
'">';
1011 print
'<div class="marginbottomonly">';
1012 print
'<span class="opacitymedium">';
1013 $s = $langs->trans(
"SelectImportFieldsSource",
'{s1}');
1014 $s = str_replace(
'{s1}',
img_picto(
'',
'grip_title',
'', 0, 0, 0,
'',
'', 0), $s);
1017 $htmlother->select_import_model((
string) $importmodelid,
'importmodelid', $datatoimport, 1, $user->id);
1018 print
'<input type="submit" class="button smallpaddingimp reposition" id="applyprofile" name="applyprofile" value="'.$langs->trans(
"Apply").
'">';
1020 if (!empty(
$conf->use_javascript_ajax)) {
1022 $(document).ready(function() {
1024 $("#applyprofile").hide();
1026 // follow change on list
1027 $("#importmodelid").change(function() {
1028 console.log("We select a new profile");
1029 if ($(this).val() && $(this).val() != "-1") {
1030 $("#applyprofile").show();
1032 $("#applyprofile").hide();
1046 print
'<div class="div-table-responsive-no-min">';
1047 print
'<table class="noborder centpercent">';
1048 print
'<tr class="liste_titre">';
1049 print
'<td>'.$langs->trans(
"FieldsInSourceFile").
'</td>';
1050 print
'<td>'.$langs->trans(
"FieldsInTargetDatabase").
'</td>';
1055 print
'<tr valign="top"><td width="50%" class="nopaddingleftimp">';
1057 $fieldsplaced = array();
1058 $valforsourcefieldnb = array();
1059 $listofkeys = array();
1060 foreach ($array_match_file_to_database as $key => $val) {
1061 $listofkeys[$key] = 1;
1064 print
"\n<!-- Box left container -->\n";
1065 print
'<div id="left" class="connectedSortable">'.
"\n";
1070 foreach ($fieldssource as $key => $val) {
1071 show_elem($fieldssource, $key, (
string) $key);
1072 $listofkeys[$key] = 1;
1073 $fieldsplaced[$key] = 1;
1074 $valforsourcefieldnb[$lefti] = $key;
1084 print
"<!-- End box left container -->\n";
1087 print
'</td><td width="50%" class="nopaddingrightimp">';
1091 $optionsall = array();
1092 foreach ($fieldstarget as $code => $line) {
1093 $tmparray = explode(
'|', $line[
"label"]);
1095 foreach ($tmparray as $tmpkey => $tmpval) {
1096 $labeltoshow .= ($labeltoshow ?
' '.$langs->trans(
'or').
' ' :
'').$langs->transnoentities($tmpval);
1101 $optionsall[$code] = array(
1102 'labelkey' => $line[
'label'],
1103 'labelkeyarray' => $tmparray,
1104 'label' => $labeltoshow,
1105 'required' => (empty($line[
"required"]) ? 0 : 1),
1106 'position' => (!empty($line[
'position']) ? $line[
'position'] : 0),
1114 $mandatoryfieldshavesource =
true;
1127 $modetoautofillmapping =
'session';
1128 if ($initialloadofstep4) {
1129 $modetoautofillmapping =
'guess';
1133 print
'<table class="nobordernopadding centpercent tableimport">';
1134 foreach ($fieldssource as $code => $line) {
1139 print
'<tr style="height:'.$height.
'" class="trimport oddevenimport">';
1141 $entity = (!empty($objimport->array_import_entities[0][$code]) ? $objimport->array_import_entities[0][$code] : $objimport->array_import_icon[0]);
1143 $entityicon = !empty($entitytoicon[$entity]) ? $entitytoicon[$entity] : $entity;
1144 $entitylang = !empty($entitytolang[$entity]) ? $entitytolang[$entity] : $objimport->array_import_label[0];
1146 print
'<td class="nowraponall hideonsmartphone" style="font-weight: normal">=> </td>';
1147 print
'<td class="nowraponall" style="font-weight: normal">';
1149 $selectforline =
'';
1150 $selectforline .=
'<select id="selectorderimport_'.($i + 1).
'" class="targetselectchange minwidth300" name="select_'.($i + 1).
'">';
1151 $selectforline .=
'<option value="-1"> </option>';
1154 $codeselectedarray = array();
1155 foreach ($optionsall as $tmpcode => $tmpval) {
1157 if (!empty($tmpval[
'picto'])) {
1158 $label .=
img_picto(
'', $tmpval[
'picto'],
'class="pictofixedwidth"');
1160 $label .= $tmpval[
'required'] ?
'<strong>' :
'';
1161 $label .= $tmpval[
'label'];
1162 $label .= $tmpval[
'required'] ?
'*</strong>' :
'';
1164 $tablealias = preg_replace(
'/(\..*)$/i',
'', $tmpcode);
1165 $tablename = !empty($objimport->array_import_tables[0][$tablealias]) ? $objimport->array_import_tables[0][$tablealias] :
"";
1169 $filecolumn = ($i + 1);
1171 if (empty($objimport->array_import_convertvalue[0][$tmpcode])) {
1174 if ($objimport->array_import_convertvalue[0][$tmpcode][
'rule'] ==
'fetchidfromref') {
1175 $htmltext .= $langs->trans(
"DataComeFromIdFoundFromRef", $langs->transnoentitiesnoconv($entitylang)).
'<br>';
1177 if ($objimport->array_import_convertvalue[0][$tmpcode][
'rule'] ==
'fetchidfromcodeid') {
1178 $dictlabel = $objimport->array_import_convertvalue[0][$tmpcode][
'dict'] ??
'';
1179 $htmltext .= $langs->trans(
"DataComeFromIdFoundFromCodeId", $langs->transnoentitiesnoconv($dictlabel)).
'<br>';
1183 $example = !empty($objimport->array_import_examplevalues[0][$tmpcode]) ? $objimport->array_import_examplevalues[0][$tmpcode] :
"";
1185 if (empty($objimport->array_import_convertvalue[0][$tmpcode])) {
1187 $htmltext .= $langs->trans(
"SourceExample").
': <b>'.str_replace(
'"',
'', $example).
'</b><br>';
1190 if ($objimport->array_import_convertvalue[0][$tmpcode][
'rule'] ==
'fetchidfromref') {
1191 $htmltext .= $langs->trans(
"SourceExample").
': <b>'.$langs->transnoentitiesnoconv(
"ExampleAnyRefFoundIntoElement", $entitylang).($example ?
' ('.$langs->transnoentitiesnoconv(
"Example").
': '.str_replace(
'"',
'', $example).
')' :
'').
'</b><br>';
1192 } elseif ($objimport->array_import_convertvalue[0][$tmpcode][
'rule'] ==
'fetchidfromcodeid') {
1193 $dictlabel = $objimport->array_import_convertvalue[0][$tmpcode][
'dict'] ??
'';
1194 $htmltext .= $langs->trans(
"SourceExample").
': <b>'.$langs->trans(
"ExampleAnyCodeOrIdFoundIntoDictionary", $langs->transnoentitiesnoconv($dictlabel)).($example ?
' ('.$langs->transnoentitiesnoconv(
"Example").
': '.str_replace(
'"',
'', $example).
')' :
'').
'</b><br>';
1195 } elseif ($example) {
1196 $htmltext .= $langs->trans(
"SourceExample").
': <b>'.str_replace(
'"',
'', $example).
'</b><br>';
1200 if (!empty($objimport->array_import_regex[0][$tmpcode])) {
1201 $htmltext .= $langs->trans(
"FormatControlRule").
': <b>'.str_replace(
'"',
'', $objimport->array_import_regex[0][$tmpcode]).
'</b><br>';
1205 $htmltext .= $langs->trans(
"InformationOnTargetTables").
': <b>'.$tablename.
"->".preg_replace(
'/^.*\./',
'', $tmpcode).
"</b>";
1207 $labelhtml = $label.
' '.$form->textwithpicto(
'', $htmltext, 1,
'help',
'', 1);
1210 $selectforline .=
'<option value="'.$tmpcode.
'"';
1211 if ($modetoautofillmapping ==
'orderoftargets') {
1214 $selectforline .=
' selected';
1216 } elseif ($modetoautofillmapping ==
'guess') {
1220 if (preg_match(
'/^(.+)\((.+\..+)\)$/', $line[
'example1'], $regs)) {
1221 $tmpstring1 = $regs[1];
1222 $tmpstring2 = $regs[2];
1224 $tmpstring1 = $line[
'example1'];
1232 foreach ($tmpval[
'labelkeyarray'] as $tmpval2) {
1233 $labeltarget = $langs->transnoentities($tmpval2);
1235 if ($tmpstring1 && ($tmpstring1 == $tmpcode || $tmpstring1 == strtolower($labeltarget)
1236 || $tmpstring1 == strtolower(
dol_string_unaccent($labeltarget)) || $tmpstring1 == strtolower($tmpval2))) {
1237 if (empty($codeselectedarray[$code])) {
1238 $selectforline .=
' selected';
1239 $codeselectedarray[$code] = 1;
1242 } elseif ($tmpstring2 && ($tmpstring2 == $tmpcode || $tmpstring2 == strtolower($labeltarget)
1243 || $tmpstring2 == strtolower(
dol_string_unaccent($labeltarget)) || $tmpstring2 == strtolower($tmpval2))) {
1244 if (empty($codeselectedarray[$code])) {
1245 $selectforline .=
' selected';
1246 $codeselectedarray[$code] = 1;
1251 } elseif ($modetoautofillmapping ==
'session' && !empty($_SESSION[
'dol_array_match_file_to_database_select'])) {
1252 $tmpselectioninsession =
dolExplodeIntoArray($_SESSION[
'dol_array_match_file_to_database_select'],
',',
'=');
1254 if (!empty($tmpselectioninsession[(
string) ($i + 1)]) && $tmpselectioninsession[(
string) ($i + 1)] == $tmpcode) {
1255 $selectforline .=
' selected';
1257 $selectforline .=
' data-debug="'.$tmpcode.
'-'.$code.
'-'.$j.
'-'.(!empty($tmpselectioninsession[(
string) ($i + 1)]) ? $tmpselectioninsession[(
string) ($i + 1)] :
"").
'"';
1259 $selectforline .=
' data-html="'.dol_escape_htmltag($labelhtml).
'"';
1260 $selectforline .=
'>';
1261 $selectforline .= $label;
1262 $selectforline .=
'</options>';
1265 $selectforline .=
'</select>';
1266 $selectforline .=
ajax_combobox(
'selectorderimport_'.($i + 1));
1268 print $selectforline;
1273 print
'<td class="nowraponall" style="font-weight:normal; text-align:right">';
1276 $htmltext =
'<b><u>'.$langs->trans(
"FieldSource").
'</u></b><br>';
1278 $htmltext .= $langs->trans(
"DataComeFromFileFieldNb", $filecolumntoshow).
'<br>';
1280 print $form->textwithpicto(
'', $htmltext);
1291 print
'<tr class="liste_titre"><td colspan="2">'.$langs->trans(
"Note").
'</td></tr>';
1292 print
'<tr><td colspan="2"><div id="div-mandatory-target-fields-not-mapped"></div></td></tr>';
1298 if (!empty(
$conf->use_javascript_ajax)) {
1299 print
'<script type="text/javascript">'.
"\n";
1300 print
'var previousselectedvalueimport = "0";'.
"\n";
1301 print
'var previousselectedlabelimport = "0";'.
"\n";
1302 print
'var arrayofselectedvalues = [];'.
"\n";
1303 print
'var arrayoftargetfields = [];'.
"\n";
1304 print
'var arrayoftargetmandatoryfields = [];'.
"\n";
1308 foreach ($fieldstarget as $key => $val) {
1309 print
"arrayoftargetfields[".$tmpi.
"] = '".
dol_escape_js($langs->trans($val[
'label'])).
"'; ";
1310 if ($val[
'required']) {
1311 print
"arrayoftargetmandatoryfields[".$tmpi.
"] = '".
dol_escape_js($key).
"'; ";
1317 print
'$(document).ready(function () {'.
"\n";
1319 print
'setOptionsToDisabled();'.
"\n";
1320 print
'saveSelection();'.
"\n";
1322 print
'$(".targetselectchange").focus(function(){'.
"\n";
1323 print
' previousselectedvalueimport = $(this).val();'.
"\n";
1324 print
' previousselectedlabelimport = $(this).children("option:selected").text();'.
"\n";
1325 print
' console.log("previousselectedvalueimport="+previousselectedvalueimport)'.
"\n";
1332 print
'function setOptionsToDisabled() {'.
"\n";
1333 print
' console.log("Remove the disabled flag everywhere");'.
"\n";
1334 print
' $("select.targetselectchange").not($( this )).find(\'option\').prop("disabled", false);'.
"\n";
1335 print
' arrayofselectedvalues = [];'.
"\n";
1337 print
' $("select.targetselectchange").each(function(){'.
"\n";
1338 print
' id = $(this).attr(\'id\')'.
"\n";
1339 print
' value = $(this).val()'.
"\n";
1340 print
' console.log("a selected value has been found for component "+id+" = "+value);'.
"\n";
1341 print
' arrayofselectedvalues.push(value);'.
"\n";
1344 print
' console.log("List of all selected values arrayofselectedvalues");'.
"\n";
1345 print
' console.log(arrayofselectedvalues);'.
"\n";
1346 print
' console.log("Set the option to disabled for every entry that is currently selected somewhere else (so into arrayofselectedvalues)");'.
"\n";
1348 print
' $.each(arrayofselectedvalues, function(key, value) {'.
"\n";
1349 print
' if (value != -1) {'.
"\n";
1350 print
' console.log("Process key="+key+" value="+value+" to disable.");'.
"\n";
1351 print
' $("select.targetselectchange").find(\'option[value="\'+value+\'"]:not(:selected)\').prop("disabled", true);'.
"\n";
1357 print
'function saveSelection() {'.
"\n";
1359 print
' arrayselectedfields = [];'.
"\n";
1360 print
' arrayselectedfields.push(0);'.
"\n";
1362 print
' $.each( arrayofselectedvalues, function( key, value ) {'.
"\n";
1363 print
' if (value != -1) {'.
"\n";
1364 print
' arrayselectedfields.push(value);'.
"\n";
1365 print
' } else {'.
"\n";
1366 print
' arrayselectedfields.push(0);'.
"\n";
1370 print
" $.ajax({\n";
1371 print
" type: 'POST',\n";
1372 print
" dataType: 'json',\n";
1373 print
" url: '".dol_escape_js($_SERVER[
"PHP_SELF"]).
"?action=saveselectorder&token=".
newToken().
"',\n";
1374 print
" data: 'selectorder='+arrayselectedfields.toString(),\n";
1375 print
" success: function(){\n";
1376 print
" console.log('The selected fields have been saved into '+arrayselectedfields.toString());\n";
1381 print
' console.log("arrayselectedfields");';
1382 print
' console.log(arrayselectedfields);';
1383 print
' console.log("arrayoftargetmandatoryfields");';
1384 print
' console.log(arrayoftargetmandatoryfields);';
1385 print
" listtoshow = '';";
1386 print
" nbelement = arrayoftargetmandatoryfields.length
1387 for (let i = 0; i < nbelement; i++) {
1388 if (arrayoftargetmandatoryfields[i] && ! arrayselectedfields.includes(arrayoftargetmandatoryfields[i])) {
1389 console.log(arrayoftargetmandatoryfields[i]+' not mapped');
1390 listtoshow = listtoshow + (listtoshow ? ', ' : '') + '<b>' + arrayoftargetfields[i] + '*</b>';
1393 console.log(listtoshow);
1395 listtoshow = '".dol_escape_js(
img_warning($langs->trans(
"MandatoryTargetFieldsNotMapped")).
' '.$langs->trans(
"MandatoryTargetFieldsNotMapped")).
": ' + listtoshow;
1396 $('#div-mandatory-target-fields-not-mapped').html(listtoshow);
1398 $('#div-mandatory-target-fields-not-mapped').html('<span class=\"opacitymedium\">".
dol_escape_js($langs->trans(
"AllTargetMandatoryFieldsAreMapped")).
"</span>');
1405 print
'$(".targetselectchange").change(function(){'.
"\n";
1406 print
' setOptionsToDisabled();'.
"\n";
1408 print
' if(previousselectedlabelimport != "" && previousselectedvalueimport != -1) {'.
"\n";
1409 print
' let valuetochange = $(this).val(); '.
"\n";
1410 print
' $(".boxtdunused").each(function(){'.
"\n";
1411 print
' if ($(this).text().includes(valuetochange)){'.
"\n";
1412 print
' arraychild = $(this)[0].childNodes'.
"\n";
1413 print
' arraytexttomodify = arraychild[0].textContent.split(" ")'.
"\n";
1414 print
' arraytexttomodify[1] = previousselectedvalueimport '.
"\n";
1415 print
' textmodified = arraytexttomodify.join(" ") '.
"\n";
1416 print
' arraychild[0].textContent = textmodified'.
"\n";
1417 print
' arraychild[1].innerHTML = previousselectedlabelimport'.
"\n";
1421 print
' $(this).blur()'.
"\n";
1423 print
' saveSelection()'.
"\n";
1427 print
'</script>'.
"\n";
1433 print
'<div class="tabsAction">';
1435 if (count($array_match_file_to_database)) {
1436 if ($mandatoryfieldshavesource) {
1437 print
'<a class="butAction saveorderselect" href="import.php?step=4'.$param.
'&filetoimport='.urlencode($filetoimport).
'">'.$langs->trans(
"NextStep").
'</a>';
1439 print
'<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->transnoentitiesnoconv(
"SomeMandatoryFieldHaveNoSource")).
'">'.$langs->trans(
"NextStep").
'</a>';
1447 if (count($array_match_file_to_database)) {
1449 print
'<!-- Area to add new import profile -->'.
"\n";
1450 print
'<div class="marginbottomonly"><span class="opacitymedium">'.$langs->trans(
"SaveImportModel").
'</span></div>';
1452 print
'<form class="nocellnopadd" action="'.$_SERVER[
"PHP_SELF"].
'" method="post">';
1453 print
'<input type="hidden" name="token" value="'.newToken().
'">';
1454 print
'<input type="hidden" name="action" value="add_import_model">';
1455 print
'<input type="hidden" name="step" value="'.$step.
'">';
1456 print
'<input type="hidden" name="format" value="'.$format.
'">';
1457 print
'<input type="hidden" name="datatoimport" value="'.$datatoimport.
'">';
1458 print
'<input type="hidden" name="filetoimport" value="'.$filetoimport.
'">';
1459 print
'<input type="hidden" name="hexa" value="'.$hexa.
'">';
1460 print
'<input type="hidden" name="excludefirstline" value="'.$excludefirstline.
'">';
1461 print
'<input type="hidden" name="endatlinenb" value="'.$endatlinenb.
'">';
1462 print
'<input type="hidden" name="page_y" value="">';
1463 print
'<input type="hidden" value="'.dol_escape_htmltag($separator).
'" name="separator">';
1464 print
'<input type="hidden" value="'.dol_escape_htmltag($enclosure).
'" name="enclosure">';
1466 print
'<div class="div-table-responsive-no-min">';
1467 print
'<table summary="selectofimportprofil" class="noborder centpercent">';
1468 print
'<tr class="liste_titre">';
1469 print
'<td>'.$langs->trans(
"ImportModelName").
'</td>';
1470 print
'<td>'.$langs->trans(
"Visibility").
'</td>';
1474 $nameofimportprofile = str_replace(
' ',
'-', $langs->trans(
"ImportProfile").
' '.$titleofmodule.
' '.
dol_print_date(
dol_now(
'gmt'),
'dayxcard'));
1476 $nameofimportprofile = $import_name;
1479 print
'<tr class="oddeven">';
1480 print
'<td><input name="import_name" class="minwidth300" value="'.$nameofimportprofile.
'"></td>';
1482 $arrayvisibility = array(
'private' => $langs->trans(
"Private"),
'all' => $langs->trans(
"Everybody"));
1483 print $form->selectarray(
'visibility', $arrayvisibility,
'private');
1485 print
'<td class="right">';
1486 print
'<input type="submit" class="button smallpaddingimp reposition" value="'.$langs->trans(
"SaveImportProfile").
'">';
1490 $sql =
"SELECT rowid, label, fk_user, entity";
1491 $sql .=
" FROM ".MAIN_DB_PREFIX.
"import_model";
1492 $sql .=
" WHERE type = '".$db->escape($datatoimport).
"'";
1494 $sql .=
" AND fk_user IN (0, ".((int) $user->id).
")";
1496 $sql .=
" ORDER BY rowid";
1498 $resql =
$db->query($sql);
1500 $num =
$db->num_rows($resql);
1506 $obj =
$db->fetch_object($resql);
1508 print
'<tr class="oddeven"><td>';
1511 print
'<td class="tdoverflowmax150">';
1512 if (empty($obj->fk_user)) {
1513 print $langs->trans(
"Everybody");
1515 $tmpuser->fetch($obj->fk_user);
1516 print $tmpuser->getNomUrl(-1);
1519 print
'<td class="right">';
1520 print
'<a class="reposition" href="'.$_SERVER[
"PHP_SELF"].
'?step='.$step.$param.
'&action=deleteprof&token='.
newToken().
'&id='.$obj->rowid.
'&filetoimport='.urlencode($filetoimport).
'">';
1538if ($step == 4 && $datatoimport) {
1539 $max_execution_time_for_importexport =
getDolGlobalInt(
'IMPORT_MAX_EXECUTION_TIME', 300);
1540 $max_time = @ini_get(
"max_execution_time");
1541 if ($max_time && $max_time < $max_execution_time_for_importexport) {
1542 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.");
1543 @ini_set(
"max_execution_time", $max_execution_time_for_importexport);
1549 if ($model ===
'txt') {
1553 $list = $objmodelimport->listOfAvailableImportFormat(
$db);
1556 $dir = DOL_DOCUMENT_ROOT.
"/core/modules/import/";
1557 $file =
"import_".$model.
".modules.php";
1558 $classname =
"Import".ucfirst($model);
1559 require_once $dir.$file;
1560 $obj =
new $classname(
$db, $datatoimport);
1561 '@phan-var-force ModeleImports $obj';
1562 $obj->importtriggermode = $importtriggermode;
1563 $obj->importissimulation = 1;
1564 if ($model ==
'csv') {
1565 '@phan-var-force ImportCsv $obj';
1566 $obj->separator = $separator_used;
1567 $obj->enclosure = $enclosure;
1571 $fieldssource = array();
1572 $result = $obj->import_open_file(
$conf->import->dir_temp.
'/'.$filetoimport);
1576 $arrayrecord = $obj->import_read_record();
1579 foreach ($arrayrecord as $key => $val) {
1580 $fieldssource[$i][
'example1'] =
dol_trunc($val[
'val'], 24);
1583 $obj->import_close_file();
1586 $nboflines = $obj->import_get_nb_of_lines(
$conf->import->dir_temp.
'/'.$filetoimport);
1588 $param =
'&leftmenu=import&format='.urlencode($format).
'&datatoimport='.urlencode($datatoimport).
'&filetoimport='.urlencode($filetoimport).
'&nboflines='.((int) $nboflines).
'&separator='.urlencode($separator).
'&enclosure='.urlencode($enclosure).
'&importtriggermode='.urlencode($importtriggermode);
1590 if ($excludefirstline) {
1591 $param .=
'&excludefirstline='.urlencode($excludefirstline);
1594 $param .=
'&endatlinenb='.urlencode($endatlinenb);
1596 if (!empty($updatekeys)) {
1597 $param .=
'&updatekeys[]='.implode(
'&updatekeys[]=', $updatekeys);
1600 llxHeader(
'', $langs->trans(
"NewImport"), $help_url);
1605 print
'<form action="'.$_SERVER[
"PHP_SELF"].
'?'.$param2.
'" method="POST">';
1606 print
'<input type="hidden" name="token" value="'.newToken().
'">';
1607 print
'<input type="hidden" name="step" value="4">';
1608 print
'<input type="hidden" name="action" value="launchsimu">';
1609 print
'<input type="hidden" name="importtriggermode" value="'.dol_escape_htmltag($importtriggermode).
'">';
1613 print
'<div class="underbanner clearboth"></div>';
1614 print
'<div class="fichecenter">';
1616 print
'<table width="100%" class="border tableforfield">';
1619 print
'<tr><td class="titlefieldcreate">'.$langs->trans(
"Module").
'</td>';
1621 $titleofmodule = $objimport->array_import_module[0][
'module']->getName();
1623 if (in_array($objimport->array_import_code[0], array(
'produit_supplierprices',
'produit_multiprice',
'produit_languages'))) {
1624 $titleofmodule = $langs->trans(
"ProductOrService");
1626 print $titleofmodule;
1630 print
'<tr><td>'.$langs->trans(
"DatasetToImport").
'</td>';
1632 $entity = preg_replace(
'/:.*$/',
'', $objimport->array_import_icon[0]);
1633 $entityicon = strtolower(!empty($entitytoicon[$entity]) ? $entitytoicon[$entity] : $entity);
1634 print
img_object($objimport->array_import_module[0][
'module']->getName(), $entityicon).
' ';
1635 print $objimport->array_import_label[0];
1643 print
load_fiche_titre($langs->trans(
"InformationOnSourceFile"),
'',
'file-export');
1645 print
'<div class="underbanner clearboth"></div>';
1646 print
'<div class="fichecenter">';
1647 print
'<table width="100%" class="border tableforfield">';
1650 print
'<tr><td class="titlefieldcreate">'.$langs->trans(
"SourceFileFormat").
'</td>';
1651 print
'<td class="nowraponall">';
1652 $text = $objmodelimport->getDriverDescForKey($format);
1654 print $form->textwithpicto($objmodelimport->getDriverLabelForKey($format), $text);
1658 if ($model ==
'csv') {
1659 '@phan-var-force ImportCsv $obj';
1660 print
'<tr><td>'.$langs->trans(
"CsvOptions").
'</td>';
1663 print
' '.$langs->trans(
"Enclosure").
' : '.
dol_escape_htmltag($enclosure);
1668 print
'<tr><td>'.$langs->trans(
"FileToImport").
'</td>';
1670 $modulepart =
'import';
1671 $relativepath =
GETPOST(
'filetoimport');
1672 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">';
1673 print
img_mime($file,
'',
'pictofixedwidth');
1674 print $filetoimport;
1675 print
img_picto($langs->trans(
"Download"),
'download',
'class="paddingleft opacitymedium"');
1681 print $langs->trans(
"NbOfSourceLines");
1688 print $langs->trans(
"ImportFromToLine");
1690 if ($action ==
'launchsimu') {
1691 print
'<input type="number" min="1" class="maxwidth50 right valignmiddle" name="excludefirstlinebis" disabled="disabled" value="'.$excludefirstline.
'">';
1692 print
'<input type="hidden" name="excludefirstline" value="'.$excludefirstline.
'">';
1694 print
'<input type="number" min="1" class="maxwidth50 right valignmiddle" name="excludefirstline" value="'.$excludefirstline.
'">';
1695 print $form->textwithpicto(
"", $langs->trans(
"SetThisValueTo2ToExcludeFirstLine"));
1698 if ($action ==
'launchsimu') {
1699 print
'<input type="text" class="maxwidth50 valignmiddle" name="endatlinenbbis" disabled="disabled" value="'.$endatlinenb.
'">';
1700 print
'<input type="hidden" name="endatlinenb" value="'.$endatlinenb.
'">';
1702 print
'<input type="text" class="maxwidth50 valignmiddle" name="endatlinenb" value="'.$endatlinenb.
'">';
1703 print $form->textwithpicto(
"", $langs->trans(
"KeepEmptyToGoToEndOfFile"));
1705 if ($action ==
'launchsimu') {
1706 print
' <a href="'.$_SERVER[
"PHP_SELF"].
'?step=4'.$param.
'" class="editfielda">';
1708 print
img_picto($langs->trans(
"Modify"),
'edit');
1711 if ($excludefirstline == 2) {
1712 print $form->textwithpicto(
"", $langs->trans(
"WarningFirstImportedLine", $excludefirstline), 1,
'warning',
"warningexcludefirstline valignmiddle");
1714 $( document ).ready(function() {
1715 $("input[name=\'excludefirstline\']").on("change",function(){
1716 if($(this).val() <= 1){
1717 $(".warningexcludefirstline").hide();
1719 $(".warningexcludefirstline").show();
1729 print $form->textwithpicto($langs->trans(
"KeysToUseForUpdates"), $langs->trans(
"SelectPrimaryColumnsForUpdateAttempt"));
1731 if ($action ==
'launchsimu') {
1732 if (count($updatekeys)) {
1733 print $form->multiselectarray(
'updatekeysbis', $objimport->array_import_updatekeys[0], $updatekeys, 0, 0,
'', 1,
'80%',
'disabled');
1735 print
'<span class="opacitymedium">'.$langs->trans(
"NoUpdateAttempt").
'</span>';
1737 foreach ($updatekeys as $val) {
1738 print
'<input type="hidden" name="updatekeys[]" value="'.$val.
'">';
1740 print
' <a href="'.$_SERVER[
"PHP_SELF"].
'?step=4'.$param.
'" class="editfielda">';
1742 print
img_picto($langs->trans(
"Modify"),
'edit');
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>';
1762 print
load_fiche_titre($langs->trans(
"InformationOnTargetTables"),
'',
'file-import');
1764 print
'<div class="underbanner clearboth"></div>';
1765 print
'<div class="fichecenter">';
1767 print
'<table class="centpercent border tableforfield">';
1770 print
'<tr><td class="titlefieldcreate">';
1771 print $langs->trans(
"TablesTarget");
1773 $listtables = array();
1774 $sort_array_match_file_to_database = $array_match_file_to_database;
1775 foreach ($array_match_file_to_database as $code => $label) {
1777 if ($code > count($fieldssource)) {
1781 $alias = preg_replace(
'/(\..*)$/i',
'', $label);
1782 $listtables[$alias] = $objimport->array_import_tables[0][$alias];
1784 if (count($listtables)) {
1787 foreach ($listtables as $val) {
1806 print $langs->trans(
"Error");
1812 print $langs->trans(
"FieldsTarget").
'</td><td class="small">';
1813 $listfields = array();
1816 $sort_array_match_file_to_database = $array_match_file_to_database;
1817 ksort($sort_array_match_file_to_database);
1819 foreach ($sort_array_match_file_to_database as $code => $label) {
1822 if ($code > count($fieldssource)) {
1826 $alias = preg_replace(
'/(\..*)$/i',
'', $label);
1827 $listfields[$i] =
'<span class="nowrap">'.$langs->trans(
"Column").
' '.
num2Alpha((
int) $code - 1).
' -> '.$label.
'</span>';
1829 print count($listfields) ? (implode(
', ', $listfields)) : $langs->trans(
"Error");
1834 print $form->textwithpicto($langs->trans(
"ImportTriggerModeLabel"), $langs->trans(
"ImportTriggerModeHint"));
1836 $triggerModeChoices = array(
1837 'strict_line' => $langs->trans(
"ImportTriggerModeStrictLine"),
1838 'fast_bulk' => $langs->trans(
"ImportTriggerModeFastBulk"),
1840 if ($action ==
'launchsimu') {
1841 print
dol_escape_htmltag($triggerModeChoices[$importtriggermode] ?? $importtriggermode);
1842 print
'<input type="hidden" name="importtriggermode" value="'.dol_escape_htmltag($importtriggermode).
'">';
1843 print
' <a href="'.$_SERVER[
"PHP_SELF"].
'?step=4'.$param.
'" class="editfielda">';
1845 print
img_picto($langs->trans(
"Modify"),
'edit');
1848 print $form->selectarray(
'importtriggermode', $triggerModeChoices, $importtriggermode, 0);
1850 if ($importtriggermode ===
'fast_bulk') {
1851 print
'<br><span class="warning">';
1852 print $langs->trans(
"ImportTriggerModeFastBulkWarning");
1863 if ($action !=
'launchsimu') {
1866 print
'<div class="neutral">';
1867 print $langs->trans(
"NowClickToTestTheImport", $langs->transnoentitiesnoconv(
"RunSimulateImportFile")).
'<br>';
1871 print
'<div class="center">';
1872 if ($user->hasRight(
'import',
'run')) {
1873 print
'<input type="submit" class="butAction" value="'.$langs->trans(
"RunSimulateImportFile").
'">';
1875 print
'<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->transnoentitiesnoconv(
"NotEnoughPermissions")).
'">'.$langs->trans(
"RunSimulateImportFile").
'</a>';
1880 print
'<div class="warning">';
1881 print
'<b>'.$langs->trans(
"ImportTriggerModeSimulationWarningTitle").
'</b><br>';
1882 print $langs->trans(
"ImportTriggerModeSimulationWarning");
1886 $arrayoferrors = array();
1887 $arrayofwarnings = array();
1901 $pathfile =
$conf->import->dir_temp.
'/'.$filetoimport;
1902 $result = $obj->import_open_file($pathfile);
1904 global $tablewithentity_cache;
1905 $tablewithentity_cache = array();
1910 while (($sourcelinenb < $nboflines) && !$endoffile) {
1914 $arrayrecord = $obj->import_read_record();
1915 if ($arrayrecord ===
false) {
1916 $arrayofwarnings[$sourcelinenb][0] = array(
'lib' => $langs->trans(
'ErrorFileLinesReachEOF', $nboflines, $sourcelinenb),
'type' =>
'EOF_RECORD_ON_SEVERAL_LINES');
1920 if ($excludefirstline && ($sourcelinenb < $excludefirstline)) {
1923 if ($endatlinenb && ($sourcelinenb > $endatlinenb)) {
1927 $parameters = array(
1929 'datatoimport' => $datatoimport,
1931 'arrayrecord' => $arrayrecord,
1932 'array_match_file_to_database' => $array_match_file_to_database,
1933 'objimport' => $objimport,
1934 'fieldssource' => $fieldssource,
1935 'importid' => $importid,
1936 'updatekeys' => $updatekeys,
1937 'importtriggermode' => $importtriggermode,
1938 'arrayoferrors' => &$arrayoferrors,
1939 'arrayofwarnings' => &$arrayofwarnings,
1943 $reshook = $hookmanager->executeHooks(
'ImportInsert', $parameters);
1945 $arrayoferrors[$sourcelinenb][] = [
1946 'lib' => implode(
"<br>", array_merge([$hookmanager->error], $hookmanager->errors))
1950 if (empty($reshook)) {
1952 $result = $obj->import_insert($arrayrecord, $array_match_file_to_database, $objimport, count($fieldssource), $importid, $updatekeys);
1954 if (count($obj->errors)) {
1955 $arrayoferrors[$sourcelinenb] = $obj->errors;
1957 if (count($obj->warnings)) {
1958 $arrayofwarnings[$sourcelinenb] = $obj->warnings;
1960 if (!count($obj->errors) && !count($obj->warnings)) {
1965 $reshook = $hookmanager->executeHooks(
'AfterImportInsert', $parameters);
1967 $arrayoferrors[$sourcelinenb][] = [
1968 'lib' => implode(
"<br>", array_merge([$hookmanager->error], $hookmanager->errors))
1973 $obj->import_close_file();
1975 print $langs->trans(
"ErrorFailedToOpenFile", $pathfile);
1982 if (!empty($objimport->array_import_run_sql_after[0]) && is_array($objimport->array_import_run_sql_after[0])) {
1984 foreach ($objimport->array_import_run_sql_after[0] as $sqlafterimport) {
1986 $resqlafterimport =
$db->query($sqlafterimport);
1987 if (!$resqlafterimport) {
1988 $arrayoferrors[
'none'][] = array(
'lib' => $langs->trans(
"Error running final request: ".$sqlafterimport));
1997 if (!count($arrayoferrors) && !count($arrayofwarnings)) {
1999 print
'<div class="info">';
2000 print
'<div class=""><b>'.$langs->trans(
"ResultOfSimulationNoError").
'</b></div>';
2001 print $langs->trans(
"NbInsertSim", empty($obj->nbinsert) ? 0 : $obj->nbinsert).
'<br>';
2002 print $langs->trans(
"NbUpdateSim", empty($obj->nbupdate) ? 0 : $obj->nbupdate).
'<br>';
2007 print
'<div class="warning">';
2008 print $langs->trans(
"NbOfLinesOK", $nbok).
'...<br>';
2015 if (count($arrayoferrors)) {
2016 print
img_error().
' <b>'.$langs->trans(
"ErrorsOnXLines", count($arrayoferrors)).
'</b><br>';
2017 print
'<table width="100%" class="border"><tr><td>';
2018 foreach ($arrayoferrors as $key => $val) {
2020 if ($nboferrors > $maxnboferrors) {
2021 print $langs->trans(
"TooMuchErrors", (count($arrayoferrors) - $nboferrors)).
"<br>";
2025 foreach ($val as $i => $err) {
2026 print
' > '.dol_escape_htmltag($err[
'lib']).
'<br>';
2029 print
'</td></tr></table>';
2035 if (count($arrayofwarnings)) {
2036 print
img_warning().
' <b>'.$langs->trans(
"WarningsOnXLines", count($arrayofwarnings)).
'</b><br>';
2037 print
'<table width="100%" class="border"><tr><td>';
2038 foreach ($arrayofwarnings as $key => $val) {
2040 if ($nbofwarnings > $maxnbofwarnings) {
2041 print $langs->trans(
"TooMuchWarnings", (count($arrayofwarnings) - $nbofwarnings)).
"<br>";
2045 foreach ($val as $i => $err) {
2046 print
' > '.dol_escape_htmltag($err[
'lib']).
'<br>';
2049 print
'</td></tr></table>';
2056 print
'<div class="center">';
2057 print
'<span class="opacitymedium">'.$langs->trans(
"NowClickToRunTheImport", $langs->transnoentitiesnoconv(
"RunImportFile")).
'</span><br>';
2066 print
'<div class="center">';
2067 if ($user->hasRight(
'import',
'run')) {
2068 if (empty($nboferrors)) {
2069 print
'<a class="butAction" href="'.DOL_URL_ROOT.
'/imports/import.php?leftmenu=import&step=5&importid='.$importid.$param.
'">'.$langs->trans(
"RunImportFile").
'</a>';
2073 print
'<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->transnoentitiesnoconv(
"CorrectErrorBeforeRunningImport")).
'">'.$langs->trans(
"RunImportFile").
'</a>';
2076 print
'<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->transnoentitiesnoconv(
"NotEnoughPermissions")).
'">'.$langs->trans(
"RunSimulateImportFile").
'</a>';
2078 print
'<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->transnoentitiesnoconv(
"NotEnoughPermissions")).
'">'.$langs->trans(
"RunImportFile").
'</a>';
2088if ($step == 5 && $datatoimport) {
2089 $max_execution_time_for_importexport =
getDolGlobalInt(
'IMPORT_MAX_EXECUTION_TIME', 300);
2090 $max_time = @ini_get(
"max_execution_time");
2091 if ($max_time && $max_time < $max_execution_time_for_importexport) {
2092 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.");
2093 @ini_set(
"max_execution_time", $max_execution_time_for_importexport);
2099 if ($model ===
'txt') {
2103 $list = $objmodelimport->listOfAvailableImportFormat(
$db);
2104 $importid =
GETPOST(
"importid",
'alphanohtml');
2108 $dir = DOL_DOCUMENT_ROOT.
"/core/modules/import/";
2109 $file =
"import_".$model.
".modules.php";
2110 $classname =
"Import".ucfirst($model);
2111 require_once $dir.$file;
2112 $obj =
new $classname(
$db, $datatoimport);
2113 '@phan-var-force ModeleImports $obj';
2114 $obj->importtriggermode = $importtriggermode;
2115 $obj->importissimulation = 0;
2116 if ($model ==
'csv') {
2117 '@phan-var-force ImportCsv $obj';
2118 $obj->separator = $separator_used;
2119 $obj->enclosure = $enclosure;
2123 $fieldssource = array();
2124 $result = $obj->import_open_file(
$conf->import->dir_temp.
'/'.$filetoimport);
2127 $arrayrecord = $obj->import_read_record();
2130 foreach ($arrayrecord as $key => $val) {
2131 $fieldssource[$i][
'example1'] =
dol_trunc($val[
'val'], 24);
2134 $obj->import_close_file();
2139 $param =
'&format='.$format.
'&datatoimport='.urlencode($datatoimport).
'&filetoimport='.urlencode($filetoimport).
'&nboflines='.((int) $nboflines).
'&importtriggermode='.urlencode($importtriggermode);
2140 if ($excludefirstline) {
2141 $param .=
'&excludefirstline='.urlencode($excludefirstline);
2144 $param .=
'&endatlinenb='.urlencode($endatlinenb);
2147 $param .=
'&separator='.urlencode($separator);
2150 $param .=
'&enclosure='.urlencode($enclosure);
2153 llxHeader(
'', $langs->trans(
"NewImport"), $help_url);
2159 print
'<div class="underbanner clearboth"></div>';
2160 print
'<div class="fichecenter">';
2162 print
'<table width="100%" class="border">';
2165 print
'<tr><td class="titlefieldcreate">'.$langs->trans(
"Module").
'</td>';
2167 $titleofmodule = $objimport->array_import_module[0][
'module']->getName();
2169 if (in_array($objimport->array_import_code[0], array(
'produit_supplierprices',
'produit_multiprice',
'produit_languages'))) {
2170 $titleofmodule = $langs->trans(
"ProductOrService");
2172 print $titleofmodule;
2176 print
'<tr><td>'.$langs->trans(
"DatasetToImport").
'</td>';
2178 $entity = preg_replace(
'/:.*$/',
'', $objimport->array_import_icon[0]);
2179 $entityicon = strtolower(!empty($entitytoicon[$entity]) ? $entitytoicon[$entity] : $entity);
2180 print
img_object($objimport->array_import_module[0][
'module']->getName(), $entityicon).
' ';
2181 print $objimport->array_import_label[0];
2189 print
load_fiche_titre($langs->trans(
"InformationOnSourceFile"),
'',
'file-export');
2191 print
'<div class="underbanner clearboth"></div>';
2192 print
'<div class="fichecenter">';
2193 print
'<table width="100%" class="border tableforfield">';
2196 print
'<tr><td class="titlefieldcreate">'.$langs->trans(
"SourceFileFormat").
'</td>';
2197 print
'<td class="nowraponall">';
2198 $text = $objmodelimport->getDriverDescForKey($format);
2200 print $form->textwithpicto($objmodelimport->getDriverLabelForKey($format), $text);
2204 if ($model ==
'csv') {
2205 '@phan-var-force ImportCsv $obj';
2206 print
'<tr><td>'.$langs->trans(
"CsvOptions").
'</td>';
2208 print $langs->trans(
"Separator").
' : ';
2209 print htmlentities($separator);
2210 print
' '.$langs->trans(
"Enclosure").
' : ';
2211 print htmlentities($enclosure);
2216 print
'<tr><td>'.$langs->trans(
"FileToImport").
'</td>';
2218 $modulepart =
'import';
2219 $relativepath =
GETPOST(
'filetoimport');
2220 print
'<a data-ajax="false" href="'.DOL_URL_ROOT.
'/document.php?modulepart='.$modulepart.
'&file='.urlencode($relativepath).
'&step=4'.$param.
'" target="_blank" rel="noopener noreferrer">';
2221 print
img_mime($file,
'',
'pictofixedwidth');
2222 print $filetoimport;
2228 print $langs->trans(
"NbOfSourceLines");
2235 print $langs->trans(
"ImportFromLine");
2237 print
'<input type="text" size="4" name="excludefirstline" disabled="disabled" value="'.$excludefirstline.
'">';
2242 print $langs->trans(
"EndAtLineNb");
2244 print
'<input type="text" size="4" name="endatlinenb" disabled="disabled" value="'.$endatlinenb.
'">';
2249 print $langs->trans(
"ImportTriggerModeLabel");
2251 if ($importtriggermode ===
'fast_bulk') {
2252 print $langs->trans(
"ImportTriggerModeSummaryFast");
2254 print $langs->trans(
"ImportTriggerModeSummaryStrict");
2256 print
'<br><span class="opacitymedium">';
2257 print $langs->trans(
"ImportTriggerModeSummaryHint");
2266 print
'<b>'.$langs->trans(
"InformationOnTargetTables").
'</b>';
2267 print
'<div class="underbanner clearboth"></div>';
2268 print
'<div class="fichecenter">';
2269 print
'<table class="border centpercent">';
2272 print
'<tr><td width="25%">';
2273 print $langs->trans(
"TablesTarget");
2275 $listtables = array();
2276 foreach ($array_match_file_to_database as $code => $label) {
2278 if ($code > count($fieldssource)) {
2282 $alias = preg_replace(
'/(\..*)$/i',
'', $label);
2283 $listtables[$alias] = $objimport->array_import_tables[0][$alias];
2285 if (count($listtables)) {
2287 foreach ($listtables as $val) {
2306 print $langs->trans(
"Error");
2312 print $langs->trans(
"FieldsTarget").
'</td><td>';
2313 $listfields = array();
2315 $sort_array_match_file_to_database = $array_match_file_to_database;
2316 ksort($sort_array_match_file_to_database);
2318 foreach ($sort_array_match_file_to_database as $code => $label) {
2321 if ($code > count($fieldssource)) {
2325 $alias = preg_replace(
'/(\..*)$/i',
'', $label);
2326 $listfields[$i] = $langs->trans(
"Field").
' '.$code.
'->'.$label;
2328 print count($listfields) ? (implode(
', ', $listfields)) : $langs->trans(
"Error");
2335 $arrayoferrors = array();
2336 $arrayofwarnings = array();
2337 $maxnboferrors = !
getDolGlobalString(
'IMPORT_MAX_NB_OF_ERRORS') ? 50 :
$conf->global->IMPORT_MAX_NB_OF_ERRORS;
2338 $maxnbofwarnings = !
getDolGlobalString(
'IMPORT_MAX_NB_OF_WARNINGS') ? 50 :
$conf->global->IMPORT_MAX_NB_OF_WARNINGS;
2350 $pathfile =
$conf->import->dir_temp.
'/'.$filetoimport;
2351 $result = $obj->import_open_file($pathfile);
2353 global $tablewithentity_cache;
2354 $tablewithentity_cache = array();
2358 while ($sourcelinenb < $nboflines && !$endoffile) {
2360 $arrayrecord = $obj->import_read_record();
2361 if ($arrayrecord ===
false) {
2362 $arrayofwarnings[$sourcelinenb][0] = array(
'lib' => $langs->trans(
'ErrorFileLinesReachEOF', $nboflines, $sourcelinenb),
'type' =>
'EOF_RECORD_ON_SEVERAL_LINES');
2366 if ($excludefirstline && ($sourcelinenb < $excludefirstline)) {
2369 if ($endatlinenb && ($sourcelinenb > $endatlinenb)) {
2373 $parameters = array(
2375 'datatoimport' => $datatoimport,
2377 'arrayrecord' => $arrayrecord,
2378 'array_match_file_to_database' => $array_match_file_to_database,
2379 'objimport' => $objimport,
2380 'fieldssource' => $fieldssource,
2381 'importid' => $importid,
2382 'updatekeys' => $updatekeys,
2383 'importtriggermode' => $importtriggermode,
2384 'arrayoferrors' => &$arrayoferrors,
2385 'arrayofwarnings' => &$arrayofwarnings,
2389 $reshook = $hookmanager->executeHooks(
'ImportInsert', $parameters);
2391 $arrayoferrors[$sourcelinenb][] = [
2392 'lib' => implode(
"<br>", array_merge([$hookmanager->error], $hookmanager->errors))
2396 if (empty($reshook)) {
2398 $result = $obj->import_insert($arrayrecord, $array_match_file_to_database, $objimport, count($fieldssource), $importid, $updatekeys);
2400 if (count($obj->errors)) {
2401 $arrayoferrors[$sourcelinenb] = $obj->errors;
2403 if (count($obj->warnings)) {
2404 $arrayofwarnings[$sourcelinenb] = $obj->warnings;
2407 if (!count($obj->errors) && !count($obj->warnings)) {
2412 $reshook = $hookmanager->executeHooks(
'AfterImportInsert', $parameters);
2414 $arrayoferrors[$sourcelinenb][] = [
2415 'lib' => implode(
"<br>", array_merge([$hookmanager->error], $hookmanager->errors))
2420 $obj->import_close_file();
2422 print $langs->trans(
"ErrorFailedToOpenFile", $pathfile);
2425 if (count($arrayoferrors) > 0) {
2432 if (!empty($objimport->array_import_run_sql_after[0]) && is_array($objimport->array_import_run_sql_after[0])) {
2434 foreach ($objimport->array_import_run_sql_after[0] as $sqlafterimport) {
2436 $resqlafterimport =
$db->query($sqlafterimport);
2437 if (!$resqlafterimport) {
2438 $arrayoferrors[
'none'][] = array(
'lib' => $langs->trans(
"Error running final request: ".$sqlafterimport));
2444 if (!$error && $importtriggermode ===
'fast_bulk') {
2445 $resbulktrigger = $obj->runImportBulkTrigger($importid, $user, $langs,
$conf);
2446 if ($resbulktrigger < 0) {
2447 $arrayoferrors[
'none'][] = array(
'lib' => $langs->trans(
"ErrorFailedTriggerCall"),
'type' =>
'TRIGGER');
2448 if (!empty($obj->errors) && is_array($obj->errors)) {
2449 foreach ($obj->errors as $tmperror) {
2450 $lib = (is_array($tmperror) ? ($tmperror[
'lib'] ??
'') : $tmperror);
2452 $arrayoferrors[
'none'][] = array(
'lib' => $lib,
'type' =>
'TRIGGER');
2469 if ($importtriggermode ===
'fast_bulk') {
2470 print
'<div class="warning">';
2471 print
'<b>'.$langs->trans(
"ImportTriggerModeFastBulkFinalWarningTitle").
'</b><br>';
2472 print $langs->trans(
"ImportTriggerModeFastBulkFinalWarning");
2479 print
'<div class="info">';
2480 print $langs->trans(
"NbOfLinesImported", $nbok).
'</b><br>';
2481 print $langs->trans(
"NbInsert", empty($obj->nbinsert) ? 0 : $obj->nbinsert).
'<br>';
2482 print $langs->trans(
"NbUpdate", empty($obj->nbupdate) ? 0 : $obj->nbupdate).
'<br>';
2484 print
'<div class="center">';
2485 print $langs->trans(
"FileWasImported", $importid).
'<br>';
2486 print
'<span class="opacitymedium">'.$langs->trans(
"YouCanUseImportIdToFindRecord", $importid).
'</span><br>';
2509 global
$conf, $langs;
2513 if ($key ==
'none') {
2515 print
"\n\n<!-- Box_no-key start-->\n";
2516 print
'<div class="box boximport" style="padding:0;">'.
"\n";
2517 print
'<table summary="boxtable_no-key" class="centpercent nobordernopadding">'.
"\n";
2519 print
"\n\n<!-- Box ".$pos.
" start -->\n";
2520 print
'<div class="box boximport" style="padding: 0;" id="boxto_'.$pos.
'">'.
"\n";
2522 print
'<table summary="boxtable'.$pos.
'" class="nobordernopadding centpercent tableimport">'.
"\n";
2525 if (($pos && $pos > count($fieldssource)) && (!isset($fieldssource[$pos][
"imported"]))) {
2535 } elseif ($key ==
'none') {
2536 print
'<tr style="height:'.$height.
'" class="trimport oddevenimport">';
2537 print
'<td class="nocellnopadd" width="16" style="font-weight: normal">';
2540 print
'<td style="font-weight: normal">';
2546 print
'<tr style="height:'.$height.
'" class="trimport oddevenimport">';
2547 print
'<td class="nocellnopadd" width="16" style="font-weight: normal">';
2550 print
img_picto($langs->trans(
"Column").
' '.
num2Alpha($pos - 1),
'file',
'class="pictofixedwidth marginleftonly"');
2552 if (isset($fieldssource[$pos][
'imported']) && $fieldssource[$pos][
'imported'] ==
false) {
2553 print
'<td class="nowraponall boxtdunused" style="font-weight: normal">';
2555 print
'<td class="nowraponall tdoverflowmax500" style="font-weight: normal">';
2557 print $langs->trans(
"Column").
' '.
num2Alpha($pos - 1).
' (#'.$pos.
')';
2558 if (empty($fieldssource[$pos][
'example1'])) {
2559 $example = $fieldssource[$pos][
'label'];
2561 $example = $fieldssource[$pos][
'example1'];
2565 $example = mb_convert_encoding($example,
'UTF-8',
'ISO-8859-1');
2569 print
'<i class="opacitymedium">'.dol_escape_htmltag($example).
'</i>';
2578 print
"<!-- Box end -->\n\n";
2591 $i = count($fieldssource) + 1;
2594 foreach ($listofkey as $key => $val) {
2595 $maxkey = max($maxkey, $key);
2598 while ($i <= $maxkey) {
2599 if (empty($listofkey[$i])) {
2621 if ($position == count($array)) {
2622 $ret = $array + $insertArray;
2625 foreach ($array as $key => $value) {
2626 if ($position == $i++) {
2627 $ret += $insertArray;
2630 $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.
dolPrintHTML($s, $allowiframe=0, $moreallowedtags=array())
Return a string (that can be on several lines) ready to be output on a HTML page.
dol_get_fiche_head($links=array(), $active='', $title='', $notab=0, $picto='', $pictoisfullpath=0, $morehtmlright='', $morecss='', $limittoshow=0, $moretabssuffix='', $dragdropfile=0, $morecssdiv='')
Show tabs of a record.
dol_string_nohtmltag($stringtoclean, $removelinefeed=1, $pagecodeto='UTF-8', $strip_tags=0, $removedoublespaces=1)
Clean a string from all HTML tags and entities.
dol_get_fiche_end($notab=0)
Return tab footer of a card.
img_object($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $allowothertags=array())
Show a picto called object_picto (generic function)
dol_sanitizeFileName($str, $newstr='_', $unaccent=1, $includequotes=0, $allowdash=0)
Clean a string to use it as a file name.
img_mime($file, $titlealt='', $morecss='')
Show MIME img of a file.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
dol_escape_js($stringtoescape, $mode=0, $noescapebackslashn=0)
Returns text escaped for inclusion into JavaScript code.
dol_sort_array(&$array, $index, $order='asc', $natsort=0, $case_sensitive=0, $keepindex=0)
Advanced sort array by the value of a given key, which produces ascending (default) or descending out...
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.
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0, $nodefault=0)
Return value of a param into GET or POST supervariable.
num2Alpha($n)
Return a numeric value into an Excel like column number.
GETPOSTINT($paramname, $method=0, $nodefault=0)
Return the value of a $_GET or $_POST supervariable, converted into integer.
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.
GETPOSTISSET($paramname)
Return true if we are in a context of submitting the parameter $paramname from a POST of a form.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
utf8_check($str)
Check if a string is in UTF8.
info_admin($text, $infoonimgalt=0, $nodiv=0, $admin='1', $morecss='hideonsmartphone', $textfordropdown='', $picto='', $textonpictotooltip='', $cssfordropdown='info_admin')
Show information in HTML for admin users or standard users.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
dol_mkdir($dir, $dataroot='', $newmask='')
Creation of a directory (this can create recursive subdir)
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags='', $escapeonlyhtmltags=0, $cleanalsojavascript=0)
Returns text escaped for inclusion in HTML alt or title or value tags, or into values of HTML input f...
import_prepare_head($param, $maxstep=0)
Function to return list of tabs for import pages.
show_elem($fieldssource, $pos, $key)
Function to put the movable box of a source field.
getnewkey(&$fieldssource, &$listofkey)
Return not used field number.
arrayInsert($array, $position, $insertArray)
Return array with element inserted in it at position $position.
print $langs trans("Show") . '< td style="' . $timeColor . '" align="center"> s</td > badge status0 badge status4 badge status3 Error badge status8< td align="center">< span class="badge ' . $badge . '"></span ></td >< td align="center">< a href="#" class="button button-small" onclick="openLogModal(this)" data-req="' . dol_escape_htmltag($reqSafe) . '" data-res="' . dol_escape_htmltag($resSafe) . '" data-err="' . dol_escape_htmltag($errSafe) . '">< span class="fa fa-search-plus"></span ></a ></td ></tr >< tr >< td colspan="' . $colspan . '" class="opacitymedium"></td ></tr ></table ></div ></form > logModal none logModal none s a JSON string
buildzip.php
getMaxFileSizeArray()
Return the max allowed for file upload.
restrictedArea(User $user, $features, $object=0, $tableandshare='', $feature2='', $dbt_keyfield='fk_soc', $dbt_select='rowid', $isdraft=0, $mode=0)
Check permissions of a user to show a page and an object.