import.php 61 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776
  1. <?php
  2. /* Copyright (C) 2005-2011 Laurent Destailleur <eldy@users.sourceforge.net>
  3. * Copyright (C) 2005-2009 Regis Houssin <regis.houssin@capnetworks.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 <http://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. $langs->load("exports");
  33. $langs->load("errors");
  34. // Security check
  35. $result=restrictedArea($user, 'import');
  36. $entitytoicon=array(
  37. 'invoice'=>'bill','invoice_line'=>'bill',
  38. 'order'=>'order' ,'order_line'=>'order',
  39. 'intervention'=>'intervention' ,'inter_line'=>'intervention',
  40. 'member'=>'user' ,'member_type'=>'group','subscription'=>'payment',
  41. 'tax'=>'generic' ,'tax_type'=>'generic',
  42. 'account'=>'account',
  43. 'payment'=>'payment',
  44. 'product'=>'product','stock'=>'generic','warehouse'=>'stock',
  45. 'category'=>'generic',
  46. 'other'=>'generic'
  47. );
  48. $entitytolang=array( // Translation code
  49. 'user'=>'User',
  50. 'company'=>'Company','contact'=>'Contact',
  51. 'invoice'=>'Bill','invoice_line'=>'InvoiceLine',
  52. 'order'=>'Order','order_line'=>'OrderLine',
  53. 'intervention'=>'Intervention' ,'inter_line'=>'InterLine',
  54. 'member'=>'Member','member_type'=>'MemberType','subscription'=>'Subscription',
  55. 'tax'=>'SocialContribution','tax_type'=>'DictionarySocialContributions',
  56. 'account'=>'BankTransactions',
  57. 'payment'=>'Payment',
  58. 'product'=>'Product','stock'=>'Stock','warehouse'=>'Warehouse',
  59. 'category'=>'Category',
  60. 'other'=>'Other'
  61. );
  62. $datatoimport = GETPOST('datatoimport');
  63. $format = GETPOST('format');
  64. $filetoimport = GETPOST('filetoimport');
  65. $action = GETPOST('action','alpha');
  66. $confirm = GETPOST('confirm','alpha');
  67. $step = (GETPOST('step') ? GETPOST('step') : 1);
  68. $import_name = GETPOST('import_name');
  69. $hexa = GETPOST('hexa');
  70. $importmodelid = GETPOST('importmodelid');
  71. $excludefirstline = (GETPOST('excludefirstline') ? GETPOST('excludefirstline') : 0);
  72. $separator = (GETPOST('separator') ? GETPOST('separator') : (! empty($conf->global->IMPORT_CSV_SEPARATOR_TO_USE)?$conf->global->IMPORT_CSV_SEPARATOR_TO_USE:','));
  73. $enclosure = (GETPOST('enclosure') ? GETPOST('enclosure') : '"');
  74. $objimport=new Import($db);
  75. $objimport->load_arrays($user,($step==1?'':$datatoimport));
  76. $objmodelimport=new ModeleImports();
  77. $form = new Form($db);
  78. $htmlother = new FormOther($db);
  79. $formfile = new FormFile($db);
  80. // Init $array_match_file_to_database from _SESSION
  81. $serialized_array_match_file_to_database=isset($_SESSION["dol_array_match_file_to_database"])?$_SESSION["dol_array_match_file_to_database"]:'';
  82. $array_match_file_to_database=array();
  83. $fieldsarray=explode(',',$serialized_array_match_file_to_database);
  84. foreach($fieldsarray as $elem)
  85. {
  86. $tabelem=explode('=',$elem,2);
  87. $key=$tabelem[0];
  88. $val=(isset($tabelem[1])?$tabelem[1]:'');
  89. if ($key && $val)
  90. {
  91. $array_match_file_to_database[$key]=$val;
  92. }
  93. }
  94. /*
  95. * Actions
  96. */
  97. /*
  98. if ($action=='downfield' || $action=='upfield')
  99. {
  100. $pos=$array_match_file_to_database[$_GET["field"]];
  101. if ($action=='downfield') $newpos=$pos+1;
  102. if ($action=='upfield') $newpos=$pos-1;
  103. // Recherche code avec qui switcher
  104. $newcode="";
  105. foreach($array_match_file_to_database as $code=>$value)
  106. {
  107. if ($value == $newpos)
  108. {
  109. $newcode=$code;
  110. break;
  111. }
  112. }
  113. //print("Switch pos=$pos (code=".$_GET["field"].") and newpos=$newpos (code=$newcode)");
  114. if ($newcode) // Si newcode trouve (protection contre resoumission de page)
  115. {
  116. $array_match_file_to_database[$_GET["field"]]=$newpos;
  117. $array_match_file_to_database[$newcode]=$pos;
  118. $_SESSION["dol_array_match_file_to_database"]=$serialized_array_match_file_to_database;
  119. }
  120. }
  121. */
  122. if ($action == 'builddoc')
  123. {
  124. // Build import file
  125. $result=$objimport->build_file($user, GETPOST('model','alpha'), $datatoimport, $array_match_file_to_database);
  126. if ($result < 0)
  127. {
  128. setEventMessage($objimport->error, 'errors');
  129. }
  130. else
  131. {
  132. setEventMessage($langs->trans("FileSuccessfullyBuilt"));
  133. }
  134. }
  135. if ($action == 'deleteprof')
  136. {
  137. if ($_GET["id"])
  138. {
  139. $objimport->fetch($_GET["id"]);
  140. $result=$objimport->delete($user);
  141. }
  142. }
  143. // Save import config to database
  144. if ($action == 'add_import_model')
  145. {
  146. if ($import_name)
  147. {
  148. // Set save string
  149. $hexa='';
  150. foreach($array_match_file_to_database as $key=>$val)
  151. {
  152. if ($hexa) $hexa.=',';
  153. $hexa.=$key.'='.$val;
  154. }
  155. $objimport->model_name = $import_name;
  156. $objimport->datatoimport = $datatoimport;
  157. $objimport->hexa = $hexa;
  158. $result = $objimport->create($user);
  159. if ($result >= 0)
  160. {
  161. setEventMessage($langs->trans("ImportModelSaved",$objimport->model_name));
  162. }
  163. else
  164. {
  165. $langs->load("errors");
  166. if ($objimport->errno == 'DB_ERROR_RECORD_ALREADY_EXISTS')
  167. {
  168. setEventMessage($langs->trans("ErrorImportDuplicateProfil"), 'errors');
  169. }
  170. else {
  171. setEventMessage($objimport->error, 'errors');
  172. }
  173. }
  174. }
  175. else
  176. {
  177. setEventMessage($langs->trans("ErrorFieldRequired",$langs->transnoentities("ImportModelName")), 'errors');
  178. }
  179. }
  180. if ($step == 3 && $datatoimport)
  181. {
  182. if (GETPOST('sendit') && ! empty($conf->global->MAIN_UPLOAD_DOC))
  183. {
  184. dol_mkdir($conf->import->dir_temp);
  185. $nowyearmonth=dol_print_date(dol_now(),'%Y%m%d%H%M%S');
  186. $fullpath=$conf->import->dir_temp . "/" . $nowyearmonth . '-'.$_FILES['userfile']['name'];
  187. if (dol_move_uploaded_file($_FILES['userfile']['tmp_name'], $fullpath,1) > 0)
  188. {
  189. dol_syslog("File ".$fullpath." was added for import");
  190. }
  191. else
  192. {
  193. $langs->load("errors");
  194. setEventMessage($langs->trans("ErrorFailedToSaveFile"), 'errors');
  195. }
  196. }
  197. // Delete file
  198. if ($action == 'confirm_deletefile' && $confirm == 'yes')
  199. {
  200. $langs->load("other");
  201. $param='&datatoimport='.$datatoimport.'&format='.$format;
  202. if ($excludefirstline) $param.='&excludefirstline=1';
  203. $file = $conf->import->dir_temp . '/' . GETPOST('urlfile'); // Do not use urldecode here ($_GET and $_REQUEST are already decoded by PHP).
  204. $ret=dol_delete_file($file);
  205. if ($ret) setEventMessage($langs->trans("FileWasRemoved", GETPOST('urlfile')));
  206. else setEventMessage($langs->trans("ErrorFailToDeleteFile", GETPOST('urlfile')), 'errors');
  207. Header('Location: '.$_SERVER["PHP_SELF"].'?step='.$step.$param);
  208. exit;
  209. }
  210. }
  211. if ($step == 4 && $action == 'select_model')
  212. {
  213. // Reinit match arrays
  214. $_SESSION["dol_array_match_file_to_database"]='';
  215. $serialized_array_match_file_to_database='';
  216. $array_match_file_to_database=array();
  217. // Load model from $importmodelid and set $array_match_file_to_database
  218. // and $_SESSION["dol_array_match_file_to_database"]
  219. $result = $objimport->fetch($importmodelid);
  220. if ($result > 0)
  221. {
  222. $serialized_array_match_file_to_database=$objimport->hexa;
  223. $fieldsarray=explode(',',$serialized_array_match_file_to_database);
  224. foreach($fieldsarray as $elem)
  225. {
  226. $tabelem=explode('=',$elem);
  227. $key=$tabelem[0];
  228. $val=$tabelem[1];
  229. if ($key && $val)
  230. {
  231. $array_match_file_to_database[$key]=$val;
  232. }
  233. }
  234. $_SESSION["dol_array_match_file_to_database"]=$serialized_array_match_file_to_database;
  235. }
  236. }
  237. if ($action == 'saveorder')
  238. {
  239. // Enregistrement de la position des champs
  240. dol_syslog("boxorder=".$_GET['boxorder']." datatoimport=".$_GET["datatoimport"], LOG_DEBUG);
  241. $part=explode(':',$_GET['boxorder']);
  242. $colonne=$part[0];
  243. $list=$part[1];
  244. dol_syslog('column='.$colonne.' list='.$list);
  245. // Init targets fields array
  246. $fieldstarget=$objimport->array_import_fields[0];
  247. // Reinit match arrays. We redefine array_match_file_to_database
  248. $serialized_array_match_file_to_database='';
  249. $array_match_file_to_database=array();
  250. $fieldsarray=explode(',',$list);
  251. $pos=0;
  252. foreach($fieldsarray as $fieldnb) // For each elem in list. fieldnb start from 1 to ...
  253. {
  254. // Get name of database fields at position $pos and put it into $namefield
  255. $posbis=0;$namefield='';
  256. foreach($fieldstarget as $key => $val) // key: val:
  257. {
  258. //dol_syslog('AjaxImport key='.$key.' val='.$val);
  259. if ($posbis < $pos)
  260. {
  261. $posbis++;
  262. continue;
  263. }
  264. // We found the key of targets that is at position pos
  265. $namefield=$key;
  266. //dol_syslog('AjaxImport Field name found for file field nb '.$fieldnb.'='.$namefield);
  267. break;
  268. }
  269. if ($fieldnb && $namefield)
  270. {
  271. $array_match_file_to_database[$fieldnb]=$namefield;
  272. if ($serialized_array_match_file_to_database) $serialized_array_match_file_to_database.=',';
  273. $serialized_array_match_file_to_database.=($fieldnb.'='.$namefield);
  274. }
  275. $pos++;
  276. }
  277. // We save new matching in session
  278. $_SESSION["dol_array_match_file_to_database"]=$serialized_array_match_file_to_database;
  279. dol_syslog('dol_array_match_file_to_database='.$serialized_array_match_file_to_database);
  280. }
  281. /*
  282. * View
  283. */
  284. // STEP 1: Page to select dataset to import
  285. if ($step == 1 || ! $datatoimport)
  286. {
  287. // Clean saved file-database matching
  288. $serialized_array_match_file_to_database='';
  289. $array_match_file_to_database=array();
  290. $_SESSION["dol_array_match_file_to_database"]='';
  291. $param='';
  292. if ($excludefirstline) $param.='&excludefirstline=1';
  293. if ($separator) $param.='&separator='.urlencode($separator);
  294. if ($enclosure) $param.='&enclosure='.urlencode($enclosure);
  295. llxHeader('',$langs->trans("NewImport"),'EN:Module_Imports_En|FR:Module_Imports|ES:M&oacute;dulo_Importaciones');
  296. $head = import_prepare_head($param, 1);
  297. dol_fiche_head($head, 'step1', $langs->trans("NewImport"));
  298. print '<table class="notopnoleftnoright" width="100%">';
  299. print $langs->trans("SelectImportDataSet").'<br>';
  300. // Affiche les modules d'imports
  301. print '<table class="noborder" width="100%">';
  302. print '<tr class="liste_titre">';
  303. print '<td>'.$langs->trans("Module").'</td>';
  304. print '<td>'.$langs->trans("ImportableDatas").'</td>';
  305. print '<td>&nbsp;</td>';
  306. print '</tr>';
  307. $val=true;
  308. if (count($objimport->array_import_code))
  309. {
  310. foreach ($objimport->array_import_code as $key => $value)
  311. {
  312. //var_dump($objimport->array_import_code[$key]);
  313. $val=!$val;
  314. print '<tr '.$bc[$val].'><td nospan="nospan">';
  315. $titleofmodule=$objimport->array_import_module[$key]->getName();
  316. // Special cas for import common to module/services
  317. if (in_array($objimport->array_import_code[$key], array('produit_supplierprices','produit_multiprice'))) $titleofmodule=$langs->trans("ProductOrService");
  318. print $titleofmodule;
  319. print '</td><td>';
  320. //print $value;
  321. print img_object($objimport->array_import_module[$key]->getName(),$objimport->array_import_icon[$key]).' ';
  322. print $objimport->array_import_label[$key];
  323. print '</td><td align="right">';
  324. if ($objimport->array_import_perms[$key])
  325. {
  326. print '<a href="'.DOL_URL_ROOT.'/imports/import.php?step=2&datatoimport='.$objimport->array_import_code[$key].$param.'">'.img_picto($langs->trans("NewImport"),'filenew').'</a>';
  327. }
  328. else
  329. {
  330. print $langs->trans("NotEnoughPermissions");
  331. }
  332. print '</td></tr>';
  333. }
  334. }
  335. else
  336. {
  337. print '<tr><td '.$bc[false].' colspan="3">'.$langs->trans("NoImportableData").'</td></tr>';
  338. }
  339. print '</table>';
  340. print '</table>';
  341. dol_fiche_end();
  342. }
  343. // STEP 2: Page to select input format file
  344. if ($step == 2 && $datatoimport)
  345. {
  346. $param='&datatoimport='.$datatoimport;
  347. if ($excludefirstline) $param.='&excludefirstline=1';
  348. if ($separator) $param.='&separator='.urlencode($separator);
  349. if ($enclosure) $param.='&enclosure='.urlencode($enclosure);
  350. llxHeader('',$langs->trans("NewImport"),'EN:Module_Imports_En|FR:Module_Imports|ES:M&oacute;dulo_Importaciones');
  351. $head = import_prepare_head($param,2);
  352. dol_fiche_head($head, 'step2', $langs->trans("NewImport"));
  353. print '<table width="100%" class="border">';
  354. // Module
  355. print '<tr><td width="25%">'.$langs->trans("Module").'</td>';
  356. print '<td>';
  357. $titleofmodule=$objimport->array_import_module[0]->getName();
  358. // Special cas for import common to module/services
  359. if (in_array($objimport->array_import_code[0], array('produit_supplierprices','produit_multiprice'))) $titleofmodule=$langs->trans("ProductOrService");
  360. print $titleofmodule;
  361. print '</td></tr>';
  362. // Lot de donnees a importer
  363. print '<tr><td width="25%">'.$langs->trans("DatasetToImport").'</td>';
  364. print '<td>';
  365. print img_object($objimport->array_import_module[0]->getName(),$objimport->array_import_icon[0]).' ';
  366. print $objimport->array_import_label[0];
  367. print '</td></tr>';
  368. print '</table>';
  369. print '<br>'."\n";
  370. print '<form name="userfile" action="'.$_SERVER["PHP_SELF"].'" enctype="multipart/form-data" METHOD="POST">';
  371. print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
  372. print '<input type="hidden" name="max_file_size" value="'.$conf->maxfilesize.'">';
  373. print $langs->trans("ChooseFormatOfFileToImport",img_picto('','filenew')).'<br>';
  374. print '<table class="noborder" width="100%" cellspacing="0" cellpadding="4">';
  375. $filetoimport='';
  376. $var=true;
  377. // Add format informations and link to download example
  378. print '<tr class="liste_titre"><td colspan="6">';
  379. print $langs->trans("FileMustHaveOneOfFollowingFormat");
  380. print '</td></tr>';
  381. $liste=$objmodelimport->liste_modeles($db);
  382. foreach($liste as $key)
  383. {
  384. $var=!$var;
  385. print '<tr '.$bc[$var].'>';
  386. print '<td width="16">'.img_picto_common($key,$objmodelimport->getPictoForKey($key)).'</td>';
  387. $text=$objmodelimport->getDriverDescForKey($key);
  388. print '<td>'.$form->textwithpicto($objmodelimport->getDriverLabelForKey($key),$text).'</td>';
  389. print '<td align="center"><a href="'.DOL_URL_ROOT.'/imports/emptyexample.php?format='.$key.$param.'" target="_blank">'.$langs->trans("DownloadEmptyExample").'</a></td>';
  390. // Action button
  391. print '<td align="right">';
  392. print '<a href="'.DOL_URL_ROOT.'/imports/import.php?step=3&format='.$key.$param.'">'.img_picto($langs->trans("SelectFormat"),'filenew').'</a>';
  393. print '</td>';
  394. print '</tr>';
  395. }
  396. print '</table></form>';
  397. dol_fiche_end();
  398. }
  399. // STEP 3: Page to select file
  400. if ($step == 3 && $datatoimport)
  401. {
  402. $param='&datatoimport='.$datatoimport.'&format='.$format;
  403. if ($excludefirstline) $param.='&excludefirstline=1';
  404. if ($separator) $param.='&separator='.urlencode($separator);
  405. if ($enclosure) $param.='&enclosure='.urlencode($enclosure);
  406. $liste=$objmodelimport->liste_modeles($db);
  407. llxHeader('',$langs->trans("NewImport"),'EN:Module_Imports_En|FR:Module_Imports|ES:M&oacute;dulo_Importaciones');
  408. $head = import_prepare_head($param, 3);
  409. dol_fiche_head($head, 'step3', $langs->trans("NewImport"));
  410. /*
  411. * Confirm delete file
  412. */
  413. if ($action == 'delete')
  414. {
  415. print $form->formconfirm($_SERVER["PHP_SELF"].'?urlfile='.urlencode(GETPOST('urlfile')).'&step=3'.$param, $langs->trans('DeleteFile'), $langs->trans('ConfirmDeleteFile'), 'confirm_deletefile', '', 0, 1);
  416. }
  417. print '<table width="100%" class="border">';
  418. // Module
  419. print '<tr><td width="25%">'.$langs->trans("Module").'</td>';
  420. print '<td>';
  421. $titleofmodule=$objimport->array_import_module[0]->getName();
  422. // Special cas for import common to module/services
  423. if (in_array($objimport->array_import_code[0], array('produit_supplierprices','produit_multiprice'))) $titleofmodule=$langs->trans("ProductOrService");
  424. print $titleofmodule;
  425. print '</td></tr>';
  426. // Lot de donnees a importer
  427. print '<tr><td width="25%">'.$langs->trans("DatasetToImport").'</td>';
  428. print '<td>';
  429. print img_object($objimport->array_import_module[0]->getName(),$objimport->array_import_icon[0]).' ';
  430. print $objimport->array_import_label[0];
  431. print '</td></tr>';
  432. print '</table><br>';
  433. print '<b>'.$langs->trans("InformationOnSourceFile").'</b>';
  434. print '<table width="100%" class="border">';
  435. //print '<tr><td colspan="2"><b>'.$langs->trans("InformationOnSourceFile").'</b></td></tr>';
  436. // Source file format
  437. print '<tr><td width="25%">'.$langs->trans("SourceFileFormat").'</td>';
  438. print '<td>';
  439. $text=$objmodelimport->getDriverDescForKey($format);
  440. print $form->textwithpicto($objmodelimport->getDriverLabelForKey($format),$text);
  441. print '</td><td align="right" class="nowrap"><a href="'.DOL_URL_ROOT.'/imports/emptyexample.php?format='.$format.$param.'" target="_blank">'.$langs->trans("DownloadEmptyExample").'</a>';
  442. print '</td></tr>';
  443. print '</table>';
  444. print '<br>'."\n";
  445. print '<form name="userfile" action="'.$_SERVER["PHP_SELF"].'" enctype="multipart/form-data" METHOD="POST">';
  446. print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
  447. print '<input type="hidden" name="max_file_size" value="'.$conf->maxfilesize.'">';
  448. print '<table class="noborder" width="100%" cellspacing="0" cellpadding="4">';
  449. $filetoimport='';
  450. $var=true;
  451. print '<tr><td colspan="6">'.$langs->trans("ChooseFileToImport",img_picto('','filenew')).'</td></tr>';
  452. print '<tr class="liste_titre"><td colspan="6">'.$langs->trans("FileWithDataToImport").'</td></tr>';
  453. // Input file name box
  454. $var=false;
  455. print '<tr '.$bc[$var].'><td colspan="6">';
  456. print '<input type="file" name="userfile" size="20" maxlength="80"> &nbsp; &nbsp; ';
  457. print '<input type="submit" class="button" value="'.$langs->trans("AddFile").'" name="sendit">';
  458. print '<input type="hidden" value="'.$step.'" name="step">';
  459. print '<input type="hidden" value="'.$format.'" name="format">';
  460. print '<input type="hidden" value="'.$excludefirstline.'" name="excludefirstline">';
  461. print '<input type="hidden" value="'.$separator.'" name="separator">';
  462. print '<input type="hidden" value="'.$enclosure.'" name="enclosure">';
  463. print '<input type="hidden" value="'.$datatoimport.'" name="datatoimport">';
  464. print "</tr>\n";
  465. // Search available imports
  466. $filearray=dol_dir_list($conf->import->dir_temp, 'files', 0, '', '', 'name', SORT_DESC);
  467. if (count($filearray) > 0)
  468. {
  469. $dir=$conf->import->dir_temp;
  470. // Search available files to import
  471. $i=0;
  472. foreach ($filearray as $key => $val)
  473. {
  474. $file=$val['name'];
  475. // readdir return value in ISO and we want UTF8 in memory
  476. if (! utf8_check($file)) $file=utf8_encode($file);
  477. if (preg_match('/^\./',$file)) continue;
  478. $modulepart='import';
  479. $urlsource=$_SERVER["PHP_SELF"].'?step='.$step.$param.'&filetoimport='.urlencode($filetoimport);
  480. $relativepath=$file;
  481. $var=!$var;
  482. print '<tr '.$bc[$var].'>';
  483. print '<td width="16">'.img_mime($file).'</td>';
  484. print '<td>';
  485. print '<a data-ajax="false" href="'.DOL_URL_ROOT.'/document.php?modulepart='.$modulepart.'&file='.urlencode($relativepath).'&step=3'.$param.'" target="_blank">';
  486. print $file;
  487. print '</a>';
  488. print '</td>';
  489. // Affiche taille fichier
  490. print '<td align="right">'.dol_print_size(dol_filesize($dir.'/'.$file)).'</td>';
  491. // Affiche date fichier
  492. print '<td align="right">'.dol_print_date(dol_filemtime($dir.'/'.$file),'dayhour').'</td>';
  493. // Del button
  494. print '<td align="right"><a href="'.$_SERVER['PHP_SELF'].'?action=delete&step=3'.$param.'&urlfile='.urlencode($relativepath);
  495. print '">'.img_delete().'</a></td>';
  496. // Action button
  497. print '<td align="right">';
  498. print '<a href="'.$_SERVER['PHP_SELF'].'?step=4'.$param.'&filetoimport='.urlencode($relativepath).'">'.img_picto($langs->trans("NewImport"),'filenew').'</a>';
  499. print '</td>';
  500. print '</tr>';
  501. }
  502. }
  503. print '</table></form>';
  504. dol_fiche_end();
  505. }
  506. // STEP 4: Page to make matching between source file and database fields
  507. if ($step == 4 && $datatoimport)
  508. {
  509. $model=$format;
  510. $liste=$objmodelimport->liste_modeles($db);
  511. // Create classe to use for import
  512. $dir = DOL_DOCUMENT_ROOT . "/core/modules/import/";
  513. $file = "import_".$model.".modules.php";
  514. $classname = "Import".ucfirst($model);
  515. require_once $dir.$file;
  516. $obj = new $classname($db,$datatoimport);
  517. if ($model == 'csv') {
  518. $obj->separator = $separator;
  519. $obj->enclosure = $enclosure;
  520. }
  521. // Load source fields in input file
  522. $fieldssource=array();
  523. $result=$obj->import_open_file($conf->import->dir_temp.'/'.$filetoimport,$langs);
  524. if ($result >= 0)
  525. {
  526. // Read first line
  527. $arrayrecord=$obj->import_read_record();
  528. // Put into array fieldssource starting with 1.
  529. $i=1;
  530. foreach($arrayrecord as $key => $val)
  531. {
  532. $fieldssource[$i]['example1']=dol_trunc($val['val'],24);
  533. $i++;
  534. }
  535. $obj->import_close_file();
  536. }
  537. // Load targets fields in database
  538. $fieldstarget=$objimport->array_import_fields[0];
  539. $maxpos=max(count($fieldssource),count($fieldstarget));
  540. //var_dump($array_match_file_to_database);
  541. // Is it a first time in page (if yes, we must initialize array_match_file_to_database)
  542. if (count($array_match_file_to_database) == 0)
  543. {
  544. // This is first input in screen, we need to define
  545. // $array_match_file_to_database
  546. // $serialized_array_match_file_to_database
  547. // $_SESSION["dol_array_match_file_to_database"]
  548. $pos=1;
  549. $num=count($fieldssource);
  550. while ($pos <= $num)
  551. {
  552. if ($num >= 1 && $pos <= $num)
  553. {
  554. $posbis=1;
  555. foreach($fieldstarget as $key => $val)
  556. {
  557. if ($posbis < $pos)
  558. {
  559. $posbis++;
  560. continue;
  561. }
  562. // We found the key of targets that is at position pos
  563. $array_match_file_to_database[$pos]=$key;
  564. if ($serialized_array_match_file_to_database) $serialized_array_match_file_to_database.=',';
  565. $serialized_array_match_file_to_database.=($pos.'='.$key);
  566. break;
  567. }
  568. }
  569. $pos++;
  570. }
  571. // Save the match array in session. We now will use the array in session.
  572. $_SESSION["dol_array_match_file_to_database"]=$serialized_array_match_file_to_database;
  573. }
  574. $array_match_database_to_file=array_flip($array_match_file_to_database);
  575. //print $serialized_array_match_file_to_database;
  576. //print $_SESSION["dol_array_match_file_to_database"];
  577. //var_dump($array_match_file_to_database);exit;
  578. // Now $array_match_file_to_database contains fieldnb(1,2,3...)=>fielddatabase(key in $array_match_file_to_database)
  579. $param='&format='.$format.'&datatoimport='.$datatoimport.'&filetoimport='.urlencode($filetoimport);
  580. if ($excludefirstline) $param.='&excludefirstline=1';
  581. if ($separator) $param.='&separator='.urlencode($separator);
  582. if ($enclosure) $param.='&enclosure='.urlencode($enclosure);
  583. llxHeader('',$langs->trans("NewImport"),'EN:Module_Imports_En|FR:Module_Imports|ES:M&oacute;dulo_Importaciones');
  584. $head = import_prepare_head($param,4);
  585. dol_fiche_head($head, 'step4', $langs->trans("NewImport"));
  586. print '<table width="100%" class="border">';
  587. // Module
  588. print '<tr><td width="25%">'.$langs->trans("Module").'</td>';
  589. print '<td>';
  590. $titleofmodule=$objimport->array_import_module[0]->getName();
  591. // Special cas for import common to module/services
  592. if (in_array($objimport->array_import_code[0], array('produit_supplierprices','produit_multiprice'))) $titleofmodule=$langs->trans("ProductOrService");
  593. print $titleofmodule;
  594. print '</td></tr>';
  595. // Lot de donnees a importer
  596. print '<tr><td width="25%">'.$langs->trans("DatasetToImport").'</td>';
  597. print '<td>';
  598. print img_object($objimport->array_import_module[0]->getName(),$objimport->array_import_icon[0]).' ';
  599. print $objimport->array_import_label[0];
  600. print '</td></tr>';
  601. print '</table><br>';
  602. print '<b>'.$langs->trans("InformationOnSourceFile").'</b>';
  603. print '<table width="100%" class="border">';
  604. //print '<tr><td colspan="2"><b>'.$langs->trans("InformationOnSourceFile").'</b></td></tr>';
  605. // Source file format
  606. print '<tr><td width="25%">'.$langs->trans("SourceFileFormat").'</td>';
  607. print '<td>';
  608. $text=$objmodelimport->getDriverDescForKey($format);
  609. print $form->textwithpicto($objmodelimport->getDriverLabelForKey($format),$text);
  610. print '</td></tr>';
  611. // Separator and enclosure
  612. if ($model == 'csv') {
  613. print '<tr><td width="25%">'.$langs->trans("CsvOptions").'</td>';
  614. print '<td>';
  615. print '<form>';
  616. print '<input type="hidden" value="'.$step.'" name="step">';
  617. print '<input type="hidden" value="'.$format.'" name="format">';
  618. print '<input type="hidden" value="'.$excludefirstline.'" name="excludefirstline">';
  619. print '<input type="hidden" value="'.$datatoimport.'" name="datatoimport">';
  620. print '<input type="hidden" value="'.$filetoimport.'" name="filetoimport">';
  621. print $langs->trans("Separator").' : ';
  622. print '<input type="text" size="1" name="separator" value="'.htmlentities($separator).'"/>';
  623. print '&nbsp;&nbsp;&nbsp;&nbsp;'.$langs->trans("Enclosure").' : ';
  624. print '<input type="text" size="1" name="enclosure" value="'.htmlentities($enclosure).'"/>';
  625. print '<input type="submit" value="'.$langs->trans('Update').'" class="button" />';
  626. print '</form>';
  627. print '</td></tr>';
  628. }
  629. // File to import
  630. print '<tr><td width="25%">'.$langs->trans("FileToImport").'</td>';
  631. print '<td>';
  632. $modulepart='import';
  633. $relativepath=GETPOST('filetoimport');
  634. print '<a data-ajax="false" href="'.DOL_URL_ROOT.'/document.php?modulepart='.$modulepart.'&file='.urlencode($relativepath).'&step=4'.$param.'" target="_blank">';
  635. print $filetoimport;
  636. print '</a>';
  637. print '</td></tr>';
  638. print '</table>';
  639. print '<br>'."\n";
  640. // List of source fields
  641. print '<!-- List of source fields -->'."\n";
  642. print '<form action="'.$_SERVER["PHP_SELF"].'" method="post">';
  643. print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
  644. print '<input type="hidden" name="action" value="select_model">';
  645. print '<input type="hidden" name="step" value="4">';
  646. print '<input type="hidden" name="format" value="'.$format.'">';
  647. print '<input type="hidden" name="datatoimport" value="'.$datatoimport.'">';
  648. print '<input type="hidden" name="filetoimport" value="'.$filetoimport.'">';
  649. print '<input type="hidden" name="excludefirstline" value="'.$excludefirstline.'">';
  650. print '<input type="hidden" name="separator" value="'.$separator.'">';
  651. print '<input type="hidden" name="enclosure" value="'.$enclosure.'">';
  652. print '<table><tr><td colspan="2">';
  653. print $langs->trans("SelectImportFields",img_picto('','uparrow','')).' ';
  654. $htmlother->select_import_model($importmodelid,'importmodelid',$datatoimport,1);
  655. print '<input type="submit" class="button" value="'.$langs->trans("Select").'">';
  656. print '</td></tr></table>';
  657. print '</form>';
  658. // Title of array with fields
  659. print '<table class="nobordernopadding" width="100%">';
  660. print '<tr class="liste_titre">';
  661. print '<td>'.$langs->trans("FieldsInSourceFile").'</td>';
  662. print '<td>'.$langs->trans("FieldsInTargetDatabase").'</td>';
  663. print '</tr>';
  664. //var_dump($array_match_file_to_database);
  665. print '<tr valign="top"><td width="50%">';
  666. $fieldsplaced=array();
  667. $valforsourcefieldnb=array();
  668. $listofkeys=array();
  669. foreach($array_match_file_to_database as $key => $val)
  670. {
  671. $listofkeys[$key]=1;
  672. }
  673. print "\n<!-- Box left container -->\n";
  674. print '<div id="left" class="connectedSortable">'."\n";
  675. // List of source fields
  676. $var=true;
  677. $lefti=1;
  678. foreach ($array_match_file_to_database as $key => $val)
  679. {
  680. $var=!$var;
  681. show_elem($fieldssource,$key,$val,$var); // key is field number in source file
  682. //print '> '.$lefti.'-'.$key.'-'.$val;
  683. $listofkeys[$key]=1;
  684. $fieldsplaced[$key]=1;
  685. $valforsourcefieldnb[$lefti]=$key;
  686. $lefti++;
  687. if ($lefti > count($fieldstarget)) break; // Other fields are in the not imported area
  688. }
  689. //var_dump($valforsourcefieldnb);
  690. // Complete source fields from count($fieldssource)+1 to count($fieldstarget)
  691. $more=1;
  692. $num=count($fieldssource);
  693. while ($lefti <= $num)
  694. {
  695. $var=!$var;
  696. $newkey=getnewkey($fieldssource,$listofkeys);
  697. show_elem($fieldssource,$newkey,'',$var); // key start after field number in source file
  698. //print '> '.$lefti.'-'.$newkey;
  699. $listofkeys[$key]=1;
  700. $lefti++;
  701. $more++;
  702. }
  703. print "</div>\n";
  704. print "<!-- End box left container -->\n";
  705. print '</td><td width="50%">';
  706. // List of targets fields
  707. $i = 0;
  708. $var=true;
  709. $mandatoryfieldshavesource=true;
  710. print '<table width="100%" class="nobordernopadding">';
  711. foreach($fieldstarget as $code=>$label)
  712. {
  713. $var=!$var;
  714. print '<tr '.$bc[$var].' height="20">';
  715. $i++;
  716. $entity=(! empty($objimport->array_import_entities[0][$code])?$objimport->array_import_entities[0][$code]:$objimport->array_import_icon[0]);
  717. $tablealias=preg_replace('/(\..*)$/i','',$code);
  718. $tablename=$objimport->array_import_tables[0][$tablealias];
  719. $entityicon=$entitytoicon[$entity]?$entitytoicon[$entity]:$entity;
  720. $entitylang=$entitytolang[$entity]?$entitytolang[$entity]:$entity;
  721. print '<td class="nowrap" style="font-weight: normal">=>'.img_object('',$entityicon).' '.$langs->trans($entitylang).'</td>';
  722. print '<td style="font-weight: normal">';
  723. $newlabel=preg_replace('/\*$/','',$label);
  724. $text=$langs->trans($newlabel);
  725. $more='';
  726. if (preg_match('/\*$/',$label))
  727. {
  728. $text='<span class="fieldrequired">'.$text.'</span>';
  729. $more=((! empty($valforsourcefieldnb[$i]) && $valforsourcefieldnb[$i] <= count($fieldssource)) ? '' : img_warning($langs->trans("FieldNeedSource")));
  730. if ($mandatoryfieldshavesource) $mandatoryfieldshavesource=(! empty($valforsourcefieldnb[$i]) && ($valforsourcefieldnb[$i] <= count($fieldssource)));
  731. //print 'xx'.($i).'-'.$valforsourcefieldnb[$i].'-'.$mandatoryfieldshavesource;
  732. }
  733. print $text;
  734. print '</td>';
  735. // Info field
  736. print '<td style="font-weight: normal" align="right">';
  737. $filecolumn=$array_match_database_to_file[$code];
  738. // Source field info
  739. $htmltext ='<b><u>'.$langs->trans("FieldSource").'</u></b><br>';
  740. if ($filecolumn > count($fieldssource)) $htmltext.=$langs->trans("DataComeFromNoWhere").'<br>';
  741. else
  742. {
  743. if (empty($objimport->array_import_convertvalue[0][$code])) // If source file does not need convertion
  744. {
  745. $filecolumntoshow=$filecolumn;
  746. $htmltext.=$langs->trans("DataComeFromFileFieldNb",$filecolumntoshow).'<br>';
  747. }
  748. else
  749. {
  750. if ($objimport->array_import_convertvalue[0][$code]['rule']=='fetchidfromref') $htmltext.=$langs->trans("DataComeFromIdFoundFromRef",$filecolumn,$langs->transnoentitiesnoconv($entitylang)).'<br>';
  751. if ($objimport->array_import_convertvalue[0][$code]['rule']=='fetchidfromcodeid') $htmltext.=$langs->trans("DataComeFromIdFoundFromCodeId",$filecolumn,$langs->transnoentitiesnoconv($objimport->array_import_convertvalue[0][$code]['dict'])).'<br>';
  752. }
  753. }
  754. $htmltext.=$langs->trans("SourceRequired").': <b>'.yn(preg_match('/\*$/',$label)).'</b><br>';
  755. $example=$objimport->array_import_examplevalues[0][$code];
  756. if (empty($objimport->array_import_convertvalue[0][$code])) // If source file does not need convertion
  757. {
  758. if ($example) $htmltext.=$langs->trans("SourceExample").': <b>'.$example.'</b><br>';
  759. }
  760. else
  761. {
  762. if ($objimport->array_import_convertvalue[0][$code]['rule']=='fetchidfromref') $htmltext.=$langs->trans("SourceExample").': <b>'.$langs->transnoentitiesnoconv("ExampleAnyRefFoundIntoElement",$entitylang).($example?' ('.$langs->transnoentitiesnoconv("Example").': '.$example.')':'').'</b><br>';
  763. if ($objimport->array_import_convertvalue[0][$code]['rule']=='fetchidfromcodeid') $htmltext.=$langs->trans("SourceExample").': <b>'.$langs->trans("ExampleAnyCodeOrIdFoundIntoDictionary",$langs->transnoentitiesnoconv($objimport->array_import_convertvalue[0][$code]['dict'])).($example?' ('.$langs->transnoentitiesnoconv("Example").': '.$example.')':'').'</b><br>';
  764. }
  765. $htmltext.='<br>';
  766. // Target field info
  767. $htmltext.='<b><u>'.$langs->trans("FieldTarget").'</u></b><br>';
  768. if (empty($objimport->array_import_convertvalue[0][$code])) // If source file does not need convertion
  769. {
  770. $htmltext.=$langs->trans("DataIsInsertedInto").'<br>';
  771. }
  772. else
  773. {
  774. if ($objimport->array_import_convertvalue[0][$code]['rule']=='fetchidfromref') $htmltext.=$langs->trans("DataIDSourceIsInsertedInto").'<br>';
  775. if ($objimport->array_import_convertvalue[0][$code]['rule']=='fetchidfromcodeid') $htmltext.=$langs->trans("DataCodeIDSourceIsInsertedInto").'<br>';
  776. }
  777. $htmltext.=$langs->trans("FieldTitle").": <b>".$langs->trans($newlabel)."</b><br>";
  778. $htmltext.=$langs->trans("Table")." -> ".$langs->trans("Field").': <b>'.$tablename." -> ".preg_replace('/^.*\./','',$code)."</b><br>";
  779. print $form->textwithpicto($more,$htmltext);
  780. print '</td>';
  781. print '</tr>';
  782. $save_select.=$bit;
  783. }
  784. print '</table>';
  785. print '</td></tr>';
  786. // List of not imported fields
  787. print '<tr class="liste_titre"><td colspan="2">'.$langs->trans("NotImportedFields").'</td></tr>';
  788. print '<tr valign="top"><td width="50%">';
  789. print "\n<!-- Box ignore container -->\n";
  790. print '<div id="right" class="connectedSortable">'."\n";
  791. $nbofnotimportedfields=0;
  792. foreach ($fieldssource as $key => $val)
  793. {
  794. if (empty($fieldsplaced[$key]))
  795. {
  796. //$var=!$var;
  797. $nbofnotimportedfields++;
  798. show_elem($fieldssource,$key,'',$var,'nostyle');
  799. //print '> '.$lefti.'-'.$key;
  800. $listofkeys[$key]=1;
  801. $lefti++;
  802. }
  803. }
  804. // Print one more empty field
  805. $newkey=getnewkey($fieldssource,$listofkeys);
  806. show_elem($fieldssource,$newkey,'',$var,'nostyle');
  807. //print '> '.$lefti.'-'.$newkey;
  808. $listofkeys[$newkey]=1;
  809. $nbofnotimportedfields++;
  810. print "</div>\n";
  811. print "<!-- End box ignore container -->\n";
  812. print '</td>';
  813. print '<td width="50%">';
  814. $i=0;
  815. while ($i < $nbofnotimportedfields)
  816. {
  817. // Print empty cells
  818. show_elem('','','none',$var,'nostyle');
  819. $i++;
  820. }
  821. print '</td></tr>';
  822. print '</table>';
  823. dol_fiche_end();
  824. if ($conf->use_javascript_ajax)
  825. {
  826. print '<script type="text/javascript" language="javascript">';
  827. print 'jQuery(function() {
  828. jQuery("#left, #right").sortable({
  829. /* placeholder: \'ui-state-highlight\', */
  830. handle: \'.boxhandle\',
  831. revert: \'invalid\',
  832. items: \'.box\',
  833. containment: \'.fiche\',
  834. connectWith: \'.connectedSortable\',
  835. stop: function(event, ui) {
  836. updateOrder();
  837. }
  838. });
  839. });
  840. ';
  841. print "\n";
  842. print 'function updateOrder(){'."\n";
  843. print 'var left_list = cleanSerialize(jQuery("#left").sortable("serialize" ));'."\n";
  844. //print 'var right_list = cleanSerialize(jQuery("#right").sortable("serialize" ));'."\n";
  845. print 'var boxorder = \'A:\' + left_list;'."\n";
  846. //print 'var boxorder = \'A:\' + left_list + \'-B:\' + right_list;'."\n";
  847. //print 'alert(\'boxorder=\' + boxorder);';
  848. //print 'var userid = \''.$user->id.'\';'."\n";
  849. //print 'var datatoimport = "'.$datatoimport.'";'."\n";
  850. // print 'jQuery.ajax({ url: "ajaximport.php?step=4&boxorder=" + boxorder + "&userid=" + userid + "&datatoimport=" + datatoimport,
  851. // async: false
  852. // });'."\n";
  853. // Now reload page
  854. print 'var newlocation= \''.$_SERVER["PHP_SELF"].'?step=4'.$param.'&action=saveorder&boxorder=\' + boxorder;'."\n";
  855. //print 'alert(newlocation);';
  856. print 'window.location.href=newlocation;'."\n";
  857. print '}'."\n";
  858. print '</script>'."\n";
  859. }
  860. /*
  861. * Barre d'action
  862. */
  863. print '<div class="tabsAction">';
  864. if (count($array_match_file_to_database))
  865. {
  866. if ($mandatoryfieldshavesource)
  867. {
  868. print '<a class="butAction" href="import.php?step=5'.$param.'&filetoimport='.urlencode($filetoimport).'">'.$langs->trans("NextStep").'</a>';
  869. }
  870. else
  871. {
  872. print '<a class="butActionRefused" href="#" title="'.dol_escape_htmltag($langs->transnoentitiesnoconv("SomeMandatoryFieldHaveNoSource")).'">'.$langs->trans("NextStep").'</a>';
  873. }
  874. }
  875. print '</div>';
  876. // Area for profils import
  877. if (count($array_match_file_to_database))
  878. {
  879. print '<br>'."\n";
  880. print '<!-- Area to add new import profile -->'."\n";
  881. print $langs->trans("SaveImportModel");
  882. print '<form class="nocellnopadd" action="'.$_SERVER["PHP_SELF"].'" method="post">';
  883. print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
  884. print '<input type="hidden" name="action" value="add_import_model">';
  885. print '<input type="hidden" name="step" value="'.$step.'">';
  886. print '<input type="hidden" name="format" value="'.$format.'">';
  887. print '<input type="hidden" name="datatoimport" value="'.$datatoimport.'">';
  888. print '<input type="hidden" name="filetoimport" value="'.$filetoimport.'">';
  889. print '<input type="hidden" name="hexa" value="'.$hexa.'">';
  890. print '<input type="hidden" name="excludefirstline" value="'.$excludefirstline.'">';
  891. print '<input type="hidden" value="'.$separator.'" name="separator">';
  892. print '<input type="hidden" value="'.$enclosure.'" name="enclosure">';
  893. print '<table summary="selectofimportprofil" class="noborder" width="100%">';
  894. print '<tr class="liste_titre">';
  895. print '<td>'.$langs->trans("ImportModelName").'</td>';
  896. print '<td>&nbsp;</td>';
  897. print '</tr>';
  898. $var=false;
  899. print '<tr '.$bc[$var].'>';
  900. print '<td><input name="import_name" size="48" value=""></td><td align="right">';
  901. print '<input type="submit" class="button" value="'.$langs->trans("SaveImportProfile").'">';
  902. print '</td></tr>';
  903. // List of existing import profils
  904. $sql = "SELECT rowid, label";
  905. $sql.= " FROM ".MAIN_DB_PREFIX."import_model";
  906. $sql.= " WHERE type = '".$datatoimport."'";
  907. $sql.= " ORDER BY rowid";
  908. $resql = $db->query($sql);
  909. if ($resql)
  910. {
  911. $num = $db->num_rows($resql);
  912. $i = 0;
  913. $var=false;
  914. while ($i < $num)
  915. {
  916. $var=!$var;
  917. $obj = $db->fetch_object($resql);
  918. print '<tr '.$bc[$var].'><td>';
  919. print $obj->label;
  920. print '</td><td align="right">';
  921. print '<a href="'.$_SERVER["PHP_SELF"].'?step='.$step.$param.'&action=deleteprof&id='.$obj->rowid.'&filetoimport='.urlencode($filetoimport).'">';
  922. print img_delete();
  923. print '</a>';
  924. print '</tr>';
  925. $i++;
  926. }
  927. }
  928. else {
  929. dol_print_error($db);
  930. }
  931. print '</table>';
  932. print '</form>';
  933. }
  934. }
  935. // STEP 5: Summary of choices and launch simulation
  936. if ($step == 5 && $datatoimport)
  937. {
  938. $model=$format;
  939. $liste=$objmodelimport->liste_modeles($db);
  940. // Create classe to use for import
  941. $dir = DOL_DOCUMENT_ROOT . "/core/modules/import/";
  942. $file = "import_".$model.".modules.php";
  943. $classname = "Import".ucfirst($model);
  944. require_once $dir.$file;
  945. $obj = new $classname($db,$datatoimport);
  946. if ($model == 'csv') {
  947. $obj->separator = $separator;
  948. $obj->enclosure = $enclosure;
  949. }
  950. // Load source fields in input file
  951. $fieldssource=array();
  952. $result=$obj->import_open_file($conf->import->dir_temp.'/'.$filetoimport,$langs);
  953. if ($result >= 0)
  954. {
  955. // Read first line
  956. $arrayrecord=$obj->import_read_record();
  957. // Put into array fieldssource starting with 1.
  958. $i=1;
  959. foreach($arrayrecord as $key => $val)
  960. {
  961. $fieldssource[$i]['example1']=dol_trunc($val['val'],24);
  962. $i++;
  963. }
  964. $obj->import_close_file();
  965. }
  966. $nboflines=dol_count_nb_of_line($conf->import->dir_temp.'/'.$filetoimport);
  967. $param='&leftmenu=import&format='.$format.'&datatoimport='.$datatoimport.'&filetoimport='.urlencode($filetoimport).'&nboflines='.$nboflines.'&separator='.urlencode($separator).'&enclosure='.urlencode($enclosure);
  968. $param2 = $param;
  969. if ($excludefirstline) {
  970. $param.='&excludefirstline=1';
  971. }
  972. llxHeader('',$langs->trans("NewImport"),'EN:Module_Imports_En|FR:Module_Imports|ES:M&oacute;dulo_Importaciones');
  973. $head = import_prepare_head($param,5);
  974. dol_fiche_head($head, 'step5', $langs->trans("NewImport"));
  975. print '<table width="100%" class="border">';
  976. // Module
  977. print '<tr><td width="25%">'.$langs->trans("Module").'</td>';
  978. print '<td>';
  979. $titleofmodule=$objimport->array_import_module[0]->getName();
  980. // Special cas for import common to module/services
  981. if (in_array($objimport->array_import_code[0], array('produit_supplierprices','produit_multiprice'))) $titleofmodule=$langs->trans("ProductOrService");
  982. print $titleofmodule;
  983. print '</td></tr>';
  984. // Lot de donnees a importer
  985. print '<tr><td>'.$langs->trans("DatasetToImport").'</td>';
  986. print '<td>';
  987. print img_object($objimport->array_import_module[0]->getName(),$objimport->array_import_icon[0]).' ';
  988. print $objimport->array_import_label[0];
  989. print '</td></tr>';
  990. print '</table><br>';
  991. print '<b>'.$langs->trans("InformationOnSourceFile").'</b>';
  992. print '<table width="100%" class="border">';
  993. //print '<tr><td colspan="2"><b>'.$langs->trans("InformationOnSourceFile").'</b></td></tr>';
  994. // Source file format
  995. print '<tr><td width="25%">'.$langs->trans("SourceFileFormat").'</td>';
  996. print '<td>';
  997. $text=$objmodelimport->getDriverDescForKey($format);
  998. print $form->textwithpicto($objmodelimport->getDriverLabelForKey($format),$text);
  999. print '</td></tr>';
  1000. // File to import
  1001. print '<tr><td>'.$langs->trans("FileToImport").'</td>';
  1002. print '<td>';
  1003. $modulepart='import';
  1004. $relativepath=GETPOST('filetoimport');
  1005. print '<a data-ajax="false" href="'.DOL_URL_ROOT.'/document.php?modulepart='.$modulepart.'&file='.urlencode($relativepath).'&step=4'.$param.'" target="_blank">';
  1006. print $filetoimport;
  1007. print '</a>';
  1008. print '</td></tr>';
  1009. // Nb of fields
  1010. print '<tr><td>';
  1011. print $langs->trans("NbOfSourceLines");
  1012. print '</td><td>';
  1013. print $nboflines;
  1014. print '</td></tr>';
  1015. // Checkbox do not import first line
  1016. print '<tr><td>';
  1017. print $langs->trans("Option");
  1018. print '</td><td>';
  1019. print '<input type="checkbox" name="excludefirstline" value="1"';
  1020. print ($excludefirstline?' checked="checked"':'');
  1021. print ' onClick="javascript: window.location=\''.$_SERVER["PHP_SELF"].'?step=5&excludefirstline='.($excludefirstline?'0':'1').$param2.'\';">';
  1022. print ' '.$langs->trans("DoNotImportFirstLine");
  1023. print '</td></tr>';
  1024. print '</table>';
  1025. print '<br>';
  1026. print '<b>'.$langs->trans("InformationOnTargetTables").'</b>';
  1027. print '<table width="100%" class="border">';
  1028. //print '<tr><td colspan="2"><b>'.$langs->trans("InformationOnTargetTables").'</b></td></tr>';
  1029. // Tables imported
  1030. print '<tr><td width="25%">';
  1031. print $langs->trans("TablesTarget");
  1032. print '</td><td>';
  1033. $listtables=array();
  1034. $sort_array_match_file_to_database=$array_match_file_to_database;
  1035. foreach($array_match_file_to_database as $code=>$label)
  1036. {
  1037. //var_dump($fieldssource);
  1038. if ($code > count($fieldssource)) continue;
  1039. //print $code.'-'.$label;
  1040. $alias=preg_replace('/(\..*)$/i','',$label);
  1041. $listtables[$alias]=$objimport->array_import_tables[0][$alias];
  1042. }
  1043. if (count($listtables))
  1044. {
  1045. $newval='';
  1046. //ksort($listtables);
  1047. foreach ($listtables as $val)
  1048. {
  1049. if ($newval) print ', ';
  1050. $newval=$val;
  1051. // Link to Dolibarr wiki pages
  1052. /*$helppagename='EN:Table_'.$newval;
  1053. if ($helppagename && empty($conf->global->MAIN_HELP_DISABLELINK))
  1054. {
  1055. // Get helpbaseurl, helppage and mode from helppagename and langs
  1056. $arrayres=getHelpParamFor($helppagename,$langs);
  1057. $helpbaseurl=$arrayres['helpbaseurl'];
  1058. $helppage=$arrayres['helppage'];
  1059. $mode=$arrayres['mode'];
  1060. $newval.=' <a href="'.sprintf($helpbaseurl,$helppage).'">'.img_picto($langs->trans($mode == 'wiki' ? 'GoToWikiHelpPage': 'GoToHelpPage'),DOL_URL_ROOT.'/theme/common/helpdoc.png','',1).'</a>';
  1061. }*/
  1062. print $newval;
  1063. }
  1064. }
  1065. else print $langs->trans("Error");
  1066. print '</td></tr>';
  1067. // Fields imported
  1068. print '<tr><td>';
  1069. print $langs->trans("FieldsTarget").'</td><td>';
  1070. $listfields=array();
  1071. $i=0;
  1072. //print 'fieldsource='.$fieldssource;
  1073. $sort_array_match_file_to_database=$array_match_file_to_database;
  1074. ksort($sort_array_match_file_to_database);
  1075. //var_dump($sort_array_match_file_to_database);
  1076. foreach($sort_array_match_file_to_database as $code=>$label)
  1077. {
  1078. $i++;
  1079. //var_dump($fieldssource);
  1080. if ($code > count($fieldssource)) continue;
  1081. //print $code.'-'.$label;
  1082. $alias=preg_replace('/(\..*)$/i','',$label);
  1083. $listfields[$i]=$langs->trans("Field").' '.$code.'->'.$label;
  1084. }
  1085. print count($listfields)?(join(', ',$listfields)):$langs->trans("Error");
  1086. print '</td></tr>';
  1087. print '</table>';
  1088. dol_fiche_end();
  1089. if (GETPOST('action') != 'launchsimu')
  1090. {
  1091. // Show import id
  1092. print $langs->trans("NowClickToTestTheImport",$langs->transnoentitiesnoconv("RunSimulateImportFile")).'<br>';
  1093. print '<br>';
  1094. // Actions
  1095. print '<div class="center">';
  1096. if ($user->rights->import->run)
  1097. {
  1098. print '<a class="butAction" href="'.DOL_URL_ROOT.'/imports/import.php?leftmenu=import&step=5&action=launchsimu'.$param.'">'.$langs->trans("RunSimulateImportFile").'</a>';
  1099. }
  1100. else
  1101. {
  1102. print '<a class="butActionRefused" href="#" title="'.dol_escape_htmltag($langs->transnoentitiesnoconv("NotEnoughPermissions")).'">'.$langs->trans("RunSimulateImportFile").'</a>';
  1103. }
  1104. print '</div>';
  1105. }
  1106. else
  1107. {
  1108. // Launch import
  1109. $arrayoferrors=array();
  1110. $arrayofwarnings=array();
  1111. $maxnboferrors=empty($conf->global->IMPORT_MAX_NB_OF_ERRORS)?50:$conf->global->IMPORT_MAX_NB_OF_ERRORS;
  1112. $maxnbofwarnings=empty($conf->global->IMPORT_MAX_NB_OF_WARNINGS)?50:$conf->global->IMPORT_MAX_NB_OF_WARNINGS;
  1113. $nboferrors=0;
  1114. $nbofwarnings=0;
  1115. $importid=dol_print_date(dol_now(),'%Y%m%d%H%M%S');
  1116. //var_dump($array_match_file_to_database);
  1117. $db->begin();
  1118. // Open input file
  1119. $nbok=0;
  1120. $pathfile=$conf->import->dir_temp.'/'.$filetoimport;
  1121. $result=$obj->import_open_file($pathfile,$langs);
  1122. if ($result > 0)
  1123. {
  1124. global $tablewithentity_cache;
  1125. $tablewithentity_cache=array();
  1126. $sourcelinenb=0; $endoffile=0;
  1127. // Loop on each input file record
  1128. while ($sourcelinenb < $nboflines && ! $endoffile)
  1129. {
  1130. $sourcelinenb++;
  1131. // Read line and stor it into $arrayrecord
  1132. $arrayrecord=$obj->import_read_record();
  1133. if ($arrayrecord === false)
  1134. {
  1135. $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');
  1136. $endoffile++;
  1137. continue;
  1138. }
  1139. if ($excludefirstline && $sourcelinenb == 1) continue;
  1140. //
  1141. $result=$obj->import_insert($arrayrecord,$array_match_file_to_database,$objimport,count($fieldssource),$importid);
  1142. if (count($obj->errors)) $arrayoferrors[$sourcelinenb]=$obj->errors;
  1143. if (count($obj->warnings)) $arrayofwarnings[$sourcelinenb]=$obj->warnings;
  1144. if (! count($obj->errors) && ! count($obj->warnings)) $nbok++;
  1145. }
  1146. // Close file
  1147. $obj->import_close_file();
  1148. }
  1149. else
  1150. {
  1151. print $langs->trans("ErrorFailedToOpenFile",$pathfile);
  1152. }
  1153. $db->rollback(); // We force rollback because this was just a simulation.
  1154. // Show OK
  1155. if (! count($arrayoferrors) && ! count($arrayofwarnings)) print img_picto($langs->trans("OK"),'tick').' <b>'.$langs->trans("NoError").'</b><br><br>';
  1156. else print $langs->trans("NbOfLinesOK",$nbok).'</b><br><br>';
  1157. // Show Errors
  1158. //var_dump($arrayoferrors);
  1159. if (count($arrayoferrors))
  1160. {
  1161. print img_error().' <b>'.$langs->trans("ErrorsOnXLines",count($arrayoferrors)).'</b><br>';
  1162. print '<table width="100%" class="border"><tr><td>';
  1163. foreach ($arrayoferrors as $key => $val)
  1164. {
  1165. $nboferrors++;
  1166. if ($nboferrors > $maxnboferrors)
  1167. {
  1168. print $langs->trans("TooMuchErrors",(count($arrayoferrors)-$nboferrors))."<br>";
  1169. break;
  1170. }
  1171. print '* '.$langs->trans("Line").' '.$key.'<br>';
  1172. foreach($val as $i => $err)
  1173. {
  1174. print ' &nbsp; &nbsp; > '.$err['lib'].'<br>';
  1175. }
  1176. }
  1177. print '</td></tr></table>';
  1178. print '<br>';
  1179. }
  1180. // Show Warnings
  1181. //var_dump($arrayoferrors);
  1182. if (count($arrayofwarnings))
  1183. {
  1184. print img_warning().' <b>'.$langs->trans("WarningsOnXLines",count($arrayofwarnings)).'</b><br>';
  1185. print '<table width="100%" class="border"><tr><td>';
  1186. foreach ($arrayofwarnings as $key => $val)
  1187. {
  1188. $nbofwarnings++;
  1189. if ($nbofwarnings > $maxnbofwarnings)
  1190. {
  1191. print $langs->trans("TooMuchWarnings",(count($arrayofwarnings)-$nbofwarnings))."<br>";
  1192. break;
  1193. }
  1194. print ' * '.$langs->trans("Line").' '.$key.'<br>';
  1195. foreach($val as $i => $err)
  1196. {
  1197. print ' &nbsp; &nbsp; > '.$err['lib'].'<br>';
  1198. }
  1199. }
  1200. print '</td></tr></table>';
  1201. print '<br>';
  1202. }
  1203. // Show import id
  1204. $importid=dol_print_date(dol_now(),'%Y%m%d%H%M%S');
  1205. print '<div class="center">';
  1206. print $langs->trans("NowClickToRunTheImport",$langs->transnoentitiesnoconv("RunImportFile")).'<br>';
  1207. print $langs->trans("DataLoadedWithId",$importid).'<br>';
  1208. print '</div>';
  1209. print '<br>';
  1210. // Actions
  1211. print '<div class="center">';
  1212. if ($user->rights->import->run)
  1213. {
  1214. if (empty($nboferrors))
  1215. {
  1216. print '<a class="butAction" href="'.DOL_URL_ROOT.'/imports/import.php?leftmenu=import&step=6&importid='.$importid.$param.'">'.$langs->trans("RunImportFile").'</a>';
  1217. }
  1218. else
  1219. {
  1220. //print '<a class="butAction" href="'.DOL_URL_ROOT.'/imports/import.php?leftmenu=import&step=5&action=launchsimu'.$param.'">'.$langs->trans("RunSimulateImportFile").'</a>';
  1221. print '<a class="butActionRefused" href="#" title="'.dol_escape_htmltag($langs->transnoentitiesnoconv("CorrectErrorBeforeRunningImport")).'">'.$langs->trans("RunImportFile").'</a>';
  1222. }
  1223. }
  1224. else
  1225. {
  1226. print '<a class="butActionRefused" href="#" title="'.dol_escape_htmltag($langs->transnoentitiesnoconv("NotEnoughPermissions")).'">'.$langs->trans("RunSimulateImportFile").'</a>';
  1227. print '<a class="butActionRefused" href="#" title="'.dol_escape_htmltag($langs->transnoentitiesnoconv("NotEnoughPermissions")).'">'.$langs->trans("RunImportFile").'</a>';
  1228. }
  1229. print '</div>';
  1230. }
  1231. }
  1232. // STEP 6: Real import
  1233. if ($step == 6 && $datatoimport)
  1234. {
  1235. $model=$format;
  1236. $liste=$objmodelimport->liste_modeles($db);
  1237. $importid=$_REQUEST["importid"];
  1238. // Create classe to use for import
  1239. $dir = DOL_DOCUMENT_ROOT . "/core/modules/import/";
  1240. $file = "import_".$model.".modules.php";
  1241. $classname = "Import".ucfirst($model);
  1242. require_once $dir.$file;
  1243. $obj = new $classname($db,$datatoimport);
  1244. if ($model == 'csv') {
  1245. $obj->separator = $separator;
  1246. $obj->enclosure = $enclosure;
  1247. }
  1248. // Load source fields in input file
  1249. $fieldssource=array();
  1250. $result=$obj->import_open_file($conf->import->dir_temp.'/'.$filetoimport,$langs);
  1251. if ($result >= 0)
  1252. {
  1253. // Read first line
  1254. $arrayrecord=$obj->import_read_record();
  1255. // Put into array fieldssource starting with 1.
  1256. $i=1;
  1257. foreach($arrayrecord as $key => $val)
  1258. {
  1259. $fieldssource[$i]['example1']=dol_trunc($val['val'],24);
  1260. $i++;
  1261. }
  1262. $obj->import_close_file();
  1263. }
  1264. $nboflines=(! empty($_GET["nboflines"])?$_GET["nboflines"]:dol_count_nb_of_line($conf->import->dir_temp.'/'.$filetoimport));
  1265. $param='&format='.$format.'&datatoimport='.$datatoimport.'&filetoimport='.urlencode($filetoimport).'&nboflines='.$nboflines;
  1266. if ($excludefirstline) $param.='&excludefirstline=1';
  1267. if ($separator) $param.='&separator='.urlencode($separator);
  1268. if ($enclosure) $param.='&enclosure='.urlencode($enclosure);
  1269. llxHeader('',$langs->trans("NewImport"),'EN:Module_Imports_En|FR:Module_Imports|ES:M&oacute;dulo_Importaciones');
  1270. $head = import_prepare_head($param,6);
  1271. dol_fiche_head($head, 'step6', $langs->trans("NewImport"));
  1272. print '<table width="100%" class="border">';
  1273. // Module
  1274. print '<tr><td width="25%">'.$langs->trans("Module").'</td>';
  1275. print '<td>';
  1276. $titleofmodule=$objimport->array_import_module[0]->getName();
  1277. // Special cas for import common to module/services
  1278. if (in_array($objimport->array_import_code[0], array('produit_supplierprices','produit_multiprice'))) $titleofmodule=$langs->trans("ProductOrService");
  1279. print $titleofmodule;
  1280. print '</td></tr>';
  1281. // Lot de donnees a importer
  1282. print '<tr><td>'.$langs->trans("DatasetToImport").'</td>';
  1283. print '<td>';
  1284. print img_object($objimport->array_import_module[0]->getName(),$objimport->array_import_icon[0]).' ';
  1285. print $objimport->array_import_label[0];
  1286. print '</td></tr>';
  1287. print '</table><br>';
  1288. print '<b>'.$langs->trans("InformationOnSourceFile").'</b>';
  1289. print '<table width="100%" class="border">';
  1290. //print '<tr><td colspan="2"><b>'.$langs->trans("InformationOnSourceFile").'</b></td></tr>';
  1291. // Source file format
  1292. print '<tr><td width="25%">'.$langs->trans("SourceFileFormat").'</td>';
  1293. print '<td>';
  1294. $text=$objmodelimport->getDriverDescForKey($format);
  1295. print $form->textwithpicto($objmodelimport->getDriverLabelForKey($format),$text);
  1296. print '</td></tr>';
  1297. // File to import
  1298. print '<tr><td>'.$langs->trans("FileToImport").'</td>';
  1299. print '<td>';
  1300. $modulepart='import';
  1301. $relativepath=GETPOST('filetoimport');
  1302. print '<a data-ajax="false" href="'.DOL_URL_ROOT.'/document.php?modulepart='.$modulepart.'&file='.urlencode($relativepath).'&step=4'.$param.'" target="_blank">';
  1303. print $filetoimport;
  1304. print '</a>';
  1305. print '</td></tr>';
  1306. // Nb of fields
  1307. print '<tr><td>';
  1308. print $langs->trans("NbOfSourceLines");
  1309. print '</td><td>';
  1310. print $nboflines;
  1311. print '</td></tr>';
  1312. // Checkbox do not import first line
  1313. print '<tr><td>';
  1314. print $langs->trans("Option");
  1315. print '</td><td>';
  1316. print '<input type="checkbox" name="excludefirstline" value="1" disabled="disabled"';
  1317. print ($excludefirstline?' checked="checked"':'');
  1318. print '>';
  1319. print ' '.$langs->trans("DoNotImportFirstLine");
  1320. print '</td></tr>';
  1321. print '</table>';
  1322. print '<br>';
  1323. print '<b>'.$langs->trans("InformationOnTargetTables").'</b>';
  1324. print '<table width="100%" class="border">';
  1325. //print '<tr><td colspan="2"><b>'.$langs->trans("InformationOnTargetTables").'</b></td></tr>';
  1326. // Tables imported
  1327. print '<tr><td width="25%">';
  1328. print $langs->trans("TablesTarget");
  1329. print '</td><td>';
  1330. $listtables=array();
  1331. foreach($array_match_file_to_database as $code=>$label)
  1332. {
  1333. //var_dump($fieldssource);
  1334. if ($code > count($fieldssource)) continue;
  1335. //print $code.'-'.$label;
  1336. $alias=preg_replace('/(\..*)$/i','',$label);
  1337. $listtables[$alias]=$objimport->array_import_tables[0][$alias];
  1338. }
  1339. if (count($listtables))
  1340. {
  1341. $newval='';
  1342. foreach ($listtables as $val)
  1343. {
  1344. if ($newval) print ', ';
  1345. $newval=$val;
  1346. // Link to Dolibarr wiki pages
  1347. /*$helppagename='EN:Table_'.$newval;
  1348. if ($helppagename && empty($conf->global->MAIN_HELP_DISABLELINK))
  1349. {
  1350. // Get helpbaseurl, helppage and mode from helppagename and langs
  1351. $arrayres=getHelpParamFor($helppagename,$langs);
  1352. $helpbaseurl=$arrayres['helpbaseurl'];
  1353. $helppage=$arrayres['helppage'];
  1354. $mode=$arrayres['mode'];
  1355. $newval.=' <a href="'.sprintf($helpbaseurl,$helppage).'">'.img_picto($langs->trans($mode == 'wiki' ? 'GoToWikiHelpPage': 'GoToHelpPage'),DOL_URL_ROOT.'/theme/common/helpdoc.png','',1).'</a>';
  1356. }*/
  1357. print $newval;
  1358. }
  1359. }
  1360. else print $langs->trans("Error");
  1361. print '</td></tr>';
  1362. // Fields imported
  1363. print '<tr><td>';
  1364. print $langs->trans("FieldsTarget").'</td><td>';
  1365. $listfields=array();
  1366. $i=0;
  1367. $sort_array_match_file_to_database=$array_match_file_to_database;
  1368. ksort($sort_array_match_file_to_database);
  1369. //var_dump($sort_array_match_file_to_database);
  1370. foreach($sort_array_match_file_to_database as $code=>$label)
  1371. {
  1372. $i++;
  1373. //var_dump($fieldssource);
  1374. if ($code > count($fieldssource)) continue;
  1375. //print $code.'-'.$label;
  1376. $alias=preg_replace('/(\..*)$/i','',$label);
  1377. $listfields[$i]=$langs->trans("Field").' '.$code.'->'.$label;
  1378. }
  1379. print count($listfields)?(join(', ',$listfields)):$langs->trans("Error");
  1380. print '</td></tr>';
  1381. print '</table>';
  1382. // Launch import
  1383. $arrayoferrors=array();
  1384. $arrayofwarnings=array();
  1385. $maxnboferrors=empty($conf->global->IMPORT_MAX_NB_OF_ERRORS)?50:$conf->global->IMPORT_MAX_NB_OF_ERRORS;
  1386. $maxnbofwarnings=empty($conf->global->IMPORT_MAX_NB_OF_WARNINGS)?50:$conf->global->IMPORT_MAX_NB_OF_WARNINGS;
  1387. $nboferrors=0;
  1388. $nbofwarnings=0;
  1389. $importid=dol_print_date(dol_now(),'%Y%m%d%H%M%S');
  1390. //var_dump($array_match_file_to_database);
  1391. $db->begin();
  1392. // Open input file
  1393. $nbok=0;
  1394. $pathfile=$conf->import->dir_temp.'/'.$filetoimport;
  1395. $result=$obj->import_open_file($pathfile,$langs);
  1396. if ($result > 0)
  1397. {
  1398. global $tablewithentity_cache;
  1399. $tablewithentity_cache=array();
  1400. $sourcelinenb=0; $endoffile=0;
  1401. while ($sourcelinenb < $nboflines && ! $endoffile)
  1402. {
  1403. $sourcelinenb++;
  1404. $arrayrecord=$obj->import_read_record();
  1405. if ($arrayrecord === false)
  1406. {
  1407. $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');
  1408. $endoffile++;
  1409. continue;
  1410. }
  1411. if ($excludefirstline && $sourcelinenb == 1) continue;
  1412. $result=$obj->import_insert($arrayrecord,$array_match_file_to_database,$objimport,count($fieldssource),$importid);
  1413. if (count($obj->errors)) $arrayoferrors[$sourcelinenb]=$obj->errors;
  1414. if (count($obj->warnings)) $arrayofwarnings[$sourcelinenb]=$obj->warnings;
  1415. if (! count($obj->errors) && ! count($obj->warnings)) $nbok++;
  1416. }
  1417. // Close file
  1418. $obj->import_close_file();
  1419. }
  1420. else
  1421. {
  1422. print $langs->trans("ErrorFailedToOpenFile",$pathfile);
  1423. }
  1424. if (count($arrayoferrors) > 0) $db->rollback(); // We force rollback because this was errors.
  1425. else $db->commit(); // We can commit if no errors.
  1426. dol_fiche_end();
  1427. // Show result
  1428. print '<br>';
  1429. print '<div class="center">';
  1430. print $langs->trans("NbOfLinesImported",$nbok).'</b><br><br>';
  1431. print $langs->trans("FileWasImported",$importid).'<br>';
  1432. print $langs->trans("YouCanUseImportIdToFindRecord",$importid).'<br>';
  1433. print '</div>';
  1434. }
  1435. print '<br>';
  1436. llxFooter();
  1437. $db->close();
  1438. /**
  1439. * Function to put the movable box of a source field
  1440. *
  1441. * @param array $fieldssource List of source fields
  1442. * @param int $pos Pos
  1443. * @param string $key Key
  1444. * @param boolean $var Line style (odd or not)
  1445. * @param int $nostyle Hide style
  1446. * @return void
  1447. */
  1448. function show_elem($fieldssource,$pos,$key,$var,$nostyle='')
  1449. {
  1450. global $langs,$bc;
  1451. print "\n\n<!-- Box ".$pos." start -->\n";
  1452. print '<div class="box" style="padding: 0px 0px 0px 0px;" id="boxto_'.$pos.'">'."\n";
  1453. print '<table summary="boxtable'.$pos.'" width="100%" class="nobordernopadding">'."\n";
  1454. if ($pos && $pos > count($fieldssource)) // No fields
  1455. {
  1456. print '<tr '.($nostyle?'':$bc[$var]).' height="20">';
  1457. print '<td class="nocellnopadding" width="16" style="font-weight: normal">';
  1458. print img_picto(($pos>0?$langs->trans("MoveField",$pos):''),'uparrow','class="boxhandle" style="cursor:move;"');
  1459. print '</td>';
  1460. print '<td style="font-weight: normal">';
  1461. print $langs->trans("NoFields");
  1462. print '</td>';
  1463. print '</tr>';
  1464. }
  1465. elseif ($key == 'none') // Empty line
  1466. {
  1467. print '<tr '.($nostyle?'':$bc[$var]).' height="20">';
  1468. print '<td class="nocellnopadding" width="16" style="font-weight: normal">';
  1469. print '&nbsp;';
  1470. print '</td>';
  1471. print '<td style="font-weight: normal">';
  1472. print '&nbsp;';
  1473. print '</td>';
  1474. print '</tr>';
  1475. }
  1476. else // Print field of source file
  1477. {
  1478. print '<tr '.($nostyle?'':$bc[$var]).' height="20">';
  1479. print '<td class="nocellnopadding" width="16" style="font-weight: normal">';
  1480. // 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
  1481. print img_picto($langs->trans("MoveField",$pos),'uparrow','class="boxhandle" style="cursor:move;"');
  1482. print '</td>';
  1483. print '<td style="font-weight: normal">';
  1484. print $langs->trans("Field").' '.$pos;
  1485. $example=$fieldssource[$pos]['example1'];
  1486. if ($example)
  1487. {
  1488. if (! utf8_check($example)) $example=utf8_encode($example);
  1489. print ' (<i>'.$example.'</i>)';
  1490. }
  1491. print '</td>';
  1492. print '</tr>';
  1493. }
  1494. print "</table>\n";
  1495. print "</div>\n";
  1496. print "<!-- Box end -->\n\n";
  1497. }
  1498. /**
  1499. * Return not used field number
  1500. *
  1501. * @param array $fieldssource Array of field source
  1502. * @param array $listofkey Array of keys
  1503. * @return void
  1504. */
  1505. function getnewkey(&$fieldssource,&$listofkey)
  1506. {
  1507. $i=count($fieldssource)+1;
  1508. // Max number of key
  1509. $maxkey=0;
  1510. foreach($listofkey as $key=>$val)
  1511. {
  1512. $maxkey=max($maxkey,$key);
  1513. }
  1514. // Found next empty key
  1515. while($i <= $maxkey)
  1516. {
  1517. if (empty($listofkey[$i])) break;
  1518. else $i++;
  1519. }
  1520. $listofkey[$i]=1;
  1521. return $i;
  1522. }