dolibarr 25.0.0-alpha
import.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2005-2016 Laurent Destailleur <eldy@users.sourceforge.net>
3 * Copyright (C) 2005-2009 Regis Houssin <regis.houssin@inodbox.com>
4 * Copyright (C) 2012 Christophe Battarel <christophe.battarel@altairis.fr>
5 * Copyright (C) 2022 Charlene Benke <charlene@patas-monkey.com>
6 * Copyright (C) 2024-2026 MDW <mdeweerd@users.noreply.github.com>
7 * Copyright (C) 2024-2026 Frédéric France <frederic.france@free.fr>
8 *
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 3 of the License, or
12 * (at your option) any later version.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License
20 * along with this program. If not, see <https://www.gnu.org/licenses/>.
21 */
22
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';
44
45// Load translation files required by the page
46$langs->loadLangs(array('exports', 'compta', 'projects', 'admin', 'products', 'margins'));
47
48// Initialize a technical object to manage hooks of page. Note that conf->hooks_modules contains an array of hook context
49$hookmanager->initHooks(array('imports'));
50
51// Security check
52$result = restrictedArea($user, 'import');
53
54// Map icons, array duplicated in export.php, was not synchronized, TODO put it somewhere only once
55$entitytoicon = array(
56 'invoice' => 'bill',
57 'invoice_line' => 'bill',
58 'order' => 'order',
59 'order_line' => 'order',
60 'propal' => 'propal',
61 'propal_line' => 'propal',
62 'intervention' => 'intervention',
63 'inter_line' => 'intervention',
64 'member' => 'user',
65 'member_type' => 'group',
66 'subscription' => 'payment',
67 'payment' => 'payment',
68 'tax' => 'bill',
69 'tax_type' => 'generic',
70 'other' => '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',
79 'stock' => 'stock',
80 'warehouse' => 'stock',
81 'batch' => 'stock',
82 'stockbatch' => 'stock',
83 'category' => 'category',
84 'shipment' => 'sending',
85 'shipment_line' => 'sending',
86 'project' => 'project',
87 'task' => 'tasks',
88 'reception' => 'sending',
89 'reception_line' => 'sending',
90 'expensereport' => 'trip',
91 'expensereport_line' => 'trip',
92 'holiday' => 'holiday',
93 'contract_line' => 'contract',
94 'translation' => 'generic',
95 'bomm' => 'bom',
96 'bomline' => 'bom'
97);
98
99// Translation code, array duplicated in export.php, was not synchronized, TODO put it somewhere only once
100$entitytolang = array(
101 'user' => 'User',
102 'company' => 'Company',
103 'contact' => 'Contact',
104 'invoice' => 'Bill',
105 'invoice_line' => 'InvoiceLine',
106 'order' => 'Order',
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',
127 'stock' => 'Stock',
128 'movement' => 'StockMovement',
129 'batch' => 'Batch',
130 'stockbatch' => 'StockDetailPerBatch',
131 'warehouse' => 'Warehouse',
132 'category' => 'Category',
133 'other' => 'Other',
134 'trip' => 'TripsAndExpenses',
135 'shipment' => 'Shipments',
136 'shipment_line' => 'ShipmentLine',
137 'project' => 'Projects',
138 'projecttask' => 'Tasks',
139 'task_time' => 'TaskTimeSpent',
140 'action' => 'Event',
141 'expensereport' => 'ExpenseReport',
142 'expensereport_line' => 'ExpenseReportLine',
143 'holiday' => 'TitreRequestCP',
144 'contract' => 'Contract',
145 'contract_line' => 'ContractLine',
146 'translation' => 'Translation',
147 'bom' => 'BOM',
148 'bomline' => 'BOMLine'
149);
150
151$datatoimport = GETPOST('datatoimport');
152$format = GETPOST('format');
153$filetoimport = GETPOST('filetoimport');
154$action = GETPOST('action', 'alpha');
155$confirm = GETPOST('confirm', 'alpha');
156$step = (GETPOST('step') ? GETPOST('step') : 1);
157$import_name = GETPOST('import_name');
158$hexa = GETPOST('hexa');
159$importmodelid = GETPOSTINT('importmodelid');
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) : ''); // We must use 'nohtml' and not 'alphanohtml' because we must accept "
165$enclosure = (GETPOST('enclosure', 'nohtml') ? GETPOST('enclosure', 'nohtml') : '"'); // We must use 'nohtml' and not 'alphanohtml' because we must accept "
166$charset = GETPOST('charset', 'aZ09');
167$separator_used = str_replace('\t', "\t", $separator);
168$relativepath = '';
169
170if (empty($importtriggermode)) {
171 $importtriggermode = getDolGlobalString('IMPORT_TRIGGER_MODE_DEFAULT', 'strict_line');
172}
173if (!in_array($importtriggermode, array('strict_line', 'fast_bulk'), true)) {
174 $importtriggermode = 'strict_line';
175}
176
177$objimport = new Import($db);
178$objimport->load_arrays($user, ($step == 1 ? '' : $datatoimport));
179
180if (empty($updatekeys) && !empty($objimport->array_import_preselected_updatekeys[0])) {
181 $updatekeys = $objimport->array_import_preselected_updatekeys[0];
182}
183
184$objmodelimport = new ModeleImports();
185
186$form = new Form($db);
187$htmlother = new FormOther($db);
188
189// Init $array_match_file_to_database from _SESSION
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);
196 $key = $tabelem[0];
197 $val = (isset($tabelem[1]) ? $tabelem[1] : '');
198 if ($key && $val) {
199 $array_match_file_to_database[$key] = $val;
200 }
201 }
202}
203
204
205/*
206 * Actions
207 */
208
209if ($action == 'deleteprof' && $user->hasRight('import', 'run')) {
210 if (GETPOSTINT("id")) {
211 $objimport->fetch(GETPOSTINT("id"));
212 $result = $objimport->delete($user);
213 if ($result < 0) {
214 setEventMessages($objimport->error, $objimport->errors, 'errors');
215 }
216 }
217}
218
219// Save import config to database
220if ($action == 'add_import_model' && $user->hasRight('import', 'run')) {
221 if ($import_name) {
222 // Set save string
223 $hexa = '';
224 foreach ($array_match_file_to_database as $key => $val) {
225 if ($hexa) {
226 $hexa .= ',';
227 }
228 $hexa .= $key.'='.$val;
229 }
230
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);
235
236 $result = $objimport->create($user);
237 if ($result >= 0) {
238 setEventMessages($langs->trans("ImportModelSaved", $objimport->model_name), null, 'mesgs');
239 $import_name = '';
240 } else {
241 $langs->load("errors");
242 if ($objimport->errno == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
243 setEventMessages($langs->trans("ErrorImportDuplicateProfil"), null, 'errors');
244 } else {
245 setEventMessages($objimport->error, null, 'errors');
246 }
247 }
248 } else {
249 setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("ImportModelName")), null, 'errors');
250 }
251}
252
253if ($step == 2 && $datatoimport) {
254 if (GETPOST('sendit') && getDolGlobalString('MAIN_UPLOAD_DOC')) {
255 dol_mkdir($conf->import->dir_temp);
256 $nowyearmonth = dol_print_date(dol_now(), '%Y%m%d%H%M%S');
257
258 $fullpath = $conf->import->dir_temp."/".$nowyearmonth.'-'.dol_string_nohtmltag(dol_sanitizeFileName($_FILES['userfile']['name']));
259 // Note: the returned value is a string when the file was refused and, in PHP 8, such a string compares as greater than 0
260 $resultupload = dol_move_uploaded_file($_FILES['userfile']['tmp_name'], $fullpath, 1);
261 if (is_numeric($resultupload) && $resultupload > 0) {
262 dol_syslog("File ".$fullpath." was added for import");
263 } else {
264 $langs->load("errors");
265 setEventMessages($langs->trans("ErrorFailedToSaveFile"), null, 'errors');
266 }
267 }
268
269 // Delete file
270 if ($action == 'confirm_deletefile' && $confirm == 'yes' && $user->hasRight('import', 'run')) {
271 $langs->load("other");
272
273 $param = '&datatoimport='.urlencode($datatoimport).'&format='.urlencode($format);
274 if ($excludefirstline) {
275 $param .= '&excludefirstline='.urlencode($excludefirstline);
276 }
277 if ($endatlinenb) {
278 $param .= '&endatlinenb='.urlencode($endatlinenb);
279 }
280
281 $file = $conf->import->dir_temp.'/'.GETPOST('urlfile');
282 $ret = dol_delete_file($file, 1);
283 if ($ret) {
284 setEventMessages($langs->trans("FileWasRemoved", GETPOST('urlfile')), null, 'mesgs');
285 } else {
286 $langs->load('errors');
287 setEventMessages($langs->trans("ErrorFailToDeleteFile", GETPOST('urlfile')), null, 'errors');
288 }
289 header('Location: '.$_SERVER["PHP_SELF"].'?step='.$step.$param);
290 exit;
291 }
292}
293
294if ($step == 4 && $action == 'select_model' && $user->hasRight('import', 'run')) {
295 // Reinit match arrays
296 $_SESSION["dol_array_match_file_to_database"] = '';
297 $serialized_array_match_file_to_database = '';
298 $array_match_file_to_database = array();
299
300 // Load model from $importmodelid and set $array_match_file_to_database
301 // and $_SESSION["dol_array_match_file_to_database"]
302 $result = $objimport->fetch($importmodelid);
303 if ($result > 0) {
304 $serialized_array_match_file_to_database = $objimport->hexa;
305 $fieldsarray = explode(',', $serialized_array_match_file_to_database);
306 foreach ($fieldsarray as $elem) {
307 $tabelem = explode('=', $elem);
308 $key = $tabelem[0];
309 $val = $tabelem[1];
310 if ($key && $val) {
311 $array_match_file_to_database[$key] = $val;
312 }
313 }
314 $_SESSION["dol_array_match_file_to_database"] = $serialized_array_match_file_to_database;
315 $_SESSION['dol_array_match_file_to_database_select'] = $_SESSION["dol_array_match_file_to_database"];
316 }
317}
318if ($action == 'saveselectorder' && $user->hasRight('import', 'run')) {
319 // Save the position of the fields
320 $serialized_array_match_file_to_database = '';
321 dol_syslog("selectorder=".GETPOST('selectorder'), LOG_DEBUG);
322 $selectorder = explode(",", GETPOST('selectorder'));
323 $fieldtarget = $fieldstarget = $objimport->array_import_fields[0];
324 foreach ($selectorder as $key => $code) {
325 $serialized_array_match_file_to_database .= $key.'='.$code;
326 $serialized_array_match_file_to_database .= ',';
327 }
328 $serialized_array_match_file_to_database = substr($serialized_array_match_file_to_database, 0, -1);
329 dol_syslog('dol_array_match_file_to_database_select='.$serialized_array_match_file_to_database);
330 $_SESSION["dol_array_match_file_to_database_select"] = $serialized_array_match_file_to_database;
331 echo "{}";
332 exit(0);
333}
334
335
336/*
337 * View
338 */
339
340$help_url = 'EN:Module_Imports_En|FR:Module_Imports|ES:M&oacute;dulo_Importaciones';
341
342// STEP 1: Page to select dataset to import
343if ($step == 1 || !$datatoimport) {
344 // Clean saved file-database matching
345 $serialized_array_match_file_to_database = '';
346 $array_match_file_to_database = array();
347 $_SESSION["dol_array_match_file_to_database"] = '';
348 $_SESSION["dol_array_match_file_to_database_select"] = '';
349
350 $param = '';
351 if ($excludefirstline) {
352 $param .= '&excludefirstline='.urlencode($excludefirstline);
353 }
354 if ($endatlinenb) {
355 $param .= '&endatlinenb='.urlencode($endatlinenb);
356 }
357 if ($separator) {
358 $param .= '&separator='.urlencode($separator);
359 }
360 if ($enclosure) {
361 $param .= '&enclosure='.urlencode($enclosure);
362 }
363
364 llxHeader('', $langs->trans("NewImport"), $help_url);
365
366 $head = import_prepare_head($param, 1);
367
368 print dol_get_fiche_head($head, 'step1', 'Import', -1, 'upload');
369
370 print '<div class="opacitymedium">'.$langs->trans("SelectImportDataSet").'</div>';
371
372
373 // Define $nbmodulesnotautoenabled - TODO This code is at different places
374 $nbmodulesnotautoenabled = count($conf->modules);
375 $listofmodulesautoenabled = array('user', 'agenda', 'fckeditor', 'export', 'import');
376 foreach ($listofmodulesautoenabled as $moduleautoenable) {
377 if (in_array($moduleautoenable, $conf->modules)) {
378 $nbmodulesnotautoenabled--;
379 }
380 }
381
382 if ($user->admin && $nbmodulesnotautoenabled < getDolGlobalInt('MAIN_MIN_NB_ENABLED_MODULE_FOR_WARNING', 1)) { // If only minimal initial modules enabled
383 print info_admin($langs->trans("WarningOnlyProfilesOfActivatedModules").' '.$langs->trans("YouCanEnableModulesFrom"));
384 }
385
386 print '<br>';
387
388 // Show profile for import
389 print '<div class="div-table-responsive-no-min">'; // You can use div-table-responsive-no-min if you don't need reserved height for your table
390 print '<table class="noborder centpercent nomarginbottom">';
391 print '<tr class="liste_titre">';
392 print '<td>'.$langs->trans("Module").'</td>';
393 print '<td>'.$langs->trans("ImportableDatas").'</td>';
394 print '<td>&nbsp;</td>';
395 print '</tr>';
396
397 if (count($objimport->array_import_module)) {
398 $sortedarrayofmodules = dol_sort_array($objimport->array_import_module, 'position_of_profile', 'asc', 0, 0, 1);
399 foreach ($sortedarrayofmodules as $key => $value) {
400 //var_dump($key.' '.$value['position_of_profile'].' '.$value['import_code'].' '.$objimport->array_import_module[$key]['module']->getName().' '.$objimport->array_import_code[$key]);
401 $titleofmodule = $objimport->array_import_module[$key]['module']->getName();
402 print '<tr class="oddeven"><td class="tdoverflowmax200" title="'.dolPrintHTML($titleofmodule).'">';
403 // Special case for import common to module/services
404 if (in_array($objimport->array_import_code[$key], array('produit_supplierprices', 'produit_multiprice', 'produit_languages'))) {
405 $titleofmodule = $langs->trans("ProductOrService");
406 }
407 print dolPrintHTML($titleofmodule);
408 print '</td><td>';
409 $entity = preg_replace('/:.*$/', '', $objimport->array_import_icon[$key]);
410 $entityicon = strtolower(!empty($entitytoicon[$entity]) ? $entitytoicon[$entity] : $entity);
411 $label = $objimport->array_import_label[$key];
412 print '<div class="twolinesmax-normallineheight minwidth200onall">';
413 print img_object($objimport->array_import_module[$key]['module']->getName(), $entityicon, 'class="pictofixedwidth"');
414 print dolPrintHTML($label);
415 print '</div>';
416 print '</td><td style="text-align: right">';
417 if ($objimport->array_import_perms[$key]) {
418 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 } else {
420 print $langs->trans("NotEnoughPermissions");
421 }
422 print '</td></tr>';
423 }
424 } else {
425 print '<tr><td class="oddeven" colspan="3">'.$langs->trans("NoImportableData").'</td></tr>';
426 }
427 print '</table>';
428 print '</div>';
429
430 print dol_get_fiche_end();
431}
432
433
434// STEP 2: Page to select file
435if ($step == 2 && $datatoimport) {
436 $param = '&datatoimport='.urlencode($datatoimport);
437 if ($excludefirstline) {
438 $param .= '&excludefirstline='.urlencode($excludefirstline);
439 }
440 if ($endatlinenb) {
441 $param .= '&endatlinenb='.urlencode($endatlinenb);
442 }
443 if ($separator) {
444 $param .= '&separator='.urlencode($separator);
445 }
446 if ($enclosure) {
447 $param .= '&enclosure='.urlencode($enclosure);
448 }
449
450 $list = $objmodelimport->listOfAvailableImportFormat($db);
451
452 llxHeader('', $langs->trans("NewImport"), $help_url);
453
454 $head = import_prepare_head($param, 2);
455
456 print dol_get_fiche_head($head, 'step2', 'Import', -2, 'upload');
457
458 /*
459 * Confirm delete file
460 */
461 if ($action == 'delete') {
462 print $form->formconfirm($_SERVER["PHP_SELF"].'?urlfile='.urlencode(GETPOST('urlfile')).'&step=2'.$param, $langs->trans('DeleteFile'), $langs->trans('ConfirmDeleteFile'), 'confirm_deletefile', '', 0, 1);
463 }
464
465 print '<div class="underbanner clearboth"></div>';
466 print '<div class="fichecenter">';
467
468 print '<table class="border tableforfield centpercent">';
469
470 // Module
471 print '<tr><td class="titlefieldcreate">'.$langs->trans("Module").'</td>';
472 print '<td>';
473 $titleofmodule = $objimport->array_import_module[0]['module']->getName();
474 // Special case for import common to module/services
475 if (in_array($objimport->array_import_code[0], array('produit_supplierprices', 'produit_multiprice', 'produit_languages'))) {
476 $titleofmodule = $langs->trans("ProductOrService");
477 }
478 print $titleofmodule;
479 print '</td></tr>';
480
481 // Lot de donnees a importer
482 print '<tr><td>'.$langs->trans("DatasetToImport").'</td>';
483 print '<td>';
484 $entity = preg_replace('/:.*$/', '', $objimport->array_import_icon[0]);
485 $entityicon = strtolower(!empty($entitytoicon[$entity]) ? $entitytoicon[$entity] : $entity);
486 print img_object($objimport->array_import_module[0]['module']->getName(), $entityicon).' ';
487 print $objimport->array_import_label[0];
488 print '</td></tr>';
489
490 print '</table>';
491 print '</div>';
492
493 /*print '<br>';
494
495 print load_fiche_titre($langs->trans("InformationOnSourceFile"), '', 'file-export');
496
497 print '<div class="underbanner clearboth"></div>';
498 print '<div class="fichecenter">';
499 print '<table width="100%" class="border tableforfield">';
500
501 // Source file format
502 print '<tr><td class="titlefieldcreate">'.$langs->trans("SourceFileFormat").'</td>';
503 print '<td class="nowraponall">';
504 $text = $objmodelimport->getDriverDescForKey($format);
505 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
506 print $form->textwithpicto($objmodelimport->getDriverLabelForKey($format), $text);
507 print '</td><td style="text-align:right" class="nowrap">';
508 print $form->textwithpicto('', $langs->trans("DownloadEmptyExample").'.<br>'.$langs->trans("StarAreMandatory"));
509 print '</td></tr>';
510
511 print '</table>';
512 print '</div>';*/
513
514 print dol_get_fiche_end();
515
516
517 if ($format == 'xlsx' && !class_exists('XMLWriter')) {
518 $langs->loadLangs(array("install", "errors"));
519 print info_admin($langs->trans("ErrorPHPDoesNotSupport", 'php-xml'), 0, 0, '1', 'error');
520 }
521
522
523 print '<br><br>';
524
525 print '<form name="userfile" action="'.$_SERVER["PHP_SELF"].'" enctype="multipart/form-data" method="POST">';
526 print '<input type="hidden" name="token" value="'.newToken().'">';
527 print '<input type="hidden" value="'.$step.'" name="step">';
528 print '<input type="hidden" value="'.dol_escape_htmltag($format).'" name="format">';
529 print '<input type="hidden" value="'.$excludefirstline.'" name="excludefirstline">';
530 print '<input type="hidden" value="'.$endatlinenb.'" name="endatlinenb">';
531 print '<input type="hidden" value="'.dol_escape_htmltag($separator).'" name="separator">';
532 print '<input type="hidden" value="'.dol_escape_htmltag($enclosure).'" name="enclosure">';
533 print '<input type="hidden" value="'.dol_escape_htmltag($datatoimport).'" name="datatoimport">';
534
535 print '<span class="opacitymedium">';
536 $s = $langs->trans("ChooseFileToImport", '{s1}');
537 $s = str_replace('{s1}', img_picto('', 'next'), $s);
538 print $s;
539 print '</span><br><br>';
540
541 $filetoimport = '';
542
543 // Add format information and link to download example
544 print '<table class="noborder centpercent" cellpadding="4">';
545
546 print '<tr class="liste_titre"><td colspan="4">';
547 print $langs->trans("FileMustHaveOneOfFollowingFormat").'...';
548 print '</td></tr>';
549 $list = $objmodelimport->listOfAvailableImportFormat($db);
550 foreach ($list as $key) {
551 print '<tr class="oddeven">';
552 print '<td width="16">'.img_picto_common($key, $objmodelimport->getPictoForKey($key)).'</td>';
553 $htmltext = $objmodelimport->getDriverDescForKey($key);
554 print '<td>'.$form->textwithpicto($objmodelimport->getDriverLabelForKey($key), $htmltext).'</td>';
555 print '<td style="text-align:center">';
556 if (empty($objmodelimport->drivererror[$key])) {
557 $filename = $langs->transnoentitiesnoconv("ExampleOfImportFile").'_'.$datatoimport.'.'.$key;
558 print '<a href="'.DOL_URL_ROOT.'/imports/emptyexample.php?format='.$key.$param.'&output=file&file='.urlencode($filename).'" target="_blank" rel="noopener noreferrer">';
559 print img_picto('', 'download', 'class="paddingright opacitymedium"');
560 print $langs->trans("DownloadEmptyExampleShort");
561 print '</a>';
562 print $form->textwithpicto('', $langs->trans("DownloadEmptyExample").'.<br>'.$langs->trans("StarAreMandatory"));
563 } else {
564 print dolPrintHTML($objmodelimport->drivererror[$key]);
565 }
566 print '</td>';
567 print '</tr>';
568 }
569
570 print '</table>';
571
572
573 print '<br>';
574
575 // Input file name box
576 print '<div class="marginbottomonly">';
577 $maxfilesizearray = getMaxFileSizeArray();
578 $maxmin = $maxfilesizearray['maxmin'];
579 if ($maxmin > 0) {
580 print '<input type="hidden" name="MAX_FILE_SIZE" value="'.($maxmin * 1024).'">'; // MAX_FILE_SIZE must precede the field type=file
581 }
582 print '<input type="file" name="userfile" size="20" maxlength="80"> &nbsp; &nbsp; ';
583 $out = (!getDolGlobalString('MAIN_UPLOAD_DOC') ? ' disabled' : '');
584 print '<input type="submit" class="button small" value="'.$langs->trans("AddFile").'"'.$out.' name="sendit">';
585 $out = '';
586 if (getDolGlobalString('MAIN_UPLOAD_DOC')) {
587 $max = getDolGlobalString('MAIN_UPLOAD_DOC'); // In Kb
588 $maxphp = @ini_get('upload_max_filesize'); // In unknown
589 if (preg_match('/k$/i', $maxphp)) {
590 $maxphp = (int) substr($maxphp, 0, -1);
591 }
592 if (preg_match('/m$/i', $maxphp)) {
593 $maxphp = (int) substr($maxphp, 0, -1) * 1024;
594 }
595 if (preg_match('/g$/i', $maxphp)) {
596 $maxphp = (int) substr($maxphp, 0, -1) * 1024 * 1024;
597 }
598 if (preg_match('/t$/i', $maxphp)) {
599 $maxphp = (int) substr($maxphp, 0, -1) * 1024 * 1024 * 1024;
600 }
601 $maxphp2 = @ini_get('post_max_size'); // In unknown
602 if (preg_match('/k$/i', $maxphp2)) {
603 $maxphp2 = (int) substr($maxphp2, 0, -1);
604 }
605 if (preg_match('/m$/i', $maxphp2)) {
606 $maxphp2 = (int) substr($maxphp2, 0, -1) * 1024;
607 }
608 if (preg_match('/g$/i', $maxphp2)) {
609 $maxphp2 = (int) substr($maxphp2, 0, -1) * 1024 * 1024;
610 }
611 if (preg_match('/t$/i', $maxphp2)) {
612 $maxphp2 = (int) substr($maxphp2, 0, -1) * 1024 * 1024 * 1024;
613 }
614 // Now $max and $maxphp and $maxphp2 are in Kb
615 $maxmin = $max;
616 $maxphptoshow = $maxphptoshowparam = '';
617 if ($maxphp > 0) {
618 $maxmin = min($max, $maxphp);
619 $maxphptoshow = $maxphp;
620 $maxphptoshowparam = 'upload_max_filesize';
621 }
622 if ($maxphp2 > 0) {
623 $maxmin = min($max, $maxphp2);
624 if ($maxphp2 < $maxphp) {
625 $maxphptoshow = $maxphp2;
626 $maxphptoshowparam = 'post_max_size';
627 }
628 }
629
630 $langs->load('other');
631 $out .= ' ';
632 $out .= info_admin($langs->trans("ThisLimitIsDefinedInSetup", $max, $maxphptoshow), 1);
633 } else {
634 $out .= ' ('.$langs->trans("UploadDisabled").')';
635 }
636 print $out;
637
638 print '<br><br>';
639
640 // Search available imports
641 $filearray = dol_dir_list($conf->import->dir_temp, 'files', 0, '', '', 'name', SORT_DESC);
642 if (count($filearray) > 0) {
643 print '<div class="div-table-responsive-no-min">'; // You can use div-table-responsive-no-min if you don't need reserved height for your table
644 print '<table class="noborder centpercent" width="100%" cellpadding="4">';
645
646 $dir = $conf->import->dir_temp;
647
648 // Search available files to import
649 $i = 0;
650 foreach ($filearray as $key => $val) {
651 $file = $val['name'];
652
653 // readdir return value in ISO and we want UTF8 in memory
654 if (!utf8_check($file)) {
655 $file = mb_convert_encoding($file, 'UTF-8', 'ISO-8859-1');
656 }
657
658 if (preg_match('/^\./', $file)) {
659 continue;
660 }
661
662 $modulepart = 'import';
663 $urlsource = $_SERVER["PHP_SELF"].'?step='.$step.$param.'&filetoimport='.urlencode($filetoimport);
664 $relativepath = $file;
665
666 print '<tr class="oddeven">';
667 print '<td>';
668 print img_mime($file, '', 'pictofixedwidth');
669 print '<a data-ajax="false" href="'.DOL_URL_ROOT.'/document.php?modulepart='.$modulepart.'&file='.urlencode($relativepath).'&step=2'.$param.'" target="_blank" rel="noopener noreferrer">';
670 print $file;
671 print '</a>';
672 print '</td>';
673 // Affiche taille fichier
674 print '<td style="text-align:right">'.dol_print_size(dol_filesize($dir.'/'.$file)).'</td>';
675 // Affiche date fichier
676 print '<td style="text-align:right">'.dol_print_date(dol_filemtime($dir.'/'.$file), 'dayhour').'</td>';
677 // Del button
678 print '<td style="text-align:right"><a href="'.$_SERVER['PHP_SELF'].'?action=delete&token='.newToken().'&step=2'.$param.'&urlfile='.urlencode($relativepath);
679 print '">'.img_delete().'</a></td>';
680 // Action button
681 print '<td style="text-align:right">';
682 print '<a href="'.$_SERVER['PHP_SELF'].'?step=3'.$param.'&filetoimport='.urlencode($relativepath).'">'.img_picto($langs->trans("ImportThisFile"), 'next', 'class="fa-15"').'</a>';
683 print '</td>';
684 print '</tr>';
685 }
686
687 print '</table>';
688 print '</div>';
689 }
690
691 print '</form>';
692}
693
694
695// STEP 3: Page to make matching between source file and database fields
696if ($step == 3 && $datatoimport) {
697 //var_dump($_SESSION["dol_array_match_file_to_database_select"]);
698 $serialized_array_match_file_to_database = isset($_SESSION["dol_array_match_file_to_database_select"]) ? $_SESSION["dol_array_match_file_to_database_select"] : '';
699 $fieldsarray = explode(',', $serialized_array_match_file_to_database);
700 $array_match_file_to_database = array(); // Same than $fieldsarray but with mapped value only (col1 => 's.fielda', col2 => 's.fieldb'...)
701 foreach ($fieldsarray as $elem) {
702 $tabelem = explode('=', $elem, 2);
703 $key = $tabelem[0];
704 $val = (isset($tabelem[1]) ? $tabelem[1] : '');
705 if ($key && $val) {
706 $array_match_file_to_database[$key] = $val;
707 }
708 }
709
710 //var_dump($serialized_array_match_file_to_database);
711 //var_dump($fieldsarray);
712 //var_dump($array_match_file_to_database);
713 if (empty($format) && !empty($filetoimport)) {
714 $format = pathinfo($filetoimport, PATHINFO_EXTENSION);
715 }
716
717 $model = $format;
718
719 // Fallback: txt to csv (import_txt.modules.php does not exist)
720 if ($model === 'txt') {
721 $model = 'csv';
722 }
723
724 $list = $objmodelimport->listOfAvailableImportFormat($db);
725
726 if (empty($separator)) {
727 $separator = (!getDolGlobalString('IMPORT_CSV_SEPARATOR_TO_USE') ? ',' : $conf->global->IMPORT_CSV_SEPARATOR_TO_USE);
728 }
729
730 // The separator has been defined, if it is a unique char, we check it is valid by reading the source file
731 if ($model == 'csv' && strlen($separator) == 1 && !GETPOSTISSET('separator')) {
732 '@phan-var-force ImportCsv $obj';
733 // Count the char in first line of file.
734 $fh = fopen($conf->import->dir_temp.'/'.$filetoimport, 'r');
735 if ($fh) {
736 $sline = fgets($fh, 1000000);
737 fclose($fh);
738 $nboccurence = substr_count($sline, $separator);
739 $nboccurencea = substr_count($sline, ',');
740 $nboccurenceb = substr_count($sline, ';');
741 //var_dump($nboccurence." ".$nboccurencea." ".$nboccurenceb);exit;
742 if ($nboccurence == 0) {
743 if ($nboccurencea > 2) {
744 $separator = ',';
745 } elseif ($nboccurenceb > 2) {
746 $separator = ';';
747 }
748 }
749 }
750 }
751
752 // The value to use
753 $separator_used = str_replace('\t', "\t", $separator);
754
755 // Create class to use for import
756 $dir = DOL_DOCUMENT_ROOT."/core/modules/import/";
757 $file = "import_".$model.".modules.php";
758 $classname = "Import".ucfirst($model);
759 require_once $dir.$file;
760 $obj = new $classname($db, $datatoimport);
761 '@phan-var-force ModeleImports $obj';
762
763 if (!empty($obj->error)) {
764 $langs->load("errors");
765 $param = '&datatoimport='.$datatoimport.'&format='.$format;
766 setEventMessages($obj->error, null, 'errors');
767 header("Location: ".$_SERVER["PHP_SELF"].'?step=2'.$param.'&filetoimport='.urlencode($relativepath));
768 exit;
769 }
770
771 if ($model == 'csv') {
772 '@phan-var-force ImportCsv $obj';
773 $obj->separator = $separator_used;
774 $obj->enclosure = $enclosure;
775 $obj->charset = '';
776 }
777 if ($model == 'xlsx') {
778 '@phan-var-force ImportXlsx $obj';
779 if (!preg_match('/\.xlsx$/i', $filetoimport)) {
780 $langs->load("errors");
781 $param = '&datatoimport='.$datatoimport.'&format='.$format;
782 setEventMessages($langs->trans("ErrorFileMustHaveFormat", $model), null, 'errors');
783 header("Location: ".$_SERVER["PHP_SELF"].'?step=2'.$param.'&filetoimport='.urlencode($relativepath));
784 exit;
785 }
786 }
787
788 if (GETPOST('update')) {
789 $array_match_file_to_database = array();
790 }
791
792 // Load the source fields from input file into variable $arrayrecord
793 $fieldssource = array();
795 $result = $obj->import_open_file($conf->import->dir_temp.'/'.$filetoimport);
796 if ($result >= 0) {
797 // Read first line
798 $arrayrecord = $obj->import_read_record();
799
800 // Create array $fieldssource starting with 1 with values found of first line.
801 $i = 1;
802 foreach ($arrayrecord as $key => $val) {
803 if ($val["type"] != -1) {
804 $fieldssource[$i]['example1'] = dol_trunc($val['val'], 128);
805 } else {
806 $fieldssource[$i]['example1'] = $langs->trans('Empty');
807 }
808 $fieldssource[$i]['imported'] = false;
809 $i++;
810 }
811 $obj->import_close_file();
812 }
813
814 // Load targets fields in database
815 $fieldstarget = $objimport->array_import_fields[0];
816 $minpos = min(count($fieldssource), count($fieldstarget));
817 //var_dump($array_match_file_to_database);
818
819
820 $initialloadofstep4 = false;
821 if (empty($_SESSION['dol_array_match_file_to_database_select'])) {
822 $initialloadofstep4 = true;
823 }
824
825 // Is it a first time in page (if yes, we must initialize array_match_file_to_database)
826 if (count($array_match_file_to_database) == 0) {
827 // This is first input in screen, we need to define
828 // $array_match_file_to_database
829 // $serialized_array_match_file_to_database
830 // $_SESSION["dol_array_match_file_to_database"]
831 $pos = 1;
832 $num = count($fieldssource);
833 while ($pos <= $num) {
834 if ($num >= 1 && $pos <= $num) {
835 $posbis = 1;
836 foreach ($fieldstarget as $key => $val) {
837 if ($posbis < $pos) {
838 $posbis++;
839 continue;
840 }
841 // We found the key of targets that is at position pos
842 $array_match_file_to_database[$pos] = $key;
843 break;
844 }
845 }
846 $pos++;
847 }
848 }
849 $array_match_database_to_file = array_flip($array_match_file_to_database);
850 //var_dump($array_match_database_to_file);
851 //var_dump($_SESSION["dol_array_match_file_to_database_select"]);
852
853 $fieldstarget_tmp = array();
854 $arraykeysfieldtarget = array_keys($fieldstarget);
855 $position = 0;
856 foreach ($fieldstarget as $key => $label) {
857 $isrequired = preg_match('/\*$/', $label);
858 if (!empty($isrequired)) {
859 $newlabel = substr($label, 0, -1);
860 $fieldstarget_tmp[$key] = array("label" => (string) $newlabel, "required" => true);
861 } else {
862 $fieldstarget_tmp[$key] = array("label" => (string) $label, "required" => false);
863 }
864 if (!empty($array_match_database_to_file[$key])) {
865 $fieldstarget_tmp[$key]["imported"] = true;
866 $fieldstarget_tmp[$key]["position"] = (int) $array_match_database_to_file[$key] - 1;
867 $keytoswap = $key;
868 while (!empty($array_match_database_to_file[$keytoswap])) {
869 if ($position + 1 > $array_match_database_to_file[$keytoswap]) {
870 $keytoswapwith = $array_match_database_to_file[$keytoswap] - 1;
871 $tmp = [$keytoswap => $fieldstarget_tmp[$keytoswap]];
872 unset($fieldstarget_tmp[$keytoswap]);
873 $fieldstarget_tmp = arrayInsert($fieldstarget_tmp, $keytoswapwith, $tmp);
874 $keytoswapwith = $arraykeysfieldtarget[$array_match_database_to_file[$keytoswap] - 1];
875 $tmp = $fieldstarget_tmp[$keytoswapwith];
876 unset($fieldstarget_tmp[$keytoswapwith]);
877 $fieldstarget_tmp[$keytoswapwith] = $tmp;
878 $keytoswap = $keytoswapwith;
879 } else {
880 break;
881 }
882 }
883 } else {
884 $fieldstarget_tmp[$key]["imported"] = false;
885 }
886 $position++;
887 }
888 $fieldstarget = $fieldstarget_tmp;
889
890 //print $serialized_array_match_file_to_database;
891 //print $_SESSION["dol_array_match_file_to_database"];
892 //print $_SESSION["dol_array_match_file_to_database_select"];
893 //var_dump($array_match_file_to_database);exit;
894
895 // Now $array_match_file_to_database contains fieldnb(1,2,3...)=>fielddatabase(key in $array_match_file_to_database)
896
897 $param = '&format='.$format.'&datatoimport='.urlencode($datatoimport).'&filetoimport='.urlencode($filetoimport);
898 if ($excludefirstline) {
899 $param .= '&excludefirstline='.urlencode($excludefirstline);
900 }
901 if ($endatlinenb) {
902 $param .= '&endatlinenb='.urlencode($endatlinenb);
903 }
904 if ($separator) {
905 $param .= '&separator='.urlencode($separator);
906 }
907 if ($enclosure) {
908 $param .= '&enclosure='.urlencode($enclosure);
909 }
910
911 llxHeader('', $langs->trans("NewImport"), $help_url);
912
913 $head = import_prepare_head($param, 3);
914
915 $titleofmodule = $objimport->array_import_module[0]['module']->getName();
916
917 print dol_get_fiche_head($head, 'step3', 'Import', -2, 'upload');
918
919 print '<div class="underbanner clearboth"></div>';
920 print '<div class="fichecenter">';
921
922 print '<table class="centpercent border tableforfield">';
923
924 // Module
925 print '<tr><td class="titlefieldcreate">'.$langs->trans("Module").'</td>';
926 print '<td>';
927 // Special case for import common to module/services
928 if (in_array($objimport->array_import_code[0], array('produit_supplierprices', 'produit_multiprice', 'produit_languages'))) {
929 $titleofmodule = $langs->trans("ProductOrService");
930 }
931 print dolPrintHTML($titleofmodule);
932 print '</td></tr>';
933
934 // Dataset to import
935 print '<tr><td>'.$langs->trans("DatasetToImport").'</td>';
936 print '<td>';
937 $entity = preg_replace('/:.*$/', '', $objimport->array_import_icon[0]);
938 $entityicon = strtolower(!empty($entitytoicon[$entity]) ? $entitytoicon[$entity] : $entity);
939 print img_object($objimport->array_import_module[0]['module']->getName(), $entityicon).' ';
940 print $objimport->array_import_label[0];
941 print '</td></tr>';
942
943 print '</table>';
944 print '</div>';
945
946
947 print '<br>';
948
949
950 print load_fiche_titre($langs->trans("InformationOnSourceFile"), '', 'file-export');
951
952 print '<div class="underbanner clearboth"></div>';
953 print '<div class="fichecenter">';
954 print '<table width="100%" class="border tableforfield">';
955
956 // Source file format
957 print '<tr><td class="titlefieldcreate">'.$langs->trans("SourceFileFormat").'</td>';
958 print '<td class="nowraponall">';
959 $text = $objmodelimport->getDriverDescForKey($format);
960 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
961 print $form->textwithpicto($objmodelimport->getDriverLabelForKey($format), $text);
962 print '</td></tr>';
963
964 // Separator and enclosure
965 if ($model == 'csv') {
966 '@phan-var-force ImportCsv $obj';
967 print '<tr><td>'.$langs->trans("CsvOptions").'</td>';
968 print '<td>';
969 print '<form method="POST">';
970 print '<input type="hidden" name="token" value="'.newToken().'">';
971 print '<input type="hidden" value="'.$step.'" name="step">';
972 print '<input type="hidden" value="'.$format.'" name="format">';
973 print '<input type="hidden" value="'.$excludefirstline.'" name="excludefirstline">';
974 print '<input type="hidden" value="'.$endatlinenb.'" name="endatlinenb">';
975 print '<input type="hidden" value="'.$datatoimport.'" name="datatoimport">';
976 print '<input type="hidden" value="'.$filetoimport.'" name="filetoimport">';
977 print $langs->trans("Separator").' : ';
978 print '<input type="text" class="width25 center" name="separator" value="'.dol_escape_htmltag($separator).'"/>';
979 print '&nbsp;&nbsp;&nbsp;&nbsp;'.$langs->trans("Enclosure").' : ';
980 print '<input type="text" class="width25 center" name="enclosure" value="'.dol_escape_htmltag($enclosure).'"/> ';
981 print '<input name="update" type="submit" value="'.$langs->trans('Update').'" class="button smallpaddingimp" />';
982 print '</form>';
983 print '</td></tr>';
984 }
985
986 // File to import
987 print '<tr><td>'.$langs->trans("FileToImport").'</td>';
988 print '<td>';
989 $modulepart = 'import';
990 $relativepath = GETPOST('filetoimport');
991 print '<a data-ajax="false" href="'.DOL_URL_ROOT.'/document.php?modulepart='.$modulepart.'&file='.urlencode($relativepath).'&step=3'.$param.'" target="_blank" rel="noopener noreferrer">';
992 print img_mime($file, '', 'pictofixedwidth');
993 print $filetoimport;
994 print img_picto($langs->trans("Download"), 'download', 'class="paddingleft opacitymedium"');
995 print '</a>';
996 print '</td></tr>';
997
998 print '</table>';
999 print '</div>';
1000
1001 print dol_get_fiche_end();
1002
1003 print '<br>'."\n";
1004
1005
1006 // List of source fields
1007 print '<!-- List of source fields -->'."\n";
1008 print '<form action="'.$_SERVER["PHP_SELF"].'" method="POST">';
1009 print '<input type="hidden" name="token" value="'.newToken().'">';
1010 print '<input type="hidden" name="action" value="select_model">';
1011 print '<input type="hidden" name="step" value="3">';
1012 print '<input type="hidden" name="format" value="'.$format.'">';
1013 print '<input type="hidden" name="datatoimport" value="'.$datatoimport.'">';
1014 print '<input type="hidden" name="filetoimport" value="'.$filetoimport.'">';
1015 print '<input type="hidden" name="excludefirstline" value="'.$excludefirstline.'">';
1016 print '<input type="hidden" name="endatlinenb" value="'.$endatlinenb.'">';
1017 print '<input type="hidden" name="separator" value="'.dol_escape_htmltag($separator).'">';
1018 print '<input type="hidden" name="enclosure" value="'.dol_escape_htmltag($enclosure).'">';
1019
1020 // Import profile to use/load
1021 print '<div class="marginbottomonly">';
1022 print '<span class="opacitymedium">';
1023 $s = $langs->trans("SelectImportFieldsSource", '{s1}');
1024 $s = str_replace('{s1}', img_picto('', 'grip_title', '', 0, 0, 0, '', '', 0), $s);
1025 print $s;
1026 print '</span> ';
1027 $htmlother->select_import_model((string) $importmodelid, 'importmodelid', $datatoimport, 1, $user->id);
1028 print '<input type="submit" class="button smallpaddingimp reposition nomargintop nomarginbottom" id="applyprofile" name="applyprofile" value="'.$langs->trans("Apply").'">';
1029 // Add js to show button
1030 if (!empty($conf->use_javascript_ajax)) {
1031 print '<script>
1032 $(document).ready(function() {
1033 // hide button
1034 $("#applyprofile").hide();
1035
1036 // follow change on list
1037 $("#importmodelid").change(function() {
1038 console.log("We select a new profile");
1039 if ($(this).val() && $(this).val() != "-1") {
1040 $("#applyprofile").show();
1041 } else {
1042 $("#applyprofile").hide();
1043 }
1044
1045 });
1046
1047 });
1048 </script>
1049 ';
1050 }
1051
1052 print '</div>';
1053 print '</form>';
1054
1055 // Title of array with fields
1056 print '<div class="div-table-responsive-no-min">'; // You can use div-table-responsive-no-min if you don't need reserved height for your table
1057 print '<table class="noborder centpercent">';
1058 print '<tr class="liste_titre">';
1059 print '<td>'.$langs->trans("FieldsInSourceFile").'</td>';
1060 print '<td>'.$langs->trans("FieldsInTargetDatabase").'</td>';
1061 print '</tr>';
1062
1063 //var_dump($array_match_file_to_database);
1064
1065 print '<tr valign="top"><td width="50%" class="nopaddingleftimp">';
1066
1067 $fieldsplaced = array();
1068 $valforsourcefieldnb = array();
1069 $listofkeys = array();
1070 foreach ($array_match_file_to_database as $key => $val) {
1071 $listofkeys[$key] = 1;
1072 }
1073
1074 print "\n<!-- Box left container -->\n";
1075 print '<div id="left" class="connectedSortable">'."\n";
1076
1077 // List of source fields
1078
1079 $lefti = 1;
1080 foreach ($fieldssource as $key => $val) {
1081 show_elem($fieldssource, $key, (string) $key); // key is field number in source file @phan-suppress-current-line PhanPluginSuspiciousParamPosition
1082 $listofkeys[$key] = 1;
1083 $fieldsplaced[$key] = 1;
1084 $valforsourcefieldnb[$lefti] = $key;
1085 $lefti++;
1086
1087 /*if ($lefti > count($fieldstarget)) {
1088 break; // Other fields are in the not imported area
1089 }*/
1090 }
1091 //var_dump($valforsourcefieldnb);
1092
1093 print "</div>\n";
1094 print "<!-- End box left container -->\n";
1095
1096
1097 print '</td><td width="50%" class="nopaddingrightimp">';
1098
1099 // Set the list of all possible target fields in Dolibarr.
1100
1101 $optionsall = array();
1102 foreach ($fieldstarget as $code => $line) {
1103 $tmparray = explode('|', $line["label"]); // If label of field is several translation keys separated with |
1104 $labeltoshow = '';
1105 foreach ($tmparray as $tmpkey => $tmpval) {
1106 $labeltoshow .= ($labeltoshow ? ' '.$langs->trans('or').' ' : '').$langs->transnoentities($tmpval);
1107 }
1108 // TODO Get type from a new array into module descriptor.
1109 // $picto = 'email';
1110 $picto = '';
1111 $optionsall[$code] = array(
1112 'labelkey' => $line['label'],
1113 'labelkeyarray' => $tmparray,
1114 'label' => $labeltoshow,
1115 'required' => (empty($line["required"]) ? 0 : 1),
1116 'position' => (!empty($line['position']) ? $line['position'] : 0),
1117 'picto' => $picto,
1118 );
1119 }
1120 // $optionsall is an array of all possible target fields. key=>array('label'=>..., 'xxx')
1121
1122 $height = '32px'; //needs px for css height attribute below
1123 $i = 0;
1124 $mandatoryfieldshavesource = true;
1125
1126 //var_dump($fieldstarget);
1127 //var_dump($optionsall);
1128 //exit;
1129
1130 //var_dump($_SESSION['dol_array_match_file_to_database']);
1131 //var_dump($_SESSION['dol_array_match_file_to_database_select']);
1132 //exit;
1133 //var_dump($optionsall);
1134 //var_dump($fieldssource);
1135 //var_dump($fieldstarget);
1136
1137 $modetoautofillmapping = 'session'; // Use setup in session
1138 if ($initialloadofstep4) {
1139 $modetoautofillmapping = 'guess';
1140 }
1141 //var_dump($modetoautofillmapping);
1142
1143 print '<table class="nobordernopadding centpercent tableimport">';
1144 foreach ($fieldssource as $code => $line) { // $fieldssource is an array code=column num, line=content on first line for column in source file.
1145 /*if ($i == $minpos) {
1146 break;
1147 }*/
1148 //var_dump($line);
1149 print '<tr style="height:'.$height.'" class="trimport oddevenimport">';
1150 // Note: $code is int, but index should be fieldname? -> @phan-suppress-next-line PhanTypeMismatchDimFetch
1151 $entity = (!empty($objimport->array_import_entities[0][$code]) ? $objimport->array_import_entities[0][$code] : $objimport->array_import_icon[0]);
1152
1153 $entityicon = !empty($entitytoicon[$entity]) ? $entitytoicon[$entity] : $entity; // $entityicon must string name of picto of the field like 'project', 'company', 'contact', 'modulename', ...
1154 $entitylang = !empty($entitytolang[$entity]) ? $entitytolang[$entity] : $objimport->array_import_label[0]; // $entitylang must be a translation key to describe object the field is related to, like 'Company', 'Contact', 'MyModule', ...
1155
1156 print '<td class="nowraponall hideonsmartphone" style="font-weight: normal">=> </td>';
1157 print '<td class="nowraponall" style="font-weight: normal">';
1158
1159 $selectforline = '';
1160 $selectforline .= '<select id="selectorderimport_'.($i + 1).'" class="targetselectchange minwidth300" name="select_'.($i + 1).'">';
1161 $selectforline .= '<option value="-1">&nbsp;</option>';
1162
1163 $j = 0;
1164 $codeselectedarray = array();
1165 foreach ($optionsall as $tmpcode => $tmpval) { // Loop on each entry to add into each combo list.
1166 $label = '';
1167 if (!empty($tmpval['picto'])) {
1168 $label .= img_picto('', $tmpval['picto'], 'class="pictofixedwidth"');
1169 }
1170 $label .= $tmpval['required'] ? '<strong>' : '';
1171 $label .= $tmpval['label'];
1172 $label .= $tmpval['required'] ? '*</strong>' : '';
1173
1174 $tablealias = preg_replace('/(\..*)$/i', '', $tmpcode);
1175 $tablename = !empty($objimport->array_import_tables[0][$tablealias]) ? $objimport->array_import_tables[0][$tablealias] : "";
1176
1177 $htmltext = '';
1178
1179 $filecolumn = ($i + 1);
1180 // Source field info
1181 if (empty($objimport->array_import_convertvalue[0][$tmpcode])) { // If source file does not need conversion
1182 $filecolumntoshow = num2Alpha($i);
1183 } else {
1184 if ($objimport->array_import_convertvalue[0][$tmpcode]['rule'] == 'fetchidfromref') {
1185 $htmltext .= $langs->trans("DataComeFromIdFoundFromRef", $langs->transnoentitiesnoconv($entitylang)).'<br>';
1186 }
1187 if ($objimport->array_import_convertvalue[0][$tmpcode]['rule'] == 'fetchidfromcodeid') {
1188 $dictlabel = $objimport->array_import_convertvalue[0][$tmpcode]['dict'] ?? '';
1189 $htmltext .= $langs->trans("DataComeFromIdFoundFromCodeId", $langs->transnoentitiesnoconv($dictlabel)).'<br>';
1190 }
1191 }
1192 // Source required
1193 $example = !empty($objimport->array_import_examplevalues[0][$tmpcode]) ? $objimport->array_import_examplevalues[0][$tmpcode] : "";
1194 // Example
1195 if (empty($objimport->array_import_convertvalue[0][$tmpcode])) { // If source file does not need conversion
1196 if ($example) {
1197 $htmltext .= $langs->trans("SourceExample").': <b>'.str_replace('"', '', $example).'</b><br>';
1198 }
1199 } else {
1200 if ($objimport->array_import_convertvalue[0][$tmpcode]['rule'] == 'fetchidfromref') {
1201 $htmltext .= $langs->trans("SourceExample").': <b>'.$langs->transnoentitiesnoconv("ExampleAnyRefFoundIntoElement", $entitylang).($example ? ' ('.$langs->transnoentitiesnoconv("Example").': '.str_replace('"', '', $example).')' : '').'</b><br>';
1202 } elseif ($objimport->array_import_convertvalue[0][$tmpcode]['rule'] == 'fetchidfromcodeid') {
1203 $dictlabel = $objimport->array_import_convertvalue[0][$tmpcode]['dict'] ?? '';
1204 $htmltext .= $langs->trans("SourceExample").': <b>'.$langs->trans("ExampleAnyCodeOrIdFoundIntoDictionary", $langs->transnoentitiesnoconv($dictlabel)).($example ? ' ('.$langs->transnoentitiesnoconv("Example").': '.str_replace('"', '', $example).')' : '').'</b><br>';
1205 } elseif ($example) {
1206 $htmltext .= $langs->trans("SourceExample").': <b>'.str_replace('"', '', $example).'</b><br>';
1207 }
1208 }
1209 // Format control rule
1210 if (!empty($objimport->array_import_regex[0][$tmpcode])) {
1211 $htmltext .= $langs->trans("FormatControlRule").': <b>'.str_replace('"', '', $objimport->array_import_regex[0][$tmpcode]).'</b><br>';
1212 }
1213
1214 //var_dump($htmltext);
1215 $htmltext .= $langs->trans("InformationOnTargetTables").': &nbsp; <b>'.$tablename."->".preg_replace('/^.*\./', '', $tmpcode)."</b>";
1216
1217 $labelhtml = $label.' '.$form->textwithpicto('', $htmltext, 1, 'help', '', 1);
1218
1219
1220 $selectforline .= '<option value="'.$tmpcode.'"';
1221 if ($modetoautofillmapping == 'orderoftargets') {
1222 // The mode where we fill the preselected value of combo one by one in order of available targets fields in the declaration in descriptor file.
1223 if ($j == $i) {
1224 $selectforline .= ' selected';
1225 }
1226 } elseif ($modetoautofillmapping == 'guess') {
1227 // The mode where we try to guess which value to preselect from the name in first column of source file.
1228 // $line['example1'] is the label of the column found on first line
1229 $regs = array();
1230 if (preg_match('/^(.+)\‍((.+\..+)\‍)$/', $line['example1'], $regs)) { // If text is "Label (x.abc)"
1231 $tmpstring1 = $regs[1];
1232 $tmpstring2 = $regs[2];
1233 } else {
1234 $tmpstring1 = $line['example1'];
1235 $tmpstring2 = '';
1236 }
1237 $tmpstring1 = strtolower(dol_string_unaccent(str_replace('*', '', trim($tmpstring1))));
1238 $tmpstring2 = strtolower(dol_string_unaccent(str_replace('*', '', trim($tmpstring2))));
1239
1240 // $tmpstring1 and $tmpstring2 are string from the input file title of column "Label (fieldname)".
1241 // $tmpval is array of target fields read from the module import profile.
1242 foreach ($tmpval['labelkeyarray'] as $tmpval2) {
1243 $labeltarget = $langs->transnoentities($tmpval2);
1244 //var_dump($tmpstring1.' - '.$tmpstring2.' - '.$tmpval['labelkey'].' - '.$tmpval['label'].' - '.$tmpval2.' - '.$labeltarget);
1245 if ($tmpstring1 && ($tmpstring1 == $tmpcode || $tmpstring1 == strtolower($labeltarget)
1246 || $tmpstring1 == strtolower(dol_string_unaccent($labeltarget)) || $tmpstring1 == strtolower($tmpval2))) {
1247 if (empty($codeselectedarray[$code])) {
1248 $selectforline .= ' selected';
1249 $codeselectedarray[$code] = 1;
1250 break;
1251 }
1252 } elseif ($tmpstring2 && ($tmpstring2 == $tmpcode || $tmpstring2 == strtolower($labeltarget)
1253 || $tmpstring2 == strtolower(dol_string_unaccent($labeltarget)) || $tmpstring2 == strtolower($tmpval2))) {
1254 if (empty($codeselectedarray[$code])) {
1255 $selectforline .= ' selected';
1256 $codeselectedarray[$code] = 1;
1257 break;
1258 }
1259 }
1260 }
1261 } elseif ($modetoautofillmapping == 'session' && !empty($_SESSION['dol_array_match_file_to_database_select'])) {
1262 $tmpselectioninsession = dolExplodeIntoArray($_SESSION['dol_array_match_file_to_database_select'], ',', '=');
1263 //var_dump($code);
1264 if (!empty($tmpselectioninsession[(string) ($i + 1)]) && $tmpselectioninsession[(string) ($i + 1)] == $tmpcode) {
1265 $selectforline .= ' selected';
1266 }
1267 $selectforline .= ' data-debug="'.$tmpcode.'-'.$code.'-'.$j.'-'.(!empty($tmpselectioninsession[(string) ($i + 1)]) ? $tmpselectioninsession[(string) ($i + 1)] : "").'"';
1268 }
1269 $selectforline .= ' data-html="'.dol_escape_htmltag($labelhtml).'"';
1270 $selectforline .= '>';
1271 $selectforline .= $label;
1272 $selectforline .= '</options>';
1273 $j++;
1274 }
1275 $selectforline .= '</select>';
1276 $selectforline .= ajax_combobox('selectorderimport_'.($i + 1));
1277
1278 print $selectforline;
1279
1280 print '</td>';
1281
1282 // Tooltip at end of line
1283 print '<td class="nowraponall" style="font-weight:normal; text-align:right">';
1284
1285 // Source field info
1286 $htmltext = '<b><u>'.$langs->trans("FieldSource").'</u></b><br>';
1287 $filecolumntoshow = num2Alpha($i);
1288 $htmltext .= $langs->trans("DataComeFromFileFieldNb", $filecolumntoshow).'<br>';
1289
1290 print $form->textwithpicto('', $htmltext);
1291
1292 print '</td>';
1293 print '</tr>';
1294 $i++;
1295 }
1296 print '</table>';
1297
1298 print '</td></tr>';
1299
1300 // Lines for remark
1301 print '<tr class="liste_titre"><td colspan="2">'.$langs->trans("Note").'</td></tr>';
1302 print '<tr><td colspan="2"><div id="div-mandatory-target-fields-not-mapped"></div></td></tr>';
1303
1304 print '</table>';
1305 print '</div>';
1306
1307
1308 if (!empty($conf->use_javascript_ajax)) {
1309 print '<script type="text/javascript">'."\n";
1310 print 'var previousselectedvalueimport = "0";'."\n";
1311 print 'var previousselectedlabelimport = "0";'."\n";
1312 print 'var arrayofselectedvalues = [];'."\n";
1313 print 'var arrayoftargetfields = [];'."\n";
1314 print 'var arrayoftargetmandatoryfields = [];'."\n";
1315
1316 // Loop on $fieldstarget (seems sorted by 'position') to store php array into javascript array
1317 $tmpi = 0;
1318 foreach ($fieldstarget as $key => $val) {
1319 print "arrayoftargetfields[".$tmpi."] = '".dol_escape_js($langs->trans($val['label']))."'; ";
1320 if ($val['required']) {
1321 print "arrayoftargetmandatoryfields[".$tmpi."] = '".dol_escape_js($key)."'; ";
1322 }
1323 $tmpi++;
1324 }
1325 print "\n";
1326
1327 print '$(document).ready(function () {'."\n";
1328
1329 print 'setOptionsToDisabled();'."\n";
1330 print 'saveSelection();'."\n";
1331
1332 print '$(".targetselectchange").focus(function(){'."\n";
1333 print ' previousselectedvalueimport = $(this).val();'."\n";
1334 print ' previousselectedlabelimport = $(this).children("option:selected").text();'."\n";
1335 print ' console.log("previousselectedvalueimport="+previousselectedvalueimport)'."\n";
1336 print '})'."\n";
1337
1338 // Function to set the disabled flag
1339 // - We set all option to "enabled"
1340 // - Then we scan all combo to get the value currently selected and save them into the array arrayofselectedvalues
1341 // - Then we set to disabled all fields that are selected
1342 print 'function setOptionsToDisabled() {'."\n";
1343 print ' console.log("Remove the disabled flag everywhere");'."\n";
1344 print ' $("select.targetselectchange").not($( this )).find(\'option\').prop("disabled", false);'."\n"; // Enable all options
1345 print ' arrayofselectedvalues = [];'."\n";
1346
1347 print ' $("select.targetselectchange").each(function(){'."\n";
1348 print ' id = $(this).attr(\'id\')'."\n";
1349 print ' value = $(this).val()'."\n";
1350 print ' console.log("a selected value has been found for component "+id+" = "+value);'."\n";
1351 print ' arrayofselectedvalues.push(value);'."\n";
1352 print ' });'."\n";
1353
1354 print ' console.log("List of all selected values arrayofselectedvalues");'."\n";
1355 print ' console.log(arrayofselectedvalues);'."\n";
1356 print ' console.log("Set the option to disabled for every entry that is currently selected somewhere else (so into arrayofselectedvalues)");'."\n";
1357
1358 print ' $.each(arrayofselectedvalues, function(key, value) {'."\n"; // Loop on each selected value
1359 print ' if (value != -1) {'."\n";
1360 print ' console.log("Process key="+key+" value="+value+" to disable.");'."\n";
1361 print ' $("select.targetselectchange").find(\'option[value="\'+value+\'"]:not(:selected)\').prop("disabled", true);'."\n"; // Set to disabled except if currently selected
1362 print ' }'."\n";
1363 print ' });'."\n";
1364 print '}'."\n";
1365
1366 // Function to save the selection in database
1367 print 'function saveSelection() {'."\n";
1368 //print ' console.log(arrayofselectedvalues);'."\n";
1369 print ' arrayselectedfields = [];'."\n";
1370 print ' arrayselectedfields.push(0);'."\n";
1371
1372 print ' $.each( arrayofselectedvalues, function( key, value ) {'."\n";
1373 print ' if (value != -1) {'."\n";
1374 print ' arrayselectedfields.push(value);'."\n";
1375 print ' } else {'."\n";
1376 print ' arrayselectedfields.push(0);'."\n";
1377 print ' }'."\n";
1378 print ' });'."\n";
1379
1380 print " $.ajax({\n";
1381 print " type: 'POST',\n";
1382 print " dataType: 'json',\n";
1383 print " url: '".dol_escape_js($_SERVER["PHP_SELF"])."?action=saveselectorder&token=".newToken()."',\n";
1384 print " data: 'selectorder='+arrayselectedfields.toString(),\n";
1385 print " success: function(){\n";
1386 print " console.log('The selected fields have been saved into '+arrayselectedfields.toString());\n";
1387 print " },\n";
1388 print ' });'."\n";
1389
1390 // Now we loop on all target fields that are mandatory to show if they are not mapped yet.
1391 print ' console.log("arrayselectedfields");';
1392 print ' console.log(arrayselectedfields);';
1393 print ' console.log("arrayoftargetmandatoryfields");';
1394 print ' console.log(arrayoftargetmandatoryfields);';
1395 print " listtoshow = '';";
1396 print " nbelement = arrayoftargetmandatoryfields.length
1397 for (let i = 0; i < nbelement; i++) {
1398 if (arrayoftargetmandatoryfields[i] && ! arrayselectedfields.includes(arrayoftargetmandatoryfields[i])) {
1399 console.log(arrayoftargetmandatoryfields[i]+' not mapped');
1400 listtoshow = listtoshow + (listtoshow ? ', ' : '') + '<b>' + arrayoftargetfields[i] + '*</b>';
1401 }
1402 }
1403 console.log(listtoshow);
1404 if (listtoshow) {
1405 listtoshow = '".dol_escape_js(img_warning($langs->trans("MandatoryTargetFieldsNotMapped")).' '.$langs->trans("MandatoryTargetFieldsNotMapped")).": ' + listtoshow;
1406 $('#div-mandatory-target-fields-not-mapped').html(listtoshow);
1407 } else {
1408 $('#div-mandatory-target-fields-not-mapped').html('<span class=\"opacitymedium\">".dol_escape_js($langs->trans("AllTargetMandatoryFieldsAreMapped"))."</span>');
1409 }
1410 ";
1411
1412 print '}'."\n";
1413
1414 // If we make a change on a selectbox
1415 print '$(".targetselectchange").change(function(){'."\n";
1416 print ' setOptionsToDisabled();'."\n";
1417
1418 print ' if(previousselectedlabelimport != "" && previousselectedvalueimport != -1) {'."\n";
1419 print ' let valuetochange = $(this).val(); '."\n";
1420 print ' $(".boxtdunused").each(function(){'."\n";
1421 print ' if ($(this).text().includes(valuetochange)){'."\n";
1422 print ' arraychild = $(this)[0].childNodes'."\n";
1423 print ' arraytexttomodify = arraychild[0].textContent.split(" ")'."\n";
1424 print ' arraytexttomodify[1] = previousselectedvalueimport '."\n";
1425 print ' textmodified = arraytexttomodify.join(" ") '."\n";
1426 print ' arraychild[0].textContent = textmodified'."\n";
1427 print ' arraychild[1].innerHTML = previousselectedlabelimport'."\n";
1428 print ' }'."\n";
1429 print ' })'."\n";
1430 print ' }'."\n";
1431 print ' $(this).blur()'."\n";
1432
1433 print ' saveSelection()'."\n";
1434 print '});'."\n";
1435
1436 print '})'."\n";
1437 print '</script>'."\n";
1438 }
1439
1440 /*
1441 * Action bar
1442 */
1443 print '<div class="tabsAction">';
1444
1445 if (count($array_match_file_to_database)) {
1446 if ($mandatoryfieldshavesource) {
1447 print '<a class="butAction saveorderselect" href="import.php?step=4'.$param.'&filetoimport='.urlencode($filetoimport).'">'.$langs->trans("NextStep").'</a>';
1448 } else {
1449 print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->transnoentitiesnoconv("SomeMandatoryFieldHaveNoSource")).'">'.$langs->trans("NextStep").'</a>';
1450 }
1451 }
1452
1453 print '</div>';
1454
1455
1456 // Area for profils import
1457 if (count($array_match_file_to_database)) {
1458 print '<br>'."\n";
1459 print '<!-- Area to add new import profile -->'."\n";
1460 print '<div class="marginbottomonly"><span class="opacitymedium">'.$langs->trans("SaveImportModel").'</span></div>';
1461
1462 print '<form class="nocellnopadd" action="'.$_SERVER["PHP_SELF"].'" method="post">';
1463 print '<input type="hidden" name="token" value="'.newToken().'">';
1464 print '<input type="hidden" name="action" value="add_import_model">';
1465 print '<input type="hidden" name="step" value="'.$step.'">';
1466 print '<input type="hidden" name="format" value="'.$format.'">';
1467 print '<input type="hidden" name="datatoimport" value="'.$datatoimport.'">';
1468 print '<input type="hidden" name="filetoimport" value="'.$filetoimport.'">';
1469 print '<input type="hidden" name="hexa" value="'.$hexa.'">';
1470 print '<input type="hidden" name="excludefirstline" value="'.$excludefirstline.'">';
1471 print '<input type="hidden" name="endatlinenb" value="'.$endatlinenb.'">';
1472 print '<input type="hidden" name="page_y" value="">';
1473 print '<input type="hidden" value="'.dol_escape_htmltag($separator).'" name="separator">';
1474 print '<input type="hidden" value="'.dol_escape_htmltag($enclosure).'" name="enclosure">';
1475
1476 print '<div class="div-table-responsive-no-min">'; // You can use div-table-responsive-no-min if you don't need reserved height for your table
1477 print '<table summary="selectofimportprofil" class="noborder centpercent">';
1478 print '<tr class="liste_titre">';
1479 print '<td>'.$langs->trans("ImportModelName").'</td>';
1480 print '<td>'.$langs->trans("Visibility").'</td>';
1481 print '<td></td>';
1482 print '</tr>';
1483
1484 $nameofimportprofile = str_replace(' ', '-', $langs->trans("ImportProfile").' '.$titleofmodule.' '.dol_print_date(dol_now('gmt'), 'dayxcard'));
1485 if (GETPOST('import_name')) { // If we have submitted a form, we take value used for the update try
1486 $nameofimportprofile = $import_name;
1487 }
1488
1489 print '<tr class="oddeven">';
1490 print '<td><input name="import_name" class="minwidth300" value="'.$nameofimportprofile.'"></td>';
1491 print '<td>';
1492 $arrayvisibility = array('private' => $langs->trans("Private"), 'all' => $langs->trans("Everybody"));
1493 print $form->selectarray('visibility', $arrayvisibility, 'private');
1494 print '</td>';
1495 print '<td class="right">';
1496 print '<input type="submit" class="button smallpaddingimp reposition" value="'.$langs->trans("SaveImportProfile").'">';
1497 print '</td></tr>';
1498
1499 // List of existing import profils
1500 $sql = "SELECT rowid, label, fk_user, entity";
1501 $sql .= " FROM ".MAIN_DB_PREFIX."import_model";
1502 $sql .= " WHERE type = '".$db->escape($datatoimport)."'";
1503 if (!getDolGlobalString('EXPORTS_SHARE_MODELS')) { // EXPORTS_SHARE_MODELS means all templates are visible, whatever is owner.
1504 $sql .= " AND fk_user IN (0, ".((int) $user->id).")";
1505 }
1506 $sql .= " ORDER BY rowid";
1507
1508 $resql = $db->query($sql);
1509 if ($resql) {
1510 $num = $db->num_rows($resql);
1511
1512 $tmpuser = new User($db);
1513
1514 $i = 0;
1515 while ($i < $num) {
1516 $obj = $db->fetch_object($resql);
1517
1518 print '<tr class="oddeven"><td>';
1519 print $obj->label;
1520 print '</td>';
1521 print '<td class="tdoverflowmax150">';
1522 if (empty($obj->fk_user)) {
1523 print $langs->trans("Everybody");
1524 } else {
1525 $tmpuser->fetch($obj->fk_user);
1526 print $tmpuser->getNomUrl(-1);
1527 }
1528 print '</td>';
1529 print '<td class="right">';
1530 print '<a class="reposition" href="'.$_SERVER["PHP_SELF"].'?step='.$step.$param.'&action=deleteprof&token='.newToken().'&id='.$obj->rowid.'&filetoimport='.urlencode($filetoimport).'">';
1531 print img_delete();
1532 print '</a>';
1533 print '</tr>';
1534 $i++;
1535 }
1536 } else {
1537 dol_print_error($db);
1538 }
1539
1540 print '</table>';
1541 print '</div>';
1542
1543 print '</form>';
1544 }
1545}
1546
1547// STEP 4: Summary of choices and launch simulation
1548if ($step == 4 && $datatoimport) {
1549 $max_execution_time_for_importexport = getDolGlobalInt('IMPORT_MAX_EXECUTION_TIME', 300); // 5mn if not defined
1550 $max_time = @ini_get("max_execution_time");
1551 if ($max_time && $max_time < $max_execution_time_for_importexport) {
1552 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.");
1553 @ini_set("max_execution_time", $max_execution_time_for_importexport); // This work only if safe mode is off. also web servers has timeout of 300
1554 }
1555
1556 $model = $format;
1557
1558 // Fallback: txt to csv (import_txt.modules.php does not exist)
1559 if ($model === 'txt') {
1560 $model = 'csv';
1561 }
1562
1563 $list = $objmodelimport->listOfAvailableImportFormat($db);
1564
1565 // Create class to use for import
1566 $dir = DOL_DOCUMENT_ROOT."/core/modules/import/";
1567 $file = "import_".$model.".modules.php";
1568 $classname = "Import".ucfirst($model);
1569 require_once $dir.$file;
1570 $obj = new $classname($db, $datatoimport);
1571 '@phan-var-force ModeleImports $obj';
1572 $obj->importtriggermode = $importtriggermode;
1573 $obj->importissimulation = 1;
1574 if ($model == 'csv') {
1575 '@phan-var-force ImportCsv $obj';
1576 $obj->separator = $separator_used;
1577 $obj->enclosure = $enclosure;
1578 }
1579
1580 // Load source fields in input file
1581 $fieldssource = array();
1582 $result = $obj->import_open_file($conf->import->dir_temp.'/'.$filetoimport);
1583
1584 if ($result >= 0) {
1585 // Read first line
1586 $arrayrecord = $obj->import_read_record();
1587 // Put into array fieldssource starting with 1.
1588 $i = 1;
1589 foreach ($arrayrecord as $key => $val) {
1590 $fieldssource[$i]['example1'] = dol_trunc($val['val'], 24);
1591 $i++;
1592 }
1593 $obj->import_close_file();
1594 }
1595
1596 $nboflines = $obj->import_get_nb_of_lines($conf->import->dir_temp.'/'.$filetoimport);
1597
1598 $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 $param2 = $param; // $param2 = $param without excludefirstline and endatlinenb
1600 if ($excludefirstline) {
1601 $param .= '&excludefirstline='.urlencode($excludefirstline);
1602 }
1603 if ($endatlinenb) {
1604 $param .= '&endatlinenb='.urlencode($endatlinenb);
1605 }
1606 if (!empty($updatekeys)) {
1607 $param .= '&updatekeys[]='.implode('&updatekeys[]=', $updatekeys);
1608 }
1609
1610 llxHeader('', $langs->trans("NewImport"), $help_url);
1611
1612 $head = import_prepare_head($param, 4);
1613
1614
1615 print '<form action="'.$_SERVER["PHP_SELF"].'?'.$param2.'" method="POST">';
1616 print '<input type="hidden" name="token" value="'.newToken().'">';
1617 print '<input type="hidden" name="step" value="4">'; // step 4
1618 print '<input type="hidden" name="action" value="launchsimu">'; // step 4
1619 print '<input type="hidden" name="importtriggermode" value="'.dol_escape_htmltag($importtriggermode).'">';
1620
1621 print dol_get_fiche_head($head, 'step4', 'Import', -2, 'upload');
1622
1623 print '<div class="underbanner clearboth"></div>';
1624 print '<div class="fichecenter">';
1625
1626 print '<table width="100%" class="border tableforfield">';
1627
1628 // Module
1629 print '<tr><td class="titlefieldcreate">'.$langs->trans("Module").'</td>';
1630 print '<td>';
1631 $titleofmodule = $objimport->array_import_module[0]['module']->getName();
1632 // Special case for import common to module/services
1633 if (in_array($objimport->array_import_code[0], array('produit_supplierprices', 'produit_multiprice', 'produit_languages'))) {
1634 $titleofmodule = $langs->trans("ProductOrService");
1635 }
1636 print $titleofmodule;
1637 print '</td></tr>';
1638
1639 // Lot de donnees a importer
1640 print '<tr><td>'.$langs->trans("DatasetToImport").'</td>';
1641 print '<td>';
1642 $entity = preg_replace('/:.*$/', '', $objimport->array_import_icon[0]);
1643 $entityicon = strtolower(!empty($entitytoicon[$entity]) ? $entitytoicon[$entity] : $entity);
1644 print img_object($objimport->array_import_module[0]['module']->getName(), $entityicon).' ';
1645 print $objimport->array_import_label[0];
1646 print '</td></tr>';
1647
1648 print '</table>';
1649 print '</div>';
1650
1651 print '<br>';
1652
1653 print load_fiche_titre($langs->trans("InformationOnSourceFile"), '', 'file-export');
1654
1655 print '<div class="underbanner clearboth"></div>';
1656 print '<div class="fichecenter">';
1657 print '<table width="100%" class="border tableforfield">';
1658
1659 // Source file format
1660 print '<tr><td class="titlefieldcreate">'.$langs->trans("SourceFileFormat").'</td>';
1661 print '<td class="nowraponall">';
1662 $text = $objmodelimport->getDriverDescForKey($format);
1663 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
1664 print $form->textwithpicto($objmodelimport->getDriverLabelForKey($format), $text);
1665 print '</td></tr>';
1666
1667 // Separator and enclosure
1668 if ($model == 'csv') {
1669 '@phan-var-force ImportCsv $obj';
1670 print '<tr><td>'.$langs->trans("CsvOptions").'</td>';
1671 print '<td>';
1672 print $langs->trans("Separator").' : '.dol_escape_htmltag($separator);
1673 print '&nbsp;&nbsp;&nbsp;&nbsp;'.$langs->trans("Enclosure").' : '.dol_escape_htmltag($enclosure);
1674 print '</td></tr>';
1675 }
1676
1677 // File to import
1678 print '<tr><td>'.$langs->trans("FileToImport").'</td>';
1679 print '<td>';
1680 $modulepart = 'import';
1681 $relativepath = GETPOST('filetoimport');
1682 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">';
1683 print img_mime($file, '', 'pictofixedwidth');
1684 print $filetoimport;
1685 print img_picto($langs->trans("Download"), 'download', 'class="paddingleft opacitymedium"');
1686 print '</a>';
1687 print '</td></tr>';
1688
1689 // Total lines in source file
1690 print '<tr><td>';
1691 print $langs->trans("NbOfSourceLines");
1692 print '</td><td>';
1693 print $nboflines;
1694 print '</td></tr>';
1695
1696 // Range of lines to import
1697 print '<tr><td>';
1698 print $langs->trans("ImportFromToLine");
1699 print '</td><td>';
1700 if ($action == 'launchsimu') {
1701 print '<input type="number" min="1" class="maxwidth50 right valignmiddle" name="excludefirstlinebis" disabled="disabled" value="'.$excludefirstline.'">';
1702 print '<input type="hidden" name="excludefirstline" value="'.$excludefirstline.'">';
1703 } else {
1704 print '<input type="number" min="1" class="maxwidth50 right valignmiddle" name="excludefirstline" value="'.$excludefirstline.'">';
1705 print $form->textwithpicto("", $langs->trans("SetThisValueTo2ToExcludeFirstLine"));
1706 }
1707 print ' - ';
1708 if ($action == 'launchsimu') {
1709 print '<input type="text" class="maxwidth50 valignmiddle" name="endatlinenbbis" disabled="disabled" value="'.$endatlinenb.'">';
1710 print '<input type="hidden" name="endatlinenb" value="'.$endatlinenb.'">';
1711 } else {
1712 print '<input type="text" class="maxwidth50 valignmiddle" name="endatlinenb" value="'.$endatlinenb.'">';
1713 print $form->textwithpicto("", $langs->trans("KeepEmptyToGoToEndOfFile"));
1714 }
1715 if ($action == 'launchsimu') {
1716 print ' &nbsp; <a href="'.$_SERVER["PHP_SELF"].'?step=4'.$param.'" class="editfielda">';
1717 //print $langs->trans("Modify");
1718 print img_picto($langs->trans("Modify"), 'edit');
1719 print '</a>';
1720 }
1721 if ($excludefirstline == 2) {
1722 print $form->textwithpicto("", $langs->trans("WarningFirstImportedLine", $excludefirstline), 1, 'warning', "warningexcludefirstline valignmiddle");
1723 print '<script>
1724 $( document ).ready(function() {
1725 $("input[name=\'excludefirstline\']").on("change",function(){
1726 if($(this).val() <= 1){
1727 $(".warningexcludefirstline").hide();
1728 }else{
1729 $(".warningexcludefirstline").show();
1730 }
1731 })
1732 });
1733 </script>';
1734 }
1735 print '</td></tr>';
1736
1737 // Keys for data UPDATE (not INSERT of new data)
1738 print '<tr><td>';
1739 print $form->textwithpicto($langs->trans("KeysToUseForUpdates"), $langs->trans("SelectPrimaryColumnsForUpdateAttempt"));
1740 print '</td><td>';
1741 if ($action == 'launchsimu') {
1742 if (count($updatekeys)) {
1743 print $form->multiselectarray('updatekeysbis', $objimport->array_import_updatekeys[0], $updatekeys, 0, 0, '', 1, '80%', 'disabled');
1744 } else {
1745 print '<span class="opacitymedium">'.$langs->trans("NoUpdateAttempt").'</span>';
1746 }
1747 foreach ($updatekeys as $val) {
1748 print '<input type="hidden" name="updatekeys[]" value="'.$val.'">';
1749 }
1750 print ' &nbsp; <a href="'.$_SERVER["PHP_SELF"].'?step=4'.$param.'" class="editfielda">';
1751 //print $langs->trans("Modify");
1752 print img_picto($langs->trans("Modify"), 'edit');
1753 print '</a>';
1754 } else {
1755 if (is_array($objimport->array_import_updatekeys[0]) && count($objimport->array_import_updatekeys[0])) { //TODO dropdown UL is created inside nested SPANS
1756 print $form->multiselectarray('updatekeys', $objimport->array_import_updatekeys[0], $updatekeys, 0, 0, '', 1, '80%');
1757 //print $form->textwithpicto("", $langs->trans("SelectPrimaryColumnsForUpdateAttempt"));
1758 } else {
1759 print '<span class="opacitymedium">'.$langs->trans("UpdateNotYetSupportedForThisImport").'</span>';
1760 }
1761 }
1762 /*echo '<pre>';
1763 print_r($objimport->array_import_updatekeys);
1764 echo '</pre>';*/
1765 print '</td></tr>';
1766
1767 print '</table>';
1768 print '</div>';
1769
1770 print '<br>';
1771
1772 print load_fiche_titre($langs->trans("InformationOnTargetTables"), '', 'file-import');
1773
1774 print '<div class="underbanner clearboth"></div>';
1775 print '<div class="fichecenter">';
1776
1777 print '<table class="centpercent border tableforfield">';
1778
1779 // Tables imported
1780 print '<tr><td class="titlefieldcreate">';
1781 print $langs->trans("TablesTarget");
1782 print '</td><td>';
1783 $listtables = array();
1784 $sort_array_match_file_to_database = $array_match_file_to_database;
1785 foreach ($array_match_file_to_database as $code => $label) {
1786 //var_dump($fieldssource);
1787 if ($code > count($fieldssource)) {
1788 continue;
1789 }
1790 //print $code.'-'.$label;
1791 $alias = preg_replace('/(\..*)$/i', '', $label);
1792 $listtables[$alias] = $objimport->array_import_tables[0][$alias];
1793 }
1794 if (count($listtables)) {
1795 $newval = '';
1796 //ksort($listtables);
1797 foreach ($listtables as $val) {
1798 if ($newval) {
1799 print ', ';
1800 }
1801 $newval = $val;
1802 // Link to Dolibarr wiki pages
1803 /*$helppagename='EN:Table_'.$newval;
1804 if ($helppagename && empty($conf->global->MAIN_HELP_DISABLELINK))
1805 {
1806 // Get helpbaseurl, helppage and mode from helppagename and langs
1807 $arrayres=getHelpParamFor($helppagename,$langs);
1808 $helpbaseurl=$arrayres['helpbaseurl'];
1809 $helppage=$arrayres['helppage'];
1810 $mode=$arrayres['mode'];
1811 $newval.=' <a href="'.sprintf($helpbaseurl,$helppage).'">'.img_picto($langs->trans($mode == 'wiki' ? 'GoToWikiHelpPage': 'GoToHelpPage'),DOL_URL_ROOT.'/theme/common/helpdoc.png','',1).'</a>';
1812 }*/
1813 print $newval;
1814 }
1815 } else {
1816 print $langs->trans("Error");
1817 }
1818 print '</td></tr>';
1819
1820 // Fields imported
1821 print '<tr><td>';
1822 print $langs->trans("FieldsTarget").'</td><td class="small">';
1823 $listfields = array();
1824 $i = 0;
1825 //print 'fieldsource='.$fieldssource;
1826 $sort_array_match_file_to_database = $array_match_file_to_database;
1827 ksort($sort_array_match_file_to_database);
1828 //var_dump($sort_array_match_file_to_database);
1829 foreach ($sort_array_match_file_to_database as $code => $label) {
1830 $i++;
1831 //var_dump($fieldssource);
1832 if ($code > count($fieldssource)) {
1833 continue;
1834 }
1835 //print $code.'-'.$label;
1836 $alias = preg_replace('/(\..*)$/i', '', $label);
1837 $listfields[$i] = '<span class="nowrap">'.$langs->trans("Column").' '.num2Alpha((int) $code - 1).' -> '.$label.'</span>';
1838 }
1839 print count($listfields) ? (implode(', ', $listfields)) : $langs->trans("Error");
1840 print '</td></tr>';
1841
1842 // Trigger mode
1843 print '<tr><td>';
1844 print $form->textwithpicto($langs->trans("ImportTriggerModeLabel"), $langs->trans("ImportTriggerModeHint"));
1845 print '</td><td>';
1846 $triggerModeChoices = array(
1847 'strict_line' => $langs->trans("ImportTriggerModeStrictLine"),
1848 'fast_bulk' => $langs->trans("ImportTriggerModeFastBulk"),
1849 );
1850 if ($action == 'launchsimu') {
1851 print dol_escape_htmltag($triggerModeChoices[$importtriggermode] ?? $importtriggermode);
1852 print '<input type="hidden" name="importtriggermode" value="'.dol_escape_htmltag($importtriggermode).'">';
1853 print ' &nbsp; <a href="'.$_SERVER["PHP_SELF"].'?step=4'.$param.'" class="editfielda">';
1854 //print $langs->trans("Modify");
1855 print img_picto($langs->trans("Modify"), 'edit');
1856 print '</a>';
1857 } else {
1858 print $form->selectarray('importtriggermode', $triggerModeChoices, $importtriggermode, 0);
1859 }
1860 if ($importtriggermode === 'fast_bulk') {
1861 print '<br><span class="warning">';
1862 print $langs->trans("ImportTriggerModeFastBulkWarning");
1863 print '</span>';
1864 }
1865 print '</td></tr>';
1866
1867 print '</table>';
1868 print '</div>';
1869
1870 print dol_get_fiche_end();
1871
1872
1873 if ($action != 'launchsimu') {
1874 // Show import id
1875 print '<br>';
1876 print '<div class="neutral">';
1877 print $langs->trans("NowClickToTestTheImport", $langs->transnoentitiesnoconv("RunSimulateImportFile")).'<br>';
1878 print '</div>';
1879
1880 // Actions
1881 print '<div class="center">';
1882 if ($user->hasRight('import', 'run')) {
1883 print '<input type="submit" class="butAction" value="'.$langs->trans("RunSimulateImportFile").'">';
1884 } else {
1885 print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->transnoentitiesnoconv("NotEnoughPermissions")).'">'.$langs->trans("RunSimulateImportFile").'</a>';
1886 }
1887 print '</div>';
1888 } else {
1889 print '<br>';
1890 print '<div class="warning">';
1891 print '<b>'.$langs->trans("ImportTriggerModeSimulationWarningTitle").'</b><br>';
1892 print $langs->trans("ImportTriggerModeSimulationWarning");
1893 print '</div>';
1894
1895 // Launch import
1896 $arrayoferrors = array();
1897 $arrayofwarnings = array();
1898 $maxnboferrors = getDolGlobalInt('IMPORT_MAX_NB_OF_ERRORS', 50);
1899 $maxnbofwarnings = getDolGlobalInt('IMPORT_MAX_NB_OF_WARNINGS', 50);
1900 $nboferrors = 0;
1901 $nbofwarnings = 0;
1902
1903 $importid = dol_print_date(dol_now(), '%Y%m%d%H%M%S');
1904
1905 //var_dump($array_match_file_to_database);
1906
1907 $db->begin();
1908
1909 // Open input file
1910 $nbok = 0;
1911 $pathfile = $conf->import->dir_temp.'/'.$filetoimport;
1912 $result = $obj->import_open_file($pathfile);
1913 if ($result > 0) {
1914 global $tablewithentity_cache;
1915 $tablewithentity_cache = array();
1916 $sourcelinenb = 0;
1917 $endoffile = 0;
1918
1919 // Loop on each input file record
1920 while (($sourcelinenb < $nboflines) && !$endoffile) {
1921 $sourcelinenb++;
1922 // Read line and store it into $arrayrecord
1923 //dol_syslog("line ".$sourcelinenb.' - '.$nboflines.' - '.$excludefirstline.' - '.$endatlinenb);
1924 $arrayrecord = $obj->import_read_record();
1925 if ($arrayrecord === false) {
1926 $arrayofwarnings[$sourcelinenb][0] = array('lib' => $langs->trans('ErrorFileLinesReachEOF', $nboflines, $sourcelinenb), 'type' => 'EOF_RECORD_ON_SEVERAL_LINES');
1927 $endoffile++;
1928 continue;
1929 }
1930 if ($excludefirstline && ($sourcelinenb < $excludefirstline)) {
1931 continue;
1932 }
1933 if ($endatlinenb && ($sourcelinenb > $endatlinenb)) {
1934 break;
1935 }
1936
1937 $parameters = array(
1938 'step' => $step,
1939 'datatoimport' => $datatoimport,
1940 'obj' => &$obj,
1941 'arrayrecord' => $arrayrecord,
1942 'array_match_file_to_database' => $array_match_file_to_database,
1943 'objimport' => $objimport,
1944 'fieldssource' => $fieldssource,
1945 'importid' => $importid,
1946 'updatekeys' => $updatekeys,
1947 'importtriggermode' => $importtriggermode,
1948 'arrayoferrors' => &$arrayoferrors,
1949 'arrayofwarnings' => &$arrayofwarnings,
1950 'nbok' => &$nbok,
1951 );
1952
1953 $reshook = $hookmanager->executeHooks('ImportInsert', $parameters);
1954 if ($reshook < 0) {
1955 $arrayoferrors[$sourcelinenb][] = [
1956 'lib' => implode("<br>", array_merge([$hookmanager->error], $hookmanager->errors))
1957 ];
1958 }
1959
1960 if (empty($reshook)) {
1961 // Run import
1962 $result = $obj->import_insert($arrayrecord, $array_match_file_to_database, $objimport, count($fieldssource), $importid, $updatekeys);
1963
1964 if (count($obj->errors)) {
1965 $arrayoferrors[$sourcelinenb] = $obj->errors;
1966 }
1967 if (count($obj->warnings)) {
1968 $arrayofwarnings[$sourcelinenb] = $obj->warnings;
1969 }
1970 if (!count($obj->errors) && !count($obj->warnings)) {
1971 $nbok++;
1972 }
1973 }
1974
1975 $reshook = $hookmanager->executeHooks('AfterImportInsert', $parameters);
1976 if ($reshook < 0) {
1977 $arrayoferrors[$sourcelinenb][] = [
1978 'lib' => implode("<br>", array_merge([$hookmanager->error], $hookmanager->errors))
1979 ];
1980 }
1981 }
1982 // Close file
1983 $obj->import_close_file();
1984 } else {
1985 print $langs->trans("ErrorFailedToOpenFile", $pathfile);
1986 }
1987
1988 $error = 0;
1989
1990 // Run the sql after import if defined
1991 //var_dump($objimport->array_import_run_sql_after[0]);
1992 if (!empty($objimport->array_import_run_sql_after[0]) && is_array($objimport->array_import_run_sql_after[0])) {
1993 $i = 0;
1994 foreach ($objimport->array_import_run_sql_after[0] as $sqlafterimport) {
1995 $i++;
1996 $resqlafterimport = $db->query($sqlafterimport);
1997 if (!$resqlafterimport) {
1998 $arrayoferrors['none'][] = array('lib' => $langs->trans("Error running final request: ".$sqlafterimport));
1999 $error++;
2000 }
2001 }
2002 }
2003
2004 $db->rollback(); // We force rollback because this was just a simulation.
2005
2006 // Show OK
2007 if (!count($arrayoferrors) && !count($arrayofwarnings)) {
2008 //print '<br>';
2009 print '<div class="info">';
2010 print '<div class=""><b>'.$langs->trans("ResultOfSimulationNoError").'</b></div>';
2011 print $langs->trans("NbInsertSim", empty($obj->nbinsert) ? 0 : $obj->nbinsert).'<br>';
2012 print $langs->trans("NbUpdateSim", empty($obj->nbupdate) ? 0 : $obj->nbupdate).'<br>';
2013 print '</div>';
2014 print '<br>';
2015 } else {
2016 //print '<br>';
2017 print '<div class="warning">';
2018 print $langs->trans("NbOfLinesOK", $nbok).'...<br>';
2019 print '</div>';
2020 print '<br>';
2021 }
2022
2023 // Show Errors
2024 //var_dump($arrayoferrors);
2025 if (count($arrayoferrors)) {
2026 $langs->load('errors');
2027 print img_error().' <b>'.$langs->trans("ErrorsOnXLines", count($arrayoferrors)).'</b><br>';
2028 print '<table width="100%" class="border"><tr><td>';
2029 foreach ($arrayoferrors as $key => $val) {
2030 $nboferrors++;
2031 if ($nboferrors > $maxnboferrors) {
2032 print $langs->trans("TooMuchErrors", (count($arrayoferrors) - $nboferrors))."<br>";
2033 break;
2034 }
2035 print '* '.$langs->trans("Line").' '.dol_escape_htmltag($key).'<br>';
2036 foreach ($val as $i => $err) {
2037 print ' &nbsp; &nbsp; > '.dol_escape_htmltag($err['lib']).'<br>';
2038 }
2039 }
2040 print '</td></tr></table>';
2041 print '<br>';
2042 }
2043
2044 // Show Warnings
2045 //var_dump($arrayoferrors);
2046 if (count($arrayofwarnings)) {
2047 $langs->load('errors');
2048 print img_warning().' <b>'.$langs->trans("WarningsOnXLines", count($arrayofwarnings)).'</b><br>';
2049 print '<table width="100%" class="border"><tr><td>';
2050 foreach ($arrayofwarnings as $key => $val) {
2051 $nbofwarnings++;
2052 if ($nbofwarnings > $maxnbofwarnings) {
2053 print $langs->trans("TooMuchWarnings", (count($arrayofwarnings) - $nbofwarnings))."<br>";
2054 break;
2055 }
2056 print ' * '.$langs->trans("Line").' '.dol_escape_htmltag((string) $key).'<br>';
2057 foreach ($val as $i => $err) {
2058 print ' &nbsp; &nbsp; > '.dol_escape_htmltag($err['lib']).'<br>';
2059 }
2060 }
2061 print '</td></tr></table>';
2062 print '<br>';
2063 }
2064
2065 // Show import id
2066 $importid = dol_print_date(dol_now(), '%Y%m%d%H%M%S');
2067
2068 print '<div class="center">';
2069 print '<span class="opacitymedium">'.$langs->trans("NowClickToRunTheImport", $langs->transnoentitiesnoconv("RunImportFile")).'</span><br>';
2070 /*if (empty($nboferrors)) {
2071 print $langs->trans("DataLoadedWithId", $importid).'<br>';
2072 }*/
2073 print '</div>';
2074
2075 print '<br>';
2076
2077 // Actions
2078 print '<div class="center">';
2079 if ($user->hasRight('import', 'run')) {
2080 if (empty($nboferrors)) {
2081 print '<a class="butAction" href="'.DOL_URL_ROOT.'/imports/import.php?leftmenu=import&step=5&importid='.$importid.$param.'">'.$langs->trans("RunImportFile").'</a>';
2082 } else {
2083 //print '<input type="submit" class="butAction" value="'.dol_escape_htmltag($langs->trans("RunSimulateImportFile")).'">';
2084
2085 print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->transnoentitiesnoconv("CorrectErrorBeforeRunningImport")).'">'.$langs->trans("RunImportFile").'</a>';
2086 }
2087 } else {
2088 print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->transnoentitiesnoconv("NotEnoughPermissions")).'">'.$langs->trans("RunSimulateImportFile").'</a>';
2089
2090 print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->transnoentitiesnoconv("NotEnoughPermissions")).'">'.$langs->trans("RunImportFile").'</a>';
2091 }
2092 print '</div>';
2093 }
2094
2095 print '</form>';
2096}
2097
2098
2099// STEP 6: Real import
2100if ($step == 5 && $datatoimport) {
2101 $max_execution_time_for_importexport = getDolGlobalInt('IMPORT_MAX_EXECUTION_TIME', 300); // 5mn if not defined
2102 $max_time = @ini_get("max_execution_time");
2103 if ($max_time && $max_time < $max_execution_time_for_importexport) {
2104 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.");
2105 @ini_set("max_execution_time", $max_execution_time_for_importexport); // This work only if safe mode is off. also web servers has timeout of 300
2106 }
2107
2108 $model = $format;
2109
2110 // Fallback: txt to csv (import_txt.modules.php does not exist)
2111 if ($model === 'txt') {
2112 $model = 'csv';
2113 }
2114
2115 $list = $objmodelimport->listOfAvailableImportFormat($db);
2116 $importid = GETPOST("importid", 'alphanohtml');
2117
2118
2119 // Create class to use for import
2120 $dir = DOL_DOCUMENT_ROOT."/core/modules/import/";
2121 $file = "import_".$model.".modules.php";
2122 $classname = "Import".ucfirst($model);
2123 require_once $dir.$file;
2124 $obj = new $classname($db, $datatoimport);
2125 '@phan-var-force ModeleImports $obj';
2126 $obj->importtriggermode = $importtriggermode;
2127 $obj->importissimulation = 0;
2128 if ($model == 'csv') {
2129 '@phan-var-force ImportCsv $obj';
2130 $obj->separator = $separator_used;
2131 $obj->enclosure = $enclosure;
2132 }
2133
2134 // Load source fields in input file
2135 $fieldssource = array();
2136 $result = $obj->import_open_file($conf->import->dir_temp.'/'.$filetoimport);
2137 if ($result >= 0) {
2138 // Read first line
2139 $arrayrecord = $obj->import_read_record();
2140 // Put into array fieldssource starting with 1.
2141 $i = 1;
2142 foreach ($arrayrecord as $key => $val) {
2143 $fieldssource[$i]['example1'] = dol_trunc($val['val'], 24);
2144 $i++;
2145 }
2146 $obj->import_close_file();
2147 }
2148
2149 $nboflines = (GETPOSTISSET("nboflines") ? GETPOSTINT("nboflines") : dol_count_nb_of_line($conf->import->dir_temp.'/'.$filetoimport));
2150
2151 $param = '&format='.$format.'&datatoimport='.urlencode($datatoimport).'&filetoimport='.urlencode($filetoimport).'&nboflines='.((int) $nboflines).'&importtriggermode='.urlencode($importtriggermode);
2152 if ($excludefirstline) {
2153 $param .= '&excludefirstline='.urlencode($excludefirstline);
2154 }
2155 if ($endatlinenb) {
2156 $param .= '&endatlinenb='.urlencode($endatlinenb);
2157 }
2158 if ($separator) {
2159 $param .= '&separator='.urlencode($separator);
2160 }
2161 if ($enclosure) {
2162 $param .= '&enclosure='.urlencode($enclosure);
2163 }
2164
2165 llxHeader('', $langs->trans("NewImport"), $help_url);
2166
2167 $head = import_prepare_head($param, 5);
2168
2169 print dol_get_fiche_head($head, 'step5', 'Import', -1, 'upload');
2170
2171 print '<div class="underbanner clearboth"></div>';
2172 print '<div class="fichecenter">';
2173
2174 print '<table width="100%" class="border">';
2175
2176 // Module
2177 print '<tr><td class="titlefieldcreate">'.$langs->trans("Module").'</td>';
2178 print '<td>';
2179 $titleofmodule = $objimport->array_import_module[0]['module']->getName();
2180 // Special case for import common to module/services
2181 if (in_array($objimport->array_import_code[0], array('produit_supplierprices', 'produit_multiprice', 'produit_languages'))) {
2182 $titleofmodule = $langs->trans("ProductOrService");
2183 }
2184 print $titleofmodule;
2185 print '</td></tr>';
2186
2187 // Lot de donnees a importer
2188 print '<tr><td>'.$langs->trans("DatasetToImport").'</td>';
2189 print '<td>';
2190 $entity = preg_replace('/:.*$/', '', $objimport->array_import_icon[0]);
2191 $entityicon = strtolower(!empty($entitytoicon[$entity]) ? $entitytoicon[$entity] : $entity);
2192 print img_object($objimport->array_import_module[0]['module']->getName(), $entityicon).' ';
2193 print $objimport->array_import_label[0];
2194 print '</td></tr>';
2195
2196 print '</table>';
2197 print '</div>';
2198
2199 print '<br>';
2200
2201 print load_fiche_titre($langs->trans("InformationOnSourceFile"), '', 'file-export');
2202
2203 print '<div class="underbanner clearboth"></div>';
2204 print '<div class="fichecenter">';
2205 print '<table width="100%" class="border tableforfield">';
2206
2207 // Source file format
2208 print '<tr><td class="titlefieldcreate">'.$langs->trans("SourceFileFormat").'</td>';
2209 print '<td class="nowraponall">';
2210 $text = $objmodelimport->getDriverDescForKey($format);
2211 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
2212 print $form->textwithpicto($objmodelimport->getDriverLabelForKey($format), $text);
2213 print '</td></tr>';
2214
2215 // Separator and enclosure
2216 if ($model == 'csv') {
2217 '@phan-var-force ImportCsv $obj';
2218 print '<tr><td>'.$langs->trans("CsvOptions").'</td>';
2219 print '<td>';
2220 print $langs->trans("Separator").' : ';
2221 print htmlentities($separator);
2222 print '&nbsp;&nbsp;&nbsp;&nbsp;'.$langs->trans("Enclosure").' : ';
2223 print htmlentities($enclosure);
2224 print '</td></tr>';
2225 }
2226
2227 // File to import
2228 print '<tr><td>'.$langs->trans("FileToImport").'</td>';
2229 print '<td>';
2230 $modulepart = 'import';
2231 $relativepath = GETPOST('filetoimport');
2232 print '<a data-ajax="false" href="'.DOL_URL_ROOT.'/document.php?modulepart='.$modulepart.'&file='.urlencode($relativepath).'&step=4'.$param.'" target="_blank" rel="noopener noreferrer">';
2233 print img_mime($file, '', 'pictofixedwidth');
2234 print $filetoimport;
2235 print '</a>';
2236 print '</td></tr>';
2237
2238 // Nb of fields
2239 print '<tr><td>';
2240 print $langs->trans("NbOfSourceLines");
2241 print '</td><td>';
2242 print $nboflines;
2243 print '</td></tr>';
2244
2245 // Do not import first lines
2246 print '<tr><td>';
2247 print $langs->trans("ImportFromLine");
2248 print '</td><td>';
2249 print '<input type="text" size="4" name="excludefirstline" disabled="disabled" value="'.$excludefirstline.'">';
2250 print '</td></tr>';
2251
2252 // Do not import end lines
2253 print '<tr><td>';
2254 print $langs->trans("EndAtLineNb");
2255 print '</td><td>';
2256 print '<input type="text" size="4" name="endatlinenb" disabled="disabled" value="'.$endatlinenb.'">';
2257 print '</td></tr>';
2258
2259 // Trigger mode
2260 print '<tr><td>';
2261 print $langs->trans("ImportTriggerModeLabel");
2262 print '</td><td>';
2263 if ($importtriggermode === 'fast_bulk') {
2264 print $langs->trans("ImportTriggerModeSummaryFast");
2265 } else {
2266 print $langs->trans("ImportTriggerModeSummaryStrict");
2267 }
2268 print '<br><span class="opacitymedium">';
2269 print $langs->trans("ImportTriggerModeSummaryHint");
2270 print '</span>';
2271 print '</td></tr>';
2272
2273 print '</table>';
2274 print '</div>';
2275
2276 print '<br>';
2277
2278 print '<b>'.$langs->trans("InformationOnTargetTables").'</b>';
2279 print '<div class="underbanner clearboth"></div>';
2280 print '<div class="fichecenter">';
2281 print '<table class="border centpercent">';
2282
2283 // Tables imported
2284 print '<tr><td width="25%">';
2285 print $langs->trans("TablesTarget");
2286 print '</td><td>';
2287 $listtables = array();
2288 foreach ($array_match_file_to_database as $code => $label) {
2289 //var_dump($fieldssource);
2290 if ($code > count($fieldssource)) {
2291 continue;
2292 }
2293 //print $code.'-'.$label;
2294 $alias = preg_replace('/(\..*)$/i', '', $label);
2295 $listtables[$alias] = $objimport->array_import_tables[0][$alias];
2296 }
2297 if (count($listtables)) {
2298 $newval = '';
2299 foreach ($listtables as $val) {
2300 if ($newval) {
2301 print ', ';
2302 }
2303 $newval = $val;
2304 // Link to Dolibarr wiki pages
2305 /*$helppagename='EN:Table_'.$newval;
2306 if ($helppagename && empty($conf->global->MAIN_HELP_DISABLELINK))
2307 {
2308 // Get helpbaseurl, helppage and mode from helppagename and langs
2309 $arrayres=getHelpParamFor($helppagename,$langs);
2310 $helpbaseurl=$arrayres['helpbaseurl'];
2311 $helppage=$arrayres['helppage'];
2312 $mode=$arrayres['mode'];
2313 $newval.=' <a href="'.sprintf($helpbaseurl,$helppage).'">'.img_picto($langs->trans($mode == 'wiki' ? 'GoToWikiHelpPage': 'GoToHelpPage'),DOL_URL_ROOT.'/theme/common/helpdoc.png','',1).'</a>';
2314 }*/
2315 print $newval;
2316 }
2317 } else {
2318 print $langs->trans("Error");
2319 }
2320 print '</td></tr>';
2321
2322 // Fields imported
2323 print '<tr><td>';
2324 print $langs->trans("FieldsTarget").'</td><td>';
2325 $listfields = array();
2326 $i = 0;
2327 $sort_array_match_file_to_database = $array_match_file_to_database;
2328 ksort($sort_array_match_file_to_database);
2329 //var_dump($sort_array_match_file_to_database);
2330 foreach ($sort_array_match_file_to_database as $code => $label) {
2331 $i++;
2332 //var_dump($fieldssource);
2333 if ($code > count($fieldssource)) {
2334 continue;
2335 }
2336 //print $code.'-'.$label;
2337 $alias = preg_replace('/(\..*)$/i', '', $label);
2338 $listfields[$i] = $langs->trans("Field").' '.$code.'->'.$label;
2339 }
2340 print count($listfields) ? (implode(', ', $listfields)) : $langs->trans("Error");
2341 print '</td></tr>';
2342
2343 print '</table>';
2344 print '</div>';
2345
2346 // Launch import
2347 $arrayoferrors = array();
2348 $arrayofwarnings = array();
2349 $maxnboferrors = !getDolGlobalString('IMPORT_MAX_NB_OF_ERRORS') ? 50 : $conf->global->IMPORT_MAX_NB_OF_ERRORS;
2350 $maxnbofwarnings = !getDolGlobalString('IMPORT_MAX_NB_OF_WARNINGS') ? 50 : $conf->global->IMPORT_MAX_NB_OF_WARNINGS;
2351 $nboferrors = 0;
2352 $nbofwarnings = 0;
2353
2354 $importid = dol_print_date(dol_now(), '%Y%m%d%H%M%S');
2355
2356 //var_dump($array_match_file_to_database);
2357
2358 $db->begin();
2359
2360 // Open input file
2361 $nbok = 0;
2362 $pathfile = $conf->import->dir_temp.'/'.$filetoimport;
2363 $result = $obj->import_open_file($pathfile);
2364 if ($result > 0) {
2365 global $tablewithentity_cache;
2366 $tablewithentity_cache = array();
2367 $sourcelinenb = 0;
2368 $endoffile = 0;
2369
2370 while ($sourcelinenb < $nboflines && !$endoffile) {
2371 $sourcelinenb++;
2372 $arrayrecord = $obj->import_read_record();
2373 if ($arrayrecord === false) {
2374 $arrayofwarnings[$sourcelinenb][0] = array('lib' => $langs->trans('ErrorFileLinesReachEOF', $nboflines, $sourcelinenb), 'type' => 'EOF_RECORD_ON_SEVERAL_LINES');
2375 $endoffile++;
2376 continue;
2377 }
2378 if ($excludefirstline && ($sourcelinenb < $excludefirstline)) {
2379 continue;
2380 }
2381 if ($endatlinenb && ($sourcelinenb > $endatlinenb)) {
2382 break;
2383 }
2384
2385 $parameters = array(
2386 'step' => $step,
2387 'datatoimport' => $datatoimport,
2388 'obj' => &$obj,
2389 'arrayrecord' => $arrayrecord,
2390 'array_match_file_to_database' => $array_match_file_to_database,
2391 'objimport' => $objimport,
2392 'fieldssource' => $fieldssource,
2393 'importid' => $importid,
2394 'updatekeys' => $updatekeys,
2395 'importtriggermode' => $importtriggermode,
2396 'arrayoferrors' => &$arrayoferrors,
2397 'arrayofwarnings' => &$arrayofwarnings,
2398 'nbok' => &$nbok,
2399 );
2400
2401 $reshook = $hookmanager->executeHooks('ImportInsert', $parameters);
2402 if ($reshook < 0) {
2403 $arrayoferrors[$sourcelinenb][] = [
2404 'lib' => implode("<br>", array_merge([$hookmanager->error], $hookmanager->errors))
2405 ];
2406 }
2407
2408 if (empty($reshook)) {
2409 // Run import
2410 $result = $obj->import_insert($arrayrecord, $array_match_file_to_database, $objimport, count($fieldssource), $importid, $updatekeys);
2411
2412 if (count($obj->errors)) {
2413 $arrayoferrors[$sourcelinenb] = $obj->errors;
2414 }
2415 if (count($obj->warnings)) {
2416 $arrayofwarnings[$sourcelinenb] = $obj->warnings;
2417 }
2418
2419 if (!count($obj->errors) && !count($obj->warnings)) {
2420 $nbok++;
2421 }
2422 }
2423
2424 $reshook = $hookmanager->executeHooks('AfterImportInsert', $parameters);
2425 if ($reshook < 0) {
2426 $arrayoferrors[$sourcelinenb][] = [
2427 'lib' => implode("<br>", array_merge([$hookmanager->error], $hookmanager->errors))
2428 ];
2429 }
2430 }
2431 // Close file
2432 $obj->import_close_file();
2433 } else {
2434 print $langs->trans("ErrorFailedToOpenFile", $pathfile);
2435 }
2436
2437 if (count($arrayoferrors) > 0) {
2438 $db->rollback(); // We force rollback because this was errors.
2439 } else {
2440 $error = 0;
2441
2442 // Run the sql after import if defined
2443 //var_dump($objimport->array_import_run_sql_after[0]);
2444 if (!empty($objimport->array_import_run_sql_after[0]) && is_array($objimport->array_import_run_sql_after[0])) {
2445 $i = 0;
2446 foreach ($objimport->array_import_run_sql_after[0] as $sqlafterimport) {
2447 $i++;
2448 $resqlafterimport = $db->query($sqlafterimport);
2449 if (!$resqlafterimport) {
2450 $arrayoferrors['none'][] = array('lib' => $langs->trans("Error running final request: ".$sqlafterimport));
2451 $error++;
2452 }
2453 }
2454 }
2455
2456 if (!$error && $importtriggermode === 'fast_bulk') {
2457 $resbulktrigger = $obj->runImportBulkTrigger($importid, $user, $langs, $conf);
2458 if ($resbulktrigger < 0) {
2459 $arrayoferrors['none'][] = array('lib' => $langs->trans("ErrorFailedTriggerCall"), 'type' => 'TRIGGER');
2460 if (!empty($obj->errors) && is_array($obj->errors)) {
2461 foreach ($obj->errors as $tmperror) {
2462 $lib = (is_array($tmperror) ? ($tmperror['lib'] ?? '') : $tmperror);
2463 if ($lib !== '') {
2464 $arrayoferrors['none'][] = array('lib' => $lib, 'type' => 'TRIGGER');
2465 }
2466 }
2467 }
2468 $error++;
2469 }
2470 }
2471
2472 if (!$error) {
2473 $db->commit(); // We can commit if no errors.
2474 } else {
2475 $db->rollback();
2476 }
2477 }
2478
2479 print dol_get_fiche_end();
2480
2481 if ($importtriggermode === 'fast_bulk') {
2482 print '<div class="warning">';
2483 print '<b>'.$langs->trans("ImportTriggerModeFastBulkFinalWarningTitle").'</b><br>';
2484 print $langs->trans("ImportTriggerModeFastBulkFinalWarning");
2485 print '</div><br>';
2486 }
2487
2488
2489 // Show result
2490 print '<br>';
2491 print '<div class="info">';
2492 print $langs->trans("NbOfLinesImported", $nbok).'</b><br>';
2493 print $langs->trans("NbInsert", empty($obj->nbinsert) ? 0 : $obj->nbinsert).'<br>';
2494 print $langs->trans("NbUpdate", empty($obj->nbupdate) ? 0 : $obj->nbupdate).'<br>';
2495 print '</div>';
2496 print '<div class="center">';
2497 print $langs->trans("FileWasImported", $importid).'<br>';
2498 print '<span class="opacitymedium">'.$langs->trans("YouCanUseImportIdToFindRecord", $importid).'</span><br>';
2499 print '</div>';
2500}
2501
2502
2503
2504print '<br>';
2505
2506// End of page
2507llxFooter();
2508$db->close();
2509
2510
2519function show_elem($fieldssource, $pos, $key)
2520{
2521 global $conf, $langs;
2522
2523 $height = '32px';
2524
2525 if ($key == 'none') {
2526 //stop multiple duplicate ids with no number
2527 print "\n\n<!-- Box_no-key start-->\n";
2528 print '<div class="box boximport" style="padding:0;">'."\n";
2529 print '<table summary="boxtable_no-key" class="centpercent nobordernopadding">'."\n";
2530 } else {
2531 print "\n\n<!-- Box ".$pos." start -->\n";
2532 print '<div class="box boximport" style="padding: 0;" id="boxto_'.$pos.'">'."\n";
2533
2534 print '<table summary="boxtable'.$pos.'" class="nobordernopadding centpercent tableimport">'."\n";
2535 }
2536
2537 if (($pos && $pos > count($fieldssource)) && (!isset($fieldssource[$pos]["imported"]))) { // No fields
2538 /*
2539 print '<tr style="height:'.$height.'" class="trimport oddevenimport">';
2540 print '<td class="nocellnopadd" width="16" style="font-weight: normal">';
2541 print '</td>';
2542 print '<td style="font-weight: normal">';
2543 print $langs->trans("NoFields");
2544 print '</td>';
2545 print '</tr>';
2546 */
2547 } elseif ($key == 'none') { // Empty line
2548 print '<tr style="height:'.$height.'" class="trimport oddevenimport">';
2549 print '<td class="nocellnopadd" width="16" style="font-weight: normal">';
2550 print '&nbsp;';
2551 print '</td>';
2552 print '<td style="font-weight: normal">';
2553 print '&nbsp;';
2554 print '</td>';
2555 print '</tr>';
2556 } else {
2557 // Print field of source file
2558 print '<tr style="height:'.$height.'" class="trimport oddevenimport">';
2559 print '<td class="nocellnopadd" width="16" style="font-weight: normal">';
2560 // The image must have the class 'boxhandle' because it's value used in DOM draggable objects to define the area used to catch the full object
2561 //print img_picto($langs->trans("MoveField", $pos), 'grip_title', 'class="boxhandle" style="cursor:move;"');
2562 print img_picto($langs->trans("Column").' '.num2Alpha($pos - 1), 'file', 'class="pictofixedwidth marginleftonly"');
2563 print '</td>';
2564 if (isset($fieldssource[$pos]['imported']) && $fieldssource[$pos]['imported'] == false) {
2565 print '<td class="nowraponall boxtdunused" style="font-weight: normal">';
2566 } else {
2567 print '<td class="nowraponall tdoverflowmax500" style="font-weight: normal">';
2568 }
2569 print $langs->trans("Column").' '.num2Alpha($pos - 1).' (#'.$pos.')';
2570 if (empty($fieldssource[$pos]['example1'])) {
2571 $example = $fieldssource[$pos]['label'];
2572 } else {
2573 $example = $fieldssource[$pos]['example1'];
2574 }
2575 if ($example) {
2576 if (!utf8_check($example)) {
2577 $example = mb_convert_encoding($example, 'UTF-8', 'ISO-8859-1');
2578 }
2579 // if (!empty($conf->dol_optimize_smallscreen)) { //print '<br>'; }
2580 print ' - ';
2581 print '<i class="opacitymedium">'.dol_escape_htmltag($example).'</i>';
2582 }
2583 print '</td>';
2584 print '</tr>';
2585 }
2586
2587 print "</table>\n";
2588
2589 print "</div>\n";
2590 print "<!-- Box end -->\n\n";
2591}
2592
2593
2601function getnewkey(&$fieldssource, &$listofkey)
2602{
2603 $i = count($fieldssource) + 1;
2604 // Max number of key
2605 $maxkey = 0;
2606 foreach ($listofkey as $key => $val) {
2607 $maxkey = max($maxkey, $key);
2608 }
2609 // Found next empty key
2610 while ($i <= $maxkey) {
2611 if (empty($listofkey[$i])) {
2612 break;
2613 } else {
2614 $i++;
2615 }
2616 }
2617
2618 $listofkey[$i] = 1;
2619 return $i;
2620}
2629function arrayInsert($array, $position, $insertArray)
2630{
2631 $ret = [];
2632
2633 if ($position == count($array)) {
2634 $ret = $array + $insertArray;
2635 } else {
2636 $i = 0;
2637 foreach ($array as $key => $value) {
2638 if ($position == $i++) {
2639 $ret += $insertArray;
2640 }
2641
2642 $ret[$key] = $value;
2643 }
2644 }
2645
2646 return $ret;
2647}
ajax_combobox($htmlname, $events=array(), $minLengthToAutocomplete=0, $forcefocus=0, $widthTypeOfAutocomplete='resolve', $idforemptyvalue='-1', $morecss='', $placeholder='')
Convert a html select field into an ajax combobox.
Definition ajax.lib.php:488
llxFooter($comment='', $zone='private', $disabledoutputofmessages=0)
Empty footer.
Definition wrapper.php:91
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.
Definition wrapper.php:73
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
Class to manage generation of HTML components Only common components must be here.
Class to help generate other html components Only common components are here.
Class to manage imports.
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.
Definition files.lib.php:66
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.
Definition html.lib.php:542
dol_get_fiche_end($notab=0)
Return tab footer of a card.
Definition html.lib.php:740
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)
Definition html.lib.php:183
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.
Definition import.php:2519
getnewkey(&$fieldssource, &$listofkey)
Return not used field number.
Definition import.php:2601
arrayInsert($array, $position, $insertArray)
Return array with element inserted in it at position $position.
Definition import.php:2629
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.