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 'productattribute' =>
'product',
74 'productattributevalue' =>
'product',
75 'productcombination' =>
'product',
76 'virtualproduct' =>
'product',
77 'subproduct' =>
'product',
78 'product_supplier_ref' =>
'product',
80 'warehouse' =>
'stock',
82 'stockbatch' =>
'stock',
83 'category' =>
'category',
84 'shipment' =>
'sending',
85 'shipment_line' =>
'sending',
86 'project' =>
'project',
88 'reception' =>
'sending',
89 'reception_line' =>
'sending',
90 'expensereport' =>
'trip',
91 'expensereport_line' =>
'trip',
92 'holiday' =>
'holiday',
93 'contract_line' =>
'contract',
94 'translation' =>
'generic',
100$entitytolang = array(
102 'company' =>
'Company',
103 'contact' =>
'Contact',
105 'invoice_line' =>
'InvoiceLine',
107 'order_line' =>
'OrderLine',
108 'propal' =>
'Proposal',
109 'propal_line' =>
'ProposalLine',
110 'intervention' =>
'Intervention',
111 'inter_line' =>
'InterLine',
112 'member' =>
'Member',
113 'member_type' =>
'MemberType',
114 'subscription' =>
'Subscription',
115 'tax' =>
'SocialContribution',
116 'tax_type' =>
'DictionarySocialContributions',
117 'account' =>
'BankTransactions',
118 'payment' =>
'Payment',
119 'product' =>
'Product',
120 'productattribute' =>
'ProductAttribute',
121 'productattributevalue' =>
'ProductAttributeValue',
122 'productcombination' =>
'ProductCombination',
123 'virtualproduct' =>
'AssociatedProducts',
124 'subproduct' =>
'SubProduct',
125 'product_supplier_ref' =>
'SupplierPrices',
126 'service' =>
'Service',
128 'movement' =>
'StockMovement',
130 'stockbatch' =>
'StockDetailPerBatch',
131 'warehouse' =>
'Warehouse',
132 'category' =>
'Category',
134 'trip' =>
'TripsAndExpenses',
135 'shipment' =>
'Shipments',
136 'shipment_line' =>
'ShipmentLine',
137 'project' =>
'Projects',
138 'projecttask' =>
'Tasks',
139 'task_time' =>
'TaskTimeSpent',
141 'expensereport' =>
'ExpenseReport',
142 'expensereport_line' =>
'ExpenseReportLine',
143 'holiday' =>
'TitreRequestCP',
144 'contract' =>
'Contract',
145 'contract_line' =>
'ContractLine',
146 'translation' =>
'Translation',
148 'bomline' =>
'BOMLine'
151$datatoimport =
GETPOST(
'datatoimport');
153$filetoimport =
GETPOST(
'filetoimport');
154$action =
GETPOST(
'action',
'alpha');
155$confirm =
GETPOST(
'confirm',
'alpha');
157$import_name =
GETPOST(
'import_name');
160$excludefirstline = (
GETPOST(
'excludefirstline',
'alphanohtml', 3) ?
GETPOST(
'excludefirstline',
'alphanohtml', 3) : 2);
161$endatlinenb = (
GETPOST(
'endatlinenb',
'alphanohtml', 3) ?
GETPOST(
'endatlinenb',
'alphanohtml', 3) :
'');
162$updatekeys = (
GETPOST(
'updatekeys',
'array', 3) ?
GETPOST(
'updatekeys',
'array', 3) : array());
163$importtriggermode =
GETPOST(
'importtriggermode',
'alpha', 3);
164$separator = (
GETPOST(
'separator',
'nohtml') ?
GETPOST(
'separator',
'nohtml', 3) :
'');
165$enclosure = (
GETPOST(
'enclosure',
'nohtml') ?
GETPOST(
'enclosure',
'nohtml') :
'"');
166$charset =
GETPOST(
'charset',
'aZ09');
167$separator_used = str_replace(
'\t',
"\t", $separator);
170if (empty($importtriggermode)) {
171 $importtriggermode =
getDolGlobalString(
'IMPORT_TRIGGER_MODE_DEFAULT',
'strict_line');
173if (!in_array($importtriggermode, array(
'strict_line',
'fast_bulk'),
true)) {
174 $importtriggermode =
'strict_line';
177$objimport =
new Import($db);
178$objimport->load_arrays($user, ($step == 1 ?
'' : $datatoimport));
180if (empty($updatekeys) && !empty($objimport->array_import_preselected_updatekeys[0])) {
181 $updatekeys = $objimport->array_import_preselected_updatekeys[0];
186$form =
new Form($db);
190if (empty($array_match_file_to_database)) {
191 $serialized_array_match_file_to_database = isset($_SESSION[
"dol_array_match_file_to_database_select"]) ? $_SESSION[
"dol_array_match_file_to_database_select"] :
'';
192 $array_match_file_to_database = array();
193 $fieldsarray = explode(
',', $serialized_array_match_file_to_database);
194 foreach ($fieldsarray as $elem) {
195 $tabelem = explode(
'=', $elem, 2);
197 $val = (isset($tabelem[1]) ? $tabelem[1] :
'');
199 $array_match_file_to_database[$key] = $val;
209if ($action ==
'deleteprof' && $user->hasRight(
'import',
'run')) {
212 $result = $objimport->delete($user);
214 setEventMessages($objimport->error, $objimport->errors,
'errors');
220if ($action ==
'add_import_model' && $user->hasRight(
'import',
'run')) {
224 foreach ($array_match_file_to_database as $key => $val) {
228 $hexa .= $key.
'='.$val;
231 $objimport->model_name = $import_name;
232 $objimport->datatoimport = $datatoimport;
233 $objimport->hexa = $hexa;
234 $objimport->fk_user = (
GETPOST(
'visibility',
'aZ09') ==
'all' ? 0 : $user->id);
236 $result = $objimport->create($user);
238 setEventMessages($langs->trans(
"ImportModelSaved", $objimport->model_name),
null,
'mesgs');
241 $langs->load(
"errors");
242 if ($objimport->errno ==
'DB_ERROR_RECORD_ALREADY_EXISTS') {
243 setEventMessages($langs->trans(
"ErrorImportDuplicateProfil"),
null,
'errors');
245 setEventMessages($objimport->error,
null,
'errors');
249 setEventMessages($langs->trans(
"ErrorFieldRequired", $langs->transnoentities(
"ImportModelName")),
null,
'errors');
253if ($step == 2 && $datatoimport) {
261 if (is_numeric($resultupload) && $resultupload > 0) {
262 dol_syslog(
"File ".$fullpath.
" was added for import");
264 $langs->load(
"errors");
265 setEventMessages($langs->trans(
"ErrorFailedToSaveFile"),
null,
'errors');
270 if ($action ==
'confirm_deletefile' && $confirm ==
'yes' && $user->hasRight(
'import',
'run')) {
271 $langs->load(
"other");
273 $param =
'&datatoimport='.urlencode($datatoimport).
'&format='.urlencode($format);
274 if ($excludefirstline) {
275 $param .=
'&excludefirstline='.urlencode($excludefirstline);
278 $param .=
'&endatlinenb='.urlencode($endatlinenb);
284 setEventMessages($langs->trans(
"FileWasRemoved",
GETPOST(
'urlfile')),
null,
'mesgs');
286 setEventMessages($langs->trans(
"ErrorFailToDeleteFile",
GETPOST(
'urlfile')),
null,
'errors');
288 header(
'Location: '.$_SERVER[
"PHP_SELF"].
'?step='.$step.$param);
293if ($step == 4 && $action ==
'select_model' && $user->hasRight(
'import',
'run')) {
295 $_SESSION[
"dol_array_match_file_to_database"] =
'';
296 $serialized_array_match_file_to_database =
'';
297 $array_match_file_to_database = array();
301 $result = $objimport->fetch($importmodelid);
303 $serialized_array_match_file_to_database = $objimport->hexa;
304 $fieldsarray = explode(
',', $serialized_array_match_file_to_database);
305 foreach ($fieldsarray as $elem) {
306 $tabelem = explode(
'=', $elem);
310 $array_match_file_to_database[$key] = $val;
313 $_SESSION[
"dol_array_match_file_to_database"] = $serialized_array_match_file_to_database;
314 $_SESSION[
'dol_array_match_file_to_database_select'] = $_SESSION[
"dol_array_match_file_to_database"];
317if ($action ==
'saveselectorder' && $user->hasRight(
'import',
'run')) {
319 $serialized_array_match_file_to_database =
'';
321 $selectorder = explode(
",",
GETPOST(
'selectorder'));
322 $fieldtarget = $fieldstarget = $objimport->array_import_fields[0];
323 foreach ($selectorder as $key => $code) {
324 $serialized_array_match_file_to_database .= $key.
'='.$code;
325 $serialized_array_match_file_to_database .=
',';
327 $serialized_array_match_file_to_database = substr($serialized_array_match_file_to_database, 0, -1);
328 dol_syslog(
'dol_array_match_file_to_database_select='.$serialized_array_match_file_to_database);
329 $_SESSION[
"dol_array_match_file_to_database_select"] = $serialized_array_match_file_to_database;
339$help_url =
'EN:Module_Imports_En|FR:Module_Imports|ES:Módulo_Importaciones';
342if ($step == 1 || !$datatoimport) {
344 $serialized_array_match_file_to_database =
'';
345 $array_match_file_to_database = array();
346 $_SESSION[
"dol_array_match_file_to_database"] =
'';
347 $_SESSION[
"dol_array_match_file_to_database_select"] =
'';
350 if ($excludefirstline) {
351 $param .=
'&excludefirstline='.urlencode($excludefirstline);
354 $param .=
'&endatlinenb='.urlencode($endatlinenb);
357 $param .=
'&separator='.urlencode($separator);
360 $param .=
'&enclosure='.urlencode($enclosure);
363 llxHeader(
'', $langs->trans(
"NewImport"), $help_url);
369 print
'<div class="opacitymedium">'.$langs->trans(
"SelectImportDataSet").
'</div>';
373 $nbmodulesnotautoenabled = count(
$conf->modules);
374 $listofmodulesautoenabled = array(
'user',
'agenda',
'fckeditor',
'export',
'import');
375 foreach ($listofmodulesautoenabled as $moduleautoenable) {
376 if (in_array($moduleautoenable,
$conf->modules)) {
377 $nbmodulesnotautoenabled--;
381 if ($user->admin && $nbmodulesnotautoenabled <
getDolGlobalInt(
'MAIN_MIN_NB_ENABLED_MODULE_FOR_WARNING', 1)) {
382 print
info_admin($langs->trans(
"WarningOnlyProfilesOfActivatedModules").
' '.$langs->trans(
"YouCanEnableModulesFrom"));
388 print
'<div class="div-table-responsive-no-min">';
389 print
'<table class="noborder centpercent nomarginbottom">';
390 print
'<tr class="liste_titre">';
391 print
'<td>'.$langs->trans(
"Module").
'</td>';
392 print
'<td>'.$langs->trans(
"ImportableDatas").
'</td>';
393 print
'<td> </td>';
396 if (count($objimport->array_import_module)) {
397 $sortedarrayofmodules =
dol_sort_array($objimport->array_import_module,
'position_of_profile',
'asc', 0, 0, 1);
398 foreach ($sortedarrayofmodules as $key => $value) {
400 $titleofmodule = $objimport->array_import_module[$key][
'module']->getName();
401 print
'<tr class="oddeven"><td class="tdoverflowmax200" title="'.dolPrintHTML($titleofmodule).
'">';
403 if (in_array($objimport->array_import_code[$key], array(
'produit_supplierprices',
'produit_multiprice',
'produit_languages'))) {
404 $titleofmodule = $langs->trans(
"ProductOrService");
406 print dolPrintHTML($titleofmodule);
408 $entity = preg_replace(
'/:.*$/',
'', $objimport->array_import_icon[$key]);
409 $entityicon = strtolower(!empty($entitytoicon[$entity]) ? $entitytoicon[$entity] : $entity);
410 $label = $objimport->array_import_label[$key];
411 print
'<div class="twolinesmax-normallineheight minwidth200onall">';
412 print img_object($objimport->array_import_module[$key][
'module']->getName(), $entityicon,
'class="pictofixedwidth"');
413 print dolPrintHTML($label);
415 print
'</td><td style="text-align: right">';
416 if ($objimport->array_import_perms[$key]) {
417 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>';
419 print $langs->trans(
"NotEnoughPermissions");
424 print
'<tr><td class="oddeven" colspan="3">'.$langs->trans(
"NoImportableData").
'</td></tr>';
434if ($step == 2 && $datatoimport) {
435 $param =
'&datatoimport='.urlencode($datatoimport);
436 if ($excludefirstline) {
437 $param .=
'&excludefirstline='.urlencode($excludefirstline);
440 $param .=
'&endatlinenb='.urlencode($endatlinenb);
443 $param .=
'&separator='.urlencode($separator);
446 $param .=
'&enclosure='.urlencode($enclosure);
449 $list = $objmodelimport->listOfAvailableImportFormat($db);
451 llxHeader(
'', $langs->trans(
"NewImport"), $help_url);
460 if ($action ==
'delete') {
461 print $form->formconfirm($_SERVER[
"PHP_SELF"].
'?urlfile='.urlencode(
GETPOST(
'urlfile')).
'&step=2'.$param, $langs->trans(
'DeleteFile'), $langs->trans(
'ConfirmDeleteFile'),
'confirm_deletefile',
'', 0, 1);
464 print
'<div class="underbanner clearboth"></div>';
465 print
'<div class="fichecenter">';
467 print
'<table class="border tableforfield centpercent">';
470 print
'<tr><td class="titlefieldcreate">'.$langs->trans(
"Module").
'</td>';
472 $titleofmodule = $objimport->array_import_module[0][
'module']->getName();
474 if (in_array($objimport->array_import_code[0], array(
'produit_supplierprices',
'produit_multiprice',
'produit_languages'))) {
475 $titleofmodule = $langs->trans(
"ProductOrService");
477 print $titleofmodule;
481 print
'<tr><td>'.$langs->trans(
"DatasetToImport").
'</td>';
483 $entity = preg_replace(
'/:.*$/',
'', $objimport->array_import_icon[0]);
484 $entityicon = strtolower(!empty($entitytoicon[$entity]) ? $entitytoicon[$entity] : $entity);
485 print img_object($objimport->array_import_module[0][
'module']->getName(), $entityicon).
' ';
486 print $objimport->array_import_label[0];
516 if ($format ==
'xlsx' && !class_exists(
'XMLWriter')) {
517 $langs->load(
"install");
518 print
info_admin($langs->trans(
"ErrorPHPDoesNotSupport",
'php-xml'), 0, 0,
'1',
'error');
524 print
'<form name="userfile" action="'.$_SERVER[
"PHP_SELF"].
'" enctype="multipart/form-data" method="POST">';
525 print
'<input type="hidden" name="token" value="'.newToken().
'">';
526 print
'<input type="hidden" value="'.$step.
'" name="step">';
527 print
'<input type="hidden" value="'.dol_escape_htmltag($format).
'" name="format">';
528 print
'<input type="hidden" value="'.$excludefirstline.
'" name="excludefirstline">';
529 print
'<input type="hidden" value="'.$endatlinenb.
'" name="endatlinenb">';
530 print
'<input type="hidden" value="'.dol_escape_htmltag($separator).
'" name="separator">';
531 print
'<input type="hidden" value="'.dol_escape_htmltag($enclosure).
'" name="enclosure">';
532 print
'<input type="hidden" value="'.dol_escape_htmltag($datatoimport).
'" name="datatoimport">';
534 print
'<span class="opacitymedium">';
535 $s = $langs->trans(
"ChooseFileToImport",
'{s1}');
536 $s = str_replace(
'{s1}', img_picto(
'',
'next'), $s);
538 print
'</span><br><br>';
543 print
'<table class="noborder centpercent" cellpadding="4">';
545 print
'<tr class="liste_titre"><td colspan="4">';
546 print $langs->trans(
"FileMustHaveOneOfFollowingFormat").
'...';
548 $list = $objmodelimport->listOfAvailableImportFormat($db);
549 foreach ($list as $key) {
550 print
'<tr class="oddeven">';
551 print
'<td width="16">'.img_picto_common($key, $objmodelimport->getPictoForKey($key)).
'</td>';
552 $htmltext = $objmodelimport->getDriverDescForKey($key);
553 print
'<td>'.$form->textwithpicto($objmodelimport->getDriverLabelForKey($key), $htmltext).
'</td>';
554 print
'<td style="text-align:center">';
555 if (empty($objmodelimport->drivererror[$key])) {
556 $filename = $langs->transnoentitiesnoconv(
"ExampleOfImportFile").
'_'.$datatoimport.
'.'.$key;
557 print
'<a href="'.DOL_URL_ROOT.
'/imports/emptyexample.php?format='.$key.$param.
'&output=file&file='.urlencode($filename).
'" target="_blank" rel="noopener noreferrer">';
558 print img_picto(
'',
'download',
'class="paddingright opacitymedium"');
559 print $langs->trans(
"DownloadEmptyExampleShort");
561 print $form->textwithpicto(
'', $langs->trans(
"DownloadEmptyExample").
'.<br>'.$langs->trans(
"StarAreMandatory"));
563 print dolPrintHTML($objmodelimport->drivererror[$key]);
575 print
'<div class="marginbottomonly">';
577 $maxmin = $maxfilesizearray[
'maxmin'];
579 print
'<input type="hidden" name="MAX_FILE_SIZE" value="'.($maxmin * 1024).
'">';
581 print
'<input type="file" name="userfile" size="20" maxlength="80"> ';
583 print
'<input type="submit" class="button small" value="'.$langs->trans(
"AddFile").
'"'.$out.
' name="sendit">';
587 $maxphp = @ini_get(
'upload_max_filesize');
588 if (preg_match(
'/k$/i', $maxphp)) {
589 $maxphp = (int) substr($maxphp, 0, -1);
591 if (preg_match(
'/m$/i', $maxphp)) {
592 $maxphp = (int) substr($maxphp, 0, -1) * 1024;
594 if (preg_match(
'/g$/i', $maxphp)) {
595 $maxphp = (int) substr($maxphp, 0, -1) * 1024 * 1024;
597 if (preg_match(
'/t$/i', $maxphp)) {
598 $maxphp = (int) substr($maxphp, 0, -1) * 1024 * 1024 * 1024;
600 $maxphp2 = @ini_get(
'post_max_size');
601 if (preg_match(
'/k$/i', $maxphp2)) {
602 $maxphp2 = (int) substr($maxphp2, 0, -1);
604 if (preg_match(
'/m$/i', $maxphp2)) {
605 $maxphp2 = (int) substr($maxphp2, 0, -1) * 1024;
607 if (preg_match(
'/g$/i', $maxphp2)) {
608 $maxphp2 = (int) substr($maxphp2, 0, -1) * 1024 * 1024;
610 if (preg_match(
'/t$/i', $maxphp2)) {
611 $maxphp2 = (int) substr($maxphp2, 0, -1) * 1024 * 1024 * 1024;
615 $maxphptoshow = $maxphptoshowparam =
'';
617 $maxmin = min($max, $maxphp);
618 $maxphptoshow = $maxphp;
619 $maxphptoshowparam =
'upload_max_filesize';
622 $maxmin = min($max, $maxphp2);
623 if ($maxphp2 < $maxphp) {
624 $maxphptoshow = $maxphp2;
625 $maxphptoshowparam =
'post_max_size';
629 $langs->load(
'other');
631 $out .=
info_admin($langs->trans(
"ThisLimitIsDefinedInSetup", $max, $maxphptoshow), 1);
633 $out .=
' ('.$langs->trans(
"UploadDisabled").
')';
640 $filearray =
dol_dir_list(
$conf->import->dir_temp,
'files', 0,
'',
'',
'name', SORT_DESC);
641 if (count($filearray) > 0) {
642 print
'<div class="div-table-responsive-no-min">';
643 print
'<table class="noborder centpercent" width="100%" cellpadding="4">';
645 $dir =
$conf->import->dir_temp;
649 foreach ($filearray as $key => $val) {
650 $file = $val[
'name'];
654 $file = mb_convert_encoding($file,
'UTF-8',
'ISO-8859-1');
657 if (preg_match(
'/^\./', $file)) {
661 $modulepart =
'import';
662 $urlsource = $_SERVER[
"PHP_SELF"].
'?step='.$step.$param.
'&filetoimport='.urlencode($filetoimport);
663 $relativepath = $file;
665 print
'<tr class="oddeven">';
667 print
img_mime($file,
'',
'pictofixedwidth');
668 print
'<a data-ajax="false" href="'.DOL_URL_ROOT.
'/document.php?modulepart='.$modulepart.
'&file='.urlencode($relativepath).
'&step=2'.$param.
'" target="_blank" rel="noopener noreferrer">';
673 print
'<td style="text-align:right">'.dol_print_size(
dol_filesize($dir.
'/'.$file)).
'</td>';
675 print
'<td style="text-align:right">'.dol_print_date(
dol_filemtime($dir.
'/'.$file),
'dayhour').
'</td>';
677 print
'<td style="text-align:right"><a href="'.$_SERVER[
'PHP_SELF'].
'?action=delete&token='.
newToken().
'&step=2'.$param.
'&urlfile='.urlencode($relativepath);
678 print
'">'.img_delete().
'</a></td>';
680 print
'<td style="text-align:right">';
681 print
'<a href="'.$_SERVER[
'PHP_SELF'].
'?step=3'.$param.
'&filetoimport='.urlencode($relativepath).
'">'.img_picto($langs->trans(
"ImportThisFile"),
'next',
'class="fa-15"').
'</a>';
695if ($step == 3 && $datatoimport) {
697 $serialized_array_match_file_to_database = isset($_SESSION[
"dol_array_match_file_to_database_select"]) ? $_SESSION[
"dol_array_match_file_to_database_select"] :
'';
698 $fieldsarray = explode(
',', $serialized_array_match_file_to_database);
699 $array_match_file_to_database = array();
700 foreach ($fieldsarray as $elem) {
701 $tabelem = explode(
'=', $elem, 2);
703 $val = (isset($tabelem[1]) ? $tabelem[1] :
'');
705 $array_match_file_to_database[$key] = $val;
712 if (empty($format) && !empty($filetoimport)) {
713 $format = pathinfo($filetoimport, PATHINFO_EXTENSION);
719 if ($model ===
'txt') {
723 $list = $objmodelimport->listOfAvailableImportFormat($db);
725 if (empty($separator)) {
726 $separator = (!
getDolGlobalString(
'IMPORT_CSV_SEPARATOR_TO_USE') ?
',' :
$conf->global->IMPORT_CSV_SEPARATOR_TO_USE);
730 if ($model ==
'csv' && strlen($separator) == 1 && !
GETPOSTISSET(
'separator')) {
731 '@phan-var-force ImportCsv $obj';
733 $fh = fopen(
$conf->import->dir_temp.
'/'.$filetoimport,
'r');
735 $sline = fgets($fh, 1000000);
737 $nboccurence = substr_count($sline, $separator);
738 $nboccurencea = substr_count($sline,
',');
739 $nboccurenceb = substr_count($sline,
';');
741 if ($nboccurence == 0) {
742 if ($nboccurencea > 2) {
744 } elseif ($nboccurenceb > 2) {
752 $separator_used = str_replace(
'\t',
"\t", $separator);
755 $dir = DOL_DOCUMENT_ROOT.
"/core/modules/import/";
756 $file =
"import_".$model.
".modules.php";
757 $classname =
"Import".ucfirst($model);
758 require_once $dir.$file;
759 $obj =
new $classname($db, $datatoimport);
760 '@phan-var-force ModeleImports $obj';
762 if (!empty($obj->error)) {
763 $langs->load(
"errors");
764 $param =
'&datatoimport='.$datatoimport.
'&format='.$format;
765 setEventMessages($obj->error,
null,
'errors');
766 header(
"Location: ".$_SERVER[
"PHP_SELF"].
'?step=2'.$param.
'&filetoimport='.urlencode($relativepath));
770 if ($model ==
'csv') {
771 '@phan-var-force ImportCsv $obj';
772 $obj->separator = $separator_used;
773 $obj->enclosure = $enclosure;
776 if ($model ==
'xlsx') {
777 '@phan-var-force ImportXlsx $obj';
778 if (!preg_match(
'/\.xlsx$/i', $filetoimport)) {
779 $langs->load(
"errors");
780 $param =
'&datatoimport='.$datatoimport.
'&format='.$format;
781 setEventMessages($langs->trans(
"ErrorFileMustHaveFormat", $model),
null,
'errors');
782 header(
"Location: ".$_SERVER[
"PHP_SELF"].
'?step=2'.$param.
'&filetoimport='.urlencode($relativepath));
788 $array_match_file_to_database = array();
792 $fieldssource = array();
794 $result = $obj->import_open_file(
$conf->import->dir_temp.
'/'.$filetoimport);
797 $arrayrecord = $obj->import_read_record();
801 foreach ($arrayrecord as $key => $val) {
802 if ($val[
"type"] != -1) {
803 $fieldssource[$i][
'example1'] =
dol_trunc($val[
'val'], 128);
805 $fieldssource[$i][
'example1'] = $langs->trans(
'Empty');
807 $fieldssource[$i][
'imported'] =
false;
810 $obj->import_close_file();
814 $fieldstarget = $objimport->array_import_fields[0];
815 $minpos = min(count($fieldssource), count($fieldstarget));
819 $initialloadofstep4 =
false;
820 if (empty($_SESSION[
'dol_array_match_file_to_database_select'])) {
821 $initialloadofstep4 =
true;
825 if (count($array_match_file_to_database) == 0) {
831 $num = count($fieldssource);
832 while ($pos <= $num) {
833 if ($num >= 1 && $pos <= $num) {
835 foreach ($fieldstarget as $key => $val) {
836 if ($posbis < $pos) {
841 $array_match_file_to_database[$pos] = $key;
848 $array_match_database_to_file = array_flip($array_match_file_to_database);
852 $fieldstarget_tmp = array();
853 $arraykeysfieldtarget = array_keys($fieldstarget);
855 foreach ($fieldstarget as $key => $label) {
856 $isrequired = preg_match(
'/\*$/', $label);
857 if (!empty($isrequired)) {
858 $newlabel = substr($label, 0, -1);
859 $fieldstarget_tmp[$key] = array(
"label" => (
string) $newlabel,
"required" =>
true);
861 $fieldstarget_tmp[$key] = array(
"label" => (
string) $label,
"required" =>
false);
863 if (!empty($array_match_database_to_file[$key])) {
864 $fieldstarget_tmp[$key][
"imported"] =
true;
865 $fieldstarget_tmp[$key][
"position"] = (int) $array_match_database_to_file[$key] - 1;
867 while (!empty($array_match_database_to_file[$keytoswap])) {
868 if ($position + 1 > $array_match_database_to_file[$keytoswap]) {
869 $keytoswapwith = $array_match_database_to_file[$keytoswap] - 1;
870 $tmp = [$keytoswap => $fieldstarget_tmp[$keytoswap]];
871 unset($fieldstarget_tmp[$keytoswap]);
872 $fieldstarget_tmp =
arrayInsert($fieldstarget_tmp, $keytoswapwith, $tmp);
873 $keytoswapwith = $arraykeysfieldtarget[$array_match_database_to_file[$keytoswap] - 1];
874 $tmp = $fieldstarget_tmp[$keytoswapwith];
875 unset($fieldstarget_tmp[$keytoswapwith]);
876 $fieldstarget_tmp[$keytoswapwith] = $tmp;
877 $keytoswap = $keytoswapwith;
883 $fieldstarget_tmp[$key][
"imported"] =
false;
887 $fieldstarget = $fieldstarget_tmp;
896 $param =
'&format='.$format.
'&datatoimport='.urlencode($datatoimport).
'&filetoimport='.urlencode($filetoimport);
897 if ($excludefirstline) {
898 $param .=
'&excludefirstline='.urlencode($excludefirstline);
901 $param .=
'&endatlinenb='.urlencode($endatlinenb);
904 $param .=
'&separator='.urlencode($separator);
907 $param .=
'&enclosure='.urlencode($enclosure);
910 llxHeader(
'', $langs->trans(
"NewImport"), $help_url);
914 $titleofmodule = $objimport->array_import_module[0][
'module']->getName();
918 print
'<div class="underbanner clearboth"></div>';
919 print
'<div class="fichecenter">';
921 print
'<table class="centpercent border tableforfield">';
924 print
'<tr><td class="titlefieldcreate">'.$langs->trans(
"Module").
'</td>';
927 if (in_array($objimport->array_import_code[0], array(
'produit_supplierprices',
'produit_multiprice',
'produit_languages'))) {
928 $titleofmodule = $langs->trans(
"ProductOrService");
930 print dolPrintHTML($titleofmodule);
934 print
'<tr><td>'.$langs->trans(
"DatasetToImport").
'</td>';
936 $entity = preg_replace(
'/:.*$/',
'', $objimport->array_import_icon[0]);
937 $entityicon = strtolower(!empty($entitytoicon[$entity]) ? $entitytoicon[$entity] : $entity);
938 print img_object($objimport->array_import_module[0][
'module']->getName(), $entityicon).
' ';
939 print $objimport->array_import_label[0];
949 print
load_fiche_titre($langs->trans(
"InformationOnSourceFile"),
'',
'file-export');
951 print
'<div class="underbanner clearboth"></div>';
952 print
'<div class="fichecenter">';
953 print
'<table width="100%" class="border tableforfield">';
956 print
'<tr><td class="titlefieldcreate">'.$langs->trans(
"SourceFileFormat").
'</td>';
957 print
'<td class="nowraponall">';
958 $text = $objmodelimport->getDriverDescForKey($format);
960 print $form->textwithpicto($objmodelimport->getDriverLabelForKey($format), $text);
964 if ($model ==
'csv') {
965 '@phan-var-force ImportCsv $obj';
966 print
'<tr><td>'.$langs->trans(
"CsvOptions").
'</td>';
968 print
'<form method="POST">';
969 print
'<input type="hidden" name="token" value="'.newToken().
'">';
970 print
'<input type="hidden" value="'.$step.
'" name="step">';
971 print
'<input type="hidden" value="'.$format.
'" name="format">';
972 print
'<input type="hidden" value="'.$excludefirstline.
'" name="excludefirstline">';
973 print
'<input type="hidden" value="'.$endatlinenb.
'" name="endatlinenb">';
974 print
'<input type="hidden" value="'.$datatoimport.
'" name="datatoimport">';
975 print
'<input type="hidden" value="'.$filetoimport.
'" name="filetoimport">';
976 print $langs->trans(
"Separator").
' : ';
977 print
'<input type="text" class="width25 center" name="separator" value="'.dol_escape_htmltag($separator).
'"/>';
978 print
' '.$langs->trans(
"Enclosure").
' : ';
979 print
'<input type="text" class="width25 center" name="enclosure" value="'.dol_escape_htmltag($enclosure).
'"/> ';
980 print
'<input name="update" type="submit" value="'.$langs->trans(
'Update').
'" class="button smallpaddingimp" />';
986 print
'<tr><td>'.$langs->trans(
"FileToImport").
'</td>';
988 $modulepart =
'import';
989 $relativepath =
GETPOST(
'filetoimport');
990 print
'<a data-ajax="false" href="'.DOL_URL_ROOT.
'/document.php?modulepart='.$modulepart.
'&file='.urlencode($relativepath).
'&step=3'.$param.
'" target="_blank" rel="noopener noreferrer">';
991 print
img_mime($file,
'',
'pictofixedwidth');
993 print img_picto($langs->trans(
"Download"),
'download',
'class="paddingleft opacitymedium"');
1006 print
'<!-- List of source fields -->'.
"\n";
1007 print
'<form action="'.$_SERVER[
"PHP_SELF"].
'" method="POST">';
1008 print
'<input type="hidden" name="token" value="'.newToken().
'">';
1009 print
'<input type="hidden" name="action" value="select_model">';
1010 print
'<input type="hidden" name="step" value="3">';
1011 print
'<input type="hidden" name="format" value="'.$format.
'">';
1012 print
'<input type="hidden" name="datatoimport" value="'.$datatoimport.
'">';
1013 print
'<input type="hidden" name="filetoimport" value="'.$filetoimport.
'">';
1014 print
'<input type="hidden" name="excludefirstline" value="'.$excludefirstline.
'">';
1015 print
'<input type="hidden" name="endatlinenb" value="'.$endatlinenb.
'">';
1016 print
'<input type="hidden" name="separator" value="'.dol_escape_htmltag($separator).
'">';
1017 print
'<input type="hidden" name="enclosure" value="'.dol_escape_htmltag($enclosure).
'">';
1020 print
'<div class="marginbottomonly">';
1021 print
'<span class="opacitymedium">';
1022 $s = $langs->trans(
"SelectImportFieldsSource",
'{s1}');
1023 $s = str_replace(
'{s1}', img_picto(
'',
'grip_title',
'', 0, 0, 0,
'',
'', 0), $s);
1026 $htmlother->select_import_model((
string) $importmodelid,
'importmodelid', $datatoimport, 1, $user->id);
1027 print
'<input type="submit" class="button smallpaddingimp reposition" id="applyprofile" name="applyprofile" value="'.$langs->trans(
"Apply").
'">';
1029 if (!empty(
$conf->use_javascript_ajax)) {
1031 $(document).ready(function() {
1033 $("#applyprofile").hide();
1035 // follow change on list
1036 $("#importmodelid").change(function() {
1037 console.log("We select a new profile");
1038 if ($(this).val() && $(this).val() != "-1") {
1039 $("#applyprofile").show();
1041 $("#applyprofile").hide();
1055 print
'<div class="div-table-responsive-no-min">';
1056 print
'<table class="noborder centpercent">';
1057 print
'<tr class="liste_titre">';
1058 print
'<td>'.$langs->trans(
"FieldsInSourceFile").
'</td>';
1059 print
'<td>'.$langs->trans(
"FieldsInTargetDatabase").
'</td>';
1064 print
'<tr valign="top"><td width="50%" class="nopaddingleftimp">';
1066 $fieldsplaced = array();
1067 $valforsourcefieldnb = array();
1068 $listofkeys = array();
1069 foreach ($array_match_file_to_database as $key => $val) {
1070 $listofkeys[$key] = 1;
1073 print
"\n<!-- Box left container -->\n";
1074 print
'<div id="left" class="connectedSortable">'.
"\n";
1079 foreach ($fieldssource as $key => $val) {
1080 show_elem($fieldssource, $key, (
string) $key);
1081 $listofkeys[$key] = 1;
1082 $fieldsplaced[$key] = 1;
1083 $valforsourcefieldnb[$lefti] = $key;
1093 print
"<!-- End box left container -->\n";
1096 print
'</td><td width="50%" class="nopaddingrightimp">';
1100 $optionsall = array();
1101 foreach ($fieldstarget as $code => $line) {
1102 $tmparray = explode(
'|', $line[
"label"]);
1104 foreach ($tmparray as $tmpkey => $tmpval) {
1105 $labeltoshow .= ($labeltoshow ?
' '.$langs->trans(
'or').
' ' :
'').$langs->transnoentities($tmpval);
1110 $optionsall[$code] = array(
1111 'labelkey' => $line[
'label'],
1112 'labelkeyarray' => $tmparray,
1113 'label' => $labeltoshow,
1114 'required' => (empty($line[
"required"]) ? 0 : 1),
1115 'position' => (!empty($line[
'position']) ? $line[
'position'] : 0),
1123 $mandatoryfieldshavesource =
true;
1136 $modetoautofillmapping =
'session';
1137 if ($initialloadofstep4) {
1138 $modetoautofillmapping =
'guess';
1142 print
'<table class="nobordernopadding centpercent tableimport">';
1143 foreach ($fieldssource as $code => $line) {
1148 print
'<tr style="height:'.$height.
'" class="trimport oddevenimport">';
1150 $entity = (!empty($objimport->array_import_entities[0][$code]) ? $objimport->array_import_entities[0][$code] : $objimport->array_import_icon[0]);
1152 $entityicon = !empty($entitytoicon[$entity]) ? $entitytoicon[$entity] : $entity;
1153 $entitylang = !empty($entitytolang[$entity]) ? $entitytolang[$entity] : $objimport->array_import_label[0];
1155 print
'<td class="nowraponall hideonsmartphone" style="font-weight: normal">=> </td>';
1156 print
'<td class="nowraponall" style="font-weight: normal">';
1158 $selectforline =
'';
1159 $selectforline .=
'<select id="selectorderimport_'.($i + 1).
'" class="targetselectchange minwidth300" name="select_'.($i + 1).
'">';
1160 $selectforline .=
'<option value="-1"> </option>';
1163 $codeselectedarray = array();
1164 foreach ($optionsall as $tmpcode => $tmpval) {
1166 if (!empty($tmpval[
'picto'])) {
1167 $label .= img_picto(
'', $tmpval[
'picto'],
'class="pictofixedwidth"');
1169 $label .= $tmpval[
'required'] ?
'<strong>' :
'';
1170 $label .= $tmpval[
'label'];
1171 $label .= $tmpval[
'required'] ?
'*</strong>' :
'';
1173 $tablealias = preg_replace(
'/(\..*)$/i',
'', $tmpcode);
1174 $tablename = !empty($objimport->array_import_tables[0][$tablealias]) ? $objimport->array_import_tables[0][$tablealias] :
"";
1178 $filecolumn = ($i + 1);
1180 if (empty($objimport->array_import_convertvalue[0][$tmpcode])) {
1183 if ($objimport->array_import_convertvalue[0][$tmpcode][
'rule'] ==
'fetchidfromref') {
1184 $htmltext .= $langs->trans(
"DataComeFromIdFoundFromRef", $langs->transnoentitiesnoconv($entitylang)).
'<br>';
1186 if ($objimport->array_import_convertvalue[0][$tmpcode][
'rule'] ==
'fetchidfromcodeid') {
1187 $dictlabel = $objimport->array_import_convertvalue[0][$tmpcode][
'dict'] ??
'';
1188 $htmltext .= $langs->trans(
"DataComeFromIdFoundFromCodeId", $langs->transnoentitiesnoconv($dictlabel)).
'<br>';
1192 $example = !empty($objimport->array_import_examplevalues[0][$tmpcode]) ? $objimport->array_import_examplevalues[0][$tmpcode] :
"";
1194 if (empty($objimport->array_import_convertvalue[0][$tmpcode])) {
1196 $htmltext .= $langs->trans(
"SourceExample").
': <b>'.str_replace(
'"',
'', $example).
'</b><br>';
1199 if ($objimport->array_import_convertvalue[0][$tmpcode][
'rule'] ==
'fetchidfromref') {
1200 $htmltext .= $langs->trans(
"SourceExample").
': <b>'.$langs->transnoentitiesnoconv(
"ExampleAnyRefFoundIntoElement", $entitylang).($example ?
' ('.$langs->transnoentitiesnoconv(
"Example").
': '.str_replace(
'"',
'', $example).
')' :
'').
'</b><br>';
1201 } elseif ($objimport->array_import_convertvalue[0][$tmpcode][
'rule'] ==
'fetchidfromcodeid') {
1202 $dictlabel = $objimport->array_import_convertvalue[0][$tmpcode][
'dict'] ??
'';
1203 $htmltext .= $langs->trans(
"SourceExample").
': <b>'.$langs->trans(
"ExampleAnyCodeOrIdFoundIntoDictionary", $langs->transnoentitiesnoconv($dictlabel)).($example ?
' ('.$langs->transnoentitiesnoconv(
"Example").
': '.str_replace(
'"',
'', $example).
')' :
'').
'</b><br>';
1204 } elseif ($example) {
1205 $htmltext .= $langs->trans(
"SourceExample").
': <b>'.str_replace(
'"',
'', $example).
'</b><br>';
1209 if (!empty($objimport->array_import_regex[0][$tmpcode])) {
1210 $htmltext .= $langs->trans(
"FormatControlRule").
': <b>'.str_replace(
'"',
'', $objimport->array_import_regex[0][$tmpcode]).
'</b><br>';
1214 $htmltext .= $langs->trans(
"InformationOnTargetTables").
': <b>'.$tablename.
"->".preg_replace(
'/^.*\./',
'', $tmpcode).
"</b>";
1216 $labelhtml = $label.
' '.$form->textwithpicto(
'', $htmltext, 1,
'help',
'', 1);
1219 $selectforline .=
'<option value="'.$tmpcode.
'"';
1220 if ($modetoautofillmapping ==
'orderoftargets') {
1223 $selectforline .=
' selected';
1225 } elseif ($modetoautofillmapping ==
'guess') {
1229 if (preg_match(
'/^(.+)\((.+\..+)\)$/', $line[
'example1'], $regs)) {
1230 $tmpstring1 = $regs[1];
1231 $tmpstring2 = $regs[2];
1233 $tmpstring1 = $line[
'example1'];
1241 foreach ($tmpval[
'labelkeyarray'] as $tmpval2) {
1242 $labeltarget = $langs->transnoentities($tmpval2);
1244 if ($tmpstring1 && ($tmpstring1 == $tmpcode || $tmpstring1 == strtolower($labeltarget)
1245 || $tmpstring1 == strtolower(
dol_string_unaccent($labeltarget)) || $tmpstring1 == strtolower($tmpval2))) {
1246 if (empty($codeselectedarray[$code])) {
1247 $selectforline .=
' selected';
1248 $codeselectedarray[$code] = 1;
1251 } elseif ($tmpstring2 && ($tmpstring2 == $tmpcode || $tmpstring2 == strtolower($labeltarget)
1252 || $tmpstring2 == strtolower(
dol_string_unaccent($labeltarget)) || $tmpstring2 == strtolower($tmpval2))) {
1253 if (empty($codeselectedarray[$code])) {
1254 $selectforline .=
' selected';
1255 $codeselectedarray[$code] = 1;
1260 } elseif ($modetoautofillmapping ==
'session' && !empty($_SESSION[
'dol_array_match_file_to_database_select'])) {
1261 $tmpselectioninsession =
dolExplodeIntoArray($_SESSION[
'dol_array_match_file_to_database_select'],
',',
'=');
1263 if (!empty($tmpselectioninsession[(
string) ($i + 1)]) && $tmpselectioninsession[(
string) ($i + 1)] == $tmpcode) {
1264 $selectforline .=
' selected';
1266 $selectforline .=
' data-debug="'.$tmpcode.
'-'.$code.
'-'.$j.
'-'.(!empty($tmpselectioninsession[(
string) ($i + 1)]) ? $tmpselectioninsession[(string) ($i + 1)] :
"").
'"';
1268 $selectforline .=
' data-html="'.dol_escape_htmltag($labelhtml).
'"';
1269 $selectforline .=
'>';
1270 $selectforline .= $label;
1271 $selectforline .=
'</options>';
1274 $selectforline .=
'</select>';
1275 $selectforline .=
ajax_combobox(
'selectorderimport_'.($i + 1));
1277 print $selectforline;
1282 print
'<td class="nowraponall" style="font-weight:normal; text-align:right">';
1285 $htmltext =
'<b><u>'.$langs->trans(
"FieldSource").
'</u></b><br>';
1287 $htmltext .= $langs->trans(
"DataComeFromFileFieldNb", $filecolumntoshow).
'<br>';
1289 print $form->textwithpicto(
'', $htmltext);
1300 print
'<tr class="liste_titre"><td colspan="2">'.$langs->trans(
"Note").
'</td></tr>';
1301 print
'<tr><td colspan="2"><div id="div-mandatory-target-fields-not-mapped"></div></td></tr>';
1307 if (!empty(
$conf->use_javascript_ajax)) {
1308 print
'<script type="text/javascript">'.
"\n";
1309 print
'var previousselectedvalueimport = "0";'.
"\n";
1310 print
'var previousselectedlabelimport = "0";'.
"\n";
1311 print
'var arrayofselectedvalues = [];'.
"\n";
1312 print
'var arrayoftargetfields = [];'.
"\n";
1313 print
'var arrayoftargetmandatoryfields = [];'.
"\n";
1317 foreach ($fieldstarget as $key => $val) {
1318 print
"arrayoftargetfields[".$tmpi.
"] = '".
dol_escape_js($langs->trans($val[
'label'])).
"'; ";
1319 if ($val[
'required']) {
1320 print
"arrayoftargetmandatoryfields[".$tmpi.
"] = '".
dol_escape_js($key).
"'; ";
1326 print
'$(document).ready(function () {'.
"\n";
1328 print
'setOptionsToDisabled();'.
"\n";
1329 print
'saveSelection();'.
"\n";
1331 print
'$(".targetselectchange").focus(function(){'.
"\n";
1332 print
' previousselectedvalueimport = $(this).val();'.
"\n";
1333 print
' previousselectedlabelimport = $(this).children("option:selected").text();'.
"\n";
1334 print
' console.log("previousselectedvalueimport="+previousselectedvalueimport)'.
"\n";
1341 print
'function setOptionsToDisabled() {'.
"\n";
1342 print
' console.log("Remove the disabled flag everywhere");'.
"\n";
1343 print
' $("select.targetselectchange").not($( this )).find(\'option\').prop("disabled", false);'.
"\n";
1344 print
' arrayofselectedvalues = [];'.
"\n";
1346 print
' $("select.targetselectchange").each(function(){'.
"\n";
1347 print
' id = $(this).attr(\'id\')'.
"\n";
1348 print
' value = $(this).val()'.
"\n";
1349 print
' console.log("a selected value has been found for component "+id+" = "+value);'.
"\n";
1350 print
' arrayofselectedvalues.push(value);'.
"\n";
1353 print
' console.log("List of all selected values arrayofselectedvalues");'.
"\n";
1354 print
' console.log(arrayofselectedvalues);'.
"\n";
1355 print
' console.log("Set the option to disabled for every entry that is currently selected somewhere else (so into arrayofselectedvalues)");'.
"\n";
1357 print
' $.each(arrayofselectedvalues, function(key, value) {'.
"\n";
1358 print
' if (value != -1) {'.
"\n";
1359 print
' console.log("Process key="+key+" value="+value+" to disable.");'.
"\n";
1360 print
' $("select.targetselectchange").find(\'option[value="\'+value+\'"]:not(:selected)\').prop("disabled", true);'.
"\n";
1366 print
'function saveSelection() {'.
"\n";
1368 print
' arrayselectedfields = [];'.
"\n";
1369 print
' arrayselectedfields.push(0);'.
"\n";
1371 print
' $.each( arrayofselectedvalues, function( key, value ) {'.
"\n";
1372 print
' if (value != -1) {'.
"\n";
1373 print
' arrayselectedfields.push(value);'.
"\n";
1374 print
' } else {'.
"\n";
1375 print
' arrayselectedfields.push(0);'.
"\n";
1379 print
" $.ajax({\n";
1380 print
" type: 'POST',\n";
1381 print
" dataType: 'json',\n";
1382 print
" url: '".dol_escape_js($_SERVER[
"PHP_SELF"]).
"?action=saveselectorder&token=".
newToken().
"',\n";
1383 print
" data: 'selectorder='+arrayselectedfields.toString(),\n";
1384 print
" success: function(){\n";
1385 print
" console.log('The selected fields have been saved into '+arrayselectedfields.toString());\n";
1390 print
' console.log("arrayselectedfields");';
1391 print
' console.log(arrayselectedfields);';
1392 print
' console.log("arrayoftargetmandatoryfields");';
1393 print
' console.log(arrayoftargetmandatoryfields);';
1394 print
" listtoshow = '';";
1395 print
" nbelement = arrayoftargetmandatoryfields.length
1396 for (let i = 0; i < nbelement; i++) {
1397 if (arrayoftargetmandatoryfields[i] && ! arrayselectedfields.includes(arrayoftargetmandatoryfields[i])) {
1398 console.log(arrayoftargetmandatoryfields[i]+' not mapped');
1399 listtoshow = listtoshow + (listtoshow ? ', ' : '') + '<b>' + arrayoftargetfields[i] + '*</b>';
1402 console.log(listtoshow);
1404 listtoshow = '".dol_escape_js(img_warning($langs->trans(
"MandatoryTargetFieldsNotMapped")).
' '.$langs->trans(
"MandatoryTargetFieldsNotMapped")).
": ' + listtoshow;
1405 $('#div-mandatory-target-fields-not-mapped').html(listtoshow);
1407 $('#div-mandatory-target-fields-not-mapped').html('<span class=\"opacitymedium\">".
dol_escape_js($langs->trans(
"AllTargetMandatoryFieldsAreMapped")).
"</span>');
1414 print
'$(".targetselectchange").change(function(){'.
"\n";
1415 print
' setOptionsToDisabled();'.
"\n";
1417 print
' if(previousselectedlabelimport != "" && previousselectedvalueimport != -1) {'.
"\n";
1418 print
' let valuetochange = $(this).val(); '.
"\n";
1419 print
' $(".boxtdunused").each(function(){'.
"\n";
1420 print
' if ($(this).text().includes(valuetochange)){'.
"\n";
1421 print
' arraychild = $(this)[0].childNodes'.
"\n";
1422 print
' arraytexttomodify = arraychild[0].textContent.split(" ")'.
"\n";
1423 print
' arraytexttomodify[1] = previousselectedvalueimport '.
"\n";
1424 print
' textmodified = arraytexttomodify.join(" ") '.
"\n";
1425 print
' arraychild[0].textContent = textmodified'.
"\n";
1426 print
' arraychild[1].innerHTML = previousselectedlabelimport'.
"\n";
1430 print
' $(this).blur()'.
"\n";
1432 print
' saveSelection()'.
"\n";
1436 print
'</script>'.
"\n";
1442 print
'<div class="tabsAction">';
1444 if (count($array_match_file_to_database)) {
1445 if ($mandatoryfieldshavesource) {
1446 print
'<a class="butAction saveorderselect" href="import.php?step=4'.$param.
'&filetoimport='.urlencode($filetoimport).
'">'.$langs->trans(
"NextStep").
'</a>';
1448 print
'<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->transnoentitiesnoconv(
"SomeMandatoryFieldHaveNoSource")).
'">'.$langs->trans(
"NextStep").
'</a>';
1456 if (count($array_match_file_to_database)) {
1458 print
'<!-- Area to add new import profile -->'.
"\n";
1459 print
'<div class="marginbottomonly"><span class="opacitymedium">'.$langs->trans(
"SaveImportModel").
'</span></div>';
1461 print
'<form class="nocellnopadd" action="'.$_SERVER[
"PHP_SELF"].
'" method="post">';
1462 print
'<input type="hidden" name="token" value="'.newToken().
'">';
1463 print
'<input type="hidden" name="action" value="add_import_model">';
1464 print
'<input type="hidden" name="step" value="'.$step.
'">';
1465 print
'<input type="hidden" name="format" value="'.$format.
'">';
1466 print
'<input type="hidden" name="datatoimport" value="'.$datatoimport.
'">';
1467 print
'<input type="hidden" name="filetoimport" value="'.$filetoimport.
'">';
1468 print
'<input type="hidden" name="hexa" value="'.$hexa.
'">';
1469 print
'<input type="hidden" name="excludefirstline" value="'.$excludefirstline.
'">';
1470 print
'<input type="hidden" name="endatlinenb" value="'.$endatlinenb.
'">';
1471 print
'<input type="hidden" name="page_y" value="">';
1472 print
'<input type="hidden" value="'.dol_escape_htmltag($separator).
'" name="separator">';
1473 print
'<input type="hidden" value="'.dol_escape_htmltag($enclosure).
'" name="enclosure">';
1475 print
'<div class="div-table-responsive-no-min">';
1476 print
'<table summary="selectofimportprofil" class="noborder centpercent">';
1477 print
'<tr class="liste_titre">';
1478 print
'<td>'.$langs->trans(
"ImportModelName").
'</td>';
1479 print
'<td>'.$langs->trans(
"Visibility").
'</td>';
1483 $nameofimportprofile = str_replace(
' ',
'-', $langs->trans(
"ImportProfile").
' '.$titleofmodule.
' '.
dol_print_date(
dol_now(
'gmt'),
'dayxcard'));
1485 $nameofimportprofile = $import_name;
1488 print
'<tr class="oddeven">';
1489 print
'<td><input name="import_name" class="minwidth300" value="'.$nameofimportprofile.
'"></td>';
1491 $arrayvisibility = array(
'private' => $langs->trans(
"Private"),
'all' => $langs->trans(
"Everybody"));
1492 print $form->selectarray(
'visibility', $arrayvisibility,
'private');
1494 print
'<td class="right">';
1495 print
'<input type="submit" class="button smallpaddingimp reposition" value="'.$langs->trans(
"SaveImportProfile").
'">';
1499 $sql =
"SELECT rowid, label, fk_user, entity";
1500 $sql .=
" FROM ".MAIN_DB_PREFIX.
"import_model";
1501 $sql .=
" WHERE type = '".$db->escape($datatoimport).
"'";
1503 $sql .=
" AND fk_user IN (0, ".((int) $user->id).
")";
1505 $sql .=
" ORDER BY rowid";
1507 $resql = $db->query($sql);
1509 $num = $db->num_rows($resql);
1511 $tmpuser =
new User($db);
1515 $obj = $db->fetch_object($resql);
1517 print
'<tr class="oddeven"><td>';
1520 print
'<td class="tdoverflowmax150">';
1521 if (empty($obj->fk_user)) {
1522 print $langs->trans(
"Everybody");
1524 $tmpuser->fetch($obj->fk_user);
1525 print $tmpuser->getNomUrl(-1);
1528 print
'<td class="right">';
1529 print
'<a class="reposition" href="'.$_SERVER[
"PHP_SELF"].
'?step='.$step.$param.
'&action=deleteprof&token='.
newToken().
'&id='.$obj->rowid.
'&filetoimport='.urlencode($filetoimport).
'">';
1536 dol_print_error($db);
1547if ($step == 4 && $datatoimport) {
1548 $max_execution_time_for_importexport =
getDolGlobalInt(
'IMPORT_MAX_EXECUTION_TIME', 300);
1549 $max_time = @ini_get(
"max_execution_time");
1550 if ($max_time && $max_time < $max_execution_time_for_importexport) {
1551 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.");
1552 @ini_set(
"max_execution_time", $max_execution_time_for_importexport);
1558 if ($model ===
'txt') {
1562 $list = $objmodelimport->listOfAvailableImportFormat($db);
1565 $dir = DOL_DOCUMENT_ROOT.
"/core/modules/import/";
1566 $file =
"import_".$model.
".modules.php";
1567 $classname =
"Import".ucfirst($model);
1568 require_once $dir.$file;
1569 $obj =
new $classname($db, $datatoimport);
1570 '@phan-var-force ModeleImports $obj';
1571 $obj->importtriggermode = $importtriggermode;
1572 $obj->importissimulation = 1;
1573 if ($model ==
'csv') {
1574 '@phan-var-force ImportCsv $obj';
1575 $obj->separator = $separator_used;
1576 $obj->enclosure = $enclosure;
1580 $fieldssource = array();
1581 $result = $obj->import_open_file(
$conf->import->dir_temp.
'/'.$filetoimport);
1585 $arrayrecord = $obj->import_read_record();
1588 foreach ($arrayrecord as $key => $val) {
1589 $fieldssource[$i][
'example1'] =
dol_trunc($val[
'val'], 24);
1592 $obj->import_close_file();
1595 $nboflines = $obj->import_get_nb_of_lines(
$conf->import->dir_temp.
'/'.$filetoimport);
1597 $param =
'&leftmenu=import&format='.urlencode($format).
'&datatoimport='.urlencode($datatoimport).
'&filetoimport='.urlencode($filetoimport).
'&nboflines='.((int) $nboflines).
'&separator='.urlencode($separator).
'&enclosure='.urlencode($enclosure).
'&importtriggermode='.urlencode($importtriggermode);
1599 if ($excludefirstline) {
1600 $param .=
'&excludefirstline='.urlencode($excludefirstline);
1603 $param .=
'&endatlinenb='.urlencode($endatlinenb);
1605 if (!empty($updatekeys)) {
1606 $param .=
'&updatekeys[]='.implode(
'&updatekeys[]=', $updatekeys);
1609 llxHeader(
'', $langs->trans(
"NewImport"), $help_url);
1614 print
'<form action="'.$_SERVER[
"PHP_SELF"].
'?'.$param2.
'" method="POST">';
1615 print
'<input type="hidden" name="token" value="'.newToken().
'">';
1616 print
'<input type="hidden" name="step" value="4">';
1617 print
'<input type="hidden" name="action" value="launchsimu">';
1618 print
'<input type="hidden" name="importtriggermode" value="'.dol_escape_htmltag($importtriggermode).
'">';
1622 print
'<div class="underbanner clearboth"></div>';
1623 print
'<div class="fichecenter">';
1625 print
'<table width="100%" class="border tableforfield">';
1628 print
'<tr><td class="titlefieldcreate">'.$langs->trans(
"Module").
'</td>';
1630 $titleofmodule = $objimport->array_import_module[0][
'module']->getName();
1632 if (in_array($objimport->array_import_code[0], array(
'produit_supplierprices',
'produit_multiprice',
'produit_languages'))) {
1633 $titleofmodule = $langs->trans(
"ProductOrService");
1635 print $titleofmodule;
1639 print
'<tr><td>'.$langs->trans(
"DatasetToImport").
'</td>';
1641 $entity = preg_replace(
'/:.*$/',
'', $objimport->array_import_icon[0]);
1642 $entityicon = strtolower(!empty($entitytoicon[$entity]) ? $entitytoicon[$entity] : $entity);
1643 print img_object($objimport->array_import_module[0][
'module']->getName(), $entityicon).
' ';
1644 print $objimport->array_import_label[0];
1652 print
load_fiche_titre($langs->trans(
"InformationOnSourceFile"),
'',
'file-export');
1654 print
'<div class="underbanner clearboth"></div>';
1655 print
'<div class="fichecenter">';
1656 print
'<table width="100%" class="border tableforfield">';
1659 print
'<tr><td class="titlefieldcreate">'.$langs->trans(
"SourceFileFormat").
'</td>';
1660 print
'<td class="nowraponall">';
1661 $text = $objmodelimport->getDriverDescForKey($format);
1663 print $form->textwithpicto($objmodelimport->getDriverLabelForKey($format), $text);
1667 if ($model ==
'csv') {
1668 '@phan-var-force ImportCsv $obj';
1669 print
'<tr><td>'.$langs->trans(
"CsvOptions").
'</td>';
1672 print
' '.$langs->trans(
"Enclosure").
' : '.
dol_escape_htmltag($enclosure);
1677 print
'<tr><td>'.$langs->trans(
"FileToImport").
'</td>';
1679 $modulepart =
'import';
1680 $relativepath =
GETPOST(
'filetoimport');
1681 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">';
1682 print
img_mime($file,
'',
'pictofixedwidth');
1683 print $filetoimport;
1684 print img_picto($langs->trans(
"Download"),
'download',
'class="paddingleft opacitymedium"');
1690 print $langs->trans(
"NbOfSourceLines");
1697 print $langs->trans(
"ImportFromToLine");
1699 if ($action ==
'launchsimu') {
1700 print
'<input type="number" min="1" class="maxwidth50 right valignmiddle" name="excludefirstlinebis" disabled="disabled" value="'.$excludefirstline.
'">';
1701 print
'<input type="hidden" name="excludefirstline" value="'.$excludefirstline.
'">';
1703 print
'<input type="number" min="1" class="maxwidth50 right valignmiddle" name="excludefirstline" value="'.$excludefirstline.
'">';
1704 print $form->textwithpicto(
"", $langs->trans(
"SetThisValueTo2ToExcludeFirstLine"));
1707 if ($action ==
'launchsimu') {
1708 print
'<input type="text" class="maxwidth50 valignmiddle" name="endatlinenbbis" disabled="disabled" value="'.$endatlinenb.
'">';
1709 print
'<input type="hidden" name="endatlinenb" value="'.$endatlinenb.
'">';
1711 print
'<input type="text" class="maxwidth50 valignmiddle" name="endatlinenb" value="'.$endatlinenb.
'">';
1712 print $form->textwithpicto(
"", $langs->trans(
"KeepEmptyToGoToEndOfFile"));
1714 if ($action ==
'launchsimu') {
1715 print
' <a href="'.$_SERVER[
"PHP_SELF"].
'?step=4'.$param.
'" class="editfielda">';
1717 print img_picto($langs->trans(
"Modify"),
'edit');
1720 if ($excludefirstline == 2) {
1721 print $form->textwithpicto(
"", $langs->trans(
"WarningFirstImportedLine", $excludefirstline), 1,
'warning',
"warningexcludefirstline valignmiddle");
1723 $( document ).ready(function() {
1724 $("input[name=\'excludefirstline\']").on("change",function(){
1725 if($(this).val() <= 1){
1726 $(".warningexcludefirstline").hide();
1728 $(".warningexcludefirstline").show();
1738 print $form->textwithpicto($langs->trans(
"KeysToUseForUpdates"), $langs->trans(
"SelectPrimaryColumnsForUpdateAttempt"));
1740 if ($action ==
'launchsimu') {
1741 if (count($updatekeys)) {
1742 print $form->multiselectarray(
'updatekeysbis', $objimport->array_import_updatekeys[0], $updatekeys, 0, 0,
'', 1,
'80%',
'disabled');
1744 print
'<span class="opacitymedium">'.$langs->trans(
"NoUpdateAttempt").
'</span>';
1746 foreach ($updatekeys as $val) {
1747 print
'<input type="hidden" name="updatekeys[]" value="'.$val.
'">';
1749 print
' <a href="'.$_SERVER[
"PHP_SELF"].
'?step=4'.$param.
'" class="editfielda">';
1751 print img_picto($langs->trans(
"Modify"),
'edit');
1754 if (is_array($objimport->array_import_updatekeys[0]) && count($objimport->array_import_updatekeys[0])) {
1755 print $form->multiselectarray(
'updatekeys', $objimport->array_import_updatekeys[0], $updatekeys, 0, 0,
'', 1,
'80%');
1758 print
'<span class="opacitymedium">'.$langs->trans(
"UpdateNotYetSupportedForThisImport").
'</span>';
1771 print
load_fiche_titre($langs->trans(
"InformationOnTargetTables"),
'',
'file-import');
1773 print
'<div class="underbanner clearboth"></div>';
1774 print
'<div class="fichecenter">';
1776 print
'<table class="centpercent border tableforfield">';
1779 print
'<tr><td class="titlefieldcreate">';
1780 print $langs->trans(
"TablesTarget");
1782 $listtables = array();
1783 $sort_array_match_file_to_database = $array_match_file_to_database;
1784 foreach ($array_match_file_to_database as $code => $label) {
1786 if ($code > count($fieldssource)) {
1790 $alias = preg_replace(
'/(\..*)$/i',
'', $label);
1791 $listtables[$alias] = $objimport->array_import_tables[0][$alias];
1793 if (count($listtables)) {
1796 foreach ($listtables as $val) {
1815 print $langs->trans(
"Error");
1821 print $langs->trans(
"FieldsTarget").
'</td><td class="small">';
1822 $listfields = array();
1825 $sort_array_match_file_to_database = $array_match_file_to_database;
1826 ksort($sort_array_match_file_to_database);
1828 foreach ($sort_array_match_file_to_database as $code => $label) {
1831 if ($code > count($fieldssource)) {
1835 $alias = preg_replace(
'/(\..*)$/i',
'', $label);
1836 $listfields[$i] =
'<span class="nowrap">'.$langs->trans(
"Column").
' '.
num2Alpha((
int) $code - 1).
' -> '.$label.
'</span>';
1838 print count($listfields) ? (implode(
', ', $listfields)) : $langs->trans(
"Error");
1843 print $form->textwithpicto($langs->trans(
"ImportTriggerModeLabel"), $langs->trans(
"ImportTriggerModeHint"));
1845 $triggerModeChoices = array(
1846 'strict_line' => $langs->trans(
"ImportTriggerModeStrictLine"),
1847 'fast_bulk' => $langs->trans(
"ImportTriggerModeFastBulk"),
1849 if ($action ==
'launchsimu') {
1850 print
dol_escape_htmltag($triggerModeChoices[$importtriggermode] ?? $importtriggermode);
1851 print
'<input type="hidden" name="importtriggermode" value="'.dol_escape_htmltag($importtriggermode).
'">';
1852 print
' <a href="'.$_SERVER[
"PHP_SELF"].
'?step=4'.$param.
'" class="editfielda">';
1854 print img_picto($langs->trans(
"Modify"),
'edit');
1857 print $form->selectarray(
'importtriggermode', $triggerModeChoices, $importtriggermode, 0);
1859 if ($importtriggermode ===
'fast_bulk') {
1860 print
'<br><span class="warning">';
1861 print $langs->trans(
"ImportTriggerModeFastBulkWarning");
1872 if ($action !=
'launchsimu') {
1875 print
'<div class="neutral">';
1876 print $langs->trans(
"NowClickToTestTheImport", $langs->transnoentitiesnoconv(
"RunSimulateImportFile")).
'<br>';
1880 print
'<div class="center">';
1881 if ($user->hasRight(
'import',
'run')) {
1882 print
'<input type="submit" class="butAction" value="'.$langs->trans(
"RunSimulateImportFile").
'">';
1884 print
'<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->transnoentitiesnoconv(
"NotEnoughPermissions")).
'">'.$langs->trans(
"RunSimulateImportFile").
'</a>';
1889 print
'<div class="warning">';
1890 print
'<b>'.$langs->trans(
"ImportTriggerModeSimulationWarningTitle").
'</b><br>';
1891 print $langs->trans(
"ImportTriggerModeSimulationWarning");
1895 $arrayoferrors = array();
1896 $arrayofwarnings = array();
1910 $pathfile =
$conf->import->dir_temp.
'/'.$filetoimport;
1911 $result = $obj->import_open_file($pathfile);
1913 global $tablewithentity_cache;
1914 $tablewithentity_cache = array();
1919 while (($sourcelinenb < $nboflines) && !$endoffile) {
1923 $arrayrecord = $obj->import_read_record();
1924 if ($arrayrecord ===
false) {
1925 $arrayofwarnings[$sourcelinenb][0] = array(
'lib' => $langs->trans(
'ErrorFileLinesReachEOF', $nboflines, $sourcelinenb),
'type' =>
'EOF_RECORD_ON_SEVERAL_LINES');
1929 if ($excludefirstline && ($sourcelinenb < $excludefirstline)) {
1932 if ($endatlinenb && ($sourcelinenb > $endatlinenb)) {
1936 $parameters = array(
1938 'datatoimport' => $datatoimport,
1940 'arrayrecord' => $arrayrecord,
1941 'array_match_file_to_database' => $array_match_file_to_database,
1942 'objimport' => $objimport,
1943 'fieldssource' => $fieldssource,
1944 'importid' => $importid,
1945 'updatekeys' => $updatekeys,
1946 'importtriggermode' => $importtriggermode,
1947 'arrayoferrors' => &$arrayoferrors,
1948 'arrayofwarnings' => &$arrayofwarnings,
1952 $reshook = $hookmanager->executeHooks(
'ImportInsert', $parameters);
1954 $arrayoferrors[$sourcelinenb][] = [
1955 'lib' => implode(
"<br>", array_merge([$hookmanager->error], $hookmanager->errors))
1959 if (empty($reshook)) {
1961 $result = $obj->import_insert($arrayrecord, $array_match_file_to_database, $objimport, count($fieldssource), $importid, $updatekeys);
1963 if (count($obj->errors)) {
1964 $arrayoferrors[$sourcelinenb] = $obj->errors;
1966 if (count($obj->warnings)) {
1967 $arrayofwarnings[$sourcelinenb] = $obj->warnings;
1969 if (!count($obj->errors) && !count($obj->warnings)) {
1974 $reshook = $hookmanager->executeHooks(
'AfterImportInsert', $parameters);
1976 $arrayoferrors[$sourcelinenb][] = [
1977 'lib' => implode(
"<br>", array_merge([$hookmanager->error], $hookmanager->errors))
1982 $obj->import_close_file();
1984 print $langs->trans(
"ErrorFailedToOpenFile", $pathfile);
1991 if (!empty($objimport->array_import_run_sql_after[0]) && is_array($objimport->array_import_run_sql_after[0])) {
1993 foreach ($objimport->array_import_run_sql_after[0] as $sqlafterimport) {
1995 $resqlafterimport = $db->query($sqlafterimport);
1996 if (!$resqlafterimport) {
1997 $arrayoferrors[
'none'][] = array(
'lib' => $langs->trans(
"Error running final request: ".$sqlafterimport));
2006 if (!count($arrayoferrors) && !count($arrayofwarnings)) {
2008 print
'<div class="info">';
2009 print
'<div class=""><b>'.$langs->trans(
"ResultOfSimulationNoError").
'</b></div>';
2010 print $langs->trans(
"NbInsertSim", empty($obj->nbinsert) ? 0 : $obj->nbinsert).
'<br>';
2011 print $langs->trans(
"NbUpdateSim", empty($obj->nbupdate) ? 0 : $obj->nbupdate).
'<br>';
2016 print
'<div class="warning">';
2017 print $langs->trans(
"NbOfLinesOK", $nbok).
'...<br>';
2024 if (count($arrayoferrors)) {
2025 print img_error().
' <b>'.$langs->trans(
"ErrorsOnXLines", count($arrayoferrors)).
'</b><br>';
2026 print
'<table width="100%" class="border"><tr><td>';
2027 foreach ($arrayoferrors as $key => $val) {
2029 if ($nboferrors > $maxnboferrors) {
2030 print $langs->trans(
"TooMuchErrors", (count($arrayoferrors) - $nboferrors)).
"<br>";
2034 foreach ($val as $i => $err) {
2035 print
' > '.dol_escape_htmltag($err[
'lib']).
'<br>';
2038 print
'</td></tr></table>';
2044 if (count($arrayofwarnings)) {
2045 print img_warning().
' <b>'.$langs->trans(
"WarningsOnXLines", count($arrayofwarnings)).
'</b><br>';
2046 print
'<table width="100%" class="border"><tr><td>';
2047 foreach ($arrayofwarnings as $key => $val) {
2049 if ($nbofwarnings > $maxnbofwarnings) {
2050 print $langs->trans(
"TooMuchWarnings", (count($arrayofwarnings) - $nbofwarnings)).
"<br>";
2054 foreach ($val as $i => $err) {
2055 print
' > '.dol_escape_htmltag($err[
'lib']).
'<br>';
2058 print
'</td></tr></table>';
2065 print
'<div class="center">';
2066 print
'<span class="opacitymedium">'.$langs->trans(
"NowClickToRunTheImport", $langs->transnoentitiesnoconv(
"RunImportFile")).
'</span><br>';
2075 print
'<div class="center">';
2076 if ($user->hasRight(
'import',
'run')) {
2077 if (empty($nboferrors)) {
2078 print
'<a class="butAction" href="'.DOL_URL_ROOT.
'/imports/import.php?leftmenu=import&step=5&importid='.$importid.$param.
'">'.$langs->trans(
"RunImportFile").
'</a>';
2082 print
'<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->transnoentitiesnoconv(
"CorrectErrorBeforeRunningImport")).
'">'.$langs->trans(
"RunImportFile").
'</a>';
2085 print
'<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->transnoentitiesnoconv(
"NotEnoughPermissions")).
'">'.$langs->trans(
"RunSimulateImportFile").
'</a>';
2087 print
'<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->transnoentitiesnoconv(
"NotEnoughPermissions")).
'">'.$langs->trans(
"RunImportFile").
'</a>';
2097if ($step == 5 && $datatoimport) {
2098 $max_execution_time_for_importexport =
getDolGlobalInt(
'IMPORT_MAX_EXECUTION_TIME', 300);
2099 $max_time = @ini_get(
"max_execution_time");
2100 if ($max_time && $max_time < $max_execution_time_for_importexport) {
2101 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.");
2102 @ini_set(
"max_execution_time", $max_execution_time_for_importexport);
2108 if ($model ===
'txt') {
2112 $list = $objmodelimport->listOfAvailableImportFormat($db);
2113 $importid =
GETPOST(
"importid",
'alphanohtml');
2117 $dir = DOL_DOCUMENT_ROOT.
"/core/modules/import/";
2118 $file =
"import_".$model.
".modules.php";
2119 $classname =
"Import".ucfirst($model);
2120 require_once $dir.$file;
2121 $obj =
new $classname($db, $datatoimport);
2122 '@phan-var-force ModeleImports $obj';
2123 $obj->importtriggermode = $importtriggermode;
2124 $obj->importissimulation = 0;
2125 if ($model ==
'csv') {
2126 '@phan-var-force ImportCsv $obj';
2127 $obj->separator = $separator_used;
2128 $obj->enclosure = $enclosure;
2132 $fieldssource = array();
2133 $result = $obj->import_open_file(
$conf->import->dir_temp.
'/'.$filetoimport);
2136 $arrayrecord = $obj->import_read_record();
2139 foreach ($arrayrecord as $key => $val) {
2140 $fieldssource[$i][
'example1'] =
dol_trunc($val[
'val'], 24);
2143 $obj->import_close_file();
2148 $param =
'&format='.$format.
'&datatoimport='.urlencode($datatoimport).
'&filetoimport='.urlencode($filetoimport).
'&nboflines='.((int) $nboflines).
'&importtriggermode='.urlencode($importtriggermode);
2149 if ($excludefirstline) {
2150 $param .=
'&excludefirstline='.urlencode($excludefirstline);
2153 $param .=
'&endatlinenb='.urlencode($endatlinenb);
2156 $param .=
'&separator='.urlencode($separator);
2159 $param .=
'&enclosure='.urlencode($enclosure);
2162 llxHeader(
'', $langs->trans(
"NewImport"), $help_url);
2168 print
'<div class="underbanner clearboth"></div>';
2169 print
'<div class="fichecenter">';
2171 print
'<table width="100%" class="border">';
2174 print
'<tr><td class="titlefieldcreate">'.$langs->trans(
"Module").
'</td>';
2176 $titleofmodule = $objimport->array_import_module[0][
'module']->getName();
2178 if (in_array($objimport->array_import_code[0], array(
'produit_supplierprices',
'produit_multiprice',
'produit_languages'))) {
2179 $titleofmodule = $langs->trans(
"ProductOrService");
2181 print $titleofmodule;
2185 print
'<tr><td>'.$langs->trans(
"DatasetToImport").
'</td>';
2187 $entity = preg_replace(
'/:.*$/',
'', $objimport->array_import_icon[0]);
2188 $entityicon = strtolower(!empty($entitytoicon[$entity]) ? $entitytoicon[$entity] : $entity);
2189 print img_object($objimport->array_import_module[0][
'module']->getName(), $entityicon).
' ';
2190 print $objimport->array_import_label[0];
2198 print
load_fiche_titre($langs->trans(
"InformationOnSourceFile"),
'',
'file-export');
2200 print
'<div class="underbanner clearboth"></div>';
2201 print
'<div class="fichecenter">';
2202 print
'<table width="100%" class="border tableforfield">';
2205 print
'<tr><td class="titlefieldcreate">'.$langs->trans(
"SourceFileFormat").
'</td>';
2206 print
'<td class="nowraponall">';
2207 $text = $objmodelimport->getDriverDescForKey($format);
2209 print $form->textwithpicto($objmodelimport->getDriverLabelForKey($format), $text);
2213 if ($model ==
'csv') {
2214 '@phan-var-force ImportCsv $obj';
2215 print
'<tr><td>'.$langs->trans(
"CsvOptions").
'</td>';
2217 print $langs->trans(
"Separator").
' : ';
2218 print htmlentities($separator);
2219 print
' '.$langs->trans(
"Enclosure").
' : ';
2220 print htmlentities($enclosure);
2225 print
'<tr><td>'.$langs->trans(
"FileToImport").
'</td>';
2227 $modulepart =
'import';
2228 $relativepath =
GETPOST(
'filetoimport');
2229 print
'<a data-ajax="false" href="'.DOL_URL_ROOT.
'/document.php?modulepart='.$modulepart.
'&file='.urlencode($relativepath).
'&step=4'.$param.
'" target="_blank" rel="noopener noreferrer">';
2230 print
img_mime($file,
'',
'pictofixedwidth');
2231 print $filetoimport;
2237 print $langs->trans(
"NbOfSourceLines");
2244 print $langs->trans(
"ImportFromLine");
2246 print
'<input type="text" size="4" name="excludefirstline" disabled="disabled" value="'.$excludefirstline.
'">';
2251 print $langs->trans(
"EndAtLineNb");
2253 print
'<input type="text" size="4" name="endatlinenb" disabled="disabled" value="'.$endatlinenb.
'">';
2258 print $langs->trans(
"ImportTriggerModeLabel");
2260 if ($importtriggermode ===
'fast_bulk') {
2261 print $langs->trans(
"ImportTriggerModeSummaryFast");
2263 print $langs->trans(
"ImportTriggerModeSummaryStrict");
2265 print
'<br><span class="opacitymedium">';
2266 print $langs->trans(
"ImportTriggerModeSummaryHint");
2275 print
'<b>'.$langs->trans(
"InformationOnTargetTables").
'</b>';
2276 print
'<div class="underbanner clearboth"></div>';
2277 print
'<div class="fichecenter">';
2278 print
'<table class="border centpercent">';
2281 print
'<tr><td width="25%">';
2282 print $langs->trans(
"TablesTarget");
2284 $listtables = array();
2285 foreach ($array_match_file_to_database as $code => $label) {
2287 if ($code > count($fieldssource)) {
2291 $alias = preg_replace(
'/(\..*)$/i',
'', $label);
2292 $listtables[$alias] = $objimport->array_import_tables[0][$alias];
2294 if (count($listtables)) {
2296 foreach ($listtables as $val) {
2315 print $langs->trans(
"Error");
2321 print $langs->trans(
"FieldsTarget").
'</td><td>';
2322 $listfields = array();
2324 $sort_array_match_file_to_database = $array_match_file_to_database;
2325 ksort($sort_array_match_file_to_database);
2327 foreach ($sort_array_match_file_to_database as $code => $label) {
2330 if ($code > count($fieldssource)) {
2334 $alias = preg_replace(
'/(\..*)$/i',
'', $label);
2335 $listfields[$i] = $langs->trans(
"Field").
' '.$code.
'->'.$label;
2337 print count($listfields) ? (implode(
', ', $listfields)) : $langs->trans(
"Error");
2344 $arrayoferrors = array();
2345 $arrayofwarnings = array();
2346 $maxnboferrors = !
getDolGlobalString(
'IMPORT_MAX_NB_OF_ERRORS') ? 50 :
$conf->global->IMPORT_MAX_NB_OF_ERRORS;
2347 $maxnbofwarnings = !
getDolGlobalString(
'IMPORT_MAX_NB_OF_WARNINGS') ? 50 :
$conf->global->IMPORT_MAX_NB_OF_WARNINGS;
2359 $pathfile =
$conf->import->dir_temp.
'/'.$filetoimport;
2360 $result = $obj->import_open_file($pathfile);
2362 global $tablewithentity_cache;
2363 $tablewithentity_cache = array();
2367 while ($sourcelinenb < $nboflines && !$endoffile) {
2369 $arrayrecord = $obj->import_read_record();
2370 if ($arrayrecord ===
false) {
2371 $arrayofwarnings[$sourcelinenb][0] = array(
'lib' => $langs->trans(
'ErrorFileLinesReachEOF', $nboflines, $sourcelinenb),
'type' =>
'EOF_RECORD_ON_SEVERAL_LINES');
2375 if ($excludefirstline && ($sourcelinenb < $excludefirstline)) {
2378 if ($endatlinenb && ($sourcelinenb > $endatlinenb)) {
2382 $parameters = array(
2384 'datatoimport' => $datatoimport,
2386 'arrayrecord' => $arrayrecord,
2387 'array_match_file_to_database' => $array_match_file_to_database,
2388 'objimport' => $objimport,
2389 'fieldssource' => $fieldssource,
2390 'importid' => $importid,
2391 'updatekeys' => $updatekeys,
2392 'importtriggermode' => $importtriggermode,
2393 'arrayoferrors' => &$arrayoferrors,
2394 'arrayofwarnings' => &$arrayofwarnings,
2398 $reshook = $hookmanager->executeHooks(
'ImportInsert', $parameters);
2400 $arrayoferrors[$sourcelinenb][] = [
2401 'lib' => implode(
"<br>", array_merge([$hookmanager->error], $hookmanager->errors))
2405 if (empty($reshook)) {
2407 $result = $obj->import_insert($arrayrecord, $array_match_file_to_database, $objimport, count($fieldssource), $importid, $updatekeys);
2409 if (count($obj->errors)) {
2410 $arrayoferrors[$sourcelinenb] = $obj->errors;
2412 if (count($obj->warnings)) {
2413 $arrayofwarnings[$sourcelinenb] = $obj->warnings;
2416 if (!count($obj->errors) && !count($obj->warnings)) {
2421 $reshook = $hookmanager->executeHooks(
'AfterImportInsert', $parameters);
2423 $arrayoferrors[$sourcelinenb][] = [
2424 'lib' => implode(
"<br>", array_merge([$hookmanager->error], $hookmanager->errors))
2429 $obj->import_close_file();
2431 print $langs->trans(
"ErrorFailedToOpenFile", $pathfile);
2434 if (count($arrayoferrors) > 0) {
2441 if (!empty($objimport->array_import_run_sql_after[0]) && is_array($objimport->array_import_run_sql_after[0])) {
2443 foreach ($objimport->array_import_run_sql_after[0] as $sqlafterimport) {
2445 $resqlafterimport = $db->query($sqlafterimport);
2446 if (!$resqlafterimport) {
2447 $arrayoferrors[
'none'][] = array(
'lib' => $langs->trans(
"Error running final request: ".$sqlafterimport));
2453 if (!$error && $importtriggermode ===
'fast_bulk') {
2454 $resbulktrigger = $obj->runImportBulkTrigger($importid, $user, $langs,
$conf);
2455 if ($resbulktrigger < 0) {
2456 $arrayoferrors[
'none'][] = array(
'lib' => $langs->trans(
"ErrorFailedTriggerCall"),
'type' =>
'TRIGGER');
2457 if (!empty($obj->errors) && is_array($obj->errors)) {
2458 foreach ($obj->errors as $tmperror) {
2459 $lib = (is_array($tmperror) ? ($tmperror[
'lib'] ??
'') : $tmperror);
2461 $arrayoferrors[
'none'][] = array(
'lib' => $lib,
'type' =>
'TRIGGER');
2478 if ($importtriggermode ===
'fast_bulk') {
2479 print
'<div class="warning">';
2480 print
'<b>'.$langs->trans(
"ImportTriggerModeFastBulkFinalWarningTitle").
'</b><br>';
2481 print $langs->trans(
"ImportTriggerModeFastBulkFinalWarning");
2488 print
'<div class="info">';
2489 print $langs->trans(
"NbOfLinesImported", $nbok).
'</b><br>';
2490 print $langs->trans(
"NbInsert", empty($obj->nbinsert) ? 0 : $obj->nbinsert).
'<br>';
2491 print $langs->trans(
"NbUpdate", empty($obj->nbupdate) ? 0 : $obj->nbupdate).
'<br>';
2493 print
'<div class="center">';
2494 print $langs->trans(
"FileWasImported", $importid).
'<br>';
2495 print
'<span class="opacitymedium">'.$langs->trans(
"YouCanUseImportIdToFindRecord", $importid).
'</span><br>';
2518 global
$conf, $langs;
2522 if ($key ==
'none') {
2524 print
"\n\n<!-- Box_no-key start-->\n";
2525 print
'<div class="box boximport" style="padding:0;">'.
"\n";
2526 print
'<table summary="boxtable_no-key" class="centpercent nobordernopadding">'.
"\n";
2528 print
"\n\n<!-- Box ".$pos.
" start -->\n";
2529 print
'<div class="box boximport" style="padding: 0;" id="boxto_'.$pos.
'">'.
"\n";
2531 print
'<table summary="boxtable'.$pos.
'" class="nobordernopadding centpercent tableimport">'.
"\n";
2534 if (($pos && $pos > count($fieldssource)) && (!isset($fieldssource[$pos][
"imported"]))) {
2544 } elseif ($key ==
'none') {
2545 print
'<tr style="height:'.$height.
'" class="trimport oddevenimport">';
2546 print
'<td class="nocellnopadd" width="16" style="font-weight: normal">';
2549 print
'<td style="font-weight: normal">';
2555 print
'<tr style="height:'.$height.
'" class="trimport oddevenimport">';
2556 print
'<td class="nocellnopadd" width="16" style="font-weight: normal">';
2559 print img_picto($langs->trans(
"Column").
' '.
num2Alpha($pos - 1),
'file',
'class="pictofixedwidth marginleftonly"');
2561 if (isset($fieldssource[$pos][
'imported']) && $fieldssource[$pos][
'imported'] ==
false) {
2562 print
'<td class="nowraponall boxtdunused" style="font-weight: normal">';
2564 print
'<td class="nowraponall tdoverflowmax500" style="font-weight: normal">';
2566 print $langs->trans(
"Column").
' '.
num2Alpha($pos - 1).
' (#'.$pos.
')';
2567 if (empty($fieldssource[$pos][
'example1'])) {
2568 $example = $fieldssource[$pos][
'label'];
2570 $example = $fieldssource[$pos][
'example1'];
2574 $example = mb_convert_encoding($example,
'UTF-8',
'ISO-8859-1');
2578 print
'<i class="opacitymedium">'.dol_escape_htmltag($example).
'</i>';
2587 print
"<!-- Box end -->\n\n";
2600 $i = count($fieldssource) + 1;
2603 foreach ($listofkey as $key => $val) {
2604 $maxkey = max($maxkey, $key);
2607 while ($i <= $maxkey) {
2608 if (empty($listofkey[$i])) {
2630 if ($position == count($array)) {
2631 $ret = $array + $insertArray;
2634 foreach ($array as $key => $value) {
2635 if ($position == $i++) {
2636 $ret += $insertArray;
2639 $ret[$key] = $value;
ajax_combobox($htmlname, $events=array(), $minLengthToAutocomplete=0, $forcefocus=0, $widthTypeOfAutocomplete='resolve', $idforemptyvalue='-1', $morecss='', $placeholder='')
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.
dolExplodeIntoArray($string, $delimiter=';', $kv='=')
Split a string with 2 keys into key array.
dol_string_nohtmltag($stringtoclean, $removelinefeed=1, $pagecodeto='UTF-8', $strip_tags=0, $removedoublespaces=1)
Clean a string from all HTML tags and entities.
dol_sanitizeFileName($str, $newstr='_', $unaccent=1, $includequotes=0, $allowdash=0)
Clean a string to use it as a file name.
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).
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.
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_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_get_fiche_end($notab=0)
Return tab footer of a card.
img_mime($file, $titlealt='', $morecss='')
Show MIME img of a file.
load_fiche_titre($title, $morehtmlright='', $picto='generic', $pictoisfullpath=0, $id='', $morecssontable='', $morehtmlcenter='', $morecssonpicto='widthpictotitle')
Load a title with picto.
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_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags='', $escapeonlyhtmltags=0, $cleanalsojavascript=0)
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.
restrictedArea(User $user, $features, $object=0, $tableandshare='', $feature2='', $dbt_keyfield='fk_soc', $dbt_select='rowid', $isdraft=0, $nodie=0, $mode='')
Check permissions of a user to show a page and an object.
getMaxFileSizeArray()
Return the max allowed for file upload.