PageRenderTime 55ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/modules/storecommander/ead6f6fce09/SC/lib/cus/win-import/cus_win-import_process.php

https://gitlab.com/ptisky/API_prestashop
PHP | 767 lines | 673 code | 49 blank | 45 comment | 131 complexity | 6393a1897ca13672e62e950c04a3c36d MD5 | raw file
  1. <?php
  2. /**
  3. * Store Commander
  4. *
  5. * @category administration
  6. * @author Store Commander - support@storecommander.com
  7. * @version 2015-09-15
  8. * @uses Prestashop modules
  9. * @since 2009
  10. * @copyright Copyright &copy; 2009-2015, Store Commander
  11. * @license commercial
  12. * All rights reserved! Copying, duplication strictly prohibited
  13. *
  14. * *****************************************
  15. * * STORE COMMANDER *
  16. * * http://www.StoreCommander.com *
  17. * * V 2015-09-15 *
  18. * *****************************************
  19. *
  20. * Compatibility: PS version: 1.1 to 1.6.1
  21. *
  22. **/
  23. error_reporting(E_ALL ^ E_NOTICE);
  24. @ini_set('display_errors', 'on');
  25. if (!isset($CRON)) $CRON=0;
  26. $action=Tools::getValue('action');
  27. $id_lang=intval(Tools::getValue('id_lang'));
  28. $mapping=Tools::getValue('mapping','');
  29. $create_categories=intval(Tools::getValue('create_categories',-1));
  30. if(SCAS)
  31. $stock_manager = StockManagerFactory::getManager();
  32. if (version_compare(_PS_VERSION_, '1.5.0.0', '<'))
  33. include_once(SC_PS_PATH_DIR.'images.inc.php');
  34. include_once(SC_DIR.'lib/php/parsecsv.lib.php');
  35. require_once(SC_DIR.'lib/cat/win-import/cat_win-import_tools.php');
  36. require_once(SC_DIR.'lib/cus/win-import/cus_win-import_tools.php');
  37. switch($action){
  38. case 'conf_delete':
  39. $imp_opt_files=Tools::getValue('imp_opt_files','');
  40. if ($imp_opt_files=='') die(_l('You should mark at least one file to delete'));
  41. $imp_opt_file_array=preg_split('/;/',$imp_opt_files);
  42. foreach($imp_opt_file_array as $imp_opt_file)
  43. {
  44. if ($imp_opt_file!='')
  45. {
  46. if (@unlink(SC_CSV_IMPORT_DIR."customers/".$imp_opt_file))
  47. {
  48. echo $imp_opt_file." "._l('deleted')."\n";
  49. }else{
  50. echo _l("Unable to delete this file, please check write permissions:")." ".$imp_opt_file."\n";
  51. }
  52. }
  53. }
  54. break;
  55. case 'mapping_load':
  56. echo loadMappingCus(Tools::getValue('filename',''));
  57. break;
  58. case 'mapping_delete':
  59. $filename=str_replace('.map.xml','',Tools::getValue('filename'));
  60. @unlink(SC_CSV_IMPORT_DIR."customers/".$filename.'.map.xml');
  61. break;
  62. case 'mapping_saveas':
  63. $filename=str_replace('.map.xml','',Tools::getValue('filename'));
  64. @unlink(SC_CSV_IMPORT_DIR."customers/".$filename.'.map.xml');
  65. $mapping=preg_split('/;/',$mapping);
  66. $content='<mapping><id_lang>'.(int)$sc_agent->id_lang.'</id_lang>';
  67. foreach($mapping AS $map)
  68. {
  69. $val=preg_split('/,/',$map);
  70. if (count($val)==3)
  71. {
  72. $content.='<map>';
  73. $content.='<csvname><![CDATA['.$val[0].']]></csvname>';
  74. $content.='<dbname><![CDATA['.$val[1].']]></dbname>';
  75. $content.='<options><![CDATA['.$val[2].']]></options>';
  76. $content.='</map>';
  77. }
  78. }
  79. $content.='</mapping>';
  80. file_put_contents(SC_CSV_IMPORT_DIR."customers/".$filename.'.map.xml', $content);
  81. echo _l('Data saved!');
  82. break;
  83. case 'mapping_process':
  84. if (SC_BETA)
  85. $time_start = microtime(true);
  86. checkDB();
  87. $scdebug=false;
  88. global $switchObject; // variable for custom import fields check
  89. $switchObject='';
  90. global $TODO; // actions
  91. $TODO=array();
  92. global $id_customer;
  93. $id_customer=0;
  94. $warehousesArray = array();
  95. $productsStockAdvancedTypeArray = array();
  96. $addressFields=array('address_title','address_country','address_state','address_company','address_lastname','address_firstname','address_1','address_2','address_postcode','address_city','address_other','address_phone','address_phonemobile');
  97. $defaultLanguageId = intval(Configuration::get('PS_LANG_DEFAULT'));
  98. $defaultLanguage=new Language($defaultLanguageId);
  99. $getIDlangByISO=array();
  100. $id_lang_sc=intval(Tools::getValue('id_lang_sc'));
  101. foreach($languages AS $lang)
  102. {
  103. $getIDlangByISO[$lang['iso_code']]=$lang['id_lang'];
  104. }
  105. $files = array_diff( scandir( SC_CSV_IMPORT_DIR."customers/" ), array_merge( Array( ".", "..", "index.php", ".htaccess", SC_CSV_IMPORT_CONF)) );
  106. readCusImportConfigXML($files);
  107. $filename=Tools::getValue('filename',0);
  108. if ($create_categories <= 0) $create_categories=intval($importConfig[$filename]['createcategories']);
  109. $importlimit=intval(Tools::getValue('importlimit',0));
  110. $importlimit=($importlimit > 0 ? $importlimit : intval($importConfig[$filename]['importlimit']));
  111. if ($importConfig[$filename]['firstlinecontent']!='') $importlimit--;
  112. if ($CRON) $mapping=loadMappingCus($importConfig[$filename]['mapping']);
  113. if ($filename===0 || $mapping=='')
  114. die(_l('You have to select a file and a mapping.'));
  115. $mappingDataArray=explode(';',$mapping);
  116. $mappingData=array('CSVArray' => array(),'DBArray' => array(),'CSV2DB' => array(),'CSV2DBOptions' => array(),'CSV2DBOptionsMerged' => array());
  117. foreach($mappingDataArray AS $val)
  118. {
  119. if ($val!='')
  120. {
  121. $tmp=explode(',',$val);
  122. $tmp2=$tmp[0];
  123. escapeCharForPS($tmp2);
  124. $mappingData['CSVArray'][]=$tmp2;
  125. $mappingData['DBArray'][]=$tmp[1];
  126. $mappingData['CSV2DB'][$tmp[0]]=$tmp[1];
  127. $mappingData['CSV2DBOptions'][$tmp[0]]=$tmp[2];
  128. $mappingData['CSV2DBOptionsMerged'][$tmp[0]]=$tmp[1].'_'.$tmp[2];
  129. }
  130. }
  131. // check mapping
  132. switch ($importConfig[$filename]['idby']){
  133. case'idcustomer':
  134. if (!sc_in_array('id_customer',$mappingData['DBArray'],"cusWinImportProcess_DBArray"))
  135. die(_l('Wrong mapping, mapping should contain the id_customer field'));
  136. break;
  137. case'email':
  138. if (!sc_in_array('email',$mappingData['DBArray'],"cusWinImportProcess_DBArray"))
  139. die(_l('Wrong mapping, mapping should contain the email field'));
  140. break;
  141. case'idcustomeradresse':
  142. if (!sc_in_array('id_customer',$mappingData['DBArray'],"cusWinImportProcess_DBArray") && !sc_in_array('address_title',$mappingData['DBArray'],"cusWinImportProcess_DBArray"))
  143. die(_l('Wrong mapping, mapping should contain the id_customer and the address title fields'));
  144. else if (!sc_in_array('id_customer',$mappingData['DBArray'],"cusWinImportProcess_DBArray"))
  145. die(_l('Wrong mapping, mapping should contain the id_customer field'));
  146. else if (!sc_in_array('address_title',$mappingData['DBArray'],"cusWinImportProcess_DBArray"))
  147. die(_l('Wrong mapping, mapping should contain the address title field'));
  148. break;
  149. case'emailadresse':
  150. if (!sc_in_array('email',$mappingData['DBArray'],"cusWinImportProcess_DBArray") && !sc_in_array('address_title',$mappingData['DBArray'],"cusWinImportProcess_DBArray"))
  151. die(_l('Wrong mapping, mapping should contain the email and the address title fields'));
  152. else if (!sc_in_array('email',$mappingData['DBArray'],"cusWinImportProcess_DBArray"))
  153. die(_l('Wrong mapping, mapping should contain the email field'));
  154. else if (!sc_in_array('address_title',$mappingData['DBArray'],"cusWinImportProcess_DBArray"))
  155. die(_l('Wrong mapping, mapping should contain the address title field'));
  156. break;
  157. case'idcustomeridadresse':
  158. if (!sc_in_array('id_customer',$mappingData['DBArray'],"cusWinImportProcess_DBArray") && !sc_in_array('id_address',$mappingData['DBArray'],"cusWinImportProcess_DBArray"))
  159. die(_l('Wrong mapping, mapping should contain the id_customer and the id_address fields'));
  160. else if (!sc_in_array('id_customer',$mappingData['DBArray'],"cusWinImportProcess_DBArray"))
  161. die(_l('Wrong mapping, mapping should contain the id_customer field'));
  162. else if (!sc_in_array('id_address',$mappingData['DBArray'],"cusWinImportProcess_DBArray"))
  163. die(_l('Wrong mapping, mapping should contain the id_address field'));
  164. break;
  165. case'emailidadresse':
  166. if (!sc_in_array('email',$mappingData['DBArray'],"cusWinImportProcess_DBArray") && !sc_in_array('id_address',$mappingData['DBArray'],"cusWinImportProcess_DBArray"))
  167. die(_l('Wrong mapping, mapping should contain the email and the id_address fields'));
  168. else if (!sc_in_array('email',$mappingData['DBArray'],"cusWinImportProcess_DBArray"))
  169. die(_l('Wrong mapping, mapping should contain the email field'));
  170. else if (!sc_in_array('id_address',$mappingData['DBArray'],"cusWinImportProcess_DBArray"))
  171. die(_l('Wrong mapping, mapping should contain the id_address field'));
  172. break;
  173. }
  174. // create TODO file
  175. if (substr($filename,strlen($filename)-9,9)=='.TODO.csv' && !file_exists(SC_CSV_IMPORT_DIR."customers/".$filename))
  176. die(_l('The TODO file has been deleted, please select the original CSV file.'));
  177. if (substr($filename,strlen($filename)-9,9)!='.TODO.csv')
  178. {
  179. $TODOfilename=substr($filename,0,-4).'.TODO.csv';
  180. if (!file_exists(SC_CSV_IMPORT_DIR."customers/".$TODOfilename))
  181. {
  182. copy(SC_CSV_IMPORT_DIR."customers/".$filename,SC_CSV_IMPORT_DIR."customers/".$TODOfilename);
  183. foreach($importConfig[$filename] AS $k => $v)
  184. {
  185. $importConfig[$TODOfilename][$k]=$v;
  186. if ($k=='name') $importConfig[$TODOfilename][$k]=$TODOfilename;
  187. }
  188. writeCusImportConfigXML();
  189. }
  190. }else{
  191. $TODOfilename=$filename;
  192. }
  193. $needSaveTODO=false;
  194. // Get Other Informations
  195. $all_genders = array();
  196. if (version_compare(_PS_VERSION_, '1.5.0.0', '>='))
  197. {
  198. $sql = "SELECT id_gender, name
  199. FROM "._DB_PREFIX_."gender_lang
  200. WHERE id_lang = '".(int)$id_lang_sc."'
  201. ORDER BY name";
  202. $res=Db::getInstance()->ExecuteS($sql);
  203. foreach($res as $re)
  204. {
  205. $all_genders[$re["id_gender"]] = $re["id_gender"];
  206. $all_genders[mb_strtolower($re["name"], ($importConfig[$TODOfilename]['utf8']?'UTF-8':''))] = $re["id_gender"];
  207. }
  208. $id_lang_en = Language::getIdByIso("en");
  209. if($id_lang_en!=$id_lang_sc)
  210. {
  211. $sql = "SELECT id_gender, name
  212. FROM "._DB_PREFIX_."gender_lang
  213. WHERE id_lang = '".(int)$id_lang_en."'
  214. ORDER BY name";
  215. $res=Db::getInstance()->ExecuteS($sql);
  216. foreach($res as $re)
  217. {
  218. $all_genders[$re["id_gender"]] = $re["id_gender"];
  219. $all_genders[mb_strtolower($re["name"], ($importConfig[$TODOfilename]['utf8']?'UTF-8':''))] = $re["id_gender"];
  220. }
  221. }
  222. if (version_compare(_PS_VERSION_, '1.6.0.0', '>='))
  223. {
  224. $all_genders[strtolower(_l("Miss"))] = 2;
  225. $all_genders[strtolower(("Miss"))] = 2;
  226. }
  227. }
  228. else
  229. {
  230. $all_genders[0] = 0;
  231. $all_genders[strtolower(_l("Unk."))] = 0;
  232. $all_genders[strtolower("Unk.")] = 0;
  233. $all_genders[1] = 1;
  234. $all_genders[strtolower(_l("Mr."))] = 1;
  235. $all_genders[strtolower(("Mr."))] = 1;
  236. $all_genders[2] = 2;
  237. $all_genders[strtolower(_l("Ms."))] = 2;
  238. $all_genders[strtolower(("Ms."))] = 2;
  239. $all_genders[3] = 3;
  240. $all_genders[strtolower(_l("Miss"))] = 3;
  241. $all_genders[strtolower(("Miss"))] = 3;
  242. $all_genders[4] = 4;
  243. $all_genders[9] = 9;
  244. }
  245. if (version_compare(_PS_VERSION_, '1.2.0.0', '>='))
  246. {
  247. $all_groups = array();
  248. $sql = "SELECT id_group, name
  249. FROM "._DB_PREFIX_."group_lang
  250. WHERE id_lang = '".(int)$id_lang_sc."'
  251. ORDER BY name";
  252. $res=Db::getInstance()->ExecuteS($sql);
  253. foreach($res as $re)
  254. {
  255. $all_groups[$re["id_group"]] = $re["id_group"];
  256. $all_groups[mb_strtolower($re["name"], ($importConfig[$TODOfilename]['utf8']?'UTF-8':''))] = $re["id_group"];
  257. }
  258. }
  259. $all_countries = array();
  260. $sql = "SELECT id_country, name
  261. FROM "._DB_PREFIX_."country_lang
  262. WHERE id_lang = '".(int)$id_lang_sc."'
  263. ORDER BY name";
  264. $res=Db::getInstance()->ExecuteS($sql);
  265. foreach($res as $re)
  266. {
  267. $all_countries[$re["id_country"]] = $re["id_country"];
  268. $all_countries[mb_strtolower($re["name"], ($importConfig[$TODOfilename]['utf8']?'UTF-8':''))] = $re["id_country"];
  269. }
  270. $all_states = array();
  271. $sql = "SELECT id_state, name
  272. FROM "._DB_PREFIX_."state
  273. ORDER BY name";
  274. $res=Db::getInstance()->ExecuteS($sql);
  275. foreach($res as $re)
  276. {
  277. $all_states[$re["id_state"]] = $re["id_state"];
  278. $all_states[mb_strtolower($re["name"], ($importConfig[$TODOfilename]['utf8']?'UTF-8':''))] = $re["id_state"];
  279. }
  280. // open csv filename
  281. if ($importConfig[$TODOfilename]['fieldsep']=='dcomma') $importConfig[$TODOfilename]['fieldsep']=';';
  282. if ($importConfig[$TODOfilename]['fieldsep']=='dcommamac') $importConfig[$TODOfilename]['fieldsep']=';';
  283. // get first line
  284. $DATAFILE=file_get_contents(SC_CSV_IMPORT_DIR."customers/".$TODOfilename);
  285. $DATA = preg_split("/(?:\r\n|\r|\n)/", $DATAFILE);
  286. if ($importConfig[$TODOfilename]['firstlinecontent']!='')
  287. {
  288. $firstLineData=explode($importConfig[$TODOfilename]['fieldsep'],$importConfig[$TODOfilename]['firstlinecontent']);
  289. $FIRST_CONTENT_LINE=0;
  290. }else{
  291. $firstLineData=explode($importConfig[$TODOfilename]['fieldsep'],$DATA[0]);
  292. $FIRST_CONTENT_LINE=1;
  293. }
  294. if (count($firstLineData)!=count(array_unique($firstLineData)))
  295. die(_l('Error : at least 2 columns have the same name in CSV file. You must use a unique name by column in the first line of your CSV file.'));
  296. foreach($firstLineData AS $key => $val)
  297. escapeCharForPS($firstLineData[$key]);
  298. $firstLineData=array_map('cleanQuotes',$firstLineData);
  299. if ($importConfig[$TODOfilename]['utf8'])
  300. utf8_encode_array($firstLineData);
  301. // CHECK FILE VALIDITY
  302. if (count($mappingData['CSVArray']) > count($firstLineData))
  303. die(_l('Error in mapping: too much field to import').' (CSVArray:'.count($mappingData['CSVArray']).' - firstLineData:'.count($firstLineData).')');
  304. foreach($mappingData['CSVArray'] AS $val)
  305. {
  306. if (!sc_in_array($val,$firstLineData,"cusWinImportProcess_firstLineData"))
  307. die(_l('Error in mapping: the fields are not in the CSV file')._l(':').$val);
  308. }
  309. if ($err!='')
  310. die($err.'<br/><br/>'._l('The process has been stopped before any modification in the database. You need to fix these errors first.'));
  311. $stats=array('created' => 0,'modified' => 0,'skipped' => 0,'group_created' => 0);
  312. $noWholesalepriceArray = array();
  313. $CSVDataStr = file_get_contents(SC_CSV_IMPORT_DIR."customers/".$TODOfilename);
  314. $CSVData = preg_split("/(?:\r\n|\r|\n)/", $CSVDataStr);
  315. $lastIdentifier='';
  316. $id_shop_default=1;
  317. if (SCMS)
  318. $id_shop_default=array((int)Configuration::get('PS_SHOP_DEFAULT'));
  319. $lastid_customer=0;
  320. $id_shop=$id_shop_default;
  321. if(!empty($importConfig[$TODOfilename]['id_shop']))
  322. $id_shop=(int)$importConfig[$TODOfilename]['id_shop'];
  323. $customersWithTagUpdatedList=array();
  324. for ($current_line = $FIRST_CONTENT_LINE; ((($current_line <= (count($DATA)-1)) && $line = parseCSVLine($importConfig[$TODOfilename]['fieldsep'],$DATA[$current_line])) && ($current_line <= $importlimit)) ; $current_line++)
  325. {
  326. if ($DATA[$current_line]=='') continue;
  327. $line=array_map('cleanQuotes',$line);
  328. if ($scdebug) echo 'line '.$current_line.': ';
  329. $line[count($line)-1]=rtrim($line[count($line)-1]);
  330. $TODO=array();
  331. $TODOSHOP=array();
  332. if ($importConfig[$TODOfilename]['utf8']==1)
  333. utf8_encode_array($line);
  334. switch($importConfig[$TODOfilename]['idby'])
  335. {
  336. case 'idcustomer':
  337. $sql="SELECT id_customer,date_upd FROM "._DB_PREFIX_."customer WHERE id_customer='".intval(findCSVLineValue('id_customer'))."' ".((SCMS)?" AND id_shop='".(int)$id_shop."'":"")."";
  338. break;
  339. case 'email':
  340. $sql="SELECT id_customer,date_upd FROM "._DB_PREFIX_."customer WHERE email='".pSQL(findCSVLineValue('email'))."' ".((SCMS)?" AND id_shop='".(int)$id_shop."'":"")."";
  341. break;
  342. case 'idcustomeradresse':
  343. $sql="SELECT id_customer,date_upd FROM "._DB_PREFIX_."customer WHERE id_customer='".intval(findCSVLineValue('id_customer'))."' ".((SCMS)?" AND id_shop='".(int)$id_shop."'":"")."";
  344. break;
  345. case 'emailadresse':
  346. $sql="SELECT id_customer,date_upd FROM "._DB_PREFIX_."customer WHERE email='".pSQL(findCSVLineValue('email'))."' ".((SCMS)?" AND id_shop='".(int)$id_shop."'":"")."";
  347. break;
  348. case 'idcustomeridadresse':
  349. $sql="SELECT id_customer,date_upd FROM "._DB_PREFIX_."customer WHERE id_customer='".intval(findCSVLineValue('id_customer'))."' ".((SCMS)?" AND id_shop='".(int)$id_shop."'":"")."";
  350. break;
  351. case 'emailidadresse':
  352. $sql="SELECT id_customer,date_upd FROM "._DB_PREFIX_."customer WHERE email='".pSQL(findCSVLineValue('email'))."' ".((SCMS)?" AND id_shop='".(int)$id_shop."'":"")."";
  353. break;
  354. /*case 'specialIdentifier':
  355. sc_ext::readImportCSVConfigXML('importProcessIdentifier');
  356. break;*/
  357. }
  358. $res=Db::getInstance()->getRow($sql);
  359. if (is_array($res) && count($res))
  360. {
  361. $id_customer=$res['id_customer'];
  362. }else{
  363. $id_customer=0;
  364. }
  365. $id_address = 0;
  366. if(!empty($id_customer))
  367. {
  368. $sql_address = "";
  369. switch($importConfig[$TODOfilename]['idby'])
  370. {
  371. case 'idcustomeradresse':
  372. $sql_address="SELECT id_address,date_upd FROM "._DB_PREFIX_."address WHERE id_customer='".intval($id_customer)."' AND LOWER(alias)='".pSQL(mb_strtolower(findCSVLineValue('address_title'), ($importConfig[$TODOfilename]['utf8']?'UTF-8':'')))."'";
  373. break;
  374. case 'emailadresse':
  375. $sql_address="SELECT id_address,date_upd FROM "._DB_PREFIX_."address WHERE id_customer='".intval($id_customer)."' AND LOWER(alias)='".pSQL(mb_strtolower(findCSVLineValue('address_title'), ($importConfig[$TODOfilename]['utf8']?'UTF-8':'')))."'";
  376. break;
  377. case 'idcustomeridadresse':
  378. $sql_address="SELECT id_address,date_upd FROM "._DB_PREFIX_."address WHERE id_customer='".intval($id_customer)."' AND id_address='".intval(findCSVLineValue('id_address'))."'";
  379. break;
  380. case 'emailidadresse':
  381. $sql_address="SELECT id_address,date_upd FROM "._DB_PREFIX_."address WHERE id_customer='".intval($id_customer)."' AND id_address='".intval(findCSVLineValue('id_address'))."'";
  382. break;
  383. }
  384. if(!empty($sql_address))
  385. {
  386. $res_address=Db::getInstance()->getRow($sql_address);
  387. if (is_array($res_address) && count($res_address))
  388. {
  389. $id_address=$res_address['id_address'];
  390. }
  391. }
  392. }
  393. if ($scdebug) echo findCSVLineValue('email').' : '.$id_customer.'<br/>';
  394. if ($scdebug) echo 'a';
  395. if ($CRON && isset($CRON_OLDERTHAN) && $CRON_OLDERTHAN > 0)
  396. {
  397. $date_upd=strtotime($res['date_upd']);
  398. $nowres=Db::getInstance()->getRow('SELECT UNIX_TIMESTAMP() AS ut');
  399. $now=($nowres ? $nowres['ut'] : 0);
  400. if (($date_upd > ($now - ((int)$CRON_OLDERTHAN * 60)))) // if not a recent updated object...
  401. {
  402. $stats['skipped']++;
  403. $importlimit++; // on suppose que tous les éléments ont été créés en BDD : le cron ne sert que pour mettre à jour stock et/ou prix
  404. continue;
  405. }
  406. }
  407. if ($importConfig[$TODOfilename]['iffoundindb']=='skip' && $id_customer)
  408. {
  409. $stats['skipped']++;
  410. if (_s('CAT_IMPORT_IGNORED_LINES')==1)
  411. {
  412. unset($CSVData[$current_line]);
  413. $needSaveTODO=true;
  414. }
  415. // ne pas augmenter la limite totale car les prochaines lignes n'ont pas été analysées et donc des éléments peuvent manquer.
  416. //$importlimit++;
  417. continue;
  418. }
  419. elseif ($importConfig[$TODOfilename]['iffoundindb']=='replace' && $id_customer)
  420. {
  421. //in_array($importConfig[$TODOfilename]['idby'],array('idcustomeradresse','emailadresse','idcustomeridadresse','emailidadresse')) ||
  422. if(hasAddress())
  423. {
  424. if(!empty($id_address))
  425. $newaddress=new Address($id_address);
  426. else
  427. {
  428. $newaddress=new Address();
  429. $newaddress->id_customer=$id_customer;
  430. $newaddress->active=1;
  431. $newaddress->alias=_l('My address');
  432. }
  433. }
  434. if (SCMS)
  435. {
  436. $newcustomer=new Customer($id_customer, null, $id_shop);
  437. }else{
  438. $newcustomer=new Customer($id_customer);
  439. }
  440. $stats['modified']++;
  441. }
  442. elseif ($importConfig[$TODOfilename]['iffoundindb']=='replaceonly')
  443. {
  444. $skip=false;
  445. if(!empty($id_customer))
  446. {
  447. if(hasAddress())
  448. {
  449. if(!empty($id_address))
  450. $newaddress=new Address($id_address);
  451. else
  452. $skip = true;
  453. }
  454. }
  455. else
  456. $skip=true;
  457. if($skip)
  458. {
  459. $stats['skipped']++;
  460. if (_s('CAT_IMPORT_IGNORED_LINES')==1)
  461. {
  462. unset($CSVData[$current_line]);
  463. $needSaveTODO=true;
  464. }
  465. // ne pas augmenter la limite totale car les prochaines lignes n'ont pas été analysées et donc des éléments peuvent manquer.
  466. //$importlimit++;
  467. continue;
  468. }
  469. else
  470. {
  471. if (SCMS)
  472. {
  473. $newcustomer=new Customer($id_customer, null, $id_shop);
  474. }else{
  475. $newcustomer=new Customer($id_customer);
  476. }
  477. $stats['modified']++;
  478. }
  479. }else{
  480. $email = findCSVLineValue('email');
  481. if(empty($email))
  482. die(_l('Email can\'t be empty to create a customer: line n°').' '.$current_line);
  483. // create new customer with default values
  484. $newcustomer=new Customer();
  485. $newcustomer->active=0;
  486. $newcustomer->firstname=_l("Firstname");
  487. $newcustomer->lastname=_l("Lastname");
  488. $newcustomer->email=$email;
  489. $newcustomer->passwd="password";
  490. if(SCMS)
  491. $newcustomer->id_shop=$id_shop;
  492. if(hasAddress())
  493. {
  494. $newaddress=new Address();
  495. $newaddress->active=1;
  496. $newaddress->alias=_l('My address');
  497. }
  498. $stats['created']++;
  499. }
  500. if ($scdebug) echo 'b';
  501. foreach($line AS $key => $value)
  502. {
  503. $value=trim($value);
  504. $GLOBALS['import_value']=$value;
  505. if ($scdebug && !sc_array_key_exists($key,$firstLineData)) echo 'ERR'.$key.'x'.$current_line.'x'.join(';',$line).'xxx'.join(';',array_keys($firstLineData)).'<br/>';
  506. if (sc_array_key_exists($key,$firstLineData) && sc_in_array($firstLineData[$key],$mappingData['CSVArray'],"cusWinImportProcess_CSVArray"))
  507. {
  508. if ($scdebug) echo 'c';
  509. //@$id_lang=intval($getIDlangByISO[$mappingData['CSV2DBOptions'][$firstLineData[$key]]]);
  510. $switchObject=$mappingData['CSV2DB'][$firstLineData[$key]];
  511. switch($switchObject)
  512. {
  513. // CUSTOMER
  514. case 'company':$newcustomer->company=psql($value);break;
  515. case 'siret':$newcustomer->siret=psql($value);break;
  516. case 'ape':$newcustomer->ape=psql($value);break;
  517. case 'firstname':$newcustomer->firstname=psql($value);break;
  518. case 'lastname':$newcustomer->lastname=psql($value);break;
  519. case 'email':$newcustomer->email=psql($value);break;
  520. case 'passwd':$newcustomer->passwd=psql(Tools::encrypt($value));break;
  521. case 'birthday':$newcustomer->birthday=psql(importConv2Date($value));break;
  522. case 'date_add':$newcustomer->date_add=psql(importConv2Date($value));break;
  523. case 'newsletter':$newcustomer->newsletter=intval(getBoolean($value));break;
  524. case 'optin':$newcustomer->optin=intval(getBoolean($value));break;
  525. case 'website':$newcustomer->website=psql($value);break;
  526. case 'active':$newcustomer->active=intval(getBoolean($value));break;
  527. case 'note':$newcustomer->note=psql($value);break;
  528. case 'id_gender':
  529. $gender = mb_strtolower($value, ($importConfig[$TODOfilename]['utf8']?'UTF-8':''));
  530. if(!empty($all_genders[$gender]))
  531. $newcustomer->id_gender=(int)$all_genders[$gender];
  532. break;
  533. case 'id_default_group':
  534. $group = mb_strtolower($value, ($importConfig[$TODOfilename]['utf8']?'UTF-8':''));
  535. if(!empty($all_groups[$group]))
  536. $newcustomer->id_default_group=(int)$all_groups[$group];
  537. else
  538. {
  539. if(!is_numeric($value))
  540. {
  541. $newGroup = new Group();
  542. $newGroup->name = $value;
  543. $newGroup->price_display_method = 0;
  544. $newGroup->save();
  545. $all_groups[$group]=$newGroup->id;
  546. $newcustomer->id_default_group=(int)$all_groups[$group];
  547. $stats['group_created']++;
  548. }
  549. }
  550. break;
  551. // ADDRESS
  552. case 'address_title':$newaddress->alias=psql($value);break;
  553. case 'address_country':
  554. $country = mb_strtolower($value, ($importConfig[$TODOfilename]['utf8']?'UTF-8':''));
  555. if (sc_array_key_exists($country, $all_countries))
  556. $newaddress->id_country=(int)$all_countries[$country];
  557. break;
  558. case 'address_state':
  559. $state = mb_strtolower($value, ($importConfig[$TODOfilename]['utf8']?'UTF-8':''));
  560. if(!empty($all_states[$state]))
  561. $newaddress->id_state=(int)$all_states[$state];
  562. break;
  563. case 'address_company':$newaddress->company=psql($value);break;
  564. case 'address_lastname':$newaddress->lastname=psql($value);break;
  565. case 'address_firstname':$newaddress->firstname=psql($value);break;
  566. case 'address_1':$newaddress->address1=psql($value);break;
  567. case 'address_2':$newaddress->address2=psql($value);break;
  568. case 'address_postcode':$newaddress->postcode=psql($value);break;
  569. case 'address_city':$newaddress->city=psql($value);break;
  570. case 'address_other':$newaddress->other=psql($value);break;
  571. case 'address_phone':$newaddress->phone=psql($value);break;
  572. case 'address_phonemobile':$newaddress->phone_mobile=psql($value);break;
  573. // ACTIONS
  574. case 'ActionDeleteAllCustomers':
  575. if (getBoolean($value))
  576. {
  577. $sql = "SELECT id_customer FROM "._DB_PREFIX_."customer WHERE deleted!=1";
  578. $all_customers = Db::getInstance()->ExecuteS($sql);
  579. foreach($all_customers as $customer_id)
  580. {
  581. $customer_id = $customer_id["id_customer"];
  582. $customer = new Customer((int)$customer_id);
  583. if (count(Order::getCustomerOrders((int)$customer_id))==0)
  584. $customer->delete();
  585. else
  586. {
  587. $customer->deleted=1;
  588. $customer->save();
  589. }
  590. }
  591. }
  592. break;
  593. case 'ActionDeleteAllAddresses':
  594. if (getBoolean($value))
  595. {
  596. $sql = "SELECT id_address FROM "._DB_PREFIX_."address WHERE deleted!=1";
  597. $all_addresses = Db::getInstance()->ExecuteS($sql);
  598. foreach($all_addresses as $address_id)
  599. {
  600. $address_id = $address_id["id_address"];
  601. $address = new Address((int)$address_id);
  602. $address->delete();
  603. }
  604. }
  605. break;
  606. case 'ActionRegenerateAllPasswords':
  607. if (getBoolean($value))
  608. {
  609. $sql = "SELECT id_customer FROM "._DB_PREFIX_."customer WHERE deleted!=1";
  610. $all_customers = Db::getInstance()->ExecuteS($sql);
  611. foreach($all_customers as $customer_id)
  612. {
  613. $customer_id = $customer_id["id_customer"];
  614. $customer = new Customer((int)$customer_id);
  615. $customer->passwd = Tools::encrypt(randomPassword());
  616. $customer->save();
  617. }
  618. }
  619. break;
  620. //case 'date_add':$TODO[]="UPDATE "._DB_PREFIX_."product SET date_add='".psql($value)."' WHERE id_customer=ID_PRODUCT";break;
  621. //default:
  622. //sc_ext::readImportCSVConfigXML('importProcessProduct');
  623. }
  624. }
  625. }
  626. if ($scdebug) echo 'd';
  627. $newcustomer->date_upd=date("Y-m-d H:i:s");
  628. if ($newcustomer->save())
  629. {
  630. $lastid_customer=$newcustomer->id;
  631. if ($scdebug) echo 'e';
  632. foreach($TODO AS $sql)
  633. {
  634. $sql=str_replace('ID_PRODUCT',$newcustomer->id,$sql);
  635. Db::getInstance()->Execute($sql);
  636. }
  637. // SAVE ADDRESS
  638. if(hasAddress())
  639. {
  640. $newaddress->id_customer = $lastid_customer;
  641. if(empty($newaddress->firstname))
  642. $newaddress->firstname = $newcustomer->firstname;
  643. if(empty($newaddress->lastname))
  644. $newaddress->lastname = $newcustomer->lastname;
  645. if($newaddress->id_country == 0 || !$newaddress->save())
  646. {
  647. echo _l('The customer has been imported but there is a problem with his address.').'<br/>';
  648. echo _l('You need to check these fields on the first line of').' '.$TODOfilename._l(':').' alias, lastname, firstname, address1, city, country<br/>';
  649. echo _l('More information about the address')._l(':').'<br/>';
  650. var_dump($newaddress);
  651. exit;
  652. }
  653. }
  654. // ADD IN GROUPS
  655. $name_groups = findCSVLineValue("groups");
  656. if(sc_in_array("groups",$mappingData['DBArray'],"cusWinImportProcess_DBArray") && !empty($name_groups))
  657. {
  658. $temp_groups = array();
  659. $groups = explode($importConfig[$TODOfilename]['valuesep'], $name_groups);
  660. foreach($groups as $value)
  661. {
  662. $group = mb_strtolower($value, ($importConfig[$TODOfilename]['utf8']?'UTF-8':''));
  663. if(!empty($all_groups[$group]))
  664. $temp_groups[]=(int)$all_groups[$group];
  665. else
  666. {
  667. if(!is_numeric($value))
  668. {
  669. $newGroup = new Group();
  670. $newGroup->name = $value;
  671. $newGroup->price_display_method = 0;
  672. $newGroup->save();
  673. $all_groups[$group]=$newGroup->id;
  674. $temp_groups[]=(int)$all_groups[$group];
  675. $stats['group_created']++;
  676. }
  677. }
  678. }
  679. if(!empty($temp_groups))
  680. $newcustomer->updateGroup($temp_groups);
  681. }
  682. unset($CSVData[$current_line]);
  683. file_put_contents(SC_CSV_IMPORT_DIR."customers/".$TODOfilename,join("\n",$CSVData));
  684. $needSaveTODO=false;
  685. }
  686. }
  687. if ($needSaveTODO)
  688. file_put_contents(SC_CSV_IMPORT_DIR."customers/".$TODOfilename,join("\n",$CSVData));
  689. echo '<b>'._l('Stats:').'</b><br/>';
  690. $msg = _l('New customers:').' '.$stats['created'].'<br/>';
  691. $msg.= _l('Modified customers:').' '.$stats['modified'].'<br/>';
  692. $msg.= _l('Skipped lines:').' '.$stats['skipped'].'<br/>';
  693. if(!empty($stats['group_created']))
  694. $msg.= _l('New groups:').' '.$stats['group_created'].'<br/>';
  695. echo $msg.'<br/>';
  696. if ((count($CSVData)==1) || (count($CSVData)==2 && $CSVData[0]==join('',$CSVData)) || (filesize(SC_CSV_IMPORT_DIR."customers/".$TODOfilename)==0))
  697. {
  698. @unlink(SC_CSV_IMPORT_DIR."customers/".$TODOfilename);
  699. echo _l('All customers have been imported. The TODO file is deleted.').'<br/><br/>';
  700. echo '<b>'._l('End of import process.').'</b><br/><br/>';
  701. echo '<b>'._l('You need to refresh the page, click here:').' <a target="_top" href="index.php">Go!</a></b><br/>';
  702. echo '<script type="text/javascript">window.top.displayOptionsCus();window.top.stopAutoImportCus(true);</script>';
  703. $msg2 = 'All customers have been imported.';
  704. }else{
  705. echo '<b>'._l('There are still customers to be imported in the working file. It can mean errors you need to correct or lines which have been ignored on purpose. Once corrections have been made, click again on the import icon to proceed further.').'</b><br/><br/>';
  706. echo '<script type="text/javascript">window.top.displayOptionsCus();window.top.prepareNextStepCus('.($stats['created']+$stats['modified']+$stats['skipped']==0?0:filesize(SC_CSV_IMPORT_DIR."customers/".$TODOfilename)).');</script>';
  707. $msg2 = 'Need fix and run import again.';
  708. }
  709. $msg3='';
  710. if ($CRON)
  711. {
  712. $msg3 .= _l('CRON task name')._l(':').' '.$CRON_NAME.'<br/>';
  713. $msg3 .= ( isset($CRON_DELETETODO) && $CRON_DELETETODO ? $TODOfilename.' '._l('deleted').'<br/>':'');
  714. $msg3 .= _l('Update customers older than').' '.$CRON_OLDERTHAN;
  715. }
  716. addToHistory('customer_import','import','','','','','Imported file: '.$TODOfilename.'<br/>'.$msg.$msg2.($msg3!=''?'<br/>'.$msg3:''),'');
  717. break;
  718. }