PageRenderTime 50ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/modules/storecommander/ead6f6fce09/SC/lib/cat/win-catimport/cat_win-catimport_process.php

https://gitlab.com/ptisky/API_prestashop
PHP | 1187 lines | 888 code | 76 blank | 223 comment | 196 complexity | d34946542e242b614c693d208b62038e 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_ERROR);
  24. @ini_set('display_errors', 'on');
  25. $action=Tools::getValue('action');
  26. $id_lang=intval(Tools::getValue('id_lang'));
  27. $mapping=Tools::getValue('mapping','');
  28. if (version_compare(_PS_VERSION_, '1.5.0.0', '<'))
  29. {
  30. include_once(SC_PS_PATH_DIR.'images.inc.php');
  31. require_once(dirname(__FILE__).'/../../../all/upload/upload-image.inc.php');
  32. }
  33. include_once(SC_DIR.'lib/php/parsecsv.lib.php');
  34. require_once(SC_DIR.'lib/cat/win-catimport/cat_win-catimport_tools.php');
  35. switch($action){
  36. case 'conf_delete':
  37. $imp_opt_files=Tools::getValue('imp_opt_files','');
  38. if ($imp_opt_files=='') die(_l('You should mark at least one file to delete'));
  39. $imp_opt_file_array=preg_split('/;/',$imp_opt_files);
  40. foreach($imp_opt_file_array as $imp_opt_file)
  41. {
  42. if ($imp_opt_file!='')
  43. {
  44. if (@unlink(SC_CSV_IMPORT_DIR."category/".$imp_opt_file))
  45. {
  46. echo $imp_opt_file." "._l('deleted')."\n";
  47. }else{
  48. echo _l("Unable to delete this file, please check write permissions:")." ".$imp_opt_file."\n";
  49. }
  50. }
  51. }
  52. break;
  53. case 'mapping_load':
  54. echo loadCatMapping(Tools::getValue('filename',''));
  55. break;
  56. case 'mapping_delete':
  57. $filename=str_replace('.map.xml','',Tools::getValue('filename'));
  58. @unlink(SC_CSV_IMPORT_DIR."category/".$filename.'.map.xml');
  59. break;
  60. case 'mapping_saveas':
  61. $filename=str_replace('.map.xml','',Tools::getValue('filename'));
  62. @unlink(SC_CSV_IMPORT_DIR."category/".$filename.'.map.xml');
  63. $mapping=preg_split('/;/',$mapping);
  64. $content='<mapping><id_lang>'.(int)$sc_agent->id_lang.'</id_lang>';
  65. foreach($mapping AS $map)
  66. {
  67. $val=preg_split('/,/',$map);
  68. if (count($val)==3)
  69. {
  70. $content.='<map>';
  71. $content.='<csvname><![CDATA['.$val[0].']]></csvname>';
  72. $content.='<dbname><![CDATA['.$val[1].']]></dbname>';
  73. $content.='<options><![CDATA['.$val[2].']]></options>';
  74. $content.='</map>';
  75. }
  76. }
  77. $content.='</mapping>';
  78. file_put_contents(SC_CSV_IMPORT_DIR."category/".$filename.'.map.xml', $content);
  79. echo _l('Data saved!');
  80. break;
  81. case 'mapping_process':
  82. echo '<div style="width: 100%; height: 100%; overflow: auto;">';
  83. if (_s('APP_DEBUG_CATALOG_IMPORT'))
  84. $time_start = microtime(true);
  85. if (_s('APP_DEBUG_CATALOG_IMPORT'))
  86. {
  87. // Affichage des modules greffer au hook UpdateProduct
  88. if (version_compare(_PS_VERSION_,'1.5.0.0','>='))
  89. $hook_id = Hook::getIdByName("actionCategoryUpdate");
  90. else
  91. $hook_id = Hook::get("categoryUpdate");
  92. if(!empty($hook_id))
  93. {
  94. $hook = new Hook((int)$hook_id);
  95. $modules = $hook->getHookModuleList();
  96. if(!empty($modules[(int)$hook_id]))
  97. {
  98. echo "<br/><br/>Liste des modules :";
  99. foreach($modules[(int)$hook_id] as $module)
  100. {
  101. echo "<br/>".$module["name"]." (".($module["active"]?"Activé":"Désactivé").")";
  102. }
  103. }
  104. }
  105. }
  106. checkDB();
  107. $scdebug=false;
  108. global $switchObject; // variable for custom import fields check
  109. $switchObject='';
  110. global $TODO; // actions
  111. $TODO=array();
  112. global $id_category;
  113. $id_category=0;
  114. $id_category_todo=0;
  115. $defaultLanguageId = intval(Configuration::get('PS_LANG_DEFAULT'));
  116. $defaultLanguage=new Language($defaultLanguageId);
  117. $getIDlangByISO=array();
  118. $generate_hight_dpi_images = (bool)SCI::getConfigurationValue('PS_HIGHT_DPI');
  119. foreach($languages AS $lang)
  120. {
  121. $getIDlangByISO[$lang['iso_code']]=$lang['id_lang'];
  122. }
  123. $files = array_diff( scandir( SC_CSV_IMPORT_DIR."category/" ), array_merge( Array( ".", "..", "index.php", ".htaccess", SC_CSV_IMPORT_CONF)) );
  124. readCatImportConfigXML($files);
  125. $filename=Tools::getValue('filename',0);
  126. $importlimit=intval(Tools::getValue('importlimit',0));
  127. $importlimit=($importlimit > 0 ? $importlimit : intval($importConfig[$filename]['importlimit']));
  128. if ($importConfig[$filename]['firstlinecontent']!='') $importlimit--;
  129. if ($filename===0 || $mapping=='')
  130. die(_l('You have to select a file and a mapping.'));
  131. $mapping = str_replace("&amp;", "&", $mapping);
  132. $mappingDataArray=explode(';',$mapping);
  133. $mappingData=array('CSVArray' => array(),'DBArray' => array(),'CSV2DB' => array(),'CSV2DBOptions' => array(),'CSV2DBOptionsMerged' => array());
  134. foreach($mappingDataArray AS $val)
  135. {
  136. if ($val!='')
  137. {
  138. $tmp=explode(',',$val);
  139. $tmp2=$tmp[0];
  140. escapeCharForPS($tmp2);
  141. $mappingData['CSVArray'][]=$tmp2;
  142. $mappingData['DBArray'][]=$tmp[1];
  143. $mappingData['CSV2DB'][$tmp[0]]=$tmp[1];
  144. $mappingData['CSV2DBOptions'][$tmp[0]]=$tmp[2];
  145. $mappingData['CSV2DBOptionsMerged'][$tmp[0]]=$tmp[1].'_'.$tmp[2];
  146. }
  147. }
  148. // check mapping
  149. switch ($importConfig[$filename]['idby']){
  150. case'catname':
  151. if (!sc_in_array('name_'.$defaultLanguage->iso_code,$mappingData['CSV2DBOptionsMerged'],"catWinCatImportProcess_CSV2DBOptionsMerged"))
  152. die(_l('Wrong mapping, mapping should contain the field name in ').$defaultLanguage->iso_code.'<br/><br/>'.
  153. _l('For each line of the mapping you need to double click in the Database field column to fill the mapping.').'<br/><br/>'.
  154. _l('If the cell in the Options column becomes blue, you need to edit this cell and complete the mapping.'));
  155. break;
  156. case'idcategory':
  157. if (!sc_in_array('id_category',$mappingData['DBArray'],"catWinCatImportProcess_DBArray"))
  158. die(_l('Wrong mapping, mapping should contain the field: id_category'));
  159. break;
  160. case'path':
  161. if (!sc_in_array('path',$mappingData['DBArray'],"catWinCatImportProcess_DBArray"))
  162. die(_l('Wrong mapping, mapping should contain the field: path'));
  163. break;
  164. }
  165. if($importConfig[$TODOfilename]['fornewcat']=='create')
  166. {
  167. if(!((fieldInMapping("name") && fieldInMapping("parents")) || fieldInMapping("path")))
  168. die(_l('Wrong mapping, mapping should contain the fields: name + parents or path'));
  169. }
  170. // create TODO file
  171. if (substr($filename,strlen($filename)-9,9)=='.TODO.csv' && !file_exists(SC_CSV_IMPORT_DIR."category/".$filename))
  172. die(_l('The TODO file has been deleted, please select the original CSV file.'));
  173. if (substr($filename,strlen($filename)-9,9)!='.TODO.csv')
  174. {
  175. $TODOfilename=substr($filename,0,-4).'.TODO.csv';
  176. if (!file_exists(SC_CSV_IMPORT_DIR."category/".$TODOfilename))
  177. {
  178. copy(SC_CSV_IMPORT_DIR."category/".$filename,SC_CSV_IMPORT_DIR."category/".$TODOfilename);
  179. foreach($importConfig[$filename] AS $k => $v)
  180. {
  181. $importConfig[$TODOfilename][$k]=$v;
  182. if ($k=='name') $importConfig[$TODOfilename][$k]=$TODOfilename;
  183. }
  184. writeCatImportConfigXML();
  185. }
  186. }else{
  187. $TODOfilename=$filename;
  188. }
  189. $needSaveTODO=false;
  190. if(empty($importConfig[$TODOfilename]['fornewcat']))
  191. $importConfig[$TODOfilename]['fornewcat'] = "skip";
  192. if(empty($importConfig[$TODOfilename]['forfoundcat']))
  193. $importConfig[$TODOfilename]['forfoundcat'] = "skip";
  194. // open csv filename
  195. if ($importConfig[$TODOfilename]['fieldsep']=='dcomma') $importConfig[$TODOfilename]['fieldsep']=';';
  196. if ($importConfig[$TODOfilename]['fieldsep']=='dcommamac') $importConfig[$TODOfilename]['fieldsep']=';';
  197. // get first line
  198. $DATAFILE=remove_utf8_bom(file_get_contents(SC_CSV_IMPORT_DIR."category/".$TODOfilename));
  199. $DATA = preg_split("/(?:\r\n|\r|\n)/", $DATAFILE);
  200. if ($importConfig[$TODOfilename]['firstlinecontent']!='')
  201. {
  202. $importConfig[$TODOfilename]['firstlinecontent'] = str_replace("&amp;","&",$importConfig[$TODOfilename]['firstlinecontent']);
  203. $firstLineData=explode($importConfig[$TODOfilename]['fieldsep'],$importConfig[$TODOfilename]['firstlinecontent']);
  204. $FIRST_CONTENT_LINE=0;
  205. }else{
  206. $DATA[0] = str_replace("&amp;","&",$DATA[0]);
  207. $firstLineData=explode($importConfig[$TODOfilename]['fieldsep'],$DATA[0]);
  208. $FIRST_CONTENT_LINE=1;
  209. }
  210. if (count($firstLineData)!=count(array_unique($firstLineData)))
  211. 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.'));
  212. foreach($firstLineData AS $key => $val)
  213. escapeCharForPS($firstLineData[$key]);
  214. $firstLineData=array_map('cleanQuotes',$firstLineData);
  215. if ($importConfig[$TODOfilename]['utf8'])
  216. utf8_encode_array($firstLineData);
  217. // CHECK FILE VALIDITY
  218. if (count($mappingData['CSVArray']) > count($firstLineData))
  219. die(_l('Error in mapping: too much field to import').' (CSVArray:'.count($mappingData['CSVArray']).' - firstLineData:'.count($firstLineData).')');
  220. foreach($mappingData['CSVArray'] AS $val)
  221. {
  222. if (!in_array($val,$firstLineData))
  223. die(_l('Error in mapping: the fields are not in the CSV file')._l(':').$val);
  224. }
  225. // PLACE VALUES IN CACHE
  226. $err='';
  227. // VAT second check
  228. if ($err!='' && $importConfig[$TODOfilename]['createelements']!=1)
  229. die($err.'<br/><br/>'._l('The process has been stopped before any modification in the database. You need to fix these errors first.'));
  230. // CHECK IF CATEGORY EXISTS
  231. /*$categ=Db::getInstance()->getRow("
  232. SELECT c.id_category
  233. FROM `"._DB_PREFIX_."category` c
  234. LEFT JOIN `"._DB_PREFIX_."category_lang` cl ON (c.`id_category` = cl.`id_category`)
  235. WHERE `name` = '".pSQL($TODOfilename)."'
  236. GROUP BY c.id_category");
  237. if (is_array($categ) && $categ['id_category']!='')
  238. {
  239. $id_category_todo=intval($categ['id_category']);
  240. }else{
  241. $newcategory=new Category();
  242. $newcategory->id_parent=Configuration::get("PS_ROOT_CATEGORY");//1;
  243. $newcategory->level_depth=$newcategory->calcLevelDepth();
  244. $newcategory->active=0;
  245. foreach($languages AS $lang)
  246. {
  247. $newcategory->link_rewrite[$lang['id_lang']]='import';
  248. $newcategory->name[$lang['id_lang']]=$TODOfilename;
  249. }
  250. if (version_compare(_PS_VERSION_, '1.4.0.0', '>='))
  251. {
  252. $newcategory->position=SCI::getLastPositionFromCategory(1);
  253. }
  254. $newcategory->save();
  255. //$newcategory->addGroups(array(1));
  256. $id_category_todo=$newcategory->id;
  257. }*/
  258. $stats=array('created' => 0,'modified' => 0,'skipped' => 0);
  259. $CSVDataStr = remove_utf8_bom(file_get_contents(SC_CSV_IMPORT_DIR."category/".$TODOfilename));
  260. $CSVData = preg_split("/(?:\r\n|\r|\n)/", $CSVDataStr);
  261. $lastIdentifier='';
  262. $lastid_category=0;
  263. $updated_categories = array();
  264. $id_shop_list=array();
  265. $id_shop_list_default=array(1);
  266. if (version_compare(_PS_VERSION_,'1.5.0.0','>='))
  267. {
  268. $id_shop_list_default=array((int)Configuration::get('PS_SHOP_DEFAULT'));
  269. $cache_id_shop = array();
  270. $cache_current_line_for_combination = array();
  271. }
  272. $imageList=array();
  273. $shop_home_category=array();
  274. $sql="SELECT c.id_category,c.id_parent,cl.name,c.level_depth
  275. FROM "._DB_PREFIX_."category c
  276. LEFT JOIN "._DB_PREFIX_."category_lang cl ON (cl.id_category=c.id_category AND cl.id_lang=".intval($defaultLanguage->id).")
  277. GROUP BY c.id_category
  278. ORDER BY c.level_depth ASC";
  279. $res=Db::getInstance()->ExecuteS($sql);
  280. $categories=array();
  281. $categoriesProperties=array();
  282. $categoryNameByID=array();
  283. $categoryIDByPath=array();
  284. $categoriesFirstLevel=array();
  285. foreach($res AS $categ)
  286. {
  287. if ($categ['id_category']==$categ['id_parent']) die(_l('A category cannot be parent of itself, you must fix this error for category ID').' '.$categ['id_category'].' - '.trim(hideCategoryPosition($categ['name'])));
  288. $categories[trim(hideCategoryPosition($categ['name']))]=array('id_category' => $categ['id_category'], 'id_parent' => $categ['id_parent']);
  289. $categoryNameByID[$categ['id_category']]=hideCategoryPosition($categ['name']);
  290. $categoriesProperties[$categ['id_category']]=array('id_category' => $categ['id_category'], 'id_parent' => $categ['id_parent']);
  291. $categoryIDByPath[forceCategoryPathFormat(getCategoryPath($categ['id_category']))]=$categ['id_category'];
  292. if ($categ['level_depth']==1) $categoriesFirstLevel[]=hideCategoryPosition($categ['name']);
  293. }
  294. $has_customergroup=false;
  295. for ($current_line = $FIRST_CONTENT_LINE; ((($current_line <= (count($DATA)-1)) && $line = parseCSVLine($importConfig[$TODOfilename]['fieldsep'],$DATA[$current_line])) && ($current_line <= $importlimit)) ; $current_line++)
  296. {
  297. if ($DATA[$current_line]=='') continue;
  298. if ($importConfig[$TODOfilename]['utf8']==1)
  299. utf8_encode_array($line);
  300. $line=array_map('cleanQuotes',$line);
  301. if (fieldInMapping("customergroups"))
  302. $has_customergroup=true;
  303. if (count($line)!=count($firstLineData))
  304. $err.=_l("Error on line ").($current_line+1)._l(": wrong column count: ").substr(join($importConfig[$TODOfilename]['fieldsep'],$line),0,22)." (".count($line)."-".count($firstLineData).")<br/>";
  305. }
  306. $dataDB_customergroup=array();
  307. $dataDB_customergroupByName=array();
  308. if($has_customergroup)
  309. {
  310. if (version_compare(_PS_VERSION_,'1.5.0.0','>='))
  311. $DB_customergroup = Db::getInstance()->ExecuteS('SELECT g.id_group,gl.name
  312. FROM `'._DB_PREFIX_.'group_shop` g
  313. INNER JOIN `'._DB_PREFIX_.'group_lang` gl ON (g.id_group=gl.id_group AND gl.id_lang = '.(int)$defaultLanguageId.')
  314. GROUP BY g.id_group,g.id_shop');
  315. else
  316. $DB_customergroup = Db::getInstance()->ExecuteS('SELECT g.id_group,gl.name
  317. FROM `'._DB_PREFIX_.'group` g
  318. INNER JOIN `'._DB_PREFIX_.'group_lang` gl ON (g.id_group=gl.id_group AND gl.id_lang = '.(int)$defaultLanguageId.')
  319. GROUP BY g.id_group');
  320. foreach($DB_customergroup AS $customergroup)
  321. {
  322. $dataDB_customergroup[$customergroup['id_group']]=$customergroup['name'];
  323. $dataDB_customergroupByName[$customergroup['name']]=$customergroup['id_group'];
  324. }
  325. }
  326. for ($current_line = $FIRST_CONTENT_LINE; ((($current_line <= (count($DATA)-1)) && $line = parseCSVLine($importConfig[$TODOfilename]['fieldsep'],$DATA[$current_line])) && ($current_line <= $importlimit)) ; $current_line++)
  327. {
  328. if ($DATA[$current_line]=='') continue;
  329. if (_s('APP_DEBUG_CATALOG_IMPORT'))
  330. {
  331. $time_end = microtime(true);
  332. $time = $time_end - $time_start;
  333. echo "<br/><br/>Start line : $time seconds";
  334. }
  335. $extension_vars = array();
  336. $id_shop_list=$id_shop_list_default;
  337. $line=array_map('cleanQuotes',$line);
  338. if ($scdebug) echo 'line '.$current_line.': ';
  339. $line[count($line)-1]=rtrim($line[count($line)-1]);
  340. $TODO=array();
  341. $TODOSHOP=array();
  342. if ($importConfig[$TODOfilename]['utf8']==1)
  343. utf8_encode_array($line);
  344. $where_shop_list = "";
  345. if(SCMS && findCSVLineValue('id_shop_list')!='' && $importConfig[$TODOfilename]['fornewcat']=='skip' && $importConfig[$TODOfilename]['forfoundcat']=='update')
  346. $where_shop_list = findCSVLineValue('id_shop_list');
  347. $res=array();
  348. $id_category = 0;
  349. switch($importConfig[$TODOfilename]['idby'])
  350. {
  351. case 'catname':
  352. $name = findCSVLineValue('name');
  353. if(!empty($name))
  354. {
  355. $sql = "SELECT c.id_category,c.date_upd
  356. FROM "._DB_PREFIX_."category c
  357. LEFT JOIN "._DB_PREFIX_."category_lang cl on (c.id_category=cl.id_category AND cl.id_lang=".intval($defaultLanguage->id).")
  358. WHERE cl.name='".psql($name)."'
  359. ".(!empty($where_shop_list)? ' AND EXISTS (SELECT * FROM '._DB_PREFIX_.'category_shop cs WHERE c.id_category=cs.id_category AND id_shop IN ('.psql($where_shop_list).'))' : '')."
  360. LIMIT 1";
  361. }
  362. else
  363. $sql = "";
  364. break;
  365. case 'idcategory':
  366. $id_category_find = findCSVLineValue('id_category');
  367. if(!empty($id_category_find))
  368. {
  369. $sql="SELECT c.id_category,c.date_upd
  370. FROM "._DB_PREFIX_."category c
  371. WHERE c.id_category='".intval($id_category_find)."'
  372. ".(!empty($where_shop_list)? ' AND EXISTS (SELECT * FROM '._DB_PREFIX_.'category_shop cs WHERE c.id_category=cs.id_category AND id_shop IN ('.psql($where_shop_list).'))' : '')."
  373. LIMIT 1";
  374. }
  375. else
  376. $sql = "";
  377. break;
  378. case 'path':
  379. $path_find = findCSVLineValue('path');
  380. $c=$path_find;
  381. $c=forceCategoryPathFormat($c);
  382. $c=cleanQuotes($c);
  383. if ((strpos($c,'>')!==false) || in_array(trim($c),$categoriesFirstLevel)) // category path
  384. {
  385. $id_category=(sc_array_key_exists(($c),$categoryIDByPath) ? intval($categoryIDByPath[($c)]) : 0);
  386. }
  387. break;
  388. case 'specialIdentifier':
  389. sc_ext::readCatImportCSVConfigXML('importProcessIdentifier');
  390. break;
  391. }
  392. if($importConfig[$TODOfilename]['idby']!="path")
  393. {
  394. if(!empty($sql))
  395. $res=Db::getInstance()->executeS($sql);
  396. if(!empty($res[0]))
  397. $res = $res[0];
  398. else
  399. $res = array();
  400. }
  401. if (_s('APP_DEBUG_CATALOG_IMPORT'))
  402. {
  403. $time_end = microtime(true);
  404. $time = $time_end - $time_start;
  405. echo "<br/><br/>Results of identification queries : $time seconds";
  406. echo "<br/><br/>".$sql;
  407. echo "<br/><br/>";
  408. print_r($res);
  409. echo "<br/><br/>";
  410. }
  411. if($importConfig[$TODOfilename]['idby']!="path")
  412. {
  413. if (is_array($res) && count($res))
  414. {
  415. $id_category = $res['id_category'];
  416. }
  417. }
  418. if ($scdebug) echo findCSVLineValue('reference').' : '.$id_category.'<br/>';
  419. if ($scdebug) echo 'a';
  420. //$needUnitPriceRatio=(findCSVLineValue('quantity') !== '' ? true : false );
  421. if (SCMS)
  422. {
  423. $id_shop=(int)Configuration::get('PS_SHOP_DEFAULT');
  424. if (findCSVLineValue('id_shop_list')!='')
  425. {
  426. $id_shop_list_in_csv = explode(',',findCSVLineValue('id_shop_list'));
  427. $id_shop_list = $id_shop_list_in_csv;
  428. foreach($id_shop_list_in_csv as $id_shop_to_check)
  429. {
  430. if (sc_array_key_exists($id_category, $cache_id_shop) && in_array($id_shop_to_check, $cache_id_shop[$id_category]))
  431. continue;
  432. $id_shop = $id_shop_to_check;
  433. }
  434. }
  435. }
  436. else
  437. $id_shop=(int)Configuration::get('PS_SHOP_DEFAULT');
  438. $id_category_home = Configuration::get("PS_ROOT_CATEGORY");
  439. if(SCMS)
  440. {
  441. if(empty($shop_home_category[$id_shop]))
  442. {
  443. $shop = new Shop((int)$id_shop);
  444. $shop_home_category[$id_shop] = $shop->id_category;
  445. }
  446. if(!empty($shop_home_category[$id_shop]))
  447. {
  448. $id_category_home = $shop_home_category[$id_shop];
  449. }
  450. }
  451. // CATEGORY EXISTANTE
  452. if(!empty($id_category))
  453. {
  454. // IGNORE LIGNE
  455. if($importConfig[$TODOfilename]['forfoundcat']=='skip')
  456. {
  457. $stats['skipped']++;
  458. if (_s('CAT_IMPORT_IGNORED_LINES')==1)
  459. {
  460. unset($CSVData[$current_line]);
  461. $needSaveTODO=true;
  462. }
  463. continue;
  464. }
  465. // MODIFIE LA CATEGORY
  466. elseif($importConfig[$TODOfilename]['forfoundcat']=='update')
  467. {
  468. if (SCMS)
  469. {
  470. $newcat=new Category($id_category, null, $id_shop);
  471. if ($id_shop==null)
  472. $id_shop_list=array($newcat->id_shop_default);
  473. }
  474. elseif(version_compare(_PS_VERSION_, '1.5.0.0', '>='))
  475. $newcat=new Category($id_category, null,1);
  476. else
  477. $newcat=new Category($id_category);
  478. $newcat->date_upd = date("Y-m-d H:i:s");
  479. $stats['modified']++;
  480. }
  481. // CREE DOUBLON
  482. /*elseif($importConfig[$TODOfilename]['forfoundcat']=='create')
  483. {
  484. if (findCSVLineValue('name')=='') // TODO ajouter msg erreur
  485. {
  486. $stats['skipped']++;
  487. if (_s('CAT_IMPORT_IGNORED_LINES')==1)
  488. {
  489. unset($CSVData[$current_line]);
  490. $needSaveTODO=true;
  491. }
  492. continue;
  493. }
  494. // if combination with same identifier
  495. if ($importConfig[$TODOfilename]['idby']=='catname'
  496. && isCombination()
  497. && $lastIdentifier==findCSVLineValue('name')
  498. )
  499. {
  500. if (SCMS)
  501. {
  502. $newcat=new Category($lastid_category, null, $id_shop);
  503. if ($id_shop==null)
  504. $id_shop_list=array($newcat->id_shop_default);
  505. }
  506. elseif(version_compare(_PS_VERSION_, '1.5.0.0', '>='))
  507. $newcat=new Category($lastid_category, null,1);
  508. else
  509. $newcat=new Category($lastid_category);
  510. $stats['modified']++;
  511. }else{
  512. // create new category with default values
  513. $newcat=new Category();
  514. $newcat->id_parent=$id_category_todo;
  515. $newcat->active=0;
  516. $newcat->link_rewrite[$defaultLanguage->id]='new cat';
  517. if (version_compare(_PS_VERSION_, '1.5.0.0', '>='))
  518. $newcat->id_shop_default = $id_shop_list[0];
  519. foreach($languages AS $lang)
  520. {
  521. $newcat->link_rewrite[$lang['id_lang']]='category';
  522. $newcat->name[$lang['id_lang']]='category';
  523. $newcat->description[$lang['id_lang']]='';
  524. }
  525. $stats['created']++;
  526. }
  527. }*/
  528. }
  529. // NOUVELLE CATEGORY
  530. elseif(empty($id_category))
  531. {
  532. // IGNORE LIGNE
  533. if($importConfig[$TODOfilename]['fornewcat']=='skip')
  534. {
  535. $stats['skipped']++;
  536. if (_s('CAT_IMPORT_IGNORED_LINES')==1)
  537. {
  538. unset($CSVData[$current_line]);
  539. $needSaveTODO=true;
  540. }
  541. continue;
  542. }
  543. // CREE NOUVELLE CATEGORIE
  544. elseif($importConfig[$TODOfilename]['fornewcat']=='create' || $importConfig[$TODOfilename]['fornewcat']=='createall')
  545. {
  546. $id_parent = 0;
  547. $name_cat = "category";
  548. if(fieldInMapping("path"))
  549. {
  550. if (findCSVLineValue('path')=='') // TODO ajouter msg erreur
  551. {
  552. $stats['skipped']++;
  553. if (_s('CAT_IMPORT_IGNORED_LINES')==1)
  554. {
  555. unset($CSVData[$current_line]);
  556. $needSaveTODO=true;
  557. }
  558. continue;
  559. }
  560. else
  561. {
  562. $c = findCSVLineValue("path");
  563. $c = cleanQuotes($c);
  564. $c = forceCategoryPathFormat($c);
  565. $idc = 0;
  566. // IF CATEGORY HAS PARENTS
  567. if (strpos($c, '>') !== false)
  568. {
  569. $exp = explode(">", $c);
  570. $name_cat = $exp[count($exp) - 1];
  571. array_pop($exp);
  572. $c = implode(">", $exp);
  573. $c = forceCategoryPathFormat($c);
  574. if ((strpos($c, '>') !== false) || (in_array(trim($c), $categoriesFirstLevel))) // category path
  575. {
  576. $idc = (sc_array_key_exists(($c), $categoryIDByPath) ? intval($categoryIDByPath[($c)]) : 0);
  577. }
  578. if ($idc != 0) // IF PARENTS EXIST
  579. {
  580. $id_parent = intval($idc);
  581. } // IF PARENTS NOT EXIST & NOT CREATE THEM
  582. elseif ($importConfig[$TODOfilename]['fornewcat'] == 'create') {
  583. $stats['skipped']++;
  584. if (_s('CAT_IMPORT_IGNORED_LINES') == 1) {
  585. unset($CSVData[$current_line]);
  586. $needSaveTODO = true;
  587. }
  588. continue;
  589. } // IF PARENTS NOT EXIST & CREATE THEM
  590. elseif ($importConfig[$TODOfilename]['fornewcat'] == 'createall') {
  591. checkAndCreateCategory($c);
  592. if ((strpos($c, '>') !== false) || (in_array(trim($c), $categoriesFirstLevel))) // category path
  593. {
  594. $idc = (sc_array_key_exists(($c), $categoryIDByPath) ? intval($categoryIDByPath[($c)]) : 0);
  595. }
  596. if ($idc != 0) {
  597. $id_parent = intval($idc);
  598. } else {
  599. $stats['skipped']++;
  600. if (_s('CAT_IMPORT_IGNORED_LINES') == 1) {
  601. unset($CSVData[$current_line]);
  602. $needSaveTODO = true;
  603. }
  604. continue;
  605. }
  606. }
  607. }
  608. else
  609. {
  610. $id_parent = $id_category_home;
  611. $name_cat = trim($c);
  612. }
  613. }
  614. }
  615. elseif(fieldInMapping("name") && fieldInMapping("parents"))
  616. {
  617. if (findCSVLineValue('name')=='') // TODO ajouter msg erreur
  618. {
  619. $stats['skipped']++;
  620. if (_s('CAT_IMPORT_IGNORED_LINES')==1)
  621. {
  622. unset($CSVData[$current_line]);
  623. $needSaveTODO=true;
  624. }
  625. continue;
  626. }
  627. else
  628. $name_cat = trim(findCSVLineValue('name'));
  629. if (findCSVLineValue('parents')!='')
  630. {
  631. $c=findCSVLineValue('parents');
  632. $c=forceCategoryPathFormat($c);
  633. $c=cleanQuotes($c);
  634. $idc=0;
  635. if ((strpos($c,'>')!==false) || in_array(trim($c),$categoriesFirstLevel)) // category path
  636. {
  637. $idc=(sc_array_key_exists(($c),$categoryIDByPath) ? intval($categoryIDByPath[($c)]) : 0);
  638. }
  639. if ($idc!=0) // IF PARENTS EXIST
  640. {
  641. $id_parent=intval($idc);
  642. }
  643. // IF PARENTS NOT EXIST & NOT CREATE THEM
  644. elseif($importConfig[$TODOfilename]['fornewcat']=='create')
  645. {
  646. $stats['skipped']++;
  647. if (_s('CAT_IMPORT_IGNORED_LINES')==1)
  648. {
  649. unset($CSVData[$current_line]);
  650. $needSaveTODO=true;
  651. }
  652. continue;
  653. }
  654. // IF PARENTS NOT EXIST & CREATE THEM
  655. elseif($importConfig[$TODOfilename]['fornewcat']=='createall')
  656. {
  657. checkAndCreateCategory($c);
  658. if ((strpos($c,'>')!==false) || (in_array(trim($c),$categoriesFirstLevel))) // category path
  659. {
  660. $idc=(sc_array_key_exists(($c),$categoryIDByPath) ? intval($categoryIDByPath[($c)]) : 0);
  661. }
  662. if ($idc!=0)
  663. {
  664. $id_parent=intval($idc);
  665. }
  666. else
  667. {
  668. $stats['skipped']++;
  669. if (_s('CAT_IMPORT_IGNORED_LINES')==1)
  670. {
  671. unset($CSVData[$current_line]);
  672. $needSaveTODO=true;
  673. }
  674. continue;
  675. }
  676. }
  677. }
  678. else
  679. $id_parent = $id_category_home;
  680. }
  681. if (empty($id_parent)) // TODO ajouter msg erreur
  682. {
  683. $stats['skipped']++;
  684. if (_s('CAT_IMPORT_IGNORED_LINES')==1)
  685. {
  686. unset($CSVData[$current_line]);
  687. $needSaveTODO=true;
  688. }
  689. continue;
  690. }
  691. if(empty($name_cat))
  692. $name_cat = "Category";
  693. // create new category with default values
  694. $newcat=new Category();
  695. //$newcat->id_parent=$id_category_todo;
  696. $newcat->id_parent=$id_parent;
  697. $newcat->active=(int)_s('CAT_IMPORT_CATEGCREA_ACTIVE');
  698. if (version_compare(_PS_VERSION_, '1.5.0.0', '>='))
  699. $newcat->id_shop_default = $id_shop_list[0];
  700. $newcat->name[$defaultLanguage->id]=trim($name_cat);
  701. $newcat->link_rewrite[$defaultLanguage->id]=link_rewrite(($name_cat));
  702. foreach($languages AS $lang)
  703. {
  704. $newcat->name[$lang['id_lang']]=trim($name_cat);
  705. $newcat->link_rewrite[$lang['id_lang']]=link_rewrite(($name_cat));
  706. $newcat->description[$lang['id_lang']]='';
  707. }
  708. $stats['created']++;
  709. }
  710. }
  711. if (SCMS)
  712. {
  713. if(empty($newcat->id))
  714. $newcat->id_shop_list=$id_shop_list;
  715. else
  716. $newcat->id_shop_list=$id_shop;
  717. if(!is_array($newcat->id_shop_list))
  718. $newcat->id_shop_list = array($newcat->id_shop_list);
  719. }
  720. foreach($line AS $key => $value)
  721. {
  722. $value=trim($value);
  723. $GLOBALS['import_value']=$value;
  724. if ($scdebug && !sc_array_key_exists($key,$firstLineData)) echo 'ERR'.$key.'x'.$current_line.'x'.join(';',$line).'xxx'.join(';',array_keys($firstLineData)).'<br/>';
  725. if (sc_array_key_exists($key,$firstLineData) && sc_in_array($firstLineData[$key],$mappingData['CSVArray'],"catWinCatImportProcess_CSVArray"))
  726. {
  727. if ($scdebug) echo 'c';
  728. @$id_lang=intval($getIDlangByISO[$mappingData['CSV2DBOptions'][$firstLineData[$key]]]);
  729. $switchObject=$mappingData['CSV2DB'][$firstLineData[$key]];
  730. switch($switchObject)
  731. {
  732. case 'active':$newcat->active=intval(getBoolean($value));break;
  733. case 'position':$newcat->position=intval($value);break;
  734. case 'id_parent':
  735. if(Category::categoryExists((int)$value))
  736. $newcat->id_parent=intval($value);
  737. break;
  738. case 'link_rewrite':if ($value!='') $newcat->link_rewrite[$id_lang]=link_rewrite($value);break;
  739. case 'name':
  740. escapeCharForPS($value);
  741. $newcat->name[$id_lang]=$value;
  742. if (!sc_in_array('link_rewrite',$mappingData['DBArray'],"catWinCatImportProcess_DBArray"))
  743. {
  744. foreach($languages AS $lang)
  745. {
  746. if(_s('CAT_SEO_NAME_TO_URL'))
  747. $newcat->link_rewrite[$id_lang]=link_rewrite($value);
  748. }
  749. }
  750. break;
  751. case 'description':
  752. escapeCharForPS($value,true);
  753. $newcat->description[$id_lang]=$value;break;
  754. case 'meta_title':escapeCharForPS($value);$newcat->meta_title[$id_lang]=$value;break;
  755. case 'meta_description':escapeCharForPS($value);$newcat->meta_description[$id_lang]=$value;break;
  756. case 'meta_keywords':escapeCharForPS($value);$newcat->meta_keywords[$id_lang]=$value;break;
  757. case 'id_shop_default':$newcat->id_shop_default=(int)$value;break;
  758. /*case 'parents':
  759. $value=trim(trim(trim($value),'>'));
  760. if ($value!='' && !empty($newcat->id))
  761. {
  762. $c=$value;
  763. //checkAndCreateCategory($c);
  764. $c=forceCategoryPathFormat($c);
  765. $c=cleanQuotes($c);
  766. $idc=0;
  767. if ((strpos($c,'>')!==false) || (in_array(trim($c),$categoriesFirstLevel))) // category path
  768. {
  769. $idc=(sc_array_key_exists(($c),$categoryIDByPath) ? intval($categoryIDByPath[($c)]) : 0);
  770. }
  771. if ($idc!=0)
  772. {
  773. $newcat->id_parent=intval($idc);
  774. }
  775. }
  776. break;
  777. case 'path':
  778. $value=trim(trim(trim($value),'>'));
  779. if ($value!='' && !empty($newcat->id))
  780. {
  781. $c=$value;
  782. //checkAndCreateCategory($c);
  783. $c=cleanQuotes($c);
  784. $c=forceCategoryPathFormat($c);
  785. $idc=0;
  786. // IF CATEGORY HAS PARENTS
  787. if(strpos($c,'>')!==false)
  788. {
  789. $exp = explode(">",$c);
  790. $name_cat = $exp[count($exp)-1];
  791. array_pop($exp);
  792. $c = implode(">",$exp);
  793. $c=forceCategoryPathFormat($c);
  794. if ((strpos($c,'>')!==false) || (in_array(trim($c),$categoriesFirstLevel))) // category path
  795. {
  796. $idc=(sc_array_key_exists(($c),$categoryIDByPath) ? intval($categoryIDByPath[($c)]) : 0);
  797. }
  798. if ($idc!=0)
  799. {
  800. //$newcat->id_parent=intval($idc);
  801. foreach($languages AS $lang)
  802. $newcat->name[$lang['id_lang']]=$name_cat;
  803. }
  804. }
  805. else
  806. {
  807. // IF CATEGORY NOT EXIST
  808. if(!( (in_array(trim($c),$categoriesFirstLevel)) || sc_array_key_exists(forceCategoryPathFormat($c),$categoryIDByPath) ))
  809. {
  810. //$newcat->id_parent=$id_category_home;
  811. foreach($languages AS $lang)
  812. $newcat->name[$lang['id_lang']]=$c;
  813. }
  814. }
  815. }
  816. break;*/
  817. default:
  818. sc_ext::readCatImportCSVConfigXML('importProcessCategory');
  819. }
  820. /* inutile pour le moment, on gère champ par champ
  821. if (version_compare(_PS_VERSION_, '1.5.0.0', '>=')
  822. && ($def = ObjectModel::getDefinition('Product'))
  823. && isset($def['fields'][$switchObject]['shop'])
  824. && $def['fields'][$switchObject]['shop'])
  825. {
  826. $TODOSHOP[]='`'.$field."`='".psql($value)."'";
  827. }*/
  828. }
  829. }
  830. if ($scdebug) echo 'd';
  831. if (_s('APP_DEBUG_CATALOG_IMPORT'))
  832. {
  833. $time_end = microtime(true);
  834. $time = $time_end - $time_start;
  835. echo "<br/><br/>Before category->save : $time seconds";
  836. }
  837. foreach($languages AS $lang)
  838. if ($newcat->link_rewrite[$lang['id_lang']]=='')
  839. $newcat->link_rewrite[$lang['id_lang']] = 'category';
  840. if ($newcat->save())
  841. {
  842. $categories[trim(hideCategoryPosition($newcat->name[$defaultLanguage->id]))]=array('id_category' => $newcat->id, 'id_parent' => $newcat->id_parent);
  843. $categoryNameByID[$newcat->id]=hideCategoryPosition($newcat->name[$defaultLanguage->id]);
  844. $categoriesProperties[$newcat->id]=array('id_category' => $newcat->id, 'id_parent' => $newcat->id_parent);
  845. $categoryIDByPath[forceCategoryPathFormat(getCategoryPath($newcat->id))]=$newcat->id;
  846. if ($newcat->level_depth==1) $categoriesFirstLevel[]=hideCategoryPosition($newcat->name[$defaultLanguage->id]);
  847. if (_s('APP_DEBUG_CATALOG_IMPORT'))
  848. {
  849. $time_end = microtime(true);
  850. $time = $time_end - $time_start;
  851. echo "<br/><br/>After product->save : $time seconds";
  852. }
  853. $lastid_category=$newcat->id;
  854. if (_s('APP_COMPAT_HOOK'))
  855. SCI::hookExec('categoryUpdate', array('category' => $newcat));
  856. if (_s('APP_DEBUG_CATALOG_IMPORT'))
  857. {
  858. $time_end = microtime(true);
  859. $time = $time_end - $time_start;
  860. echo "<br/><br/>After categoryUpdate Hook : $time seconds";
  861. }
  862. if ($scdebug) echo 'e';
  863. if (_s('APP_DEBUG_CATALOG_IMPORT'))
  864. {
  865. $time_end = microtime(true);
  866. $time = $time_end - $time_start;
  867. echo "<br/><br/>Before category TODO : $time seconds";
  868. }
  869. $TODO[]="UPDATE "._DB_PREFIX_."category SET `date_upd`='".psql(date("Y-m-d H:i:s"))."' WHERE id_category=".intval($newcat->id)."";
  870. if(SCMS)
  871. $TODO[]="UPDATE "._DB_PREFIX_."category_shop SET `date_upd`='".psql(date("Y-m-d H:i:s"))."' WHERE id_category=".intval($newcat->id)." AND id_shop IN (".psql(join(',',$id_shop_list)).")";
  872. foreach($TODO AS $sql)
  873. {
  874. $sql=str_replace('ID_PRODUCT',$newcat->id,$sql);
  875. Db::getInstance()->Execute($sql);
  876. }
  877. if (_s('APP_DEBUG_CATALOG_IMPORT'))
  878. {
  879. $time_end = microtime(true);
  880. $time = $time_end - $time_start;
  881. echo "<br/><br/>After category TODO : $time seconds";
  882. }
  883. if(!empty($newcat->id))
  884. {
  885. if (SCMS)
  886. {
  887. $newcat=new Category($newcat->id, null, $id_shop);
  888. if ($id_shop==null)
  889. $id_shop_list=array($newcat->id_shop_default);
  890. }
  891. elseif(version_compare(_PS_VERSION_, '1.5.0.0', '>='))
  892. $newcat=new Category($newcat->id, null,1);
  893. else
  894. $newcat=new Category($newcat->id);
  895. $newcat->date_upd = date("Y-m-d H:i:s");
  896. }
  897. $imagesListFromCSVLine=array(); // contains images to link to the current combination
  898. $imagesListFromDB=array(); // contains images of current product
  899. sc_ext::readCatImportCSVConfigXML('importProcessInitRowVars');
  900. foreach($line AS $key => $value)
  901. {
  902. $GLOBALS['import_value']=$value;
  903. $TODO=array();
  904. if ($scdebug && !in_array($key,array_keys($firstLineData))) {print_r($line);}
  905. if (sc_array_key_exists($key,$firstLineData) && sc_in_array($firstLineData[$key],$mappingData['CSVArray'],"catWinCatImportProcess_CSVArray"))
  906. {
  907. @$id_lang=intval($getIDlangByISO[$mappingData['CSV2DBOptions'][$firstLineData[$key]]]);
  908. $switchObject=$mappingData['CSV2DB'][$firstLineData[$key]];
  909. if (_s('APP_DEBUG_CATALOG_IMPORT'))
  910. {
  911. $time_end = microtime(true);
  912. $time = $time_end - $time_start;
  913. echo "<br/><br/>Before ".$switchObject." column : $time seconds";
  914. }
  915. switch($switchObject)
  916. {
  917. case 'ActionCleanGroups':
  918. if ($value!='' && $value!='0' && $newcat->id)
  919. {
  920. $newcat->cleanGroups();
  921. }
  922. break;
  923. case 'customergroups':
  924. if ($value!='' && $value!='0' && $newcat->id)
  925. {
  926. $group_list = explode($importConfig[$TODOfilename]['valuesep'],$value);
  927. $groups = array();
  928. foreach($group_list as $group)
  929. {
  930. $id_group = (sc_array_key_exists($group,$dataDB_customergroupByName)? intval($dataDB_customergroupByName[$group]):0);
  931. if(!empty($id_group))
  932. $groups[] = $id_group;
  933. }
  934. if(!empty($groups) && count($groups)>0)
  935. $newcat->addGroups($groups);
  936. }
  937. break;
  938. case 'ActionDeleteImages':
  939. if ($value!='' && $value!='0' && $newcat->id)
  940. {
  941. $newcat->deleteImage(true);
  942. }
  943. break;
  944. case 'imageURL':
  945. if ($value!='')
  946. {
  947. $imagefilename=findImageFileName($value);
  948. if($imagefilename==false)
  949. {
  950. $imagefilename = tempnam(_PS_TMP_IMG_DIR_, 'ps_import');
  951. $copy = copy($value, $imagefilename);
  952. }
  953. $image_name = _PS_CAT_IMG_DIR_.(int)$newcat->id.'.jpg';
  954. @unlink($image_name);
  955. if(copy ( $imagefilename , $image_name ))
  956. {
  957. $images_types = ImageType::getImagesTypes('categories');
  958. foreach ($images_types as $k => $image_type)
  959. {
  960. if (version_compare(_PS_VERSION_, '1.5.0.0', '>='))
  961. {
  962. ImageManager::resize(
  963. $image_name,
  964. _PS_CAT_IMG_DIR_.$newcat->id.'-'.stripslashes($image_type['name']).'.jpg',
  965. (int)$image_type['width'], (int)$image_type['height']
  966. );
  967. if($generate_hight_dpi_images)
  968. ImageManager::resize(
  969. $image_name,
  970. _PS_CAT_IMG_DIR_.$newcat->id.'-'.stripslashes($image_type['name']).'2x.jpg',
  971. (int)$image_type['width']*2, (int)$image_type['height']*2
  972. );
  973. }
  974. else
  975. imageResize($image_name, _PS_CAT_IMG_DIR_.$newcat->id.'-'.stripslashes($image_type['name']).'.jpg', (int)($image_type['width']), (int)($image_type['height']));
  976. }
  977. }
  978. }
  979. break;
  980. default:
  981. sc_ext::readCatImportCSVConfigXML('importProcessCombination');
  982. }
  983. $TODO[]="UPDATE "._DB_PREFIX_."category SET `date_upd`='".psql(date("Y-m-d H:i:s"))."' WHERE id_category=".intval($newcat->id)."";
  984. if(SCMS)
  985. $TODO[]="UPDATE "._DB_PREFIX_."category_shop SET `date_upd`='".psql(date("Y-m-d H:i:s"))."' WHERE id_category=".intval($newcat->id)." AND id_shop IN (".psql(join(',',$id_shop_list)).")";
  986. foreach($TODO AS $sql)
  987. Db::getInstance()->Execute($sql);
  988. if (_s('APP_DEBUG_CATALOG_IMPORT'))
  989. {
  990. $time_end = microtime(true);
  991. $time = $time_end - $time_start;
  992. echo "<br/><br/>After ".$switchObject." column : $time seconds";
  993. }
  994. }
  995. }// foreach cols
  996. if (_s('APP_DEBUG_CATALOG_IMPORT'))
  997. {
  998. $time_end = microtime(true);
  999. $time = $time_end - $time_start;
  1000. echo "<br/><br/>Fields processins after category creation : $time seconds";
  1001. }
  1002. if($skip_line_scas)
  1003. continue;
  1004. foreach($line AS $key => $value)
  1005. {
  1006. $value = trim($value);
  1007. if (sc_array_key_exists($key, $firstLineData) && sc_in_array($firstLineData[$key],$mappingData['CSVArray'],"catWinCatImportProcess_CSVArray")
  1008. ) {
  1009. $switchObject = $mappingData['CSV2DB'][$firstLineData[$key]];
  1010. sc_ext::readCatImportCSVConfigXML('importProcessAfterCreateAll');
  1011. }
  1012. }
  1013. if (SCMS && $importConfig[$TODOfilename]['forfoundcat']!='skip' && ( (!sc_array_key_exists($id_category,$cache_id_shop) && count($id_shop_list_in_csv)>1) || count($cache_id_shop[$id_category]) < count($id_shop_list_in_csv)-1))
  1014. {
  1015. //mise en cache
  1016. $cache_id_shop[$id_category][] = $id_shop;
  1017. $current_line--;
  1018. }else{
  1019. unset($CSVData[$current_line]);
  1020. file_put_contents(SC_CSV_IMPORT_DIR."category/".$TODOfilename,join("\n",$CSVData));
  1021. }
  1022. $needSaveTODO=false;
  1023. }else{
  1024. if ($scdebug) echo 'Z<br/>';
  1025. }
  1026. if ($scdebug) echo 'f<br/>';
  1027. if (_s('APP_DEBUG_CATALOG_IMPORT'))
  1028. {
  1029. $time_end = microtime(true);
  1030. $time = $time_end - $time_start;
  1031. echo "<br/><br/>Total time for the line: $time seconds";
  1032. if(!empty($id_product))
  1033. die();
  1034. }
  1035. $updated_categories[$id_category]=$id_category;
  1036. } // FIN BOUCLE LINE
  1037. // PM Cache
  1038. if(!empty($updated_categories))
  1039. ExtensionPMCM::clearFromIdsCategory($updated_categories);
  1040. // DELETE TODO CATEGORY
  1041. /*if(!empty($id_category_todo))
  1042. {
  1043. $sql="SELECT COUNT(id_category) AS nb FROM "._DB_PREFIX_."category WHERE id_parent = ".intval($id_category_todo);
  1044. $res = Db::getInstance()->executeS($sql);
  1045. if(empty($res[0]["nb"]))
  1046. {
  1047. $categoryTODO = new Category((int)$id_category_todo);
  1048. if (SCMS)
  1049. {
  1050. $categoryTODO->id_shop_list = $categoryTODO->getAssociatedShops();
  1051. $categoryTODO->deleteLite();
  1052. $categoryTODO->deleteImage(true);
  1053. $categoryTODO->cleanGroups();
  1054. $categoryTODO->cleanAssoProducts();
  1055. // Delete associated restrictions on cart rules
  1056. CartRule::cleanProductRuleIntegrity('categories', array($categoryTODO->id));
  1057. /* Delete Categories in GroupReduction */
  1058. /*if (GroupReduction::getGroupsReductionByCategoryId((int)$categoryTODO->id))
  1059. GroupReduction::deleteCategory($categoryTODO->id);
  1060. Hook::exec('actionCategoryDelete', array('category' => $categoryTODO));
  1061. }
  1062. else
  1063. $categoryTODO->delete();
  1064. $sql="SELECT (MAX(id_category)+1) as maxId FROM "._DB_PREFIX_."category";
  1065. $resMax = Db::getInstance()->executeS($sql);
  1066. if(!empty($resMax[0]["maxId"]) && is_numeric($resMax[0]["maxId"]))
  1067. {
  1068. $sql="ALTER TABLE "._DB_PREFIX_."category AUTO_INCREMENT = ".(int)$resMax[0]["maxId"];
  1069. @Db::getInstance()->execute($sql);
  1070. }
  1071. }
  1072. }*/
  1073. fixLevelDepth();
  1074. if (version_compare(_PS_VERSION_, '1.4.0.17', '>='))
  1075. Category::regenerateEntireNtree();
  1076. if ($needSaveTODO)
  1077. file_put_contents(SC_CSV_IMPORT_DIR."category/".$TODOfilename,join("\n",$CSVData));
  1078. echo '<b>'._l('Stats:').'</b><br/>';
  1079. $msg = _l('New categories:').' '.$stats['created'].'<br/>';
  1080. $msg.= _l('Modified categories:').' '.$stats['modified'].'<br/>';
  1081. $msg.= _l('Skipped lines:').' '.$stats['skipped'].'<br/>';
  1082. echo $msg.'<br/>';
  1083. if ((count($CSVData)==1) || (count($CSVData)==2 && $CSVData[0]==join('',$CSVData)) || (filesize(SC_CSV_IMPORT_DIR."category/".$TODOfilename)==0))
  1084. {
  1085. @unlink(SC_CSV_IMPORT_DIR."category/".$TODOfilename);
  1086. echo _l('All categories have been imported. The TODO file is deleted.').'<br/><br/>';
  1087. echo '<b>'._l('End of import process.').'</b><br/><br/>';
  1088. echo '<b>'._l('You need to refresh the page, click here:').' <a target="_top" href="index.php">Go!</a></b><br/>';
  1089. echo '<script type="text/javascript">window.top.displayCatOptions();window.top.stopCatAutoImport(true);</script>';
  1090. $msg2 = 'All categories have been imported.';
  1091. }else{
  1092. echo '<b>'._l('There are still categories 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/>';
  1093. echo '<script type="text/javascript">window.top.displayCatOptions();autoCatImportUnit=999999;window.top.prepareCatNextStep('.($stats['created']+$stats['modified']+$stats['skipped']==0?0:filesize(SC_CSV_IMPORT_DIR."category/".$TODOfilename)).');</script>';
  1094. // TODO add autoImportUnit=999999; to boost import
  1095. $msg2 = 'Need fix and run import again.';
  1096. }
  1097. $msg3='';
  1098. addToHistory('catalog_catimport','catimport','','','','','Imported file: '.$TODOfilename.'<br/>'.$msg.$msg2.($msg3!=''?'<br/>'.$msg3:''),'');
  1099. if (_s('APP_DEBUG_CATALOG_IMPORT'))
  1100. {
  1101. $time_end = microtime(true);
  1102. $time = $time_end - $time_start;
  1103. echo "<br/><br/>Total: $time seconds";
  1104. }
  1105. echo '</div>';
  1106. break;
  1107. }