import.php 84 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343
  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. *
  6. * This program is free software; you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation; either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  18. */
  19. /**
  20. * \file htdocs/imports/import.php
  21. * \ingroup import
  22. * \brief Pages of import Wizard
  23. */
  24. require_once '../main.inc.php';
  25. require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
  26. require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php';
  27. require_once DOL_DOCUMENT_ROOT.'/imports/class/import.class.php';
  28. require_once DOL_DOCUMENT_ROOT.'/core/modules/import/modules_import.php';
  29. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  30. require_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
  31. require_once DOL_DOCUMENT_ROOT.'/core/lib/import.lib.php';
  32. // Load translation files required by the page
  33. $langs->loadLangs(array('exports', 'compta', 'errors'));
  34. // Security check
  35. $result = restrictedArea($user, 'import');
  36. // Map icons, array duplicated in export.php, was not synchronized, TODO put it somewhere only once
  37. $entitytoicon = array(
  38. 'invoice' => 'bill',
  39. 'invoice_line' => 'bill',
  40. 'order' => 'order',
  41. 'order_line' => 'order',
  42. 'propal' => 'propal',
  43. 'propal_line' => 'propal',
  44. 'intervention' => 'intervention',
  45. 'inter_line' => 'intervention',
  46. 'member' => 'user',
  47. 'member_type' => 'group',
  48. 'subscription' => 'payment',
  49. 'payment' => 'payment',
  50. 'tax' => 'bill',
  51. 'tax_type' => 'generic',
  52. 'other' => 'generic',
  53. 'account' => 'account',
  54. 'product' => 'product',
  55. 'virtualproduct'=>'product',
  56. 'subproduct' => 'product',
  57. 'product_supplier_ref' => 'product',
  58. 'stock' => 'stock',
  59. 'warehouse' => 'stock',
  60. 'batch' => 'stock',
  61. 'stockbatch' => 'stock',
  62. 'category' => 'category',
  63. 'shipment' => 'sending',
  64. 'shipment_line'=> 'sending',
  65. 'reception'=> 'sending',
  66. 'reception_line'=> 'sending',
  67. 'expensereport'=> 'trip',
  68. 'expensereport_line'=> 'trip',
  69. 'holiday' => 'holiday',
  70. 'contract_line' => 'contract',
  71. 'translation' => 'generic',
  72. 'bomm' => 'bom',
  73. 'bomline' => 'bom'
  74. );
  75. // Translation code, array duplicated in export.php, was not synchronized, TODO put it somewhere only once
  76. $entitytolang = array(
  77. 'user' => 'User',
  78. 'company' => 'Company',
  79. 'contact' => 'Contact',
  80. 'invoice' => 'Bill',
  81. 'invoice_line' => 'InvoiceLine',
  82. 'order' => 'Order',
  83. 'order_line' => 'OrderLine',
  84. 'propal' => 'Proposal',
  85. 'propal_line' => 'ProposalLine',
  86. 'intervention' => 'Intervention',
  87. 'inter_line' => 'InterLine',
  88. 'member' => 'Member',
  89. 'member_type' => 'MemberType',
  90. 'subscription' => 'Subscription',
  91. 'tax' => 'SocialContribution',
  92. 'tax_type' => 'DictionarySocialContributions',
  93. 'account' => 'BankTransactions',
  94. 'payment' => 'Payment',
  95. 'product' => 'Product',
  96. 'virtualproduct' => 'AssociatedProducts',
  97. 'subproduct' => 'SubProduct',
  98. 'product_supplier_ref' => 'SupplierPrices',
  99. 'service' => 'Service',
  100. 'stock' => 'Stock',
  101. 'movement' => 'StockMovement',
  102. 'batch' => 'Batch',
  103. 'stockbatch' => 'StockDetailPerBatch',
  104. 'warehouse' => 'Warehouse',
  105. 'category' => 'Category',
  106. 'other' => 'Other',
  107. 'trip' => 'TripsAndExpenses',
  108. 'shipment' => 'Shipments',
  109. 'shipment_line'=> 'ShipmentLine',
  110. 'project' => 'Projects',
  111. 'projecttask' => 'Tasks',
  112. 'task_time' => 'TaskTimeSpent',
  113. 'action' => 'Event',
  114. 'expensereport'=> 'ExpenseReport',
  115. 'expensereport_line'=> 'ExpenseReportLine',
  116. 'holiday' => 'TitreRequestCP',
  117. 'contract' => 'Contract',
  118. 'contract_line'=> 'ContractLine',
  119. 'translation' => 'Translation',
  120. 'bom' => 'BOM',
  121. 'bomline' => 'BOMLine'
  122. );
  123. $datatoimport = GETPOST('datatoimport');
  124. $format = GETPOST('format');
  125. $filetoimport = GETPOST('filetoimport');
  126. $action = GETPOST('action', 'alpha');
  127. $confirm = GETPOST('confirm', 'alpha');
  128. $step = (GETPOST('step') ? GETPOST('step') : 1);
  129. $import_name = GETPOST('import_name');
  130. $hexa = GETPOST('hexa');
  131. $importmodelid = GETPOST('importmodelid');
  132. $excludefirstline = (GETPOST('excludefirstline') ? GETPOST('excludefirstline') : 2);
  133. $endatlinenb = (GETPOST('endatlinenb') ? GETPOST('endatlinenb') : '');
  134. $updatekeys = (GETPOST('updatekeys', 'array') ? GETPOST('updatekeys', 'array') : array());
  135. $separator = (GETPOST('separator', 'nohtml') ? GETPOST('separator', 'nohtml') : (!empty($conf->global->IMPORT_CSV_SEPARATOR_TO_USE) ? $conf->global->IMPORT_CSV_SEPARATOR_TO_USE : ','));
  136. $enclosure = (GETPOST('enclosure', 'nohtml') ? GETPOST('enclosure', 'nohtml') : '"');
  137. $separator_used = str_replace('\t', "\t", $separator);
  138. $objimport = new Import($db);
  139. $objimport->load_arrays($user, ($step == 1 ? '' : $datatoimport));
  140. $objmodelimport = new ModeleImports();
  141. $form = new Form($db);
  142. $htmlother = new FormOther($db);
  143. $formfile = new FormFile($db);
  144. // Init $array_match_file_to_database from _SESSION
  145. $serialized_array_match_file_to_database = isset($_SESSION["dol_array_match_file_to_database"]) ? $_SESSION["dol_array_match_file_to_database"] : '';
  146. $array_match_file_to_database = array();
  147. $fieldsarray = explode(',', $serialized_array_match_file_to_database);
  148. foreach ($fieldsarray as $elem) {
  149. $tabelem = explode('=', $elem, 2);
  150. $key = $tabelem[0];
  151. $val = (isset($tabelem[1]) ? $tabelem[1] : '');
  152. if ($key && $val) {
  153. $array_match_file_to_database[$key] = $val;
  154. }
  155. }
  156. if (empty($array_match_file_to_database)) {
  157. $serialized_array_match_file_to_database = isset($_SESSION["dol_array_match_file_to_database_select"]) ? $_SESSION["dol_array_match_file_to_database_select"] : '';
  158. $array_match_file_to_database = array();
  159. $fieldsarray = explode(',', $serialized_array_match_file_to_database);
  160. foreach ($fieldsarray as $elem) {
  161. $tabelem = explode('=', $elem, 2);
  162. $key = $tabelem[0];
  163. $val = (isset($tabelem[1]) ? $tabelem[1] : '');
  164. if ($key && $val) {
  165. $array_match_file_to_database[$key] = $val;
  166. }
  167. }
  168. }
  169. /*
  170. * Actions
  171. */
  172. /*
  173. if ($action=='downfield' || $action=='upfield')
  174. {
  175. $pos=$array_match_file_to_database[$_GET["field"]];
  176. if ($action=='downfield') $newpos=$pos+1;
  177. if ($action=='upfield') $newpos=$pos-1;
  178. // Recherche code avec qui switcher
  179. $newcode="";
  180. foreach($array_match_file_to_database as $code=>$value)
  181. {
  182. if ($value == $newpos)
  183. {
  184. $newcode=$code;
  185. break;
  186. }
  187. }
  188. //print("Switch pos=$pos (code=".$_GET["field"].") and newpos=$newpos (code=$newcode)");
  189. if ($newcode) // Si newcode trouve (protection contre resoumission de page)
  190. {
  191. $array_match_file_to_database[$_GET["field"]]=$newpos;
  192. $array_match_file_to_database[$newcode]=$pos;
  193. $_SESSION["dol_array_match_file_to_database"]=$serialized_array_match_file_to_database;
  194. }
  195. }
  196. */
  197. if ($action == 'builddoc') {
  198. // Build import file
  199. $result = $objimport->build_file($user, GETPOST('model', 'alpha'), $datatoimport, $array_match_file_to_database);
  200. if ($result < 0) {
  201. setEventMessages($objimport->error, $objimport->errors, 'errors');
  202. } else {
  203. setEventMessages($langs->trans("FileSuccessfullyBuilt"), null, 'mesgs');
  204. }
  205. }
  206. if ($action == 'deleteprof') {
  207. if (GETPOST("id", 'int')) {
  208. $objimport->fetch(GETPOST("id", 'int'));
  209. $result = $objimport->delete($user);
  210. }
  211. }
  212. // Save import config to database
  213. if ($action == 'add_import_model') {
  214. if ($import_name) {
  215. // Set save string
  216. $hexa = '';
  217. foreach ($array_match_file_to_database as $key => $val) {
  218. if ($hexa) {
  219. $hexa .= ',';
  220. }
  221. $hexa .= $key.'='.$val;
  222. }
  223. $objimport->model_name = $import_name;
  224. $objimport->datatoimport = $datatoimport;
  225. $objimport->hexa = $hexa;
  226. $objimport->fk_user = (GETPOST('visibility', 'aZ09') == 'all' ? 0 : $user->id);
  227. $result = $objimport->create($user);
  228. if ($result >= 0) {
  229. setEventMessages($langs->trans("ImportModelSaved", $objimport->model_name), null, 'mesgs');
  230. } else {
  231. $langs->load("errors");
  232. if ($objimport->errno == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
  233. setEventMessages($langs->trans("ErrorImportDuplicateProfil"), null, 'errors');
  234. } else {
  235. setEventMessages($objimport->error, null, 'errors');
  236. }
  237. }
  238. } else {
  239. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("ImportModelName")), null, 'errors');
  240. }
  241. }
  242. if ($step == 3 && $datatoimport) {
  243. if (GETPOST('sendit') && !empty($conf->global->MAIN_UPLOAD_DOC)) {
  244. dol_mkdir($conf->import->dir_temp);
  245. $nowyearmonth = dol_print_date(dol_now(), '%Y%m%d%H%M%S');
  246. $fullpath = $conf->import->dir_temp."/".$nowyearmonth.'-'.$_FILES['userfile']['name'];
  247. if (dol_move_uploaded_file($_FILES['userfile']['tmp_name'], $fullpath, 1) > 0) {
  248. dol_syslog("File ".$fullpath." was added for import");
  249. } else {
  250. $langs->load("errors");
  251. setEventMessages($langs->trans("ErrorFailedToSaveFile"), null, 'errors');
  252. }
  253. }
  254. // Delete file
  255. if ($action == 'confirm_deletefile' && $confirm == 'yes') {
  256. $langs->load("other");
  257. $param = '&datatoimport='.urlencode($datatoimport).'&format='.urlencode($format);
  258. if ($excludefirstline) {
  259. $param .= '&excludefirstline='.urlencode($excludefirstline);
  260. }
  261. if ($endatlinenb) {
  262. $param .= '&endatlinenb='.urlencode($endatlinenb);
  263. }
  264. $file = $conf->import->dir_temp.'/'.GETPOST('urlfile'); // Do not use urldecode here ($_GET and $_REQUEST are already decoded by PHP).
  265. $ret = dol_delete_file($file);
  266. if ($ret) {
  267. setEventMessages($langs->trans("FileWasRemoved", GETPOST('urlfile')), null, 'mesgs');
  268. } else {
  269. setEventMessages($langs->trans("ErrorFailToDeleteFile", GETPOST('urlfile')), null, 'errors');
  270. }
  271. Header('Location: '.$_SERVER["PHP_SELF"].'?step='.$step.$param);
  272. exit;
  273. }
  274. }
  275. if ($step == 4 && $action == 'select_model') {
  276. // Reinit match arrays
  277. $_SESSION["dol_array_match_file_to_database"] = '';
  278. $serialized_array_match_file_to_database = '';
  279. $array_match_file_to_database = array();
  280. // Load model from $importmodelid and set $array_match_file_to_database
  281. // and $_SESSION["dol_array_match_file_to_database"]
  282. $result = $objimport->fetch($importmodelid);
  283. if ($result > 0) {
  284. $serialized_array_match_file_to_database = $objimport->hexa;
  285. $fieldsarray = explode(',', $serialized_array_match_file_to_database);
  286. foreach ($fieldsarray as $elem) {
  287. $tabelem = explode('=', $elem);
  288. $key = $tabelem[0];
  289. $val = $tabelem[1];
  290. if ($key && $val) {
  291. $array_match_file_to_database[$key] = $val;
  292. }
  293. }
  294. $_SESSION["dol_array_match_file_to_database"] = $serialized_array_match_file_to_database;
  295. }
  296. }
  297. if ($action == 'saveselectorder') {
  298. // Enregistrement de la position des champs
  299. $serialized_array_match_file_to_database = '';
  300. dol_syslog("selectorder=".GETPOST('selectorder'), LOG_DEBUG);
  301. $selectorder = explode(",", GETPOST('selectorder'));
  302. $fieldtarget = $fieldstarget = $objimport->array_import_fields[0];
  303. foreach ($selectorder as $key => $code) {
  304. $serialized_array_match_file_to_database .= $key.'='.$code;
  305. $serialized_array_match_file_to_database .= ',';
  306. }
  307. $serialized_array_match_file_to_database = substr($serialized_array_match_file_to_database, 0, -1);
  308. dol_syslog('dol_array_match_file_to_database_select='.$serialized_array_match_file_to_database);
  309. $_SESSION["dol_array_match_file_to_database_select"] = $serialized_array_match_file_to_database;
  310. echo "{}";
  311. exit(0);
  312. }
  313. /*
  314. * View
  315. */
  316. $help_url = 'EN:Module_Imports_En|FR:Module_Imports|ES:M&oacute;dulo_Importaciones';
  317. // STEP 1: Page to select dataset to import
  318. if ($step == 1 || !$datatoimport) {
  319. // Clean saved file-database matching
  320. $serialized_array_match_file_to_database = '';
  321. $array_match_file_to_database = array();
  322. $_SESSION["dol_array_match_file_to_database"] = '';
  323. $_SESSION["dol_array_match_file_to_database_select"] = '';
  324. $param = '';
  325. if ($excludefirstline) {
  326. $param .= '&excludefirstline='.urlencode($excludefirstline);
  327. }
  328. if ($endatlinenb) {
  329. $param .= '&endatlinenb='.urlencode($endatlinenb);
  330. }
  331. if ($separator) {
  332. $param .= '&separator='.urlencode($separator);
  333. }
  334. if ($enclosure) {
  335. $param .= '&enclosure='.urlencode($enclosure);
  336. }
  337. llxHeader('', $langs->trans("NewImport"), $help_url);
  338. $head = import_prepare_head($param, 1);
  339. print dol_get_fiche_head($head, 'step1', '', -1);
  340. print '<div class="opacitymedium">'.$langs->trans("SelectImportDataSet").'</div><br>';
  341. // Affiche les modules d'imports
  342. print '<div class="div-table-responsive-no-min">'; // You can use div-table-responsive-no-min if you dont need reserved height for your table
  343. print '<table class="noborder centpercent">';
  344. print '<tr class="liste_titre">';
  345. print '<td>'.$langs->trans("Module").'</td>';
  346. print '<td>'.$langs->trans("ImportableDatas").'</td>';
  347. print '<td>&nbsp;</td>';
  348. print '</tr>';
  349. if (count($objimport->array_import_module)) {
  350. $sortedarrayofmodules = dol_sort_array($objimport->array_import_module, 'position_of_profile', 'asc', 0, 0, 1);
  351. foreach ($sortedarrayofmodules as $key => $value) {
  352. //var_dump($key.' '.$value['position_of_profile'].' '.$value['import_code'].' '.$objimport->array_import_module[$key]['module']->getName().' '.$objimport->array_import_code[$key]);
  353. print '<tr class="oddeven"><td>';
  354. $titleofmodule = $objimport->array_import_module[$key]['module']->getName();
  355. // Special cas for import common to module/services
  356. if (in_array($objimport->array_import_code[$key], array('produit_supplierprices', 'produit_multiprice', 'produit_languages'))) {
  357. $titleofmodule = $langs->trans("ProductOrService");
  358. }
  359. print $titleofmodule;
  360. print '</td><td>';
  361. $entity = preg_replace('/:.*$/', '', $objimport->array_import_icon[$key]);
  362. $entityicon = strtolower(!empty($entitytoicon[$entity]) ? $entitytoicon[$entity] : $entity);
  363. print img_object($objimport->array_import_module[$key]['module']->getName(), $entityicon).' ';
  364. print $objimport->array_import_label[$key];
  365. print '</td><td style="text-align: right">';
  366. if ($objimport->array_import_perms[$key]) {
  367. 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-15x"').'</a>';
  368. } else {
  369. print $langs->trans("NotEnoughPermissions");
  370. }
  371. print '</td></tr>';
  372. }
  373. } else {
  374. print '<tr><td class="oddeven" colspan="3">'.$langs->trans("NoImportableData").'</td></tr>';
  375. }
  376. print '</table>';
  377. print '</div>';
  378. print dol_get_fiche_end();
  379. }
  380. // STEP 2: Page to select input format file
  381. if ($step == 2 && $datatoimport) {
  382. $param = '&datatoimport='.urlencode($datatoimport);
  383. if ($excludefirstline) {
  384. $param .= '&excludefirstline='.urlencode($excludefirstline);
  385. }
  386. if ($endatlinenb) {
  387. $param .= '&endatlinenb='.urlencode($endatlinenb);
  388. }
  389. if ($separator) {
  390. $param .= '&separator='.urlencode($separator);
  391. }
  392. if ($enclosure) {
  393. $param .= '&enclosure='.urlencode($enclosure);
  394. }
  395. llxHeader('', $langs->trans("NewImport"), $help_url);
  396. $head = import_prepare_head($param, 2);
  397. print dol_get_fiche_head($head, 'step2', '', -2);
  398. print '<div class="underbanner clearboth"></div>';
  399. print '<div class="fichecenter">';
  400. print '<table class="border tableforfield centpercent">';
  401. // Module
  402. print '<tr><td class="titlefieldcreate">'.$langs->trans("Module").'</td>';
  403. print '<td>';
  404. $titleofmodule = $objimport->array_import_module[0]['module']->getName();
  405. // Special cas for import common to module/services
  406. if (in_array($objimport->array_import_code[0], array('produit_supplierprices', 'produit_multiprice', 'produit_languages'))) {
  407. $titleofmodule = $langs->trans("ProductOrService");
  408. }
  409. print $titleofmodule;
  410. print '</td></tr>';
  411. // Dataset to import
  412. print '<tr><td>'.$langs->trans("DatasetToImport").'</td>';
  413. print '<td>';
  414. $entity = preg_replace('/:.*$/', '', $objimport->array_import_icon[0]);
  415. $entityicon = strtolower(!empty($entitytoicon[$entity]) ? $entitytoicon[$entity] : $entity);
  416. print img_object($objimport->array_import_module[0]['module']->getName(), $entityicon).' ';
  417. print $objimport->array_import_label[0];
  418. print '</td></tr>';
  419. print '</table>';
  420. print '</div>';
  421. print dol_get_fiche_end();
  422. print '<form name="userfile" action="'.$_SERVER["PHP_SELF"].'" enctype="multipart/form-data" METHOD="POST">';
  423. print '<input type="hidden" name="token" value="'.newToken().'">';
  424. print '<input type="hidden" name="max_file_size" value="'.$conf->maxfilesize.'">';
  425. print '<br>';
  426. print '<span class="opacitymedium">';
  427. $s = $langs->trans("ChooseFormatOfFileToImport", '{s1}');
  428. $s = str_replace('{s1}', img_picto('', 'next'), $s);
  429. print $s;
  430. print '</span><br><br>';
  431. print '<br>';
  432. print '<div class="div-table-responsive-no-min">'; // You can use div-table-responsive-no-min if you dont need reserved height for your table
  433. print '<table class="noborder centpercent" cellpadding="4">';
  434. $filetoimport = '';
  435. // Add format informations and link to download example
  436. print '<tr class="liste_titre"><td colspan="6">';
  437. print $langs->trans("FileMustHaveOneOfFollowingFormat");
  438. print '</td></tr>';
  439. $list = $objmodelimport->liste_modeles($db);
  440. foreach ($list as $key) {
  441. print '<tr class="oddeven">';
  442. print '<td width="16">'.img_picto_common($key, $objmodelimport->getPictoForKey($key)).'</td>';
  443. $text = $objmodelimport->getDriverDescForKey($key);
  444. print '<td>'.$form->textwithpicto($objmodelimport->getDriverLabelForKey($key), $text).'</td>';
  445. print '<td style="text-align:center">';
  446. print img_picto('', 'download', 'class="paddingright opacitymedium"').'<a href="'.DOL_URL_ROOT.'/imports/emptyexample.php?format='.$key.$param.'" target="_blank" rel="noopener noreferrer">'.$langs->trans("DownloadEmptyExample");
  447. print '</a>';
  448. print ' <span class="opacitymedium hideonsmartphone">('.$langs->trans("StarAreMandatory").')</span>';
  449. print '</td>';
  450. // Action button
  451. print '<td style="text-align:right">';
  452. print '<a href="'.DOL_URL_ROOT.'/imports/import.php?step=3&format='.$key.$param.'">'.img_picto($langs->trans("SelectFormat"), 'next', 'class="fa-15x"').'</a>';
  453. print '</td>';
  454. print '</tr>';
  455. }
  456. print '</table>';
  457. print '</div>';
  458. print '</form>';
  459. }
  460. // STEP 3: Page to select file
  461. if ($step == 3 && $datatoimport) {
  462. $param = '&datatoimport='.urlencode($datatoimport).'&format='.urlencode($format);
  463. if ($excludefirstline) {
  464. $param .= '&excludefirstline='.urlencode($excludefirstline);
  465. }
  466. if ($endatlinenb) {
  467. $param .= '&endatlinenb='.urlencode($endatlinenb);
  468. }
  469. if ($separator) {
  470. $param .= '&separator='.urlencode($separator);
  471. }
  472. if ($enclosure) {
  473. $param .= '&enclosure='.urlencode($enclosure);
  474. }
  475. $list = $objmodelimport->liste_modeles($db);
  476. llxHeader('', $langs->trans("NewImport"), $help_url);
  477. $head = import_prepare_head($param, 3);
  478. print dol_get_fiche_head($head, 'step3', '', -2);
  479. /*
  480. * Confirm delete file
  481. */
  482. if ($action == 'delete') {
  483. print $form->formconfirm($_SERVER["PHP_SELF"].'?urlfile='.urlencode(GETPOST('urlfile')).'&step=3'.$param, $langs->trans('DeleteFile'), $langs->trans('ConfirmDeleteFile'), 'confirm_deletefile', '', 0, 1);
  484. }
  485. print '<div class="underbanner clearboth"></div>';
  486. print '<div class="fichecenter">';
  487. print '<table class="border tableforfield centpercent">';
  488. // Module
  489. print '<tr><td class="titlefieldcreate">'.$langs->trans("Module").'</td>';
  490. print '<td>';
  491. $titleofmodule = $objimport->array_import_module[0]['module']->getName();
  492. // Special cas for import common to module/services
  493. if (in_array($objimport->array_import_code[0], array('produit_supplierprices', 'produit_multiprice', 'produit_languages'))) {
  494. $titleofmodule = $langs->trans("ProductOrService");
  495. }
  496. print $titleofmodule;
  497. print '</td></tr>';
  498. // Lot de donnees a importer
  499. print '<tr><td>'.$langs->trans("DatasetToImport").'</td>';
  500. print '<td>';
  501. $entity = preg_replace('/:.*$/', '', $objimport->array_import_icon[0]);
  502. $entityicon = strtolower(!empty($entitytoicon[$entity]) ? $entitytoicon[$entity] : $entity);
  503. print img_object($objimport->array_import_module[0]['module']->getName(), $entityicon).' ';
  504. print $objimport->array_import_label[0];
  505. print '</td></tr>';
  506. print '</table>';
  507. print '</div>';
  508. print load_fiche_titre($langs->trans("InformationOnSourceFile"), '', 'file-export');
  509. print '<div class="underbanner clearboth"></div>';
  510. print '<div class="fichecenter">';
  511. print '<table width="100%" class="border tableforfield">';
  512. // Source file format
  513. print '<tr><td class="titlefieldcreate">'.$langs->trans("SourceFileFormat").'</td>';
  514. print '<td class="nowraponall">';
  515. $text = $objmodelimport->getDriverDescForKey($format);
  516. print $form->textwithpicto($objmodelimport->getDriverLabelForKey($format), $text);
  517. print '</td><td style="text-align:right" class="nowrap">';
  518. print img_picto('', 'download', 'class="paddingright opacitymedium"').'<a href="'.DOL_URL_ROOT.'/imports/emptyexample.php?format='.$format.$param.'" target="_blank" rel="noopener noreferrer">'.$langs->trans("DownloadEmptyExample");
  519. print '</a>';
  520. print ' <span class="opacitymedium hideonsmartphone">('.$langs->trans("StarAreMandatory").')</span>';
  521. print '</td></tr>';
  522. print '</table>';
  523. print '</div>';
  524. print dol_get_fiche_end();
  525. if ($format == 'xlsx' && !class_exists('XMLWriter')) {
  526. $langs->load("install");
  527. print info_admin($langs->trans("ErrorPHPDoesNotSupport", 'php-xml'), 0, 0, 1, 'error');
  528. }
  529. print '<br>';
  530. print '<form name="userfile" action="'.$_SERVER["PHP_SELF"].'" enctype="multipart/form-data" METHOD="POST">';
  531. print '<input type="hidden" name="token" value="'.newToken().'">';
  532. print '<input type="hidden" name="max_file_size" value="'.$conf->maxfilesize.'">';
  533. print '<input type="hidden" value="'.$step.'" name="step">';
  534. print '<input type="hidden" value="'.dol_escape_htmltag($format).'" name="format">';
  535. print '<input type="hidden" value="'.$excludefirstline.'" name="excludefirstline">';
  536. print '<input type="hidden" value="'.$endatlinenb.'" name="endatlinenb">';
  537. print '<input type="hidden" value="'.dol_escape_htmltag($separator).'" name="separator">';
  538. print '<input type="hidden" value="'.dol_escape_htmltag($enclosure).'" name="enclosure">';
  539. print '<input type="hidden" value="'.dol_escape_htmltag($datatoimport).'" name="datatoimport">';
  540. print '<span class="opacitymedium">';
  541. $s = $langs->trans("ChooseFileToImport", '{s1}');
  542. $s = str_replace('{s1}', img_picto('', 'next'), $s);
  543. print $s;
  544. print '</span><br><br>';
  545. $filetoimport = '';
  546. // Input file name box
  547. print '<div class="marginbottomonly">';
  548. print '<input type="file" name="userfile" size="20" maxlength="80"> &nbsp; &nbsp; ';
  549. $out = (empty($conf->global->MAIN_UPLOAD_DOC) ? ' disabled' : '');
  550. print '<input type="submit" class="button small" value="'.$langs->trans("AddFile").'"'.$out.' name="sendit">';
  551. $out = '';
  552. if (!empty($conf->global->MAIN_UPLOAD_DOC)) {
  553. $max = $conf->global->MAIN_UPLOAD_DOC; // In Kb
  554. $maxphp = @ini_get('upload_max_filesize'); // In unknown
  555. if (preg_match('/k$/i', $maxphp)) {
  556. $maxphp = $maxphp * 1;
  557. }
  558. if (preg_match('/m$/i', $maxphp)) {
  559. $maxphp = $maxphp * 1024;
  560. }
  561. if (preg_match('/g$/i', $maxphp)) {
  562. $maxphp = $maxphp * 1024 * 1024;
  563. }
  564. if (preg_match('/t$/i', $maxphp)) {
  565. $maxphp = $maxphp * 1024 * 1024 * 1024;
  566. }
  567. $maxphp2 = @ini_get('post_max_size'); // In unknown
  568. if (preg_match('/k$/i', $maxphp2)) {
  569. $maxphp2 = $maxphp2 * 1;
  570. }
  571. if (preg_match('/m$/i', $maxphp2)) {
  572. $maxphp2 = $maxphp2 * 1024;
  573. }
  574. if (preg_match('/g$/i', $maxphp2)) {
  575. $maxphp2 = $maxphp2 * 1024 * 1024;
  576. }
  577. if (preg_match('/t$/i', $maxphp2)) {
  578. $maxphp2 = $maxphp2 * 1024 * 1024 * 1024;
  579. }
  580. // Now $max and $maxphp and $maxphp2 are in Kb
  581. $maxmin = $max;
  582. $maxphptoshow = $maxphptoshowparam = '';
  583. if ($maxphp > 0) {
  584. $maxmin = min($max, $maxphp);
  585. $maxphptoshow = $maxphp;
  586. $maxphptoshowparam = 'upload_max_filesize';
  587. }
  588. if ($maxphp2 > 0) {
  589. $maxmin = min($max, $maxphp2);
  590. if ($maxphp2 < $maxphp) {
  591. $maxphptoshow = $maxphp2;
  592. $maxphptoshowparam = 'post_max_size';
  593. }
  594. }
  595. $langs->load('other');
  596. $out .= ' ';
  597. $out .= info_admin($langs->trans("ThisLimitIsDefinedInSetup", $max, $maxphptoshow), 1);
  598. } else {
  599. $out .= ' ('.$langs->trans("UploadDisabled").')';
  600. }
  601. print $out;
  602. print '</div>';
  603. // Search available imports
  604. $filearray = dol_dir_list($conf->import->dir_temp, 'files', 0, '', '', 'name', SORT_DESC);
  605. if (count($filearray) > 0) {
  606. print '<div class="div-table-responsive-no-min">'; // You can use div-table-responsive-no-min if you dont need reserved height for your table
  607. print '<table class="noborder centpercent" width="100%" cellpadding="4">';
  608. $dir = $conf->import->dir_temp;
  609. // Search available files to import
  610. $i = 0;
  611. foreach ($filearray as $key => $val) {
  612. $file = $val['name'];
  613. // readdir return value in ISO and we want UTF8 in memory
  614. if (!utf8_check($file)) {
  615. $file = utf8_encode($file);
  616. }
  617. if (preg_match('/^\./', $file)) {
  618. continue;
  619. }
  620. $modulepart = 'import';
  621. $urlsource = $_SERVER["PHP_SELF"].'?step='.$step.$param.'&filetoimport='.urlencode($filetoimport);
  622. $relativepath = $file;
  623. print '<tr class="oddeven">';
  624. print '<td>';
  625. print img_mime($file, '', 'pictofixedwidth');
  626. print '<a data-ajax="false" href="'.DOL_URL_ROOT.'/document.php?modulepart='.$modulepart.'&file='.urlencode($relativepath).'&step=3'.$param.'" target="_blank" rel="noopener noreferrer">';
  627. print $file;
  628. print '</a>';
  629. print '</td>';
  630. // Affiche taille fichier
  631. print '<td style="text-align:right">'.dol_print_size(dol_filesize($dir.'/'.$file)).'</td>';
  632. // Affiche date fichier
  633. print '<td style="text-align:right">'.dol_print_date(dol_filemtime($dir.'/'.$file), 'dayhour').'</td>';
  634. // Del button
  635. print '<td style="text-align:right"><a href="'.$_SERVER['PHP_SELF'].'?action=delete&token='.newToken().'&step=3'.$param.'&urlfile='.urlencode($relativepath);
  636. print '">'.img_delete().'</a></td>';
  637. // Action button
  638. print '<td style="text-align:right">';
  639. print '<a href="'.$_SERVER['PHP_SELF'].'?step=4'.$param.'&filetoimport='.urlencode($relativepath).'">'.img_picto($langs->trans("NewImport"), 'next', 'class="fa-15x"').'</a>';
  640. print '</td>';
  641. print '</tr>';
  642. }
  643. print '</table>';
  644. print '</div>';
  645. }
  646. print '</form>';
  647. }
  648. // STEP 4: Page to make matching between source file and database fields
  649. if ($step == 4 && $datatoimport) {
  650. $serialized_array_match_file_to_database = isset($_SESSION["dol_array_match_file_to_database_select"]) ? $_SESSION["dol_array_match_file_to_database_select"] : '';
  651. $array_match_file_to_database = array();
  652. $fieldsarray = explode(',', $serialized_array_match_file_to_database);
  653. foreach ($fieldsarray as $elem) {
  654. $tabelem = explode('=', $elem, 2);
  655. $key = $tabelem[0];
  656. $val = (isset($tabelem[1]) ? $tabelem[1] : '');
  657. if ($key && $val) {
  658. $array_match_file_to_database[$key] = $val;
  659. }
  660. }
  661. $model = $format;
  662. $list = $objmodelimport->liste_modeles($db);
  663. // Create classe to use for import
  664. $dir = DOL_DOCUMENT_ROOT."/core/modules/import/";
  665. $file = "import_".$model.".modules.php";
  666. $classname = "Import".ucfirst($model);
  667. require_once $dir.$file;
  668. $obj = new $classname($db, $datatoimport);
  669. if ($model == 'csv') {
  670. $obj->separator = $separator_used;
  671. $obj->enclosure = $enclosure;
  672. }
  673. if ($model == 'xlsx') {
  674. if (!preg_match('/\.xlsx$/i', $filetoimport)) {
  675. $langs->load("errors");
  676. $param = '&datatoimport='.$datatoimport.'&format='.$format;
  677. setEventMessages($langs->trans("ErrorFileMustHaveFormat", $model), null, 'errors');
  678. header("Location: ".$_SERVER["PHP_SELF"].'?step=3'.$param.'&filetoimport='.urlencode($relativepath));
  679. exit;
  680. }
  681. }
  682. if (GETPOST('update')) {
  683. $array_match_file_to_database = array();
  684. }
  685. // Load source fields in input file
  686. $fieldssource = array();
  687. $result = $obj->import_open_file($conf->import->dir_temp.'/'.$filetoimport, $langs);
  688. if ($result >= 0) {
  689. // Read first line
  690. $arrayrecord = $obj->import_read_record();
  691. // Put into array fieldssource starting with 1.
  692. $i = 1;
  693. foreach ($arrayrecord as $key => $val) {
  694. if ($val["type"] != -1) {
  695. $fieldssource[$i]['example1'] = dol_trunc($val['val'], 24);
  696. $i++;
  697. }
  698. }
  699. $obj->import_close_file();
  700. }
  701. // Load targets fields in database
  702. $fieldstarget = $objimport->array_import_fields[0];
  703. $minpos = min(count($fieldssource), count($fieldstarget));
  704. //var_dump($array_match_file_to_database);
  705. // Is it a first time in page (if yes, we must initialize array_match_file_to_database)
  706. if (count($array_match_file_to_database) == 0) {
  707. // This is first input in screen, we need to define
  708. // $array_match_file_to_database
  709. // $serialized_array_match_file_to_database
  710. // $_SESSION["dol_array_match_file_to_database"]
  711. $pos = 1;
  712. $num = count($fieldssource);
  713. while ($pos <= $num) {
  714. if ($num >= 1 && $pos <= $num) {
  715. $posbis = 1;
  716. foreach ($fieldstarget as $key => $val) {
  717. if ($posbis < $pos) {
  718. $posbis++;
  719. continue;
  720. }
  721. // We found the key of targets that is at position pos
  722. $array_match_file_to_database[$pos] = $key;
  723. if ($serialized_array_match_file_to_database) {
  724. $serialized_array_match_file_to_database .= ',';
  725. }
  726. $serialized_array_match_file_to_database .= ($pos.'='.$key);
  727. break;
  728. }
  729. }
  730. $pos++;
  731. }
  732. // Save the match array in session. We now will use the array in session.
  733. $_SESSION["dol_array_match_file_to_database_select"] = $serialized_array_match_file_to_database;
  734. }
  735. $array_match_database_to_file = array_flip($array_match_file_to_database);
  736. $fieldstarget_tmp = array();
  737. $arraykeysfieldtarget = array_keys($fieldstarget);
  738. $position = 0;
  739. foreach ($fieldstarget as $key => $label) {
  740. $isrequired = preg_match('/\*$/', $label);
  741. if (!empty($isrequired)) {
  742. $newlabel = substr($label, 0, -1);
  743. $fieldstarget_tmp[$key] = array("label"=>$newlabel,"required"=>true);
  744. } else {
  745. $fieldstarget_tmp[$key] = array("label"=>$label,"required"=>false);
  746. }
  747. if (!empty($array_match_database_to_file[$key])) {
  748. $fieldstarget_tmp[$key]["imported"] = true;
  749. $fieldstarget_tmp[$key]["position"] = $array_match_database_to_file[$key]-1;
  750. $keytoswap = $key;
  751. while (!empty($array_match_database_to_file[$keytoswap])) {
  752. if ($position+1 > $array_match_database_to_file[$keytoswap]) {
  753. $keytoswapwith = $array_match_database_to_file[$keytoswap]-1;
  754. $tmp = [$keytoswap=>$fieldstarget_tmp[$keytoswap]];
  755. unset($fieldstarget_tmp[$keytoswap]);
  756. $fieldstarget_tmp = arrayInsert($fieldstarget_tmp, $keytoswapwith, $tmp);
  757. $keytoswapwith = $arraykeysfieldtarget[$array_match_database_to_file[$keytoswap]-1];
  758. $tmp = $fieldstarget_tmp[$keytoswapwith];
  759. unset($fieldstarget_tmp[$keytoswapwith]);
  760. $fieldstarget_tmp[$keytoswapwith] = $tmp;
  761. $keytoswap = $keytoswapwith;
  762. } else {
  763. break;
  764. }
  765. }
  766. } else {
  767. $fieldstarget_tmp[$key]["imported"] = false;
  768. }
  769. $position++;
  770. }
  771. $fieldstarget = $fieldstarget_tmp;
  772. //print $serialized_array_match_file_to_database;
  773. //print $_SESSION["dol_array_match_file_to_database"];
  774. //var_dump($array_match_file_to_database);exit;
  775. // Now $array_match_file_to_database contains fieldnb(1,2,3...)=>fielddatabase(key in $array_match_file_to_database)
  776. $param = '&format='.$format.'&datatoimport='.urlencode($datatoimport).'&filetoimport='.urlencode($filetoimport);
  777. if ($excludefirstline) {
  778. $param .= '&excludefirstline='.urlencode($excludefirstline);
  779. }
  780. if ($endatlinenb) {
  781. $param .= '&endatlinenb='.urlencode($endatlinenb);
  782. }
  783. if ($separator) {
  784. $param .= '&separator='.urlencode($separator);
  785. }
  786. if ($enclosure) {
  787. $param .= '&enclosure='.urlencode($enclosure);
  788. }
  789. llxHeader('', $langs->trans("NewImport"), $help_url);
  790. $head = import_prepare_head($param, 4);
  791. print dol_get_fiche_head($head, 'step4', '', -2);
  792. print '<div class="underbanner clearboth"></div>';
  793. print '<div class="fichecenter">';
  794. print '<table width="100%" class="border tableforfield">';
  795. // Module
  796. print '<tr><td class="titlefieldcreate">'.$langs->trans("Module").'</td>';
  797. print '<td>';
  798. $titleofmodule = $objimport->array_import_module[0]['module']->getName();
  799. // Special cas for import common to module/services
  800. if (in_array($objimport->array_import_code[0], array('produit_supplierprices', 'produit_multiprice', 'produit_languages'))) {
  801. $titleofmodule = $langs->trans("ProductOrService");
  802. }
  803. print $titleofmodule;
  804. print '</td></tr>';
  805. // Lot de donnees a importer
  806. print '<tr><td>'.$langs->trans("DatasetToImport").'</td>';
  807. print '<td>';
  808. $entity = preg_replace('/:.*$/', '', $objimport->array_import_icon[0]);
  809. $entityicon = strtolower(!empty($entitytoicon[$entity]) ? $entitytoicon[$entity] : $entity);
  810. print img_object($objimport->array_import_module[0]['module']->getName(), $entityicon).' ';
  811. print $objimport->array_import_label[0];
  812. print '</td></tr>';
  813. print '</table>';
  814. print '</div>';
  815. print load_fiche_titre($langs->trans("InformationOnSourceFile"), '', 'file-export');
  816. print '<div class="underbanner clearboth"></div>';
  817. print '<div class="fichecenter">';
  818. print '<table width="100%" class="border tableforfield">';
  819. // Source file format
  820. print '<tr><td class="titlefieldcreate">'.$langs->trans("SourceFileFormat").'</td>';
  821. print '<td>';
  822. $text = $objmodelimport->getDriverDescForKey($format);
  823. print $form->textwithpicto($objmodelimport->getDriverLabelForKey($format), $text);
  824. print '</td></tr>';
  825. // Separator and enclosure
  826. if ($model == 'csv') {
  827. print '<tr><td>'.$langs->trans("CsvOptions").'</td>';
  828. print '<td>';
  829. print '<form>';
  830. print '<input type="hidden" name="token" value="'.newToken().'">';
  831. print '<input type="hidden" value="'.$step.'" name="step">';
  832. print '<input type="hidden" value="'.$format.'" name="format">';
  833. print '<input type="hidden" value="'.$excludefirstline.'" name="excludefirstline">';
  834. print '<input type="hidden" value="'.$endatlinenb.'" name="endatlinenb">';
  835. print '<input type="hidden" value="'.$datatoimport.'" name="datatoimport">';
  836. print '<input type="hidden" value="'.$filetoimport.'" name="filetoimport">';
  837. print $langs->trans("Separator").' : ';
  838. print '<input type="text" size="1" name="separator" value="'.dol_escape_htmltag($separator).'"/>';
  839. print '&nbsp;&nbsp;&nbsp;&nbsp;'.$langs->trans("Enclosure").' : ';
  840. print '<input type="text" size="1" name="enclosure" value="'.dol_escape_htmltag($enclosure).'"/> ';
  841. print '<input name="update" type="submit" value="'.$langs->trans('Update').'" class="button small" />';
  842. print '</form>';
  843. print '</td></tr>';
  844. }
  845. // File to import
  846. print '<tr><td>'.$langs->trans("FileToImport").'</td>';
  847. print '<td>';
  848. $modulepart = 'import';
  849. $relativepath = GETPOST('filetoimport');
  850. print '<a data-ajax="false" href="'.DOL_URL_ROOT.'/document.php?modulepart='.$modulepart.'&file='.urlencode($relativepath).'&step=4'.$param.'" target="_blank" rel="noopener noreferrer">';
  851. print img_mime($file, '', 'pictofixedwidth');
  852. print $filetoimport;
  853. print '</a>';
  854. print '</td></tr>';
  855. print '</table>';
  856. print '</div>';
  857. print dol_get_fiche_end();
  858. print '<br>'."\n";
  859. // List of source fields
  860. print '<!-- List of source fields -->'."\n";
  861. print '<form action="'.$_SERVER["PHP_SELF"].'" method="post">';
  862. print '<input type="hidden" name="token" value="'.newToken().'">';
  863. print '<input type="hidden" name="action" value="select_model">';
  864. print '<input type="hidden" name="step" value="4">';
  865. print '<input type="hidden" name="format" value="'.$format.'">';
  866. print '<input type="hidden" name="datatoimport" value="'.$datatoimport.'">';
  867. print '<input type="hidden" name="filetoimport" value="'.$filetoimport.'">';
  868. print '<input type="hidden" name="excludefirstline" value="'.$excludefirstline.'">';
  869. print '<input type="hidden" name="endatlinenb" value="'.$endatlinenb.'">';
  870. print '<input type="hidden" name="separator" value="'.dol_escape_htmltag($separator).'">';
  871. print '<input type="hidden" name="enclosure" value="'.dol_escape_htmltag($enclosure).'">';
  872. print '<div class="marginbottomonly">';
  873. print '<span class="opacitymedium">';
  874. $s = $langs->trans("SelectImportFieldsSource", '{s1}');
  875. $s = str_replace('{s1}', img_picto('', 'grip_title', '', false, 0, 0, '', '', 0), $s);
  876. print $s;
  877. print '</span> ';
  878. $htmlother->select_import_model($importmodelid, 'importmodelid', $datatoimport, 1, $user->id);
  879. print '<input type="submit" class="button small reposition" value="'.$langs->trans("Select").'">';
  880. print '</div>';
  881. print '</form>';
  882. // Title of array with fields
  883. print '<div class="div-table-responsive-no-min">'; // You can use div-table-responsive-no-min if you dont need reserved height for your table
  884. print '<table class="noborder centpercent">';
  885. print '<tr class="liste_titre">';
  886. print '<td>'.$langs->trans("FieldsInSourceFile").'</td>';
  887. print '<td>'.$langs->trans("FieldsInTargetDatabase").'</td>';
  888. print '</tr>';
  889. //var_dump($array_match_file_to_database);
  890. print '<tr valign="top"><td width="50%" class="nopaddingleftimp">';
  891. $fieldsplaced = array();
  892. $valforsourcefieldnb = array();
  893. $listofkeys = array();
  894. foreach ($array_match_file_to_database as $key => $val) {
  895. $listofkeys[$key] = 1;
  896. }
  897. print "\n<!-- Box left container -->\n";
  898. print '<div id="left" class="connectedSortable">'."\n";
  899. // List of source fields
  900. $lefti = 1;
  901. foreach ($fieldssource as $key => $val) {
  902. show_elem($fieldssource, $key, $val, $var); // key is field number in source file
  903. $listofkeys[$key] = 1;
  904. $fieldsplaced[$key] = 1;
  905. $valforsourcefieldnb[$lefti] = $key;
  906. $lefti++;
  907. if ($lefti > count($fieldstarget)) {
  908. break; // Other fields are in the not imported area
  909. }
  910. }
  911. //var_dump($valforsourcefieldnb);
  912. print "</div>\n";
  913. print "<!-- End box left container -->\n";
  914. print '</td><td width="50%" class="nopaddingrightimp">';
  915. // List of target fields
  916. $optionsnotused = "";
  917. $optionsall = array();
  918. foreach ($fieldstarget as $code => $line) {
  919. $text = '<option value="'.$code.'">';
  920. $text .= $langs->trans($line["label"]);
  921. if ($line["required"]) {
  922. $text .= "*";
  923. }
  924. $text .= '</option>';
  925. if (!$line["imported"]) {
  926. $optionsnotused .= $text;
  927. }
  928. $optionsall[$code] = array('label'=>$langs->trans($line["label"]), 'required'=>(empty($line["required"]) ? 0 : 1));
  929. }
  930. $height = '32px'; //needs px for css height attribute below
  931. $i = 0;
  932. $mandatoryfieldshavesource = true;
  933. print '<table class="nobordernopadding centpercent tableimport">';
  934. foreach ($fieldstarget as $code => $line) {
  935. if ($i == $minpos) {
  936. break;
  937. }
  938. print '<tr style="height:'.$height.'" class="trimport oddevenimport">';
  939. $entity = (!empty($objimport->array_import_entities[0][$code]) ? $objimport->array_import_entities[0][$code] : $objimport->array_import_icon[0]);
  940. $tablealias = preg_replace('/(\..*)$/i', '', $code);
  941. $tablename = $objimport->array_import_tables[0][$tablealias];
  942. $entityicon = !empty($entitytoicon[$entity]) ? $entitytoicon[$entity] : $entity; // $entityicon must string name of picto of the field like 'project', 'company', 'contact', 'modulename', ...
  943. $entitylang = $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', 'MyModyle', ...
  944. //print '<td class="nowraponall" style="font-weight: normal">=> '.img_object('', $entityicon).' '.$langs->trans($entitylang).'</td>';
  945. print '<td class="nowraponall" style="font-weight: normal">=> </td>';
  946. print '<td class="nowraponall" style="font-weight: normal">';
  947. print '<select id="selectorderimport_'.($i+1).'" class="targetselectchange minwidth300" name="select_'.$line["label"].'">';
  948. if ($line["imported"]) {
  949. print '<option value="-1">&nbsp;</option>';
  950. } else {
  951. print '<option selected="" value="-1">&nbsp;</option>';
  952. }
  953. $j = 0;
  954. foreach ($optionsall as $code => $val) {
  955. $label = $val['required'] ? '<strong>' : '';
  956. $label .= $val['label'];
  957. $label .= $val['required'] ? '*</strong>' : '';
  958. print '<option value="'.$code.'"';
  959. if ($j == $i) {
  960. print ' selected';
  961. }
  962. print ' data-html="'.dol_escape_htmltag($label).'"';
  963. print '>';
  964. print $label;
  965. print '</options>';
  966. $j++;
  967. }
  968. print '</select>';
  969. print ajax_combobox('selectorderimport_'.($i+1));
  970. print "</td>";
  971. print '<td class="nowraponall" style="font-weight:normal; text-align:right">';
  972. $filecolumn = ($i + 1);
  973. // Source field info
  974. $htmltext = '<b><u>'.$langs->trans("FieldSource").'</u></b><br>';
  975. if ($filecolumn > count($fieldssource)) {
  976. $htmltext .= $langs->trans("DataComeFromNoWhere").'<br>';
  977. } else {
  978. if (empty($objimport->array_import_convertvalue[0][$code])) { // If source file does not need convertion
  979. $filecolumntoshow = $i + 1;
  980. $htmltext .= $langs->trans("DataComeFromFileFieldNb", $filecolumntoshow).'<br>';
  981. } else {
  982. if ($objimport->array_import_convertvalue[0][$code]['rule'] == 'fetchidfromref') {
  983. $htmltext .= $langs->trans("DataComeFromIdFoundFromRef", $filecolumn, $langs->transnoentitiesnoconv($entitylang)).'<br>';
  984. }
  985. if ($objimport->array_import_convertvalue[0][$code]['rule'] == 'fetchidfromcodeid') {
  986. $htmltext .= $langs->trans("DataComeFromIdFoundFromCodeId", $filecolumn, $langs->transnoentitiesnoconv($objimport->array_import_convertvalue[0][$code]['dict'])).'<br>';
  987. }
  988. }
  989. }
  990. // Source required
  991. $example = !empty($objimport->array_import_examplevalues[0][$code])?$objimport->array_import_examplevalues[0][$code]:"";
  992. // Example
  993. if (empty($objimport->array_import_convertvalue[0][$code])) { // If source file does not need convertion
  994. if ($example) {
  995. $htmltext .= $langs->trans("SourceExample").': <b>'.$example.'</b><br>';
  996. }
  997. } else {
  998. if ($objimport->array_import_convertvalue[0][$code]['rule'] == 'fetchidfromref') {
  999. $htmltext .= $langs->trans("SourceExample").': <b>'.$langs->transnoentitiesnoconv("ExampleAnyRefFoundIntoElement", $entitylang).($example ? ' ('.$langs->transnoentitiesnoconv("Example").': '.$example.')' : '').'</b><br>';
  1000. } elseif ($objimport->array_import_convertvalue[0][$code]['rule'] == 'fetchidfromcodeid') {
  1001. $htmltext .= $langs->trans("SourceExample").': <b>'.$langs->trans("ExampleAnyCodeOrIdFoundIntoDictionary", $langs->transnoentitiesnoconv($objimport->array_import_convertvalue[0][$code]['dict'])).($example ? ' ('.$langs->transnoentitiesnoconv("Example").': '.$example.')' : '').'</b><br>';
  1002. } elseif ($example) {
  1003. $htmltext .= $langs->trans("SourceExample").': <b>'.$example.'</b><br>';
  1004. }
  1005. }
  1006. // Format control rule
  1007. if (!empty($objimport->array_import_regex[0][$code])) {
  1008. $htmltext .= $langs->trans("FormatControlRule").': <b>'.$objimport->array_import_regex[0][$code].'</b><br>';
  1009. }
  1010. $htmltext .= '<br>';
  1011. // Target field info
  1012. $htmltext .= '<b><u>'.$langs->trans("FieldTarget").'</u></b><br>';
  1013. //$htmltext .= $langs->trans("SourceRequired").': <b>'.yn($line["label"]).'</b><br>';
  1014. if (empty($objimport->array_import_convertvalue[0][$code])) { // If source file does not need convertion
  1015. $htmltext .= $langs->trans("DataIsInsertedInto").'<br>';
  1016. } else {
  1017. if ($objimport->array_import_convertvalue[0][$code]['rule'] == 'fetchidfromref') {
  1018. $htmltext .= $langs->trans("DataIDSourceIsInsertedInto").'<br>';
  1019. }
  1020. if ($objimport->array_import_convertvalue[0][$code]['rule'] == 'fetchidfromcodeid') {
  1021. $htmltext .= $langs->trans("DataCodeIDSourceIsInsertedInto").'<br>';
  1022. }
  1023. }
  1024. $htmltext .= $langs->trans("FieldTitle").": <b>".$langs->trans($line["label"])."</b><br>";
  1025. $htmltext .= $langs->trans("Table")." -> ".$langs->trans("Field").': <b>'.$tablename." -> ".preg_replace('/^.*\./', '', $code)."</b><br>";
  1026. print $form->textwithpicto($more, $htmltext);
  1027. print '</tr>';
  1028. $i++;
  1029. }
  1030. print '</table>';
  1031. print '</td></tr>';
  1032. // List of not imported fields
  1033. /*
  1034. print '<tr class="liste_titre"><td colspan="2">'.$langs->trans("NotUsedFields").'</td></tr>';
  1035. print '<tr valign="top"><td width="50%">';
  1036. print "\n<!-- Box ignore container -->\n";
  1037. print '<div id="right" class="connectedSortable">'."\n";
  1038. $nbofnotimportedfields = 0;
  1039. foreach ($fieldstarget as $key => $val) {
  1040. if (!$fieldstarget[$key]['imported']) {
  1041. //
  1042. $nbofnotimportedfields++;
  1043. show_elem($fieldstarget, $key, '', $var, 'nostyle');
  1044. //print '> '.$lefti.'-'.$key;
  1045. $listofkeys[$key] = 1;
  1046. $lefti++;
  1047. }
  1048. }
  1049. // Print one more empty field
  1050. $newkey = getnewkey($fieldssource, $listofkeys);
  1051. show_elem($fieldssource, $newkey, '', $var, 'nostyle');
  1052. //print '> '.$lefti.'-'.$newkey;
  1053. $listofkeys[$newkey] = 1;
  1054. $nbofnotimportedfields++;
  1055. print "</div>\n";
  1056. print "<!-- End box ignore container -->\n";
  1057. print '</td>';
  1058. print '<td width="50%">';
  1059. $i = 0;
  1060. while ($i < $nbofnotimportedfields) {
  1061. // Print empty cells
  1062. show_elem('', '', 'none', $var, 'nostyle');
  1063. $i++;
  1064. }
  1065. print '</td></tr>';
  1066. */
  1067. print '</table>';
  1068. print '</div>';
  1069. if (!empty($conf->use_javascript_ajax)) {
  1070. print '<script type="text/javascript">'."\n";
  1071. print 'var previousselectedvalueimport = "0";'."\n";
  1072. print 'var previousselectedlabelimport = "0";'."\n";
  1073. print 'var arrayofselectedvalues = [];'."\n";
  1074. print '$(document).ready(function () {'."\n";
  1075. print 'setOptionsToDisabled();'."\n";
  1076. print 'saveSelection();'."\n";
  1077. print '$(".targetselectchange").focus(function(){'."\n";
  1078. print ' previousselectedvalueimport = $(this).val();'."\n";
  1079. print ' previousselectedlabelimport = $(this).children("option:selected").text();'."\n";
  1080. print ' console.log("previousselectedvalueimport="+previousselectedvalueimport)'."\n";
  1081. print '})'."\n";
  1082. // Function to set the disabled flag
  1083. // - We set all option to "enabled"
  1084. // - Then we scan all combo to get the value currently selected and save them into the array arrayofselectedvalues
  1085. // - Then we set to disabled all fields that are selected
  1086. print 'function setOptionsToDisabled() {'."\n";
  1087. print ' console.log("Remove the disabled flag everywhere");'."\n";
  1088. print ' $(".targetselectchange").not($( this )).find(\'option\').prop("disabled", false);'."\n";
  1089. print ' arrayofselectedvalues = [];'."\n";
  1090. print ' $(".targetselectchange").each(function(){'."\n";
  1091. print ' value = $(this).val()'."\n";
  1092. print ' arrayofselectedvalues.push(value);'."\n";
  1093. print ' });'."\n";
  1094. print ' console.log("List of all selected values");'."\n";
  1095. print ' console.log(arrayofselectedvalues);'."\n";
  1096. print ' console.log("Set the disabled flag for every entry in arrayofselectedvalues");'."\n";
  1097. print ' $.each( arrayofselectedvalues, function( key, value ) {'."\n";
  1098. print ' if (value != -1) {'."\n";
  1099. print ' console.log("Process key="+key+" value="+value);'."\n";
  1100. print ' $(".targetselectchange").find(\'option[value="\'+value+\'"]\').prop("disabled", true);'."\n";
  1101. print ' }'."\n";
  1102. print ' });'."\n";
  1103. print '};'."\n";
  1104. // Function to save the selection
  1105. print 'function saveSelection() {'."\n";
  1106. print ' arrayselectedfields = [];'."\n";
  1107. print ' arrayselectedfields.push("0");'."\n";
  1108. print ' $.each( arrayofselectedvalues, function( key, value ) {'."\n";
  1109. print ' if (value != -1) {'."\n";
  1110. print ' arrayselectedfields.push(value);'."\n";
  1111. print ' } else {'."\n";
  1112. print ' arrayselectedfields.push(0);'."\n";
  1113. print ' }'."\n";
  1114. print ' });'."\n";
  1115. print " $.ajax({\n";
  1116. print " type: 'POST',\n";
  1117. print " dataType: 'json',\n";
  1118. print " url: '".dol_escape_js($_SERVER["PHP_SELF"])."?action=saveselectorder&token=".newToken()."',\n";
  1119. print " data: 'selectorder='+arrayselectedfields.toString(),\n";
  1120. print " success: function(){\n";
  1121. print " console.log('Select order saved');\n";
  1122. print " },\n";
  1123. print ' });'."\n";
  1124. print '};'."\n";
  1125. // If we make a change on a selectbox
  1126. print '$(".targetselectchange").change(function(){'."\n";
  1127. print ' setOptionsToDisabled();'."\n";
  1128. print ' if(previousselectedlabelimport != "" && previousselectedvalueimport != -1) {'."\n";
  1129. print ' let valuetochange = $(this).val(); '."\n";
  1130. print ' $(".boxtdunused").each(function(){'."\n";
  1131. print ' if ($(this).text().includes(valuetochange)){'."\n";
  1132. print ' arraychild = $(this)[0].childNodes'."\n";
  1133. print ' arraytexttomodify = arraychild[0].textContent.split(" ")'."\n";
  1134. print ' arraytexttomodify[1] = previousselectedvalueimport '."\n";
  1135. print ' textmodified = arraytexttomodify.join(" ") '."\n";
  1136. print ' arraychild[0].textContent = textmodified'."\n";
  1137. print ' arraychild[1].innerHTML = previousselectedlabelimport'."\n";
  1138. print ' }'."\n";
  1139. print ' })'."\n";
  1140. print ' }'."\n";
  1141. print ' $(this).blur()'."\n";
  1142. print ' saveSelection()'."\n";
  1143. print '});'."\n";
  1144. print '})'."\n";
  1145. print '</script>'."\n";
  1146. }
  1147. /*
  1148. * Action bar
  1149. */
  1150. print '<div class="tabsAction">';
  1151. if (count($array_match_file_to_database)) {
  1152. if ($mandatoryfieldshavesource) {
  1153. print '<a class="butAction saveorderselect" href="import.php?step=5'.$param.'&filetoimport='.urlencode($filetoimport).'">'.$langs->trans("NextStep").'</a>';
  1154. } else {
  1155. print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->transnoentitiesnoconv("SomeMandatoryFieldHaveNoSource")).'">'.$langs->trans("NextStep").'</a>';
  1156. }
  1157. }
  1158. print '</div>';
  1159. // Area for profils import
  1160. if (count($array_match_file_to_database)) {
  1161. print '<br>'."\n";
  1162. print '<!-- Area to add new import profile -->'."\n";
  1163. print '<div class="marginbottomonly"><span class="opacitymedium">'.$langs->trans("SaveImportModel").'</span></div>';
  1164. print '<form class="nocellnopadd" action="'.$_SERVER["PHP_SELF"].'" method="post">';
  1165. print '<input type="hidden" name="token" value="'.newToken().'">';
  1166. print '<input type="hidden" name="action" value="add_import_model">';
  1167. print '<input type="hidden" name="step" value="'.$step.'">';
  1168. print '<input type="hidden" name="format" value="'.$format.'">';
  1169. print '<input type="hidden" name="datatoimport" value="'.$datatoimport.'">';
  1170. print '<input type="hidden" name="filetoimport" value="'.$filetoimport.'">';
  1171. print '<input type="hidden" name="hexa" value="'.$hexa.'">';
  1172. print '<input type="hidden" name="excludefirstline" value="'.$excludefirstline.'">';
  1173. print '<input type="hidden" name="endatlinenb" value="'.$endatlinenb.'">';
  1174. print '<input type="hidden" name="page_y" value="">';
  1175. print '<input type="hidden" value="'.dol_escape_htmltag($separator).'" name="separator">';
  1176. print '<input type="hidden" value="'.dol_escape_htmltag($enclosure).'" name="enclosure">';
  1177. print '<div class="div-table-responsive-no-min">'; // You can use div-table-responsive-no-min if you dont need reserved height for your table
  1178. print '<table summary="selectofimportprofil" class="noborder centpercent">';
  1179. print '<tr class="liste_titre">';
  1180. print '<td>'.$langs->trans("ImportModelName").'</td>';
  1181. print '<td>'.$langs->trans("Visibility").'</td>';
  1182. print '<td></td>';
  1183. print '</tr>';
  1184. print '<tr class="oddeven">';
  1185. print '<td><input name="import_name" value=""></td>';
  1186. print '<td>';
  1187. $arrayvisibility = array('private'=>$langs->trans("Private"), 'all'=>$langs->trans("Everybody"));
  1188. print $form->selectarray('visibility', $arrayvisibility, 'private');
  1189. print '</td>';
  1190. print '<td class="right">';
  1191. print '<input type="submit" class="button small reposition" value="'.$langs->trans("SaveImportProfile").'">';
  1192. print '</td></tr>';
  1193. // List of existing import profils
  1194. $sql = "SELECT rowid, label, fk_user, entity";
  1195. $sql .= " FROM ".MAIN_DB_PREFIX."import_model";
  1196. $sql .= " WHERE type = '".$db->escape($datatoimport)."'";
  1197. if (empty($conf->global->EXPORTS_SHARE_MODELS)) { // EXPORTS_SHARE_MODELS means all templates are visible, whatever is owner.
  1198. $sql .= " AND fk_user IN (0, ".((int) $user->id).")";
  1199. }
  1200. $sql .= " ORDER BY rowid";
  1201. $resql = $db->query($sql);
  1202. if ($resql) {
  1203. $num = $db->num_rows($resql);
  1204. $tmpuser = new user($db);
  1205. $i = 0;
  1206. while ($i < $num) {
  1207. $obj = $db->fetch_object($resql);
  1208. print '<tr class="oddeven"><td>';
  1209. print $obj->label;
  1210. print '</td>';
  1211. print '<td>';
  1212. if (empty($obj->fk_user)) {
  1213. print $langs->trans("Everybody");
  1214. } else {
  1215. $tmpuser->fetch($obj->fk_user);
  1216. print $tmpuser->getNomUrl(1);
  1217. }
  1218. print '</td>';
  1219. print '<td class="right">';
  1220. print '<a class="reposition" href="'.$_SERVER["PHP_SELF"].'?step='.$step.$param.'&action=deleteprof&token='.newToken().'&id='.$obj->rowid.'&filetoimport='.urlencode($filetoimport).'">';
  1221. print img_delete();
  1222. print '</a>';
  1223. print '</tr>';
  1224. $i++;
  1225. }
  1226. } else {
  1227. dol_print_error($db);
  1228. }
  1229. print '</table>';
  1230. print '</div>';
  1231. print '</form>';
  1232. }
  1233. }
  1234. // STEP 5: Summary of choices and launch simulation
  1235. if ($step == 5 && $datatoimport) {
  1236. $max_execution_time_for_importexport = (empty($conf->global->IMPORT_MAX_EXECUTION_TIME) ? 300 : $conf->global->IMPORT_MAX_EXECUTION_TIME); // 5mn if not defined
  1237. $max_time = @ini_get("max_execution_time");
  1238. if ($max_time && $max_time < $max_execution_time_for_importexport) {
  1239. 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.");
  1240. @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
  1241. }
  1242. $model = $format;
  1243. $list = $objmodelimport->liste_modeles($db);
  1244. // Create classe to use for import
  1245. $dir = DOL_DOCUMENT_ROOT."/core/modules/import/";
  1246. $file = "import_".$model.".modules.php";
  1247. $classname = "Import".ucfirst($model);
  1248. require_once $dir.$file;
  1249. $obj = new $classname($db, $datatoimport);
  1250. if ($model == 'csv') {
  1251. $obj->separator = $separator_used;
  1252. $obj->enclosure = $enclosure;
  1253. }
  1254. // Load source fields in input file
  1255. $fieldssource = array();
  1256. $result = $obj->import_open_file($conf->import->dir_temp.'/'.$filetoimport, $langs);
  1257. if ($result >= 0) {
  1258. // Read first line
  1259. $arrayrecord = $obj->import_read_record();
  1260. // Put into array fieldssource starting with 1.
  1261. $i = 1;
  1262. foreach ($arrayrecord as $key => $val) {
  1263. $fieldssource[$i]['example1'] = dol_trunc($val['val'], 24);
  1264. $i++;
  1265. }
  1266. $obj->import_close_file();
  1267. }
  1268. $nboflines = $obj->import_get_nb_of_lines($conf->import->dir_temp.'/'.$filetoimport);
  1269. $param = '&leftmenu=import&format='.urlencode($format).'&datatoimport='.urlencode($datatoimport).'&filetoimport='.urlencode($filetoimport).'&nboflines='.urlencode($nboflines).'&separator='.urlencode($separator).'&enclosure='.urlencode($enclosure);
  1270. $param2 = $param; // $param2 = $param without excludefirstline and endatlinenb
  1271. if ($excludefirstline) {
  1272. $param .= '&excludefirstline='.urlencode($excludefirstline);
  1273. }
  1274. if ($endatlinenb) {
  1275. $param .= '&endatlinenb='.urlencode($endatlinenb);
  1276. }
  1277. if (!empty($updatekeys)) {
  1278. $param .= '&updatekeys[]='.implode('&updatekeys[]=', $updatekeys);
  1279. }
  1280. llxHeader('', $langs->trans("NewImport"), 'EN:Module_Imports_En|FR:Module_Imports|ES:M&oacute;dulo_Importaciones');
  1281. $head = import_prepare_head($param, 5);
  1282. print '<form action="'.$_SERVER["PHP_SELF"].'?'.$param2.'" method="POST">';
  1283. print '<input type="hidden" name="token" value="'.newToken().'">';
  1284. print '<input type="hidden" name="step" value="5">'; // step 5
  1285. print '<input type="hidden" name="action" value="launchsimu">'; // step 5
  1286. print dol_get_fiche_head($head, 'step5', '', -2);
  1287. print '<div class="underbanner clearboth"></div>';
  1288. print '<div class="fichecenter">';
  1289. print '<table width="100%" class="border tableforfield">';
  1290. // Module
  1291. print '<tr><td class="titlefieldcreate">'.$langs->trans("Module").'</td>';
  1292. print '<td>';
  1293. $titleofmodule = $objimport->array_import_module[0]['module']->getName();
  1294. // Special cas for import common to module/services
  1295. if (in_array($objimport->array_import_code[0], array('produit_supplierprices', 'produit_multiprice', 'produit_languages'))) {
  1296. $titleofmodule = $langs->trans("ProductOrService");
  1297. }
  1298. print $titleofmodule;
  1299. print '</td></tr>';
  1300. // Lot de donnees a importer
  1301. print '<tr><td>'.$langs->trans("DatasetToImport").'</td>';
  1302. print '<td>';
  1303. $entity = preg_replace('/:.*$/', '', $objimport->array_import_icon[0]);
  1304. $entityicon = strtolower(!empty($entitytoicon[$entity]) ? $entitytoicon[$entity] : $entity);
  1305. print img_object($objimport->array_import_module[0]['module']->getName(), $entityicon).' ';
  1306. print $objimport->array_import_label[0];
  1307. print '</td></tr>';
  1308. print '</table>';
  1309. print '</div>';
  1310. print load_fiche_titre($langs->trans("InformationOnSourceFile"), '', 'file-export');
  1311. print '<div class="underbanner clearboth"></div>';
  1312. print '<div class="fichecenter">';
  1313. print '<table width="100%" class="border tableforfield">';
  1314. // Source file format
  1315. print '<tr><td class="titlefieldcreate">'.$langs->trans("SourceFileFormat").'</td>';
  1316. print '<td>';
  1317. $text = $objmodelimport->getDriverDescForKey($format);
  1318. print $form->textwithpicto($objmodelimport->getDriverLabelForKey($format), $text);
  1319. print '</td></tr>';
  1320. // Separator and enclosure
  1321. if ($model == 'csv') {
  1322. print '<tr><td>'.$langs->trans("CsvOptions").'</td>';
  1323. print '<td>';
  1324. print $langs->trans("Separator").' : '.dol_escape_htmltag($separator);
  1325. print '&nbsp;&nbsp;&nbsp;&nbsp;'.$langs->trans("Enclosure").' : '.dol_escape_htmltag($enclosure);
  1326. print '</td></tr>';
  1327. }
  1328. // File to import
  1329. print '<tr><td>'.$langs->trans("FileToImport").'</td>';
  1330. print '<td>';
  1331. $modulepart = 'import';
  1332. $relativepath = GETPOST('filetoimport');
  1333. print '<a data-ajax="false" href="'.DOL_URL_ROOT.'/document.php?modulepart='.$modulepart.'&file='.urlencode($relativepath).'&step=4'.$param.'" target="_blank" rel="noopener noreferrer">';
  1334. print img_mime($file, '', 'pictofixedwidth');
  1335. print $filetoimport;
  1336. print '</a>';
  1337. print '</td></tr>';
  1338. // Total lines in source file
  1339. print '<tr><td>';
  1340. print $langs->trans("NbOfSourceLines");
  1341. print '</td><td>';
  1342. print $nboflines;
  1343. print '</td></tr>';
  1344. // Range of lines to import
  1345. print '<tr><td>';
  1346. print $langs->trans("ImportFromToLine");
  1347. print '</td><td>';
  1348. if ($action == 'launchsimu') {
  1349. print '<input type="number" class="maxwidth50 right" name="excludefirstlinebis" disabled="disabled" value="'.$excludefirstline.'">';
  1350. print '<input type="hidden" name="excludefirstline" value="'.$excludefirstline.'">';
  1351. } else {
  1352. print '<input type="number" class="maxwidth50 right" name="excludefirstline" value="'.$excludefirstline.'">';
  1353. print $form->textwithpicto("", $langs->trans("SetThisValueTo2ToExcludeFirstLine"));
  1354. }
  1355. print ' - ';
  1356. if ($action == 'launchsimu') {
  1357. print '<input type="text" class="maxwidth50" name="endatlinenbbis" disabled="disabled" value="'.$endatlinenb.'">';
  1358. print '<input type="hidden" name="endatlinenb" value="'.$endatlinenb.'">';
  1359. } else {
  1360. print '<input type="text" class="maxwidth50" name="endatlinenb" value="'.$endatlinenb.'">';
  1361. print $form->textwithpicto("", $langs->trans("KeepEmptyToGoToEndOfFile"));
  1362. }
  1363. if ($action == 'launchsimu') {
  1364. print ' &nbsp; <a href="'.$_SERVER["PHP_SELF"].'?step=5'.$param.'">'.$langs->trans("Modify").'</a>';
  1365. }
  1366. if ($excludefirstline == 2) {
  1367. print $form->textwithpicto("", $langs->trans("WarningFirstImportedLine", $excludefirstline), 1, 'warning', "warningexcludefirstline");
  1368. print '<script>
  1369. $( document ).ready(function() {
  1370. $("input[name=\'excludefirstline\']").on("change",function(){
  1371. if($(this).val() <= 1){
  1372. $(".warningexcludefirstline").hide();
  1373. }else{
  1374. $(".warningexcludefirstline").show();
  1375. }
  1376. })
  1377. });
  1378. </script>';
  1379. }
  1380. print '</td></tr>';
  1381. // Keys for data UPDATE (not INSERT of new data)
  1382. print '<tr><td>';
  1383. print $langs->trans("KeysToUseForUpdates");
  1384. print '</td><td>';
  1385. if ($action == 'launchsimu') {
  1386. if (count($updatekeys)) {
  1387. print $form->multiselectarray('updatekeysbis', $objimport->array_import_updatekeys[0], $updatekeys, 0, 0, '', 1, '80%', 'disabled');
  1388. } else {
  1389. print '<span class="opacitymedium">'.$langs->trans("NoUpdateAttempt").'</span> &nbsp; -';
  1390. }
  1391. foreach ($updatekeys as $val) {
  1392. print '<input type="hidden" name="updatekeys[]" value="'.$val.'">';
  1393. }
  1394. print ' &nbsp; <a href="'.$_SERVER["PHP_SELF"].'?step=5'.$param.'">'.$langs->trans("Modify").'</a>';
  1395. } else {
  1396. if (is_array($objimport->array_import_updatekeys[0]) && count($objimport->array_import_updatekeys[0])) { //TODO dropdown UL is created inside nested SPANS
  1397. print $form->multiselectarray('updatekeys', $objimport->array_import_updatekeys[0], $updatekeys, 0, 0, '', 1, '80%');
  1398. print $form->textwithpicto("", $langs->trans("SelectPrimaryColumnsForUpdateAttempt"));
  1399. } else {
  1400. print '<span class="opacitymedium">'.$langs->trans("UpdateNotYetSupportedForThisImport").'</span>';
  1401. }
  1402. }
  1403. /*echo '<pre>';
  1404. print_r($objimport->array_import_updatekeys);
  1405. echo '</pre>';*/
  1406. print '</td></tr>';
  1407. print '</table>';
  1408. print '</div>';
  1409. print load_fiche_titre($langs->trans("InformationOnTargetTables"), '', 'file-import');
  1410. print '<div class="underbanner clearboth"></div>';
  1411. print '<div class="fichecenter">';
  1412. print '<table width="100%" class="border tableforfield">';
  1413. // Tables imported
  1414. print '<tr><td class="titlefieldcreate">';
  1415. print $langs->trans("TablesTarget");
  1416. print '</td><td>';
  1417. $listtables = array();
  1418. $sort_array_match_file_to_database = $array_match_file_to_database;
  1419. foreach ($array_match_file_to_database as $code => $label) {
  1420. //var_dump($fieldssource);
  1421. if ($code > count($fieldssource)) {
  1422. continue;
  1423. }
  1424. //print $code.'-'.$label;
  1425. $alias = preg_replace('/(\..*)$/i', '', $label);
  1426. $listtables[$alias] = $objimport->array_import_tables[0][$alias];
  1427. }
  1428. if (count($listtables)) {
  1429. $newval = '';
  1430. //ksort($listtables);
  1431. foreach ($listtables as $val) {
  1432. if ($newval) {
  1433. print ', ';
  1434. }
  1435. $newval = $val;
  1436. // Link to Dolibarr wiki pages
  1437. /*$helppagename='EN:Table_'.$newval;
  1438. if ($helppagename && empty($conf->global->MAIN_HELP_DISABLELINK))
  1439. {
  1440. // Get helpbaseurl, helppage and mode from helppagename and langs
  1441. $arrayres=getHelpParamFor($helppagename,$langs);
  1442. $helpbaseurl=$arrayres['helpbaseurl'];
  1443. $helppage=$arrayres['helppage'];
  1444. $mode=$arrayres['mode'];
  1445. $newval.=' <a href="'.sprintf($helpbaseurl,$helppage).'">'.img_picto($langs->trans($mode == 'wiki' ? 'GoToWikiHelpPage': 'GoToHelpPage'),DOL_URL_ROOT.'/theme/common/helpdoc.png','',1).'</a>';
  1446. }*/
  1447. print $newval;
  1448. }
  1449. } else {
  1450. print $langs->trans("Error");
  1451. }
  1452. print '</td></tr>';
  1453. // Fields imported
  1454. print '<tr><td>';
  1455. print $langs->trans("FieldsTarget").'</td><td>';
  1456. $listfields = array();
  1457. $i = 0;
  1458. //print 'fieldsource='.$fieldssource;
  1459. $sort_array_match_file_to_database = $array_match_file_to_database;
  1460. ksort($sort_array_match_file_to_database);
  1461. //var_dump($sort_array_match_file_to_database);
  1462. foreach ($sort_array_match_file_to_database as $code => $label) {
  1463. $i++;
  1464. //var_dump($fieldssource);
  1465. if ($code > count($fieldssource)) {
  1466. continue;
  1467. }
  1468. //print $code.'-'.$label;
  1469. $alias = preg_replace('/(\..*)$/i', '', $label);
  1470. $listfields[$i] = $langs->trans("Field").' '.$code.'->'.$label;
  1471. }
  1472. print count($listfields) ? (join(', ', $listfields)) : $langs->trans("Error");
  1473. print '</td></tr>';
  1474. print '</table>';
  1475. print '</div>';
  1476. print dol_get_fiche_end();
  1477. if ($action != 'launchsimu') {
  1478. // Show import id
  1479. print '<br><span class="opacitymedium">';
  1480. print $langs->trans("NowClickToTestTheImport", $langs->transnoentitiesnoconv("RunSimulateImportFile")).'</span><br>';
  1481. print '<br>';
  1482. // Actions
  1483. print '<div class="center">';
  1484. if ($user->rights->import->run) {
  1485. print '<input type="submit" class="butAction" value="'.$langs->trans("RunSimulateImportFile").'">';
  1486. } else {
  1487. print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->transnoentitiesnoconv("NotEnoughPermissions")).'">'.$langs->trans("RunSimulateImportFile").'</a>';
  1488. }
  1489. print '</div>';
  1490. } else {
  1491. // Launch import
  1492. $arrayoferrors = array();
  1493. $arrayofwarnings = array();
  1494. $maxnboferrors = empty($conf->global->IMPORT_MAX_NB_OF_ERRORS) ? 50 : $conf->global->IMPORT_MAX_NB_OF_ERRORS;
  1495. $maxnbofwarnings = empty($conf->global->IMPORT_MAX_NB_OF_WARNINGS) ? 50 : $conf->global->IMPORT_MAX_NB_OF_WARNINGS;
  1496. $nboferrors = 0;
  1497. $nbofwarnings = 0;
  1498. $importid = dol_print_date(dol_now(), '%Y%m%d%H%M%S');
  1499. //var_dump($array_match_file_to_database);
  1500. $db->begin();
  1501. // Open input file
  1502. $nbok = 0;
  1503. $pathfile = $conf->import->dir_temp.'/'.$filetoimport;
  1504. $result = $obj->import_open_file($pathfile, $langs);
  1505. if ($result > 0) {
  1506. global $tablewithentity_cache;
  1507. $tablewithentity_cache = array();
  1508. $sourcelinenb = 0; $endoffile = 0;
  1509. // Loop on each input file record
  1510. while (($sourcelinenb < $nboflines) && !$endoffile) {
  1511. $sourcelinenb++;
  1512. // Read line and store it into $arrayrecord
  1513. //dol_syslog("line ".$sourcelinenb.' - '.$nboflines.' - '.$excludefirstline.' - '.$endatlinenb);
  1514. $arrayrecord = $obj->import_read_record();
  1515. if ($arrayrecord === false) {
  1516. $arrayofwarnings[$sourcelinenb][0] = array('lib'=>'File has '.$nboflines.' lines. However we reach end of file after record '.$sourcelinenb.'. This may occurs when some records are split onto several lines. Ensure the complete string is delimited correctly when there is a separator character in the text string.', 'type'=>'EOF_RECORD_ON_SEVERAL_LINES');
  1517. $endoffile++;
  1518. continue;
  1519. }
  1520. if ($excludefirstline && ($sourcelinenb < $excludefirstline)) {
  1521. continue;
  1522. }
  1523. if ($endatlinenb && ($sourcelinenb > $endatlinenb)) {
  1524. break;
  1525. }
  1526. // Run import
  1527. $result = $obj->import_insert($arrayrecord, $array_match_file_to_database, $objimport, count($fieldssource), $importid, $updatekeys);
  1528. if (count($obj->errors)) {
  1529. $arrayoferrors[$sourcelinenb] = $obj->errors;
  1530. }
  1531. if (count($obj->warnings)) {
  1532. $arrayofwarnings[$sourcelinenb] = $obj->warnings;
  1533. }
  1534. if (!count($obj->errors) && !count($obj->warnings)) {
  1535. $nbok++;
  1536. }
  1537. }
  1538. // Close file
  1539. $obj->import_close_file();
  1540. } else {
  1541. print $langs->trans("ErrorFailedToOpenFile", $pathfile);
  1542. }
  1543. $error = 0;
  1544. // Run the sql after import if defined
  1545. //var_dump($objimport->array_import_run_sql_after[0]);
  1546. if (!empty($objimport->array_import_run_sql_after[0]) && is_array($objimport->array_import_run_sql_after[0])) {
  1547. $i = 0;
  1548. foreach ($objimport->array_import_run_sql_after[0] as $sqlafterimport) {
  1549. $i++;
  1550. $resqlafterimport = $db->query($sqlafterimport);
  1551. if (!$resqlafterimport) {
  1552. $arrayoferrors['none'][] = array('lib'=>$langs->trans("Error running final request: ".$sqlafterimport));
  1553. $error++;
  1554. }
  1555. }
  1556. }
  1557. $db->rollback(); // We force rollback because this was just a simulation.
  1558. // Show OK
  1559. if (!count($arrayoferrors) && !count($arrayofwarnings)) {
  1560. print '<div class="center">'.img_picto($langs->trans("OK"), 'tick').' <b>'.$langs->trans("NoError").'</b></div><br><br>';
  1561. print '<div class="ok">';
  1562. print $langs->trans("NbInsert", empty($obj->nbinsert) ? 0 : $obj->nbinsert).'<br>';
  1563. print $langs->trans("NbUpdate", empty($obj->nbupdate) ? 0 : $obj->nbupdate).'<br>';
  1564. print '</div>';
  1565. print '<br>';
  1566. } else {
  1567. print '<br>';
  1568. print '<div class="info">';
  1569. print $langs->trans("NbOfLinesOK", $nbok).'<br>';
  1570. print '</div>';
  1571. print '<br>';
  1572. }
  1573. // Show Errors
  1574. //var_dump($arrayoferrors);
  1575. if (count($arrayoferrors)) {
  1576. print img_error().' <b>'.$langs->trans("ErrorsOnXLines", count($arrayoferrors)).'</b><br>';
  1577. print '<table width="100%" class="border"><tr><td>';
  1578. foreach ($arrayoferrors as $key => $val) {
  1579. $nboferrors++;
  1580. if ($nboferrors > $maxnboferrors) {
  1581. print $langs->trans("TooMuchErrors", (count($arrayoferrors) - $nboferrors))."<br>";
  1582. break;
  1583. }
  1584. print '* '.$langs->trans("Line").' '.$key.'<br>';
  1585. foreach ($val as $i => $err) {
  1586. print ' &nbsp; &nbsp; > '.$err['lib'].'<br>';
  1587. }
  1588. }
  1589. print '</td></tr></table>';
  1590. print '<br>';
  1591. }
  1592. // Show Warnings
  1593. //var_dump($arrayoferrors);
  1594. if (count($arrayofwarnings)) {
  1595. print img_warning().' <b>'.$langs->trans("WarningsOnXLines", count($arrayofwarnings)).'</b><br>';
  1596. print '<table width="100%" class="border"><tr><td>';
  1597. foreach ($arrayofwarnings as $key => $val) {
  1598. $nbofwarnings++;
  1599. if ($nbofwarnings > $maxnbofwarnings) {
  1600. print $langs->trans("TooMuchWarnings", (count($arrayofwarnings) - $nbofwarnings))."<br>";
  1601. break;
  1602. }
  1603. print ' * '.$langs->trans("Line").' '.$key.'<br>';
  1604. foreach ($val as $i => $err) {
  1605. print ' &nbsp; &nbsp; > '.$err['lib'].'<br>';
  1606. }
  1607. }
  1608. print '</td></tr></table>';
  1609. print '<br>';
  1610. }
  1611. // Show import id
  1612. $importid = dol_print_date(dol_now(), '%Y%m%d%H%M%S');
  1613. print '<div class="center">';
  1614. print '<span class="opacitymedium">'.$langs->trans("NowClickToRunTheImport", $langs->transnoentitiesnoconv("RunImportFile")).'</span><br>';
  1615. if (empty($nboferrors)) {
  1616. print $langs->trans("DataLoadedWithId", $importid).'<br>';
  1617. }
  1618. print '</div>';
  1619. print '<br>';
  1620. // Actions
  1621. print '<div class="center">';
  1622. if ($user->rights->import->run) {
  1623. if (empty($nboferrors)) {
  1624. print '<a class="butAction" href="'.DOL_URL_ROOT.'/imports/import.php?leftmenu=import&step=6&importid='.$importid.$param.'">'.$langs->trans("RunImportFile").'</a>';
  1625. } else {
  1626. //print '<input type="submit" class="butAction" value="'.dol_escape_htmltag($langs->trans("RunSimulateImportFile")).'">';
  1627. print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->transnoentitiesnoconv("CorrectErrorBeforeRunningImport")).'">'.$langs->trans("RunImportFile").'</a>';
  1628. }
  1629. } else {
  1630. print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->transnoentitiesnoconv("NotEnoughPermissions")).'">'.$langs->trans("RunSimulateImportFile").'</a>';
  1631. print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->transnoentitiesnoconv("NotEnoughPermissions")).'">'.$langs->trans("RunImportFile").'</a>';
  1632. }
  1633. print '</div>';
  1634. }
  1635. print '</form>';
  1636. }
  1637. // STEP 6: Real import
  1638. if ($step == 6 && $datatoimport) {
  1639. $max_execution_time_for_importexport = (empty($conf->global->IMPORT_MAX_EXECUTION_TIME) ? 300 : $conf->global->IMPORT_MAX_EXECUTION_TIME); // 5mn if not defined
  1640. $max_time = @ini_get("max_execution_time");
  1641. if ($max_time && $max_time < $max_execution_time_for_importexport) {
  1642. 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.");
  1643. @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
  1644. }
  1645. $model = $format;
  1646. $list = $objmodelimport->liste_modeles($db);
  1647. $importid = GETPOST("importid", 'alphanohtml');
  1648. // Create classe to use for import
  1649. $dir = DOL_DOCUMENT_ROOT."/core/modules/import/";
  1650. $file = "import_".$model.".modules.php";
  1651. $classname = "Import".ucfirst($model);
  1652. require_once $dir.$file;
  1653. $obj = new $classname($db, $datatoimport);
  1654. if ($model == 'csv') {
  1655. $obj->separator = $separator_used;
  1656. $obj->enclosure = $enclosure;
  1657. }
  1658. // Load source fields in input file
  1659. $fieldssource = array();
  1660. $result = $obj->import_open_file($conf->import->dir_temp.'/'.$filetoimport, $langs);
  1661. if ($result >= 0) {
  1662. // Read first line
  1663. $arrayrecord = $obj->import_read_record();
  1664. // Put into array fieldssource starting with 1.
  1665. $i = 1;
  1666. foreach ($arrayrecord as $key => $val) {
  1667. $fieldssource[$i]['example1'] = dol_trunc($val['val'], 24);
  1668. $i++;
  1669. }
  1670. $obj->import_close_file();
  1671. }
  1672. $nboflines = (!empty($_GET["nboflines"]) ? $_GET["nboflines"] : dol_count_nb_of_line($conf->import->dir_temp.'/'.$filetoimport));
  1673. $param = '&format='.$format.'&datatoimport='.urlencode($datatoimport).'&filetoimport='.urlencode($filetoimport).'&nboflines='.urlencode($nboflines);
  1674. if ($excludefirstline) {
  1675. $param .= '&excludefirstline='.urlencode($excludefirstline);
  1676. }
  1677. if ($endatlinenb) {
  1678. $param .= '&endatlinenb='.urlencode($endatlinenb);
  1679. }
  1680. if ($separator) {
  1681. $param .= '&separator='.urlencode($separator);
  1682. }
  1683. if ($enclosure) {
  1684. $param .= '&enclosure='.urlencode($enclosure);
  1685. }
  1686. llxHeader('', $langs->trans("NewImport"), 'EN:Module_Imports_En|FR:Module_Imports|ES:M&oacute;dulo_Importaciones');
  1687. $head = import_prepare_head($param, 6);
  1688. print dol_get_fiche_head($head, 'step6', '', -1);
  1689. print '<div class="underbanner clearboth"></div>';
  1690. print '<div class="fichecenter">';
  1691. print '<table width="100%" class="border">';
  1692. // Module
  1693. print '<tr><td class="titlefieldcreate">'.$langs->trans("Module").'</td>';
  1694. print '<td>';
  1695. $titleofmodule = $objimport->array_import_module[0]['module']->getName();
  1696. // Special cas for import common to module/services
  1697. if (in_array($objimport->array_import_code[0], array('produit_supplierprices', 'produit_multiprice', 'produit_languages'))) {
  1698. $titleofmodule = $langs->trans("ProductOrService");
  1699. }
  1700. print $titleofmodule;
  1701. print '</td></tr>';
  1702. // Lot de donnees a importer
  1703. print '<tr><td>'.$langs->trans("DatasetToImport").'</td>';
  1704. print '<td>';
  1705. $entity = preg_replace('/:.*$/', '', $objimport->array_import_icon[0]);
  1706. $entityicon = strtolower(!empty($entitytoicon[$entity]) ? $entitytoicon[$entity] : $entity);
  1707. print img_object($objimport->array_import_module[0]['module']->getName(), $entityicon).' ';
  1708. print $objimport->array_import_label[0];
  1709. print '</td></tr>';
  1710. print '</table>';
  1711. print '</div>';
  1712. print load_fiche_titre($langs->trans("InformationOnSourceFile"), '', 'file-export');
  1713. print '<div class="underbanner clearboth"></div>';
  1714. print '<div class="fichecenter">';
  1715. print '<table width="100%" class="border">';
  1716. // Source file format
  1717. print '<tr><td class="titlefieldcreate">'.$langs->trans("SourceFileFormat").'</td>';
  1718. print '<td>';
  1719. $text = $objmodelimport->getDriverDescForKey($format);
  1720. print $form->textwithpicto($objmodelimport->getDriverLabelForKey($format), $text);
  1721. print '</td></tr>';
  1722. // Separator and enclosure
  1723. if ($model == 'csv') {
  1724. print '<tr><td>'.$langs->trans("CsvOptions").'</td>';
  1725. print '<td>';
  1726. print $langs->trans("Separator").' : ';
  1727. print htmlentities($separator);
  1728. print '&nbsp;&nbsp;&nbsp;&nbsp;'.$langs->trans("Enclosure").' : ';
  1729. print htmlentities($enclosure);
  1730. print '</td></tr>';
  1731. }
  1732. // File to import
  1733. print '<tr><td>'.$langs->trans("FileToImport").'</td>';
  1734. print '<td>';
  1735. $modulepart = 'import';
  1736. $relativepath = GETPOST('filetoimport');
  1737. print '<a data-ajax="false" href="'.DOL_URL_ROOT.'/document.php?modulepart='.$modulepart.'&file='.urlencode($relativepath).'&step=4'.$param.'" target="_blank" rel="noopener noreferrer">';
  1738. print img_mime($file, '', 'pictofixedwidth');
  1739. print $filetoimport;
  1740. print '</a>';
  1741. print '</td></tr>';
  1742. // Nb of fields
  1743. print '<tr><td>';
  1744. print $langs->trans("NbOfSourceLines");
  1745. print '</td><td>';
  1746. print $nboflines;
  1747. print '</td></tr>';
  1748. // Do not import first lines
  1749. print '<tr><td>';
  1750. print $langs->trans("ImportFromLine");
  1751. print '</td><td>';
  1752. print '<input type="text" size="4" name="excludefirstline" disabled="disabled" value="'.$excludefirstline.'">';
  1753. print '</td></tr>';
  1754. // Do not import end lines
  1755. print '<tr><td>';
  1756. print $langs->trans("EndAtLineNb");
  1757. print '</td><td>';
  1758. print '<input type="text" size="4" name="endatlinenb" disabled="disabled" value="'.$endatlinenb.'">';
  1759. print '</td></tr>';
  1760. print '</table>';
  1761. print '</div>';
  1762. print '<br>';
  1763. print '<b>'.$langs->trans("InformationOnTargetTables").'</b>';
  1764. print '<div class="underbanner clearboth"></div>';
  1765. print '<div class="fichecenter">';
  1766. print '<table class="border centpercent">';
  1767. // Tables imported
  1768. print '<tr><td width="25%">';
  1769. print $langs->trans("TablesTarget");
  1770. print '</td><td>';
  1771. $listtables = array();
  1772. foreach ($array_match_file_to_database as $code => $label) {
  1773. //var_dump($fieldssource);
  1774. if ($code > count($fieldssource)) {
  1775. continue;
  1776. }
  1777. //print $code.'-'.$label;
  1778. $alias = preg_replace('/(\..*)$/i', '', $label);
  1779. $listtables[$alias] = $objimport->array_import_tables[0][$alias];
  1780. }
  1781. if (count($listtables)) {
  1782. $newval = '';
  1783. foreach ($listtables as $val) {
  1784. if ($newval) {
  1785. print ', ';
  1786. }
  1787. $newval = $val;
  1788. // Link to Dolibarr wiki pages
  1789. /*$helppagename='EN:Table_'.$newval;
  1790. if ($helppagename && empty($conf->global->MAIN_HELP_DISABLELINK))
  1791. {
  1792. // Get helpbaseurl, helppage and mode from helppagename and langs
  1793. $arrayres=getHelpParamFor($helppagename,$langs);
  1794. $helpbaseurl=$arrayres['helpbaseurl'];
  1795. $helppage=$arrayres['helppage'];
  1796. $mode=$arrayres['mode'];
  1797. $newval.=' <a href="'.sprintf($helpbaseurl,$helppage).'">'.img_picto($langs->trans($mode == 'wiki' ? 'GoToWikiHelpPage': 'GoToHelpPage'),DOL_URL_ROOT.'/theme/common/helpdoc.png','',1).'</a>';
  1798. }*/
  1799. print $newval;
  1800. }
  1801. } else {
  1802. print $langs->trans("Error");
  1803. }
  1804. print '</td></tr>';
  1805. // Fields imported
  1806. print '<tr><td>';
  1807. print $langs->trans("FieldsTarget").'</td><td>';
  1808. $listfields = array();
  1809. $i = 0;
  1810. $sort_array_match_file_to_database = $array_match_file_to_database;
  1811. ksort($sort_array_match_file_to_database);
  1812. //var_dump($sort_array_match_file_to_database);
  1813. foreach ($sort_array_match_file_to_database as $code => $label) {
  1814. $i++;
  1815. //var_dump($fieldssource);
  1816. if ($code > count($fieldssource)) {
  1817. continue;
  1818. }
  1819. //print $code.'-'.$label;
  1820. $alias = preg_replace('/(\..*)$/i', '', $label);
  1821. $listfields[$i] = $langs->trans("Field").' '.$code.'->'.$label;
  1822. }
  1823. print count($listfields) ? (join(', ', $listfields)) : $langs->trans("Error");
  1824. print '</td></tr>';
  1825. print '</table>';
  1826. print '</div>';
  1827. // Launch import
  1828. $arrayoferrors = array();
  1829. $arrayofwarnings = array();
  1830. $maxnboferrors = empty($conf->global->IMPORT_MAX_NB_OF_ERRORS) ? 50 : $conf->global->IMPORT_MAX_NB_OF_ERRORS;
  1831. $maxnbofwarnings = empty($conf->global->IMPORT_MAX_NB_OF_WARNINGS) ? 50 : $conf->global->IMPORT_MAX_NB_OF_WARNINGS;
  1832. $nboferrors = 0;
  1833. $nbofwarnings = 0;
  1834. $importid = dol_print_date(dol_now(), '%Y%m%d%H%M%S');
  1835. //var_dump($array_match_file_to_database);
  1836. $db->begin();
  1837. // Open input file
  1838. $nbok = 0;
  1839. $pathfile = $conf->import->dir_temp.'/'.$filetoimport;
  1840. $result = $obj->import_open_file($pathfile, $langs);
  1841. if ($result > 0) {
  1842. global $tablewithentity_cache;
  1843. $tablewithentity_cache = array();
  1844. $sourcelinenb = 0; $endoffile = 0;
  1845. while ($sourcelinenb < $nboflines && !$endoffile) {
  1846. $sourcelinenb++;
  1847. $arrayrecord = $obj->import_read_record();
  1848. if ($arrayrecord === false) {
  1849. $arrayofwarnings[$sourcelinenb][0] = array('lib'=>'File has '.$nboflines.' lines. However we reach end of file after record '.$sourcelinenb.'. This may occurs when some records are split onto several lines.', 'type'=>'EOF_RECORD_ON_SEVERAL_LINES');
  1850. $endoffile++;
  1851. continue;
  1852. }
  1853. if ($excludefirstline && ($sourcelinenb < $excludefirstline)) {
  1854. continue;
  1855. }
  1856. if ($endatlinenb && ($sourcelinenb > $endatlinenb)) {
  1857. break;
  1858. }
  1859. // Run import
  1860. $result = $obj->import_insert($arrayrecord, $array_match_file_to_database, $objimport, count($fieldssource), $importid, $updatekeys);
  1861. if (count($obj->errors)) {
  1862. $arrayoferrors[$sourcelinenb] = $obj->errors;
  1863. }
  1864. if (count($obj->warnings)) {
  1865. $arrayofwarnings[$sourcelinenb] = $obj->warnings;
  1866. }
  1867. if (!count($obj->errors) && !count($obj->warnings)) {
  1868. $nbok++;
  1869. }
  1870. }
  1871. // Close file
  1872. $obj->import_close_file();
  1873. } else {
  1874. print $langs->trans("ErrorFailedToOpenFile", $pathfile);
  1875. }
  1876. if (count($arrayoferrors) > 0) {
  1877. $db->rollback(); // We force rollback because this was errors.
  1878. } else {
  1879. $error = 0;
  1880. // Run the sql after import if defined
  1881. //var_dump($objimport->array_import_run_sql_after[0]);
  1882. if (!empty($objimport->array_import_run_sql_after[0]) && is_array($objimport->array_import_run_sql_after[0])) {
  1883. $i = 0;
  1884. foreach ($objimport->array_import_run_sql_after[0] as $sqlafterimport) {
  1885. $i++;
  1886. $resqlafterimport = $db->query($sqlafterimport);
  1887. if (!$resqlafterimport) {
  1888. $arrayoferrors['none'][] = array('lib'=>$langs->trans("Error running final request: ".$sqlafterimport));
  1889. $error++;
  1890. }
  1891. }
  1892. }
  1893. if (!$error) {
  1894. $db->commit(); // We can commit if no errors.
  1895. } else {
  1896. $db->rollback();
  1897. }
  1898. }
  1899. print dol_get_fiche_end();
  1900. // Show result
  1901. print '<br>';
  1902. print '<div class="ok">';
  1903. print $langs->trans("NbOfLinesImported", $nbok).'</b><br>';
  1904. print $langs->trans("NbInsert", empty($obj->nbinsert) ? 0 : $obj->nbinsert).'<br>';
  1905. print $langs->trans("NbUpdate", empty($obj->nbupdate) ? 0 : $obj->nbupdate).'<br><br>';
  1906. print '</div>';
  1907. print '<div class="center">';
  1908. print $langs->trans("FileWasImported", $importid).'<br>';
  1909. print '<span class="opacitymedium">'.$langs->trans("YouCanUseImportIdToFindRecord", $importid).'</span><br>';
  1910. print '</div>';
  1911. }
  1912. print '<br>';
  1913. // End of page
  1914. llxFooter();
  1915. $db->close();
  1916. /**
  1917. * Function to put the movable box of a source field
  1918. *
  1919. * @param array $fieldssource List of source fields
  1920. * @param int $pos Pos
  1921. * @param string $key Key
  1922. * @param boolean $var Line style (odd or not). No more used.
  1923. * @param int $nostyle Hide style
  1924. * @return void
  1925. */
  1926. function show_elem($fieldssource, $pos, $key, $var, $nostyle = '')
  1927. {
  1928. global $langs;
  1929. $height = '32px';
  1930. if ($key == 'none') {
  1931. //stop multiple duplicate ids with no number
  1932. print "\n\n<!-- Box_no-key start-->\n";
  1933. print '<div class="box boximport" style="padding:0;">'."\n";
  1934. print '<table summary="boxtable_no-key" class="centpercent nobordernopadding">'."\n";
  1935. } else {
  1936. print "\n\n<!-- Box ".$pos." start -->\n";
  1937. print '<div class="box boximport" style="padding: 0;" id="boxto_'.$pos.'">'."\n";
  1938. print '<table summary="boxtable'.$pos.'" class="nobordernopadding centpercent tableimport">'."\n";
  1939. }
  1940. if (($pos && $pos > count($fieldssource)) && (!isset($fieldssource[$pos]["imported"]))) { // No fields
  1941. /*
  1942. print '<tr style="height:'.$height.'" class="trimport oddevenimport">';
  1943. print '<td class="nocellnopadding" width="16" style="font-weight: normal">';
  1944. print '</td>';
  1945. print '<td style="font-weight: normal">';
  1946. print $langs->trans("NoFields");
  1947. print '</td>';
  1948. print '</tr>';
  1949. */
  1950. } elseif ($key == 'none') { // Empty line
  1951. print '<tr style="height:'.$height.'" class="trimport oddevenimport">';
  1952. print '<td class="nocellnopadding" width="16" style="font-weight: normal">';
  1953. print '&nbsp;';
  1954. print '</td>';
  1955. print '<td style="font-weight: normal">';
  1956. print '&nbsp;';
  1957. print '</td>';
  1958. print '</tr>';
  1959. } else {
  1960. // Print field of source file
  1961. print '<tr style="height:'.$height.'" class="trimport oddevenimport">';
  1962. print '<td class="nocellnopadding" width="16" style="font-weight: normal">';
  1963. // The image must have the class 'boxhandle' beause it's value used in DOM draggable objects to define the area used to catch the full object
  1964. //print img_picto($langs->trans("MoveField", $pos), 'grip_title', 'class="boxhandle" style="cursor:move;"');
  1965. print img_picto($langs->trans("Field").' '.$pos, 'file', 'class="pictofixedwith"');
  1966. print '</td>';
  1967. if (isset($fieldssource[$pos]['imported']) && $fieldssource[$pos]['imported'] == false) {
  1968. print '<td class="nowraponall boxtdunused" style="font-weight: normal">';
  1969. } else {
  1970. print '<td class="nowraponall" style="font-weight: normal">';
  1971. }
  1972. print $langs->trans("Field").' '.$pos;
  1973. if (empty($fieldssource[$pos]['example1'])) {
  1974. $example = $fieldssource[$pos]['label'];
  1975. } else {
  1976. $example = $fieldssource[$pos]['example1'];
  1977. }
  1978. if ($example) {
  1979. if (!utf8_check($example)) {
  1980. $example = utf8_encode($example);
  1981. }
  1982. print ' - ';
  1983. //print '<span class="opacitymedium hideonsmartphone">'.$langs->trans("ExampleOnFirstLine").': </span>';
  1984. print '<i class="opacitymedium">'.$example.'</i>';
  1985. }
  1986. print '</td>';
  1987. print '</tr>';
  1988. }
  1989. print "</table>\n";
  1990. print "</div>\n";
  1991. print "<!-- Box end -->\n\n";
  1992. }
  1993. /**
  1994. * Return not used field number
  1995. *
  1996. * @param array $fieldssource Array of field source
  1997. * @param array $listofkey Array of keys
  1998. * @return integer
  1999. */
  2000. function getnewkey(&$fieldssource, &$listofkey)
  2001. {
  2002. $i = count($fieldssource) + 1;
  2003. // Max number of key
  2004. $maxkey = 0;
  2005. foreach ($listofkey as $key => $val) {
  2006. $maxkey = max($maxkey, $key);
  2007. }
  2008. // Found next empty key
  2009. while ($i <= $maxkey) {
  2010. if (empty($listofkey[$i])) {
  2011. break;
  2012. } else {
  2013. $i++;
  2014. }
  2015. }
  2016. $listofkey[$i] = 1;
  2017. return $i;
  2018. }
  2019. /**
  2020. * Return array with element inserted in it at position $position
  2021. *
  2022. * @param array $array Array of field source
  2023. * @param mixed $position key of postion to insert to
  2024. * @param array $insertArray Array to insert
  2025. * @return array
  2026. */
  2027. function arrayInsert($array, $position, $insertArray)
  2028. {
  2029. $ret = [];
  2030. if ($position == count($array)) {
  2031. $ret = $array + $insertArray;
  2032. } else {
  2033. $i = 0;
  2034. foreach ($array as $key => $value) {
  2035. if ($position == $i++) {
  2036. $ret += $insertArray;
  2037. }
  2038. $ret[$key] = $value;
  2039. }
  2040. }
  2041. return $ret;
  2042. }