/
import.php
2510 lines (2174 loc) · 92.6 KB
/
import.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/* Copyright (C) 2005-2016 Laurent Destailleur <eldy@users.sourceforge.net>
* Copyright (C) 2005-2009 Regis Houssin <regis.houssin@inodbox.com>
* Copyright (C) 2012 Christophe Battarel <christophe.battarel@altairis.fr>
* Copyright (C) 2022 Charlene Benke <charlene@patas-monkey.com>
* Copyright (C) 2024 MDW <mdeweerd@users.noreply.github.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/**
* \file htdocs/imports/import.php
* \ingroup import
* \brief Pages of import Wizard
*/
require_once '../main.inc.php';
require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php';
require_once DOL_DOCUMENT_ROOT.'/imports/class/import.class.php';
require_once DOL_DOCUMENT_ROOT.'/core/modules/import/modules_import.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/import.lib.php';
// Load translation files required by the page
$langs->loadLangs(array('exports', 'compta', 'errors', 'admin'));
// Security check
$result = restrictedArea($user, 'import');
// Map icons, array duplicated in export.php, was not synchronized, TODO put it somewhere only once
$entitytoicon = array(
'invoice' => 'bill',
'invoice_line' => 'bill',
'order' => 'order',
'order_line' => 'order',
'propal' => 'propal',
'propal_line' => 'propal',
'intervention' => 'intervention',
'inter_line' => 'intervention',
'member' => 'user',
'member_type' => 'group',
'subscription' => 'payment',
'payment' => 'payment',
'tax' => 'bill',
'tax_type' => 'generic',
'other' => 'generic',
'account' => 'account',
'product' => 'product',
'virtualproduct' => 'product',
'subproduct' => 'product',
'product_supplier_ref' => 'product',
'stock' => 'stock',
'warehouse' => 'stock',
'batch' => 'stock',
'stockbatch' => 'stock',
'category' => 'category',
'shipment' => 'sending',
'shipment_line' => 'sending',
'reception' => 'sending',
'reception_line' => 'sending',
'expensereport' => 'trip',
'expensereport_line' => 'trip',
'holiday' => 'holiday',
'contract_line' => 'contract',
'translation' => 'generic',
'bomm' => 'bom',
'bomline' => 'bom'
);
// Translation code, array duplicated in export.php, was not synchronized, TODO put it somewhere only once
$entitytolang = array(
'user' => 'User',
'company' => 'Company',
'contact' => 'Contact',
'invoice' => 'Bill',
'invoice_line' => 'InvoiceLine',
'order' => 'Order',
'order_line' => 'OrderLine',
'propal' => 'Proposal',
'propal_line' => 'ProposalLine',
'intervention' => 'Intervention',
'inter_line' => 'InterLine',
'member' => 'Member',
'member_type' => 'MemberType',
'subscription' => 'Subscription',
'tax' => 'SocialContribution',
'tax_type' => 'DictionarySocialContributions',
'account' => 'BankTransactions',
'payment' => 'Payment',
'product' => 'Product',
'virtualproduct' => 'AssociatedProducts',
'subproduct' => 'SubProduct',
'product_supplier_ref' => 'SupplierPrices',
'service' => 'Service',
'stock' => 'Stock',
'movement' => 'StockMovement',
'batch' => 'Batch',
'stockbatch' => 'StockDetailPerBatch',
'warehouse' => 'Warehouse',
'category' => 'Category',
'other' => 'Other',
'trip' => 'TripsAndExpenses',
'shipment' => 'Shipments',
'shipment_line' => 'ShipmentLine',
'project' => 'Projects',
'projecttask' => 'Tasks',
'task_time' => 'TaskTimeSpent',
'action' => 'Event',
'expensereport' => 'ExpenseReport',
'expensereport_line' => 'ExpenseReportLine',
'holiday' => 'TitreRequestCP',
'contract' => 'Contract',
'contract_line' => 'ContractLine',
'translation' => 'Translation',
'bom' => 'BOM',
'bomline' => 'BOMLine'
);
$datatoimport = GETPOST('datatoimport');
$format = GETPOST('format');
$filetoimport = GETPOST('filetoimport');
$action = GETPOST('action', 'alpha');
$confirm = GETPOST('confirm', 'alpha');
$step = (GETPOST('step') ? GETPOST('step') : 1);
$import_name = GETPOST('import_name');
$hexa = GETPOST('hexa');
$importmodelid = GETPOSTINT('importmodelid');
$excludefirstline = (GETPOST('excludefirstline') ? GETPOST('excludefirstline') : 2);
$endatlinenb = (GETPOST('endatlinenb') ? GETPOST('endatlinenb') : '');
$updatekeys = (GETPOST('updatekeys', 'array') ? GETPOST('updatekeys', 'array') : array());
$separator = (GETPOST('separator', 'nohtml') ? GETPOST('separator', 'nohtml', 3) : '');
$enclosure = (GETPOST('enclosure', 'nohtml') ? GETPOST('enclosure', 'nohtml') : '"'); // We must use 'nohtml' and not 'alphanohtml' because we must accept "
$charset = GETPOST('charset', 'aZ09');
$separator_used = str_replace('\t', "\t", $separator);
// Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
$hookmanager->initHooks(array('imports'));
$objimport = new Import($db);
$objimport->load_arrays($user, ($step == 1 ? '' : $datatoimport));
if (empty($updatekeys) && !empty($objimport->array_import_preselected_updatekeys[0])) {
$updatekeys = array_keys($objimport->array_import_preselected_updatekeys[0]);
}
$objmodelimport = new ModeleImports();
$form = new Form($db);
$htmlother = new FormOther($db);
$formfile = new FormFile($db);
// Init $array_match_file_to_database from _SESSION
if (empty($array_match_file_to_database)) {
$serialized_array_match_file_to_database = isset($_SESSION["dol_array_match_file_to_database_select"]) ? $_SESSION["dol_array_match_file_to_database_select"] : '';
$array_match_file_to_database = array();
$fieldsarray = explode(',', $serialized_array_match_file_to_database);
foreach ($fieldsarray as $elem) {
$tabelem = explode('=', $elem, 2);
$key = $tabelem[0];
$val = (isset($tabelem[1]) ? $tabelem[1] : '');
if ($key && $val) {
$array_match_file_to_database[$key] = $val;
}
}
}
/*
* Actions
*/
if ($action == 'deleteprof') {
if (GETPOSTINT("id")) {
$objimport->fetch(GETPOSTINT("id"));
$result = $objimport->delete($user);
}
}
// Save import config to database
if ($action == 'add_import_model') {
if ($import_name) {
// Set save string
$hexa = '';
foreach ($array_match_file_to_database as $key => $val) {
if ($hexa) {
$hexa .= ',';
}
$hexa .= $key.'='.$val;
}
$objimport->model_name = $import_name;
$objimport->datatoimport = $datatoimport;
$objimport->hexa = $hexa;
$objimport->fk_user = (GETPOST('visibility', 'aZ09') == 'all' ? 0 : $user->id);
$result = $objimport->create($user);
if ($result >= 0) {
setEventMessages($langs->trans("ImportModelSaved", $objimport->model_name), null, 'mesgs');
$import_name = '';
} else {
$langs->load("errors");
if ($objimport->errno == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
setEventMessages($langs->trans("ErrorImportDuplicateProfil"), null, 'errors');
} else {
setEventMessages($objimport->error, null, 'errors');
}
}
} else {
setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("ImportModelName")), null, 'errors');
}
}
if ($step == 3 && $datatoimport) {
if (GETPOST('sendit') && getDolGlobalString('MAIN_UPLOAD_DOC')) {
dol_mkdir($conf->import->dir_temp);
$nowyearmonth = dol_print_date(dol_now(), '%Y%m%d%H%M%S');
$fullpath = $conf->import->dir_temp."/".$nowyearmonth.'-'.$_FILES['userfile']['name'];
if (dol_move_uploaded_file($_FILES['userfile']['tmp_name'], $fullpath, 1) > 0) {
dol_syslog("File ".$fullpath." was added for import");
} else {
$langs->load("errors");
setEventMessages($langs->trans("ErrorFailedToSaveFile"), null, 'errors');
}
}
// Delete file
if ($action == 'confirm_deletefile' && $confirm == 'yes') {
$langs->load("other");
$param = '&datatoimport='.urlencode($datatoimport).'&format='.urlencode($format);
if ($excludefirstline) {
$param .= '&excludefirstline='.urlencode($excludefirstline);
}
if ($endatlinenb) {
$param .= '&endatlinenb='.urlencode($endatlinenb);
}
$file = $conf->import->dir_temp.'/'.GETPOST('urlfile');
$ret = dol_delete_file($file);
if ($ret) {
setEventMessages($langs->trans("FileWasRemoved", GETPOST('urlfile')), null, 'mesgs');
} else {
setEventMessages($langs->trans("ErrorFailToDeleteFile", GETPOST('urlfile')), null, 'errors');
}
header('Location: '.$_SERVER["PHP_SELF"].'?step='.$step.$param);
exit;
}
}
if ($step == 4 && $action == 'select_model') {
// Reinit match arrays
$_SESSION["dol_array_match_file_to_database"] = '';
$serialized_array_match_file_to_database = '';
$array_match_file_to_database = array();
// Load model from $importmodelid and set $array_match_file_to_database
// and $_SESSION["dol_array_match_file_to_database"]
$result = $objimport->fetch($importmodelid);
if ($result > 0) {
$serialized_array_match_file_to_database = $objimport->hexa;
$fieldsarray = explode(',', $serialized_array_match_file_to_database);
foreach ($fieldsarray as $elem) {
$tabelem = explode('=', $elem);
$key = $tabelem[0];
$val = $tabelem[1];
if ($key && $val) {
$array_match_file_to_database[$key] = $val;
}
}
$_SESSION["dol_array_match_file_to_database"] = $serialized_array_match_file_to_database;
$_SESSION['dol_array_match_file_to_database_select'] = $_SESSION["dol_array_match_file_to_database"];
}
}
if ($action == 'saveselectorder') {
// Enregistrement de la position des champs
$serialized_array_match_file_to_database = '';
dol_syslog("selectorder=".GETPOST('selectorder'), LOG_DEBUG);
$selectorder = explode(",", GETPOST('selectorder'));
$fieldtarget = $fieldstarget = $objimport->array_import_fields[0];
foreach ($selectorder as $key => $code) {
$serialized_array_match_file_to_database .= $key.'='.$code;
$serialized_array_match_file_to_database .= ',';
}
$serialized_array_match_file_to_database = substr($serialized_array_match_file_to_database, 0, -1);
dol_syslog('dol_array_match_file_to_database_select='.$serialized_array_match_file_to_database);
$_SESSION["dol_array_match_file_to_database_select"] = $serialized_array_match_file_to_database;
echo "{}";
exit(0);
}
/*
* View
*/
$help_url = 'EN:Module_Imports_En|FR:Module_Imports|ES:Módulo_Importaciones';
// STEP 1: Page to select dataset to import
if ($step == 1 || !$datatoimport) {
// Clean saved file-database matching
$serialized_array_match_file_to_database = '';
$array_match_file_to_database = array();
$_SESSION["dol_array_match_file_to_database"] = '';
$_SESSION["dol_array_match_file_to_database_select"] = '';
$param = '';
if ($excludefirstline) {
$param .= '&excludefirstline='.urlencode($excludefirstline);
}
if ($endatlinenb) {
$param .= '&endatlinenb='.urlencode($endatlinenb);
}
if ($separator) {
$param .= '&separator='.urlencode($separator);
}
if ($enclosure) {
$param .= '&enclosure='.urlencode($enclosure);
}
llxHeader('', $langs->trans("NewImport"), $help_url);
$head = import_prepare_head($param, 1);
print dol_get_fiche_head($head, 'step1', '', -1);
print '<div class="opacitymedium">'.$langs->trans("SelectImportDataSet").'</div><br>';
// Affiche les modules d'imports
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
print '<table class="noborder centpercent">';
print '<tr class="liste_titre">';
print '<td>'.$langs->trans("Module").'</td>';
print '<td>'.$langs->trans("ImportableDatas").'</td>';
print '<td> </td>';
print '</tr>';
if (count($objimport->array_import_module)) {
$sortedarrayofmodules = dol_sort_array($objimport->array_import_module, 'position_of_profile', 'asc', 0, 0, 1);
foreach ($sortedarrayofmodules as $key => $value) {
//var_dump($key.' '.$value['position_of_profile'].' '.$value['import_code'].' '.$objimport->array_import_module[$key]['module']->getName().' '.$objimport->array_import_code[$key]);
print '<tr class="oddeven"><td>';
$titleofmodule = $objimport->array_import_module[$key]['module']->getName();
// Special cas for import common to module/services
if (in_array($objimport->array_import_code[$key], array('produit_supplierprices', 'produit_multiprice', 'produit_languages'))) {
$titleofmodule = $langs->trans("ProductOrService");
}
print $titleofmodule;
print '</td><td>';
$entity = preg_replace('/:.*$/', '', $objimport->array_import_icon[$key]);
$entityicon = strtolower(!empty($entitytoicon[$entity]) ? $entitytoicon[$entity] : $entity);
print img_object($objimport->array_import_module[$key]['module']->getName(), $entityicon).' ';
print $objimport->array_import_label[$key];
print '</td><td style="text-align: right">';
if ($objimport->array_import_perms[$key]) {
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>';
} else {
print $langs->trans("NotEnoughPermissions");
}
print '</td></tr>';
}
} else {
print '<tr><td class="oddeven" colspan="3">'.$langs->trans("NoImportableData").'</td></tr>';
}
print '</table>';
print '</div>';
print dol_get_fiche_end();
}
// STEP 2: Page to select input format file
if ($step == 2 && $datatoimport) {
$param = '&datatoimport='.urlencode($datatoimport);
if ($excludefirstline) {
$param .= '&excludefirstline='.urlencode($excludefirstline);
}
if ($endatlinenb) {
$param .= '&endatlinenb='.urlencode($endatlinenb);
}
if ($separator) {
$param .= '&separator='.urlencode($separator);
}
if ($enclosure) {
$param .= '&enclosure='.urlencode($enclosure);
}
llxHeader('', $langs->trans("NewImport"), $help_url);
$head = import_prepare_head($param, 2);
print dol_get_fiche_head($head, 'step2', '', -2);
print '<div class="underbanner clearboth"></div>';
print '<div class="fichecenter">';
print '<table class="border tableforfield centpercent">';
// Module
print '<tr><td class="titlefieldcreate">'.$langs->trans("Module").'</td>';
print '<td>';
$titleofmodule = $objimport->array_import_module[0]['module']->getName();
// Special cas for import common to module/services
if (in_array($objimport->array_import_code[0], array('produit_supplierprices', 'produit_multiprice', 'produit_languages'))) {
$titleofmodule = $langs->trans("ProductOrService");
}
print $titleofmodule;
print '</td></tr>';
// Dataset to import
print '<tr><td>'.$langs->trans("DatasetToImport").'</td>';
print '<td>';
$entity = preg_replace('/:.*$/', '', $objimport->array_import_icon[0]);
$entityicon = strtolower(!empty($entitytoicon[$entity]) ? $entitytoicon[$entity] : $entity);
print img_object($objimport->array_import_module[0]['module']->getName(), $entityicon).' ';
print $objimport->array_import_label[0];
print '</td></tr>';
print '</table>';
print '</div>';
print dol_get_fiche_end();
print '<form name="userfile" action="'.$_SERVER["PHP_SELF"].'" enctype="multipart/form-data" METHOD="POST">';
print '<input type="hidden" name="token" value="'.newToken().'">';
print '<br>';
print '<span class="opacitymedium">';
$s = $langs->trans("ChooseFormatOfFileToImport", '{s1}');
$s = str_replace('{s1}', img_picto('', 'next'), $s);
print $s;
print '</span><br><br>';
print '<br>';
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
print '<table class="noborder centpercent" cellpadding="4">';
$filetoimport = '';
// Add format information and link to download example
print '<tr class="liste_titre"><td colspan="5">';
print $langs->trans("FileMustHaveOneOfFollowingFormat");
print '</td></tr>';
$list = $objmodelimport->listOfAvailableImportFormat($db);
foreach ($list as $key) {
print '<tr class="oddeven">';
print '<td width="16">'.img_picto_common($key, $objmodelimport->getPictoForKey($key)).'</td>';
$text = $objmodelimport->getDriverDescForKey($key);
// @phan-suppress-next-line PhanPluginSuspiciousParamPosition
print '<td>'.$form->textwithpicto($objmodelimport->getDriverLabelForKey($key), $text).'</td>';
print '<td style="text-align:center">';
$filename = $langs->transnoentitiesnoconv("ExampleOfImportFile").'_'.$datatoimport.'.'.$key;
print '<a href="'.DOL_URL_ROOT.'/imports/emptyexample.php?format='.$key.$param.'&output=file&file='.urlencode($filename).'" target="_blank" rel="noopener noreferrer">';
print img_picto('', 'download', 'class="paddingright opacitymedium"');
print $langs->trans("DownloadEmptyExampleShort");
print '</a>';
print $form->textwithpicto('', $langs->trans("DownloadEmptyExample").'.<br>'.$langs->trans("StarAreMandatory"));
print '</td>';
// Action button
print '<td style="text-align:right">';
print '<a href="'.DOL_URL_ROOT.'/imports/import.php?step=3&format='.$key.$param.'">'.img_picto($langs->trans("SelectFormat"), 'next', 'class="fa-15"').'</a>';
print '</td>';
print '</tr>';
}
print '</table>';
print '</div>';
print '</form>';
}
// STEP 3: Page to select file
if ($step == 3 && $datatoimport) {
$param = '&datatoimport='.urlencode($datatoimport).'&format='.urlencode($format);
if ($excludefirstline) {
$param .= '&excludefirstline='.urlencode($excludefirstline);
}
if ($endatlinenb) {
$param .= '&endatlinenb='.urlencode($endatlinenb);
}
if ($separator) {
$param .= '&separator='.urlencode($separator);
}
if ($enclosure) {
$param .= '&enclosure='.urlencode($enclosure);
}
$list = $objmodelimport->listOfAvailableImportFormat($db);
llxHeader('', $langs->trans("NewImport"), $help_url);
$head = import_prepare_head($param, 3);
print dol_get_fiche_head($head, 'step3', '', -2);
/*
* Confirm delete file
*/
if ($action == 'delete') {
print $form->formconfirm($_SERVER["PHP_SELF"].'?urlfile='.urlencode(GETPOST('urlfile')).'&step=3'.$param, $langs->trans('DeleteFile'), $langs->trans('ConfirmDeleteFile'), 'confirm_deletefile', '', 0, 1);
}
print '<div class="underbanner clearboth"></div>';
print '<div class="fichecenter">';
print '<table class="border tableforfield centpercent">';
// Module
print '<tr><td class="titlefieldcreate">'.$langs->trans("Module").'</td>';
print '<td>';
$titleofmodule = $objimport->array_import_module[0]['module']->getName();
// Special cas for import common to module/services
if (in_array($objimport->array_import_code[0], array('produit_supplierprices', 'produit_multiprice', 'produit_languages'))) {
$titleofmodule = $langs->trans("ProductOrService");
}
print $titleofmodule;
print '</td></tr>';
// Lot de donnees a importer
print '<tr><td>'.$langs->trans("DatasetToImport").'</td>';
print '<td>';
$entity = preg_replace('/:.*$/', '', $objimport->array_import_icon[0]);
$entityicon = strtolower(!empty($entitytoicon[$entity]) ? $entitytoicon[$entity] : $entity);
print img_object($objimport->array_import_module[0]['module']->getName(), $entityicon).' ';
print $objimport->array_import_label[0];
print '</td></tr>';
print '</table>';
print '</div>';
print load_fiche_titre($langs->trans("InformationOnSourceFile"), '', 'file-export');
print '<div class="underbanner clearboth"></div>';
print '<div class="fichecenter">';
print '<table width="100%" class="border tableforfield">';
// Source file format
print '<tr><td class="titlefieldcreate">'.$langs->trans("SourceFileFormat").'</td>';
print '<td class="nowraponall">';
$text = $objmodelimport->getDriverDescForKey($format);
// @phan-suppress-next-line PhanPluginSuspiciousParamPosition
print $form->textwithpicto($objmodelimport->getDriverLabelForKey($format), $text);
print '</td><td style="text-align:right" class="nowrap">';
$filename = $langs->transnoentitiesnoconv("ExampleOfImportFile").'_'.$datatoimport.'.'.$format;
print '<a href="'.DOL_URL_ROOT.'/imports/emptyexample.php?format='.$format.$param.'&output=file&file='.urlencode($filename).'" target="_blank" rel="noopener noreferrer">';
print img_picto('', 'download', 'class="paddingright opacitymedium"');
print $langs->trans("DownloadEmptyExampleShort");
print '</a>';
print $form->textwithpicto('', $langs->trans("DownloadEmptyExample").'.<br>'.$langs->trans("StarAreMandatory"));
print '</td></tr>';
print '</table>';
print '</div>';
print dol_get_fiche_end();
if ($format == 'xlsx' && !class_exists('XMLWriter')) {
$langs->load("install");
print info_admin($langs->trans("ErrorPHPDoesNotSupport", 'php-xml'), 0, 0, 1, 'error');
}
print '<br><br>';
print '<form name="userfile" action="'.$_SERVER["PHP_SELF"].'" enctype="multipart/form-data" method="POST">';
print '<input type="hidden" name="token" value="'.newToken().'">';
print '<input type="hidden" value="'.$step.'" name="step">';
print '<input type="hidden" value="'.dol_escape_htmltag($format).'" name="format">';
print '<input type="hidden" value="'.$excludefirstline.'" name="excludefirstline">';
print '<input type="hidden" value="'.$endatlinenb.'" name="endatlinenb">';
print '<input type="hidden" value="'.dol_escape_htmltag($separator).'" name="separator">';
print '<input type="hidden" value="'.dol_escape_htmltag($enclosure).'" name="enclosure">';
print '<input type="hidden" value="'.dol_escape_htmltag($datatoimport).'" name="datatoimport">';
print '<span class="opacitymedium">';
$s = $langs->trans("ChooseFileToImport", '{s1}');
$s = str_replace('{s1}', img_picto('', 'next'), $s);
print $s;
print '</span><br><br>';
$filetoimport = '';
// Input file name box
print '<div class="marginbottomonly">';
$maxfilesizearray = getMaxFileSizeArray();
$maxmin = $maxfilesizearray['maxmin'];
if ($maxmin > 0) {
print '<input type="hidden" name="MAX_FILE_SIZE" value="'.($maxmin * 1024).'">'; // MAX_FILE_SIZE must precede the field type=file
}
print '<input type="file" name="userfile" size="20" maxlength="80"> ';
$out = (!getDolGlobalString('MAIN_UPLOAD_DOC') ? ' disabled' : '');
print '<input type="submit" class="button small" value="'.$langs->trans("AddFile").'"'.$out.' name="sendit">';
$out = '';
if (getDolGlobalString('MAIN_UPLOAD_DOC')) {
$max = getDolGlobalString('MAIN_UPLOAD_DOC'); // In Kb
$maxphp = @ini_get('upload_max_filesize'); // In unknown
if (preg_match('/k$/i', $maxphp)) {
$maxphp = (int) substr($maxphp, 0, -1);
}
if (preg_match('/m$/i', $maxphp)) {
$maxphp = (int) substr($maxphp, 0, -1) * 1024;
}
if (preg_match('/g$/i', $maxphp)) {
$maxphp = (int) substr($maxphp, 0, -1) * 1024 * 1024;
}
if (preg_match('/t$/i', $maxphp)) {
$maxphp = (int) substr($maxphp, 0, -1) * 1024 * 1024 * 1024;
}
$maxphp2 = @ini_get('post_max_size'); // In unknown
if (preg_match('/k$/i', $maxphp2)) {
$maxphp2 = (int) substr($maxphp2, 0, -1);
}
if (preg_match('/m$/i', $maxphp2)) {
$maxphp2 = (int) substr($maxphp2, 0, -1) * 1024;
}
if (preg_match('/g$/i', $maxphp2)) {
$maxphp2 = (int) substr($maxphp2, 0, -1) * 1024 * 1024;
}
if (preg_match('/t$/i', $maxphp2)) {
$maxphp2 = (int) substr($maxphp2, 0, -1) * 1024 * 1024 * 1024;
}
// Now $max and $maxphp and $maxphp2 are in Kb
$maxmin = $max;
$maxphptoshow = $maxphptoshowparam = '';
if ($maxphp > 0) {
$maxmin = min($max, $maxphp);
$maxphptoshow = $maxphp;
$maxphptoshowparam = 'upload_max_filesize';
}
if ($maxphp2 > 0) {
$maxmin = min($max, $maxphp2);
if ($maxphp2 < $maxphp) {
$maxphptoshow = $maxphp2;
$maxphptoshowparam = 'post_max_size';
}
}
$langs->load('other');
$out .= ' ';
$out .= info_admin($langs->trans("ThisLimitIsDefinedInSetup", $max, $maxphptoshow), 1);
} else {
$out .= ' ('.$langs->trans("UploadDisabled").')';
}
print $out;
print '</div>';
// Search available imports
$filearray = dol_dir_list($conf->import->dir_temp, 'files', 0, '', '', 'name', SORT_DESC);
if (count($filearray) > 0) {
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
print '<table class="noborder centpercent" width="100%" cellpadding="4">';
$dir = $conf->import->dir_temp;
// Search available files to import
$i = 0;
foreach ($filearray as $key => $val) {
$file = $val['name'];
// readdir return value in ISO and we want UTF8 in memory
if (!utf8_check($file)) {
$file = mb_convert_encoding($file, 'UTF-8', 'ISO-8859-1');
}
if (preg_match('/^\./', $file)) {
continue;
}
$modulepart = 'import';
$urlsource = $_SERVER["PHP_SELF"].'?step='.$step.$param.'&filetoimport='.urlencode($filetoimport);
$relativepath = $file;
print '<tr class="oddeven">';
print '<td>';
print img_mime($file, '', 'pictofixedwidth');
print '<a data-ajax="false" href="'.DOL_URL_ROOT.'/document.php?modulepart='.$modulepart.'&file='.urlencode($relativepath).'&step=3'.$param.'" target="_blank" rel="noopener noreferrer">';
print $file;
print '</a>';
print '</td>';
// Affiche taille fichier
print '<td style="text-align:right">'.dol_print_size(dol_filesize($dir.'/'.$file)).'</td>';
// Affiche date fichier
print '<td style="text-align:right">'.dol_print_date(dol_filemtime($dir.'/'.$file), 'dayhour').'</td>';
// Del button
print '<td style="text-align:right"><a href="'.$_SERVER['PHP_SELF'].'?action=delete&token='.newToken().'&step=3'.$param.'&urlfile='.urlencode($relativepath);
print '">'.img_delete().'</a></td>';
// Action button
print '<td style="text-align:right">';
print '<a href="'.$_SERVER['PHP_SELF'].'?step=4'.$param.'&filetoimport='.urlencode($relativepath).'">'.img_picto($langs->trans("NewImport"), 'next', 'class="fa-15"').'</a>';
print '</td>';
print '</tr>';
}
print '</table>';
print '</div>';
}
print '</form>';
}
// STEP 4: Page to make matching between source file and database fields
if ($step == 4 && $datatoimport) {
//var_dump($_SESSION["dol_array_match_file_to_database_select"]);
$serialized_array_match_file_to_database = isset($_SESSION["dol_array_match_file_to_database_select"]) ? $_SESSION["dol_array_match_file_to_database_select"] : '';
$fieldsarray = explode(',', $serialized_array_match_file_to_database);
$array_match_file_to_database = array(); // Same than $fieldsarray but with mapped value only (col1 => 's.fielda', col2 => 's.fieldb'...)
foreach ($fieldsarray as $elem) {
$tabelem = explode('=', $elem, 2);
$key = $tabelem[0];
$val = (isset($tabelem[1]) ? $tabelem[1] : '');
if ($key && $val) {
$array_match_file_to_database[$key] = $val;
}
}
//var_dump($serialized_array_match_file_to_database);
//var_dump($fieldsarray);
//var_dump($array_match_file_to_database);
$model = $format;
$list = $objmodelimport->listOfAvailableImportFormat($db);
if (empty($separator)) {
$separator = (!getDolGlobalString('IMPORT_CSV_SEPARATOR_TO_USE') ? ',' : $conf->global->IMPORT_CSV_SEPARATOR_TO_USE);
}
// The separator has been defined, if it is a unique char, we check it is valid by reading the source file
if ($model == 'csv' && strlen($separator) == 1 && !GETPOSTISSET('separator')) {
// Count the char in first line of file.
$fh = fopen($conf->import->dir_temp.'/'.$filetoimport, 'r');
if ($fh) {
$sline = fgets($fh, 1000000);
fclose($fh);
$nboccurence = substr_count($sline, $separator);
$nboccurencea = substr_count($sline, ',');
$nboccurenceb = substr_count($sline, ';');
//var_dump($nboccurence." ".$nboccurencea." ".$nboccurenceb);exit;
if ($nboccurence == 0) {
if ($nboccurencea > 2) {
$separator = ',';
} elseif ($nboccurenceb > 2) {
$separator = ';';
}
}
}
}
// The value to use
$separator_used = str_replace('\t', "\t", $separator);
// Create class to use for import
$dir = DOL_DOCUMENT_ROOT."/core/modules/import/";
$file = "import_".$model.".modules.php";
$classname = "Import".ucfirst($model);
require_once $dir.$file;
$obj = new $classname($db, $datatoimport);
if ($model == 'csv') {
$obj->separator = $separator_used;
$obj->enclosure = $enclosure;
$obj->charset = '';
}
if ($model == 'xlsx') {
if (!preg_match('/\.xlsx$/i', $filetoimport)) {
$langs->load("errors");
$param = '&datatoimport='.$datatoimport.'&format='.$format;
setEventMessages($langs->trans("ErrorFileMustHaveFormat", $model), null, 'errors');
header("Location: ".$_SERVER["PHP_SELF"].'?step=3'.$param.'&filetoimport='.urlencode($relativepath));
exit;
}
}
if (GETPOST('update')) {
$array_match_file_to_database = array();
}
// Load the source fields from input file into variable $arrayrecord
$fieldssource = array();
$result = $obj->import_open_file($conf->import->dir_temp.'/'.$filetoimport, $langs);
if ($result >= 0) {
// Read first line
$arrayrecord = $obj->import_read_record();
// Create array $fieldssource starting with 1 with values found of first line.
$i = 1;
foreach ($arrayrecord as $key => $val) {
if ($val["type"] != -1) {
$fieldssource[$i]['example1'] = dol_trunc($val['val'], 128);
$i++;
} else {
$fieldssource[$i]['example1'] = $langs->trans('Empty');
$i++;
}
}
$obj->import_close_file();
}
// Load targets fields in database
$fieldstarget = $objimport->array_import_fields[0];
$minpos = min(count($fieldssource), count($fieldstarget));
//var_dump($array_match_file_to_database);
$initialloadofstep4 = false;
if (empty($_SESSION['dol_array_match_file_to_database_select'])) {
$initialloadofstep4 = true;
}
// Is it a first time in page (if yes, we must initialize array_match_file_to_database)
if (count($array_match_file_to_database) == 0) {
// This is first input in screen, we need to define
// $array_match_file_to_database
// $serialized_array_match_file_to_database
// $_SESSION["dol_array_match_file_to_database"]
$pos = 1;
$num = count($fieldssource);
while ($pos <= $num) {
if ($num >= 1 && $pos <= $num) {
$posbis = 1;
foreach ($fieldstarget as $key => $val) {
if ($posbis < $pos) {
$posbis++;
continue;
}
// We found the key of targets that is at position pos
$array_match_file_to_database[$pos] = $key;
break;
}
}
$pos++;
}
}
$array_match_database_to_file = array_flip($array_match_file_to_database);
//var_dump($array_match_database_to_file);
//var_dump($_SESSION["dol_array_match_file_to_database_select"]);
$fieldstarget_tmp = array();
$arraykeysfieldtarget = array_keys($fieldstarget);
$position = 0;
foreach ($fieldstarget as $key => $label) {
$isrequired = preg_match('/\*$/', $label);
if (!empty($isrequired)) {
$newlabel = substr($label, 0, -1);
$fieldstarget_tmp[$key] = array("label" => $newlabel, "required" => true);
} else {
$fieldstarget_tmp[$key] = array("label" => $label, "required" => false);
}
if (!empty($array_match_database_to_file[$key])) {
$fieldstarget_tmp[$key]["imported"] = true;
$fieldstarget_tmp[$key]["position"] = $array_match_database_to_file[$key] - 1;
$keytoswap = $key;
while (!empty($array_match_database_to_file[$keytoswap])) {
if ($position + 1 > $array_match_database_to_file[$keytoswap]) {
$keytoswapwith = $array_match_database_to_file[$keytoswap] - 1;
$tmp = [$keytoswap => $fieldstarget_tmp[$keytoswap]];
unset($fieldstarget_tmp[$keytoswap]);
$fieldstarget_tmp = arrayInsert($fieldstarget_tmp, $keytoswapwith, $tmp);
$keytoswapwith = $arraykeysfieldtarget[$array_match_database_to_file[$keytoswap] - 1];
$tmp = $fieldstarget_tmp[$keytoswapwith];
unset($fieldstarget_tmp[$keytoswapwith]);
$fieldstarget_tmp[$keytoswapwith] = $tmp;
$keytoswap = $keytoswapwith;
} else {
break;
}
}
} else {
$fieldstarget_tmp[$key]["imported"] = false;
}
$position++;
}
$fieldstarget = $fieldstarget_tmp;
//print $serialized_array_match_file_to_database;
//print $_SESSION["dol_array_match_file_to_database"];
//print $_SESSION["dol_array_match_file_to_database_select"];
//var_dump($array_match_file_to_database);exit;
// Now $array_match_file_to_database contains fieldnb(1,2,3...)=>fielddatabase(key in $array_match_file_to_database)
$param = '&format='.$format.'&datatoimport='.urlencode($datatoimport).'&filetoimport='.urlencode($filetoimport);
if ($excludefirstline) {
$param .= '&excludefirstline='.urlencode($excludefirstline);
}
if ($endatlinenb) {
$param .= '&endatlinenb='.urlencode($endatlinenb);
}
if ($separator) {
$param .= '&separator='.urlencode($separator);
}
if ($enclosure) {
$param .= '&enclosure='.urlencode($enclosure);
}
llxHeader('', $langs->trans("NewImport"), $help_url);
$head = import_prepare_head($param, 4);
print dol_get_fiche_head($head, 'step4', '', -2);
print '<div class="underbanner clearboth"></div>';
print '<div class="fichecenter">';
print '<table class="centpercent border tableforfield">';
// Module
print '<tr><td class="titlefieldcreate">'.$langs->trans("Module").'</td>';
print '<td>';
$titleofmodule = $objimport->array_import_module[0]['module']->getName();
// Special cas for import common to module/services
if (in_array($objimport->array_import_code[0], array('produit_supplierprices', 'produit_multiprice', 'produit_languages'))) {
$titleofmodule = $langs->trans("ProductOrService");
}
print $titleofmodule;
print '</td></tr>';
// Lot de donnees a importer
print '<tr><td>'.$langs->trans("DatasetToImport").'</td>';
print '<td>';
$entity = preg_replace('/:.*$/', '', $objimport->array_import_icon[0]);
$entityicon = strtolower(!empty($entitytoicon[$entity]) ? $entitytoicon[$entity] : $entity);
print img_object($objimport->array_import_module[0]['module']->getName(), $entityicon).' ';
print $objimport->array_import_label[0];
print '</td></tr>';
print '</table>';
print '</div>';
print load_fiche_titre($langs->trans("InformationOnSourceFile"), '', 'file-export');
print '<div class="underbanner clearboth"></div>';
print '<div class="fichecenter">';
print '<table width="100%" class="border tableforfield">';
// Source file format
print '<tr><td class="titlefieldcreate">'.$langs->trans("SourceFileFormat").'</td>';
print '<td>';
$text = $objmodelimport->getDriverDescForKey($format);
// @phan-suppress-next-line PhanPluginSuspiciousParamPosition
print $form->textwithpicto($objmodelimport->getDriverLabelForKey($format), $text);
print '</td></tr>';
// Separator and enclosure
if ($model == 'csv') {
print '<tr><td>'.$langs->trans("CsvOptions").'</td>';
print '<td>';
print '<form method="POST">';
print '<input type="hidden" name="token" value="'.newToken().'">';
print '<input type="hidden" value="'.$step.'" name="step">';
print '<input type="hidden" value="'.$format.'" name="format">';
print '<input type="hidden" value="'.$excludefirstline.'" name="excludefirstline">';
print '<input type="hidden" value="'.$endatlinenb.'" name="endatlinenb">';
print '<input type="hidden" value="'.$datatoimport.'" name="datatoimport">';
print '<input type="hidden" value="'.$filetoimport.'" name="filetoimport">';
print $langs->trans("Separator").' : ';
print '<input type="text" class="width25 center" name="separator" value="'.dol_escape_htmltag($separator).'"/>';
print ' '.$langs->trans("Enclosure").' : ';
print '<input type="text" class="width25 center" name="enclosure" value="'.dol_escape_htmltag($enclosure).'"/> ';
print '<input name="update" type="submit" value="'.$langs->trans('Update').'" class="button smallpaddingimp" />';
print '</form>';
print '</td></tr>';
}
// File to import
print '<tr><td>'.$langs->trans("FileToImport").'</td>';
print '<td>';
$modulepart = 'import';
$relativepath = GETPOST('filetoimport');
print '<a data-ajax="false" href="'.DOL_URL_ROOT.'/document.php?modulepart='.$modulepart.'&file='.urlencode($relativepath).'&step=4'.$param.'" target="_blank" rel="noopener noreferrer">';
print img_mime($file, '', 'pictofixedwidth');
print $filetoimport;
print img_picto($langs->trans("Download"), 'download', 'class="paddingleft opacitymedium"');
print '</a>';
print '</td></tr>';
print '</table>';
print '</div>';