PageRenderTime 63ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 1ms

/modules/storecommander/ead6f6fce09/SC/lib/cat/win-import/cat_win-import_process.php

https://gitlab.com/ptisky/API_prestashop
PHP | 1109 lines | 989 code | 40 blank | 80 comment | 179 complexity | a54b26e1fd764fa58c0a2c82c2388f2d 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. 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(!empty($CRON))
  31. Context::getContext()->employee = new Employee( Tools::getValue('id_employee') );
  32. if(SCAS)
  33. $stock_manager = StockManagerFactory::getManager();
  34. if (version_compare(_PS_VERSION_, '1.5.0.0', '<'))
  35. include_once(SC_PS_PATH_DIR.'images.inc.php');
  36. include_once(SC_DIR.'lib/php/parsecsv.lib.php');
  37. require_once(SC_DIR.'lib/cat/win-import/cat_win-import_tools.php');
  38. switch($action){
  39. case 'conf_delete':
  40. $imp_opt_files=Tools::getValue('imp_opt_files','');
  41. if ($imp_opt_files=='') die(_l('You should mark at least one file to delete'));
  42. $imp_opt_file_array=preg_split('/;/',$imp_opt_files);
  43. foreach($imp_opt_file_array as $imp_opt_file)
  44. {
  45. if ($imp_opt_file!='')
  46. {
  47. if (@unlink(SC_CSV_IMPORT_DIR.$imp_opt_file))
  48. {
  49. echo $imp_opt_file." "._l('deleted')."\n";
  50. }else{
  51. echo _l("Unable to delete this file, please check write permissions:")." ".$imp_opt_file."\n";
  52. }
  53. }
  54. }
  55. break;
  56. case 'mapping_load':
  57. echo loadMapping(Tools::getValue('filename',''));
  58. break;
  59. case 'mapping_delete':
  60. $filename=str_replace('.map.xml','',Tools::getValue('filename'));
  61. @unlink(SC_CSV_IMPORT_DIR.$filename.'.map.xml');
  62. break;
  63. case 'mapping_saveas':
  64. $filename=str_replace('.map.xml','',Tools::getValue('filename'));
  65. @unlink(SC_CSV_IMPORT_DIR.$filename.'.map.xml');
  66. $mapping=preg_split('/;/',$mapping);
  67. $content='<mapping><id_lang>'.(int)$sc_agent->id_lang.'</id_lang>';
  68. foreach($mapping AS $map)
  69. {
  70. $val=preg_split('/,/',$map);
  71. if (count($val)==3)
  72. {
  73. $content.='<map>';
  74. $content.='<csvname><![CDATA['.$val[0].']]></csvname>';
  75. $content.='<dbname><![CDATA['.$val[1].']]></dbname>';
  76. $content.='<options><![CDATA['.$val[2].']]></options>';
  77. $content.='</map>';
  78. }
  79. }
  80. $content.='</mapping>';
  81. file_put_contents(SC_CSV_IMPORT_DIR.$filename.'.map.xml', $content);
  82. echo _l('Data saved!');
  83. break;
  84. case 'addSupplier':
  85. $data=Tools::getValue('data','');
  86. if ($data!='')
  87. {
  88. addSupplier($data);
  89. die('<b>'._l('Supplier(s) created!').'</b>');
  90. }
  91. break;
  92. case 'addManufacturer':
  93. $data=Tools::getValue('data','');
  94. if ($data!='')
  95. {
  96. addManufacturer($data);
  97. die('<b>'._l('Manufacturer(s) created!').'</b>');
  98. }
  99. break;
  100. case 'addFeature':
  101. $data=Tools::getValue('data','');
  102. if ($data!='')
  103. {
  104. $features=explode("y|y",$data);
  105. sort($features);
  106. foreach($features AS $feature)
  107. {
  108. if ($feature!='')
  109. {
  110. $newFeature=new Feature();
  111. $newFeature->name[intval(Configuration::get('PS_LANG_DEFAULT'))]=trim(cleanQuotes(Tools::substr($feature,0,128)));
  112. $newFeature->save();
  113. }
  114. }
  115. die('<b>'._l('Feature(s) created!').'</b>');
  116. }
  117. break;
  118. case 'addFeatureValue':
  119. $data=Tools::getValue('data','');
  120. if ($data!='')
  121. {
  122. addFeatureValue($data);
  123. die('<b>'._l('Feature(s) created!').'</b>');
  124. }
  125. break;
  126. case 'addAttributeGroup':
  127. $data=Tools::getValue('data','');
  128. if ($data!='')
  129. {
  130. $groups=explode("y|y",$data);
  131. sort($groups);
  132. foreach($groups AS $group)
  133. {
  134. if ($group!='')
  135. {
  136. $newGroup=new AttributeGroup();
  137. if (version_compare(_PS_VERSION_, '1.5.0', '>='))
  138. {
  139. foreach($languages AS $lang)
  140. {
  141. $newgroup->name[$lang['id_lang']]=cleanQuotes(Tools::substr($group,0,64));
  142. $newgroup->public_name[$lang['id_lang']]=cleanQuotes(Tools::substr($group,0,64));
  143. }
  144. $newgroup->group_type='select';
  145. }
  146. $newGroup->save();
  147. }
  148. }
  149. die('<b>'._l('Attribute group(s) created!').'</b>');
  150. }
  151. break;
  152. case 'addAttributeValue':
  153. $data=Tools::getValue('data','');
  154. if ($data!='')
  155. {
  156. addAttributeValue($data);
  157. die('<b>'._l('Attribute(s) created!').'</b>');
  158. }
  159. break;
  160. case 'mapping_process':
  161. echo '<div style="width: 100%; height: 100%; overflow: auto;">';
  162. if (_s('APP_DEBUG_CATALOG_IMPORT'))
  163. $time_start = microtime(true);
  164. if (_s('APP_DEBUG_CATALOG_IMPORT'))
  165. {
  166. // Affichage des modules greffer au hook UpdateProduct
  167. if (version_compare(_PS_VERSION_,'1.5.0.0','>='))
  168. $hook_id = Hook::getIdByName("actionProductUpdate");
  169. else
  170. $hook_id = Hook::get("actionProductUpdate");
  171. if(!empty($hook_id))
  172. {
  173. $hook = new Hook((int)$hook_id);
  174. $modules = $hook->getHookModuleList();
  175. if(!empty($modules[(int)$hook_id]))
  176. {
  177. echo "<br/><br/>Liste des modules :";
  178. foreach($modules[(int)$hook_id] as $module)
  179. {
  180. echo "<br/>".$module["name"]." (".($module["active"]?"Activé":"Désactivé").")";
  181. }
  182. }
  183. }
  184. }
  185. checkDB();
  186. $scdebug=false;
  187. global $switchObject; // variable for custom import fields check
  188. $switchObject='';
  189. global $TODO; // actions
  190. $TODO=array();
  191. global $id_product,$id_product_attribute;
  192. $id_product=0; $id_product_attribute=0;
  193. $warehousesArray = array();
  194. $productsStockAdvancedTypeArray = array();
  195. $defaultLanguageId = intval(Configuration::get('PS_LANG_DEFAULT'));
  196. $defaultLanguage=new Language($defaultLanguageId);
  197. $getIDlangByISO=array();
  198. foreach($languages AS $lang)
  199. {
  200. $getIDlangByISO[$lang['iso_code']]=$lang['id_lang'];
  201. }
  202. $files = array_diff( scandir( SC_CSV_IMPORT_DIR ), array_merge( Array( ".", "..", "index.php", ".htaccess", SC_CSV_IMPORT_CONF)) );
  203. readImportConfigXML($files);
  204. $filename=Tools::getValue('filename',0);
  205. if ($create_categories <= 0) $create_categories=intval($importConfig[$filename]['createcategories']);
  206. $importlimit=intval(Tools::getValue('importlimit',0));
  207. $importlimit=($importlimit > 0 ? $importlimit : intval($importConfig[$filename]['importlimit']));
  208. if ($importConfig[$filename]['firstlinecontent']!='') $importlimit--;
  209. if ($CRON) $mapping=loadMapping($importConfig[$filename]['mapping']);
  210. if ($filename===0 || $mapping=='')
  211. die(_l('You have to select a file and a mapping.'));
  212. $mapping = str_replace("&amp;", "&", $mapping);
  213. $mappingDataArray=explode(';',$mapping);
  214. $mappingData=array('CSVArray' => array(),'DBArray' => array(),'CSV2DB' => array(),'CSV2DBOptions' => array(),'CSV2DBOptionsMerged' => array());
  215. foreach($mappingDataArray AS $val)
  216. {
  217. if ($val!='')
  218. {
  219. $tmp=explode(',',$val);
  220. $tmp2=$tmp[0];
  221. escapeCharForPS($tmp2);
  222. $mappingData['CSVArray'][]=$tmp2;
  223. $mappingData['DBArray'][]=$tmp[1];
  224. $mappingData['CSV2DB'][$tmp[0]]=$tmp[1];
  225. $mappingData['CSV2DBOptions'][$tmp[0]]=$tmp[2];
  226. $mappingData['CSV2DBOptionsMerged'][$tmp[0]]=$tmp[1].'_'.$tmp[2];
  227. }
  228. }
  229. // check mapping
  230. switch ($importConfig[$filename]['idby']){
  231. case'prodname':
  232. if (!sc_in_array('name_'.$defaultLanguage->iso_code,$mappingData['CSV2DBOptionsMerged'],"catWinImportProcess_CSV2DBOptionsMerged"))
  233. die(_l('Wrong mapping, mapping should contain the field name in ').$defaultLanguage->iso_code.'<br/><br/>'.
  234. _l('For each line of the mapping you need to double click in the Database field column to fill the mapping.').'<br/><br/>'.
  235. _l('If the cell in the Options column becomes blue, you need to edit this cell and complete the mapping.'));
  236. break;
  237. case'prodref':
  238. if (!sc_in_array('reference',$mappingData['DBArray'],"catWinImportProcess_DBArray"))
  239. die(_l('Wrong mapping, mapping should contain the field reference'));
  240. break;
  241. case'prodrefthenprodname':
  242. if (!sc_in_array('reference',$mappingData['DBArray'],"catWinImportProcess_DBArray") || !sc_in_array('name_'.$defaultLanguage->iso_code,$mappingData['CSV2DBOptionsMerged'],"catWinImportProcess_CSV2DBOptionsMerged"))
  243. die(_l('Wrong mapping, mapping should contain the fields reference and name in ').$defaultLanguage->iso_code);
  244. break;
  245. case'suprefthenprodname':
  246. if (!sc_in_array('supplier_reference',$mappingData['DBArray'],"catWinImportProcess_DBArray") || !sc_in_array('name_'.$defaultLanguage->iso_code,$mappingData['CSV2DBOptionsMerged'],"catWinImportProcess_CSV2DBOptionsMerged"))
  247. die(_l('Wrong mapping, mapping should contain the fields supplier_reference and name in ').$defaultLanguage->iso_code);
  248. break;
  249. case'supref':
  250. if (!sc_in_array('supplier_reference',$mappingData['DBArray'],"catWinImportProcess_DBArray"))
  251. die(_l('Wrong mapping, mapping should contain the field supplier_reference'));
  252. break;
  253. case'prodrefandsupref':
  254. if (!sc_in_array('reference',$mappingData['DBArray'],"catWinImportProcess_DBArray") || !sc_in_array('supplier_reference',$mappingData['DBArray'],"catWinImportProcess_DBArray"))
  255. die(_l('Wrong mapping, mapping should contain the fields reference and supplier_reference'));
  256. break;
  257. case'prodnameandsupref':
  258. if (!sc_in_array('name_'.$defaultLanguage->iso_code,$mappingData['CSV2DBOptionsMerged'],"catWinImportProcess_CSV2DBOptionsMerged") || !sc_in_array('supplier_reference',$mappingData['DBArray'],"catWinImportProcess_DBArray"))
  259. die(_l('Wrong mapping, mapping should contain the fields supplier_reference and name in ').$defaultLanguage->iso_code);
  260. break;
  261. case'idproduct':
  262. if (!sc_in_array('id_product',$mappingData['DBArray'],"catWinImportProcess_DBArray"))
  263. die(_l('Wrong mapping, mapping should contain the field: id_product'));
  264. break;
  265. case'idproductattribute':
  266. if (!sc_in_array('id_product_attribute',$mappingData['DBArray'],"catWinImportProcess_DBArray"))
  267. die(_l('Wrong mapping, mapping should contain the field id_product_attribute'));
  268. break;
  269. case'ean13':
  270. if (!sc_in_array('EAN13',$mappingData['DBArray'],"catWinImportProcess_DBArray"))
  271. die(_l('Wrong mapping, mapping should contain the EAN field'));
  272. break;
  273. case'upc':
  274. if (!sc_in_array('upc',$mappingData['DBArray'],"catWinImportProcess_DBArray"))
  275. die(_l('Wrong mapping, mapping should contain the UPC field'));
  276. break;
  277. }
  278. // create TODO file
  279. if (substr($filename,strlen($filename)-9,9)=='.TODO.csv' && !file_exists(SC_CSV_IMPORT_DIR.$filename))
  280. die(_l('The TODO file has been deleted, please select the original CSV file.'));
  281. if (substr($filename,strlen($filename)-9,9)!='.TODO.csv')
  282. {
  283. $TODOfilename=substr($filename,0,-4).'.TODO.csv';
  284. if (!file_exists(SC_CSV_IMPORT_DIR.$TODOfilename))
  285. {
  286. copy(SC_CSV_IMPORT_DIR.$filename,SC_CSV_IMPORT_DIR.$TODOfilename);
  287. foreach($importConfig[$filename] AS $k => $v)
  288. {
  289. $importConfig[$TODOfilename][$k]=$v;
  290. if ($k=='name') $importConfig[$TODOfilename][$k]=$TODOfilename;
  291. }
  292. writeImportConfigXML();
  293. }
  294. }else{
  295. $TODOfilename=$filename;
  296. }
  297. $needSaveTODO=false;
  298. if(empty($importConfig[$TODOfilename]['fornewproduct']))
  299. $importConfig[$TODOfilename]['fornewproduct'] = "skip";
  300. if(empty($importConfig[$TODOfilename]['forfoundproduct']))
  301. $importConfig[$TODOfilename]['forfoundproduct'] = "skip";
  302. // open csv filename
  303. if ($importConfig[$TODOfilename]['fieldsep']=='dcomma') $importConfig[$TODOfilename]['fieldsep']=';';
  304. if ($importConfig[$TODOfilename]['fieldsep']=='dcommamac') $importConfig[$TODOfilename]['fieldsep']=';';
  305. // get first line
  306. $DATAFILE=remove_utf8_bom(file_get_contents(SC_CSV_IMPORT_DIR.$TODOfilename));
  307. $DATA = preg_split("/(?:\r\n|\r|\n)/", $DATAFILE);
  308. if ($importConfig[$TODOfilename]['firstlinecontent']!='')
  309. {
  310. $importConfig[$TODOfilename]['firstlinecontent'] = str_replace("&amp;","&",$importConfig[$TODOfilename]['firstlinecontent']);
  311. $firstLineData=explode($importConfig[$TODOfilename]['fieldsep'],$importConfig[$TODOfilename]['firstlinecontent']);
  312. $FIRST_CONTENT_LINE=0;
  313. }else{
  314. $DATA[0] = str_replace("&amp;","&",$DATA[0]);
  315. $firstLineData=explode($importConfig[$TODOfilename]['fieldsep'],$DATA[0]);
  316. $FIRST_CONTENT_LINE=1;
  317. }
  318. if (count($firstLineData)!=count(array_unique($firstLineData)))
  319. 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.'));
  320. foreach($firstLineData AS $key => $val)
  321. escapeCharForPS($firstLineData[$key]);
  322. $firstLineData=array_map('cleanQuotes',$firstLineData);
  323. if ($importConfig[$TODOfilename]['utf8'])
  324. utf8_encode_array($firstLineData);
  325. // CHECK FILE VALIDITY
  326. if (count($mappingData['CSVArray']) > count($firstLineData))
  327. die(_l('Error in mapping: too much field to import').' (CSVArray:'.count($mappingData['CSVArray']).' - firstLineData:'.count($firstLineData).')');
  328. foreach($mappingData['CSVArray'] AS $val)
  329. {
  330. if (!in_array($val,$firstLineData))
  331. die(_l('Error in mapping: the fields are not in the CSV file')._l(':').$val);
  332. }
  333. // PLACE VALUES IN CACHE
  334. if (
  335. sc_in_array('feature',$mappingData['DBArray'],"catWinImportProcess_DBArray")
  336. || sc_in_array('feature_custom',$mappingData['DBArray'],"catWinImportProcess_DBArray")
  337. || sc_in_array('feature_add',$mappingData['DBArray'],"catWinImportProcess_DBArray")
  338. || sc_in_array('feature_delete',$mappingData['DBArray'],"catWinImportProcess_DBArray")
  339. )
  340. {
  341. refreshCacheFeature();
  342. }
  343. if (isCombination())
  344. {
  345. refreshCacheAttribute();
  346. }
  347. if (sc_in_array('id_category_default',$mappingData['DBArray'],"catWinImportProcess_DBArray") || sc_in_array('category_default',$mappingData['DBArray'],"catWinImportProcess_DBArray") || sc_in_array('categories',$mappingData['DBArray'],"catWinImportProcess_DBArray"))
  348. {
  349. $sql="SELECT c.id_category,c.id_parent,cl.name,c.level_depth
  350. FROM "._DB_PREFIX_."category c
  351. LEFT JOIN "._DB_PREFIX_."category_lang cl ON (cl.id_category=c.id_category AND cl.id_lang=".intval($defaultLanguage->id).")
  352. GROUP BY c.id_category
  353. ORDER BY c.level_depth ASC";
  354. $res=Db::getInstance()->ExecuteS($sql);
  355. $categories=array();
  356. $categoriesProperties=array();
  357. $categoryNameByID=array();
  358. $categoryIDByPath=array();
  359. $categoriesFirstLevel=array();
  360. // debug pour voir les catégories qui sont parentes d'elles mêmes
  361. //$kk=0;
  362. //var_dump($res);
  363. foreach($res AS $categ)
  364. {
  365. 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'])));
  366. $categories[trim(hideCategoryPosition($categ['name']))]=array('id_category' => $categ['id_category'], 'id_parent' => $categ['id_parent']);
  367. $categoryNameByID[$categ['id_category']]=hideCategoryPosition($categ['name']);
  368. $categoriesProperties[$categ['id_category']]=array('id_category' => $categ['id_category'], 'id_parent' => $categ['id_parent']);
  369. $categoryIDByPath[getCategoryPath($categ['id_category'])]=$categ['id_category'];
  370. if ($categ['level_depth']==1) $categoriesFirstLevel[]=hideCategoryPosition($categ['name']);
  371. //$kk++;
  372. //if ($kk>=370) echo trim(hideCategoryPosition($categ['name'])).' '.$categ['id_parent'].' '.$categ['id_category'].'<br/>';
  373. //if ($kk==374) die('rr');
  374. }
  375. }
  376. // get carriers
  377. $dataDB_carrier=array();
  378. $dataDB_carrierByName=array();
  379. //$DB_carrier=Carrier::getCarriers(intval($defaultLanguage->id), false);
  380. $sql = 'SELECT c.*
  381. FROM `'._DB_PREFIX_.'carrier` c
  382. WHERE c.`deleted` = "0"
  383. GROUP BY c.`id_carrier`
  384. ORDER BY c.`position` ASC';
  385. $DB_carrier = Db::getInstance()->executeS($sql);
  386. foreach($DB_carrier AS $carrier)
  387. {
  388. $dataDB_manufacturer[$carrier['id_reference']]=$carrier['name'];
  389. $dataDB_carrierByName[$carrier['name']]=$carrier['id_reference'];
  390. }
  391. // VAT first check
  392. if ((sc_in_array('priceinctax',$mappingData['DBArray'],"catWinImportProcess_DBArray") || sc_in_array('priceinctaxincecotax',$mappingData['DBArray'],"catWinImportProcess_DBArray")) && !sc_in_array('VAT',$mappingData['DBArray'],"catWinImportProcess_DBArray"))
  393. die(_l('Error in mapping: price including VAT found in CSV columns but no VAT colmun found. You need to indicate the VAT or use only price excluding VAT.'));
  394. $err_VAT=array();
  395. $dataArray_VAT=array();
  396. $dataArray_supplier=array();
  397. $dataArray_manufacturer=array();
  398. $dataArray_feature=array();
  399. $dataArray_multiplefeature=array();
  400. $dataArray_attributegroup=array();
  401. $dataArray_attributegroup=array();
  402. // $dataArray_attributegroupmultiple=array();
  403. $err='';
  404. for ($current_line = $FIRST_CONTENT_LINE; ((($current_line <= (count($DATA)-1)) && $line = parseCSVLine($importConfig[$TODOfilename]['fieldsep'],$DATA[$current_line])) && ($current_line <= $importlimit)) ; $current_line++)
  405. {
  406. if ($DATA[$current_line]=='') continue;
  407. if ($importConfig[$TODOfilename]['utf8']==1)
  408. utf8_encode_array($line);
  409. $line=array_map('cleanQuotes',$line);
  410. if (sc_in_array('VAT',$mappingData['DBArray'],"catWinImportProcess_DBArray"))
  411. {
  412. $vat=importConv2Float(findCSVLineValue('VAT'));
  413. if (!in_array($vat,$dataArray_VAT)) $dataArray_VAT[]=$vat;
  414. if ($vat < 0 || $vat > 100)
  415. $err_VAT[]=$current_line;
  416. }
  417. if (sc_in_array('supplier',$mappingData['DBArray'],"catWinImportProcess_DBArray"))
  418. {
  419. $dataArray_supplier[]=findCSVLineValue('supplier');
  420. }
  421. if (sc_in_array('supplier_default',$mappingData['DBArray'],"catWinImportProcess_DBArray"))
  422. {
  423. $dataArray_supplier[]=findCSVLineValue('supplier_default');
  424. }
  425. if (sc_in_array('manufacturer',$mappingData['DBArray'],"catWinImportProcess_DBArray"))
  426. {
  427. $dataArray_manufacturer[]=findCSVLineValue('manufacturer');
  428. }
  429. if (sc_in_array('feature',$mappingData['DBArray'],"catWinImportProcess_DBArray"))
  430. {
  431. findAllCSVLineValue('feature',$dataArray_feature,'id_feature',$features);
  432. }
  433. if (sc_in_array('feature_add',$mappingData['DBArray'],"catWinImportProcess_DBArray"))
  434. {
  435. findAllCSVLineValue('feature_add',$dataArray_multiplefeature,'id_feature',$features);
  436. }
  437. if (isCombination())
  438. {
  439. findAllCSVLineValue('attribute',$dataArray_attributegroup,'id_attribute_group',$attributeGroups);
  440. findAllCSVLineValue('attribute_multiple',$dataArray_attributegroup,'id_attribute_group',$attributeGroups);
  441. }
  442. if (count($line)!=count($firstLineData))
  443. $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/>";
  444. }
  445. /*echo "<pre>";
  446. print_r($mappingData);
  447. echo "############################";
  448. print_r($attributeGroups);
  449. echo "############################";
  450. print_r($dataArray_attributegroup);
  451. echo "</pre>";*/
  452. // VAT second check
  453. $isErr=false;
  454. if ($err_VAT)
  455. $err.=_l('Error: the VAT value should be between 0 and 100 on line(s) ').join(',',$err_VAT).'<br/>'.
  456. '<a target="_blank" href="'.SC_PS_PATH_ADMIN_REL.'index.php?tab=AdminTaxes&token='.$sc_agent->getPSToken('AdminTaxes').'">'._l('Click here to fix the problem').'</a><br/>';
  457. $dataDB_VAT=array();
  458. if (version_compare(_PS_VERSION_, '1.4.0.0', '<'))
  459. {
  460. $DB_VAT=Tax::getTaxes();
  461. foreach($DB_VAT as $tax)
  462. {
  463. $dataDB_VAT[]=importConv2Float($tax['rate']);
  464. }
  465. }else{
  466. $sql='SELECT trg.name, trg.id_tax_rules_group,t.rate
  467. FROM `'._DB_PREFIX_.'tax_rules_group` trg
  468. LEFT JOIN `'._DB_PREFIX_.'tax_rule` tr ON (trg.`id_tax_rules_group` = tr.`id_tax_rules_group` AND tr.`id_country` = '.(int)SCI::getDefaultCountryId().' AND tr.`id_state` = 0)
  469. LEFT JOIN `'._DB_PREFIX_.'tax` t ON (t.`id_tax` = tr.`id_tax`)
  470. WHERE trg.active=1';
  471. $DB_VAT=Db::getInstance()->ExecuteS($sql);
  472. foreach($DB_VAT as $tax)
  473. $dataDB_VAT[]=importConv2Float($tax['rate']);
  474. }
  475. $check_VAT=array_diff($dataArray_VAT,$dataDB_VAT);
  476. if (count($check_VAT))
  477. {
  478. foreach($check_VAT AS $tax)
  479. {
  480. if ($tax!=0)
  481. {
  482. $err.=_l('Error: tax doesn\'t exist: ').$tax.'<br/>';
  483. $isErr=true;
  484. }
  485. }
  486. }
  487. if ($isErr) $err.='<a target="_blank" href="'.SC_PS_PATH_ADMIN_REL.'index.php?tab=AdminTaxes&token='.$sc_agent->getPSToken('AdminTaxes').'">'._l('Click here to fix the problem').'</a><br/>';
  488. // supplier check
  489. $isErr=false;
  490. $dataDB_supplier=array();
  491. $dataDB_supplierByName=array();
  492. //$DB_supplier=Supplier::getSuppliers(false,0,false);
  493. $DB_supplier = Db::getInstance()->ExecuteS('SELECT m.*
  494. FROM `'._DB_PREFIX_.'supplier` m
  495. ORDER BY m.`name` ASC');
  496. foreach($DB_supplier AS $supplier)
  497. {
  498. $dataDB_supplier[$supplier['id_supplier']]=$supplier['name'];
  499. $dataDB_supplierByName[$supplier['name']]=$supplier['id_supplier'];
  500. }
  501. $check_supplier=array_diff($dataArray_supplier,$dataDB_supplier);
  502. $check_supplier=arr_unique($check_supplier);
  503. if (count($check_supplier))
  504. {
  505. $err_unique=array();
  506. foreach($check_supplier AS $supplier)
  507. {
  508. if ($supplier!='')// && !in_array($supplier,$err_unique))
  509. {
  510. $err.=_l('This supplier doesn\'t exist: ').$supplier.'<br/>';
  511. $err_unique[]=$supplier;
  512. $isErr=true;
  513. }
  514. }
  515. }
  516. if ($isErr)
  517. {
  518. if ($importConfig[$TODOfilename]['createelements']==1)
  519. {
  520. addSupplier($err_unique);
  521. }else{
  522. $err.='<form name="fSupplierCreation" id="fSupplierCreation">
  523. <textarea name="data" style="display:none">';
  524. $err.=join("_|_",$err_unique);
  525. $err.='</textarea>';
  526. $err.='<a href="javascript:$.post(\'index.php?ajax=1&act=cat_win-import_process&action=addSupplier\',$(\'#fSupplierCreation\').serialize(),function(data){$(\'#fSupplierCreation\').html(data);});void(0);">'._l('Click here to create these suppliers').'</a>';
  527. $err.='</form>';
  528. }
  529. }
  530. // visibility check
  531. $isErr=false;
  532. $dataDB_visibility=array();
  533. $dataDB_visibilityByName=array();
  534. $dataDB_visibility["both"]="both";
  535. $dataDB_visibilityByName["both"]="both";
  536. $dataDB_visibility["both"]=strtolower(_l('Both'));
  537. $dataDB_visibilityByName[strtolower(_l('Both'))]="both";
  538. $dataDB_visibility["catalog"]="catalog";
  539. $dataDB_visibilityByName["catalog"]="catalog";
  540. $dataDB_visibility["catalog"]=strtolower(_l('Catalog'));
  541. $dataDB_visibilityByName[strtolower(_l('Catalog'))]="catalog";
  542. $dataDB_visibility["search"]="search";
  543. $dataDB_visibilityByName["search"]="search";
  544. $dataDB_visibility["search"]=strtolower(_l('Search'));
  545. $dataDB_visibilityByName[strtolower(_l('Search'))]="search";
  546. $dataDB_visibility["none"]="none";
  547. $dataDB_visibilityByName["none"]="none";
  548. $dataDB_visibility["none"]=strtolower(_l('None'));
  549. $dataDB_visibilityByName[strtolower(_l('None'))]="none";
  550. // manufacturer check
  551. $isErr=false;
  552. $dataDB_manufacturer=array();
  553. $dataDB_manufacturerByName=array();
  554. //$DB_manufacturer=Manufacturer::getManufacturers(false,$id_lang,false);
  555. $DB_manufacturer = Db::getInstance()->ExecuteS('SELECT m.*
  556. FROM `'._DB_PREFIX_.'manufacturer` m
  557. ORDER BY m.`name` ASC');
  558. foreach($DB_manufacturer AS $manufacturer)
  559. {
  560. $dataDB_manufacturer[$manufacturer['id_manufacturer']]=$manufacturer['name'];
  561. $dataDB_manufacturerByName[$manufacturer['name']]=$manufacturer['id_manufacturer'];
  562. }
  563. $check_manufacturer=arrayDiffEmulation($dataArray_manufacturer,$dataDB_manufacturer);
  564. if (count($check_manufacturer))
  565. {
  566. $err_unique=array();
  567. foreach($check_manufacturer AS $manufacturer)
  568. {
  569. if ($manufacturer!='' && !in_array($manufacturer,$err_unique))
  570. {
  571. $err.=_l('This manufacturer doesn\'t exist: ').$manufacturer.'<br/>';
  572. $err_unique[]=$manufacturer;
  573. $isErr=true;
  574. }
  575. }
  576. }
  577. if ($isErr)
  578. {
  579. if ($importConfig[$TODOfilename]['createelements']==1)
  580. {
  581. addManufacturer($err_unique);
  582. }else{
  583. $err.='<form name="fManufacturerCreation" id="fManufacturerCreation">
  584. <textarea name="data" style="display:none">';
  585. $err.=join("_|_",$err_unique);
  586. $err.='</textarea>';
  587. $err.='<a href="javascript:$.post(\'index.php?ajax=1&act=cat_win-import_process&action=addManufacturer\',$(\'#fManufacturerCreation\').serialize(),function(data){$(\'#fManufacturerCreation\').html(data);});void(0);">'._l('Click here to create these manufacturers').'</a>';
  588. $err.='</form>';
  589. }
  590. }
  591. // feature check
  592. $isErr=false;
  593. $err_unique=array();
  594. foreach($mappingData['CSV2DBOptions'] AS $CSVFieldName => $featureName)
  595. {
  596. if ( sc_in_array($mappingData['CSV2DB'][$CSVFieldName], array('feature','feature_custom','feature_add','feature_delete'),"catWinImportProcess_featurefields"))
  597. {
  598. if (!sc_in_array($featureName,array_keys($features),"catWinImportProcess_features") && !in_array($featureName,$err_unique))
  599. {
  600. $err.=_l('This feature doesn\'t exist: ').$featureName.'<br/>';
  601. $err_unique[]=$featureName;
  602. $isErr=true;
  603. }
  604. }
  605. }
  606. if ($isErr)
  607. {
  608. if ($importConfig[$TODOfilename]['createelements']==1)
  609. {
  610. $data='';
  611. foreach($err_unique AS $feature)
  612. {
  613. $data.=$feature."y|y";
  614. }
  615. addFeature($data);
  616. refreshCacheFeature();
  617. $isErr = false;
  618. //$err.='<script type="text/javascript">$(document).ready(function(){$.post(\'index.php?ajax=1&act=cat_win-import_process&action=addFeature\',$(\'#fFeatureCreation\').serialize(),function(data){$(\'#fFeatureCreation\').html(data);})});</script>';
  619. }else{
  620. $err.='<form name="fFeatureCreation" id="fFeatureCreation">
  621. <textarea name="data" style="display:none">';
  622. foreach($err_unique AS $feature)
  623. {
  624. $err.=$feature."y|y";
  625. }
  626. $err.='</textarea>';
  627. $err.='<a href="javascript:$.post(\'index.php?ajax=1&act=cat_win-import_process&action=addFeature\',$(\'#fFeatureCreation\').serialize(),function(data){$(\'#fFeatureCreation\').html(data);});void(0);">'._l('Click here to create these features').'</a>';
  628. $err.='</form>';
  629. }
  630. }
  631. // feature value check
  632. if (!$isErr)
  633. {
  634. $isErr=false;
  635. $dataArray_feature_unique=array();
  636. // only for multiplefeature management
  637. foreach($dataArray_multiplefeature AS $key => $val)
  638. {
  639. $vals = explode($importConfig[$TODOfilename]['valuesep'],$val['value']);
  640. foreach ($vals AS $k => $uval)
  641. {
  642. $uarr = $dataArray_multiplefeature[$key];
  643. $uarr['value'] = $uval;
  644. $dataArray_feature[] = $uarr;
  645. }
  646. }
  647. foreach($dataArray_feature AS $f)
  648. {
  649. //echo $f['value'].'X';
  650. //echo $f['id_feature'].'x|x'.$f['object'].'x|x'.$f['value'].'<br/>';
  651. //var_dump($dataArray_feature_unique);
  652. //var_dump($featureValues);
  653. /*
  654. var_dump($dataArray_feature);
  655. die('rr');
  656. if ($f['value']=='CR250R'){
  657. if($f['value']!='') echo 'C1OK';
  658. if(!in_array($f['id_feature'].'_|_'.$f['value'],array_keys($featureValues))) echo 'C2OK';
  659. if(!in_array($f['id_feature'].'x|x'.$f['object'].'x|x'.$f['id_feature'].'_|_'.$f['value'],$dataArray_feature_unique)) echo 'C3OK';
  660. if ($f['value']!='' && !in_array($f['id_feature'].'_|_'.$f['value'],array_keys($featureValues)) && !in_array($f['id_feature'].'x|x'.$f['object'].'x|x'.$f['id_feature'].'_|_'.$f['value'],$dataArray_feature_unique)) echo 'TOTOK';
  661. echo 'XXX<br/>';
  662. die('rr');
  663. }*/
  664. $f['value']=trim($f['value']);
  665. if ($f['value']!='' && !sc_in_array($f['id_feature'].'_|_'.$f['value'],array_keys($featureValues),"catWinImportProcess_featurevalues") && !in_array($f['id_feature'].'x|x'.$f['object'].'x|x'.$f['id_feature'].'_|_'.$f['value'],$dataArray_feature_unique))
  666. {
  667. $err.=_l('This feature doesn\'t exist: ').$f['object'].' &gt; '.$f['value'].'<br/>';
  668. $dataArray_feature_unique[]=$f['id_feature'].'x|x'.$f['object'].'x|x'.$f['id_feature'].'_|_'.$f['value'];
  669. $isErr=true;
  670. }
  671. }
  672. if ($isErr)
  673. {
  674. $data='';
  675. foreach($dataArray_feature_unique AS $featureValue)
  676. {
  677. $fv=explode('x|x',$featureValue);
  678. $data.=$fv[0].'x|x'.$fv[2]."y|y";
  679. }
  680. if ($importConfig[$TODOfilename]['createelements']==1)
  681. {
  682. addFeatureValue($data);
  683. refreshCacheFeature();
  684. findAllCSVLineValue('feature',$dataArray_feature,'id_feature',$features);
  685. $isErr = false;
  686. }else{
  687. $err.='<form name="fFeatureCreation" id="fFeatureCreation">
  688. <textarea name="data" style="display:none">';
  689. $err.=$data;
  690. $err.='</textarea>';
  691. $err.='<a href="javascript:$.post(\'index.php?ajax=1&act=cat_win-import_process&action=addFeatureValue\',$(\'#fFeatureCreation\').serialize(),function(data){$(\'#fFeatureCreation\').html(data);});void(0);">'._l('Click here to create these features').'</a>';
  692. $err.='</form>';
  693. }
  694. }
  695. }
  696. // attribute group check
  697. $isErr=false;
  698. $err_unique=array();
  699. foreach($mappingData['CSV2DBOptions'] AS $CSVFieldName => $attributeGroupName)
  700. {
  701. if ($mappingData['CSV2DB'][$CSVFieldName]=='attribute' || $mappingData['CSV2DB'][$CSVFieldName]=='attribute_multiple')
  702. {
  703. if (!sc_in_array($attributeGroupName,array_keys($attributeGroups),"catWinImportProcess_attributeGroups") && !in_array($attributeGroupName,$err_unique))
  704. {
  705. $err.=_l('This attribute group doesn\'t exist: ').$attributeGroupName.'<br/>';
  706. $err_unique[]=$attributeGroupName;
  707. $isErr=true;
  708. }
  709. }
  710. }
  711. if ($isErr)
  712. {
  713. $data = "";
  714. foreach($err_unique AS $attributeGroup)
  715. {
  716. $data.=$attributeGroup."y|y";
  717. }
  718. if ($importConfig[$TODOfilename]['createelements']==1)
  719. {
  720. addAttributeGroup($data);
  721. refreshCacheAttribute();
  722. $isErr = false;
  723. //$err.='<script type="text/javascript">$(document).ready(function(){$.post(\'index.php?ajax=1&act=cat_win-import_process&action=addAttributeGroup\',$(\'#fAttributeGroupCreation\').serialize(),function(data){$(\'#fAttributeGroupCreation\').html(data);})});</script>';
  724. }else{
  725. $err.='<form name="fAttributeGroupCreation" id="fAttributeGroupCreation">
  726. <textarea name="data" style="display:none">'.$data.'</textarea>';
  727. $err.='<a href="javascript:$.post(\'index.php?ajax=1&act=cat_win-import_process&action=addAttributeGroup\',$(\'#fAttributeGroupCreation\').serialize(),function(data){$(\'#fAttributeGroupCreation\').html(data);});void(0);">'._l('Click here to create these attribute groups').'</a>';
  728. $err.='</form>';
  729. }
  730. }
  731. // attribute check
  732. if (!$isErr)
  733. {
  734. $isErr=false;
  735. $dataArray_attribute_unique=array();
  736. foreach($dataArray_attributegroup AS $ag)
  737. {
  738. // echo 'H'.$ag['value'].' '.(in_array($ag['value'],array_keys($attributeValues))).'K'.'[[[ '.$ag['id_attribute_group'].'x|x'.$ag['object'].'x|x'.$ag['value'].' ]]]<br/>';
  739. //!in_array($ag['value'],array_keys($attributeValues),true)
  740. if ($ag['value']!='' && !sc_array_key_exists($ag['id_attribute_group'].'_|_'.$ag['value'],$attributeValues) && !in_array($ag['id_attribute_group'].'x|x'.$ag['object'].'x|x'.$ag['id_attribute_group'].'_|_'.$ag['value'],$dataArray_attribute_unique))
  741. {
  742. $err.=_l('This attribute doesn\'t exist: ').$ag['object'].' &gt; '.$ag['value'].'<br/>';
  743. $dataArray_attribute_unique[]=$ag['id_attribute_group'].'x|x'.$ag['object'].'x|x'.$ag['id_attribute_group'].'_|_'.$ag['value'].'_|_'.$ag['color_attr_options'];
  744. $isErr=true;
  745. }
  746. }
  747. if ($isErr)
  748. {
  749. $data='';
  750. foreach($dataArray_attribute_unique AS $attributeValue)
  751. {
  752. $av=explode('x|x',$attributeValue);
  753. $data.=$av[0].'x|x'.$av[2]."y|y";
  754. }
  755. if ($importConfig[$TODOfilename]['createelements']==1)
  756. {
  757. addAttributeValue($data);
  758. refreshCacheAttribute();
  759. $isErr = false;
  760. }else{
  761. $err.='<form name="fAttributeCreation" id="fAttributeCreation">
  762. <textarea name="data" style="display:none">';
  763. $err.=$data;
  764. $err.='</textarea>';
  765. $err.='<a href="javascript:$.post(\'index.php?ajax=1&act=cat_win-import_process&action=addAttributeValue\',$(\'#fAttributeCreation\').serialize(),function(data){$(\'#fAttributeCreation\').html(data);});void(0);">'._l('Click here to create these attributes').'</a>';
  766. $err.='</form>';
  767. }
  768. }
  769. }
  770. if ($err!='' && $importConfig[$TODOfilename]['createelements']!=1)
  771. die($err.'<br/><br/>'._l('The process has been stopped before any modification in the database. You need to fix these errors first.'));
  772. // CHECK IF CATEGORY EXISTS
  773. $categ=Db::getInstance()->getRow("
  774. SELECT c.id_category
  775. FROM `"._DB_PREFIX_."category` c
  776. LEFT JOIN `"._DB_PREFIX_."category_lang` cl ON (c.`id_category` = cl.`id_category`)
  777. WHERE `name` = '".pSQL($TODOfilename)."'
  778. GROUP BY c.id_category");
  779. if (is_array($categ) && $categ['id_category']!='')
  780. {
  781. $id_category=intval($categ['id_category']);
  782. }else{
  783. $newcategory=new Category();
  784. $newcategory->id_parent=Configuration::get("PS_ROOT_CATEGORY");//1;
  785. $newcategory->level_depth=$newcategory->calcLevelDepth();
  786. $newcategory->active=0;
  787. foreach($languages AS $lang)
  788. {
  789. $newcategory->link_rewrite[$lang['id_lang']]='import';
  790. $newcategory->name[$lang['id_lang']]=$TODOfilename;
  791. }
  792. if (version_compare(_PS_VERSION_, '1.4.0.0', '>='))
  793. {
  794. $newcategory->position=SCI::getLastPositionFromCategory(1);
  795. }
  796. $newcategory->save();
  797. //$newcategory->addGroups(array(1));
  798. $id_category=$newcategory->id;
  799. }
  800. $refsupp_option = "";
  801. if(sc_in_array($importConfig[$TODOfilename]['idby'], array('supref'),"catWinImportProcess_supref"))
  802. {
  803. foreach($mappingData['CSV2DB'] as $key=>$field)
  804. {
  805. if($field=="supplier_reference")
  806. {
  807. $refsupp_option = $mappingData['CSV2DBOptions'][$key];
  808. break;
  809. }
  810. }
  811. }
  812. $stats=array('created' => 0,'modified' => 0,'skipped' => 0,'no_wholesaleprice' => 0);
  813. $noWholesalepriceArray = array();
  814. $CSVDataStr = remove_utf8_bom(file_get_contents(SC_CSV_IMPORT_DIR.$TODOfilename));
  815. $CSVData = preg_split("/(?:\r\n|\r|\n)/", $CSVDataStr);
  816. $lastIdentifier='';
  817. $lastid_product=0;
  818. $updated_products = array();
  819. $id_shop_list=array();
  820. $id_shop_list_default=array(1);
  821. if (version_compare(_PS_VERSION_,'1.5.0.0','>='))
  822. {
  823. $id_shop_list_default=array((int)Configuration::get('PS_SHOP_DEFAULT'));
  824. $cache_id_shop = array();
  825. $cache_current_line_for_combination = array();
  826. }
  827. $imageList=array();
  828. $productsWithTagUpdatedList=array();
  829. // for ($current_line = $FIRST_CONTENT_LINE; (($current_line <= (count($DATA)-1)) && $line = explode($importConfig[$TODOfilename]['fieldsep'],$DATA[$current_line])) && $current_line <= $importlimit ; $current_line++)
  830. //$aa= parseCSVLine($importConfig[$TODOfilename]['fieldsep'],$DATA[1]);
  831. //var_dump($aa);
  832. for ($current_line = $FIRST_CONTENT_LINE; ((($current_line <= (count($DATA)-1)) && $line = parseCSVLine($importConfig[$TODOfilename]['fieldsep'],$DATA[$current_line])) && ($current_line <= $importlimit)) ; $current_line++)
  833. {
  834. if ($DATA[$current_line]=='') continue;
  835. if (_s('APP_DEBUG_CATALOG_IMPORT'))
  836. {
  837. $time_end = microtime(true);
  838. $time = $time_end - $time_start;
  839. echo "<br/><br/>Start line : $time seconds";
  840. }
  841. $extension_vars = array();
  842. $id_shop_list=$id_shop_list_default;
  843. $useSpecificPrices=false;
  844. $line=array_map('cleanQuotes',$line);
  845. if ($scdebug) echo 'line '.$current_line.': ';
  846. $line[count($line)-1]=rtrim($line[count($line)-1]);
  847. $TODO=array();
  848. $TODOSHOP=array();
  849. if ($importConfig[$TODOfilename]['utf8']==1)
  850. utf8_encode_array($line);
  851. $filter_supplier_id = intval($importConfig[$TODOfilename]['supplier']);
  852. $where_shop_list = "";
  853. if(SCMS && findCSVLineValue('id_shop_list')!='' && $importConfig[$TODOfilename]['fornewproduct']=='skip' && $importConfig[$TODOfilename]['forfoundproduct']=='update')
  854. $where_shop_list = findCSVLineValue('id_shop_list');
  855. $has_view = (_s('CAT_PROD_IMPORT_METHOD') && SCI::getConfigurationValue('PS_SC_IMPORT_VIEW')=="1"?true:false);
  856. $res=array();
  857. switch($importConfig[$TODOfilename]['idby'])
  858. {
  859. case 'prodname':
  860. $name = findCSVLineValue('name');
  861. if(!empty($name))
  862. {
  863. $sql = "SELECT p.id_product,p.date_upd,p.id_supplier
  864. FROM "._DB_PREFIX_."product p
  865. LEFT JOIN "._DB_PREFIX_."product_lang pl on (p.id_product=pl.id_product AND pl.id_lang=".intval($defaultLanguage->id).")
  866. WHERE pl.name='".psql($name)."'
  867. ".(version_compare(_PS_VERSION_,'1.5.0.0','<') || empty($filter_supplier_id) ? '' : ' AND p.id_supplier='.$filter_supplier_id)." ".
  868. (!empty($where_shop_list)? ' AND EXISTS (SELECT * FROM '._DB_PREFIX_.'product_shop ps WHERE p.id_product=ps.id_product AND id_shop IN ('.psql($where_shop_list).'))' : '')."
  869. LIMIT 1";
  870. }
  871. else
  872. $sql = "";
  873. break;
  874. case 'idproduct':
  875. $id_product_find = findCSVLineValue('id_product');
  876. if(!empty($id_product_find))
  877. {
  878. $sql="SELECT p.id_product,p.date_upd,p.id_supplier
  879. FROM "._DB_PREFIX_."product p
  880. WHERE p.id_product='".intval($id_product_find)."'
  881. ".(version_compare(_PS_VERSION_,'1.5.0.0','<') || empty($filter_supplier_id) ? '' : ' AND id_supplier='.$filter_supplier_id)." ".
  882. (!empty($where_shop_list)? ' AND EXISTS (SELECT * FROM '._DB_PREFIX_.'product_shop ps WHERE p.id_product=ps.id_product AND id_shop IN ('.psql($where_shop_list).'))' : '')."
  883. LIMIT 1";
  884. }
  885. else
  886. $sql = "";
  887. break;
  888. case 'idproductattribute':
  889. $id_product_attribute_find = findCSVLineValue('id_product_attribute');
  890. if(!empty($id_product_attribute_find))
  891. {
  892. if($has_view)
  893. {
  894. $sql = "SELECT id_product,id_product_attribute,date_upd,id_supplier FROM "._DB_PREFIX_."sc_import_index
  895. WHERE
  896. id_product_attribute='".intval($id_product_attribute_find)."'
  897. ".(version_compare(_PS_VERSION_,'1.5.0.0','<') || empty($filter_supplier_id) ? '' : ' AND id_supplier='.$filter_supplier_id)." ".
  898. (!empty($where_shop_list)? ' AND id_shop IN ('.psql($where_shop_list).')' : '')."
  899. ORDER BY id_product_attribute DESC
  900. LIMIT 1";
  901. }
  902. else
  903. {
  904. $sql="SELECT pa.id_product,pa.id_product_attribute,pa.date_upd,p.id_supplier
  905. FROM "._DB_PREFIX_."product_attribute pa
  906. LEFT JOIN "._DB_PREFIX_."product p on (pa.id_product=p.id_product)
  907. WHERE pa.id_product_attribute='".intval($id_product_attribute_find)."'
  908. ".(version_compare(_PS_VERSION_,'1.5.0.0','<') || empty($filter_supplier_id) ? '' : ' AND p.id_supplier='.$filter_supplier_id)." ".
  909. (!empty($where_shop_list)? ' AND EXISTS (SELECT * FROM '._DB_PREFIX_.'product_shop ps WHERE pa.id_product=ps.id_product AND id_shop IN ('.psql($where_shop_list).'))' : '')."
  910. LIMIT 1";
  911. }
  912. }
  913. else
  914. $sql = "";
  915. break;
  916. case 'ean13':
  917. $EAN13_find = findCSVLineValue('EAN13');
  918. if(!empty($EAN13_find))
  919. {
  920. $sql="SELECT p.id_product,pa.id_product_attribute,pa.date_upd,p.id_supplier
  921. FROM "._DB_PREFIX_."product_attribute pa
  922. LEFT JOIN "._DB_PREFIX_."product p on (pa.id_product=p.id_product)
  923. WHERE pa.ean13='".psql($EAN13_find)."'
  924. ".(version_compare(_PS_VERSION_,'1.5.0.0','<') || empty($filter_supplier_id) ? '' : ' AND p.id_supplier='.$filter_supplier_id)." ".
  925. (!empty($where_shop_list)? ' AND EXISTS (SELECT * FROM '._DB_PREFIX_.'product_shop ps WHERE pa.id_product=ps.id_product AND id_shop IN ('.psql($where_shop_list).'))' : '')."
  926. LIMIT 1";
  927. $res=Db::getInstance()->ExecuteS($sql);
  928. if (count($res)==0)
  929. {
  930. $sql="SELECT p.id_product,p.date_upd,p.id_supplier
  931. FROM "._DB_PREFIX_."product p
  932. WHERE p.ean13='".psql($EAN13_find)."'
  933. ".(version_compare(_PS_VERSION_,'1.5.0.0','<') || empty($filter_supplier_id) ? '' : ' AND p.id_supplier='.$filter_supplier_id)." ".
  934. (!empty($where_shop_list)? ' AND EXISTS (SELECT * FROM '._DB_PREFIX_.'product_shop ps WHERE p.id_product=ps.id_product AND id_shop IN ('.psql($where_shop_list).'))' : '')."
  935. LIMIT 1";
  936. }
  937. else
  938. $sql = "";
  939. }
  940. else
  941. $sql = "";
  942. break;
  943. case 'upc':
  944. $upc_find = findCSVLineValue('upc');
  945. if(!empty($upc_find))
  946. {
  947. $sql="SELECT p.id_product,pa.id_product_attribute,pa.date_upd,p.id_supplier
  948. FROM "._DB_PREFIX_."product_attribute pa
  949. LEFT JOIN "._DB_PREFIX_."product p on (pa.id_product=p.id_product)
  950. WHERE pa.upc='".psql($upc_find)."'
  951. ".(version_compare(_PS_VERSION_,'1.5.0.0','<') || empty($filter_supplier_id) ? '' : ' AND p.id_supplier='.$filter_supplier_id)." ".
  952. (!empty($where_shop_list)? ' AND EXISTS (SELECT * FROM '._DB_PREFIX_.'product_shop ps WHERE pa.id_product=ps.id_product AND id_shop IN ('.psql($where_shop_list).'))' : '')."
  953. LIMIT 1";
  954. $res=Db::getInstance()->ExecuteS($sql);
  955. if (count($res)==0)
  956. {
  957. $sql="SELECT p.id_product,p.date_upd,p.id_supplier
  958. FROM "._DB_PREFIX_."product p
  959. WHERE p.upc='".intval($upc_find)."'
  960. ".(version_compare(_PS_VERSION_,'1.5.0.0','<') || empty($filter_supplier_id) ? '' : ' AND p.id_supplier='.$filter_supplier_id)." ".
  961. (!empty($where_shop_list)? ' AND EXISTS (SELECT * FROM '._DB_PREFIX_.'product_shop ps WHERE p.id_product=ps.id_product AND id_shop IN ('.psql($where_shop_list).'))' : '')."
  962. LIMIT 1";
  963. }
  964. else
  965. $sql = "";
  966. }
  967. else
  968. $sql = "";
  969. break;
  970. case 'prodref':
  971. $search_reference = findCSVLineValue('reference');
  972. if(!empty($search_reference))
  973. {
  974. if($has_view)
  975. {
  976. $sql = "SELECT id_product,id_product_attribute,date_upd,id_supplier FROM "._DB_PREFIX_."sc_import_index
  977. WHERE
  978. ( p_reference='".psql($search_reference)."' OR pa_reference='".psql($search_reference)."' )
  979. ".(version_compare(_PS_VERSION_,'1.5.0.0','<') || empty($filter_supplier_id) ? '' : ' AND id_supplier='.$filter_supplier_id)." ".
  980. (!empty($where_shop_list)? ' AND id_shop IN ('.psql($where_shop_list).')' : '')."
  981. ORDER BY id_product_attribute DESC
  982. LIMIT 1";
  983. }
  984. else
  985. {
  986. $sql="SELECT p.id_product,pa.id_product_attribute,pa.date_upd,p.id_supplier FROM "._DB_PREFIX_."product p
  987. LEFT JOIN "._DB_PREFIX_."product_attribute pa on (p.id_product=pa.id_product)
  988. WHERE pa.reference='".psql($search_reference)."'
  989. ".(version_compare(_PS_VERSION_,'1.5.0.0','<') || empty($filter_supplier_id) ? '' : ' AND p.id_supplier='.$filter_supplier_id)." ".
  990. (!empty($where_shop_list)? ' AND EXISTS (SELECT * FROM '._DB_PREFIX_.'product_shop ps WHERE p.id_product=ps.id_product AND id_shop IN ('.psql($where_shop_list).'))' : '').
  991. " LIMIT 1";
  992. $res=Db::getInstance()->ExecuteS($sql);
  993. if (count($res)==0)
  994. {
  995. $sql="SELECT p.id_product,p.date_upd,p.id_supplier
  996. FROM "._DB_PREFIX_."product p
  997. WHERE reference='".psql($search_reference)."'
  998. ".(version_compare(_PS_VERSION_,'1.5.0.0','<') || empty($filter_supplier_id) ? '' : ' AND id_supplier='.$filter_supplier_id)."".
  999. (!empty($where_shop_list)? ' AND EXISTS (SELECT * FROM '._DB_PREFIX_.'product_shop ps WHERE p.id_product=ps.id_product AND id_shop IN ('.psql($where_shop_list).'))' : '').
  1000. " LIMIT 1";
  1001. }
  1002. else
  1003. $sql = "";
  1004. }
  1005. }
  1006. else
  1007. $sql = "";
  1008. break;
  1009. case 'supref':
  1010. $search_ref = findCSVLineValue('supplier_reference');
  1011. if(!empty($search_ref))
  1012. {
  1013. if($has_view)
  1014. {
  1015. $search_supp_ref = "";
  1016. if(version_compare(_PS_VERSION_,'1.5.0.0','>=') && $refsupp_option!="suppref_product")
  1017. $search_supp_ref = " OR product_supplier_reference LIKE '%||".psql($search_ref)."||%' ";
  1018. $sql = "SELECT id_product,id_product_attribute,date_upd,id_supplier FROM "._DB_PREFIX_."sc_import_index
  1019. WHERE
  1020. ( pa_supplier_reference='".psql($search_ref)."' OR p_supplier_reference='".psql($search_ref)."' ".$search_supp_ref.")
  1021. ".(version_compare(_PS_VERSION_,'1.5.0.0','<') || empty($filter_supplier_id) ? '' : ' AND id_supplier='.$filter_supplier_id)." ".
  1022. (!empty($where_shop_list)? ' AND id_shop IN ('.psql($where_shop_list).')' : '')."
  1023. ORDER BY id_product_attribute DESC
  1024. LIMIT 1";
  1025. }
  1026. else
  1027. {
  1028. if (version_compare(_PS_VERSION_,'1.5.0.0','>=') && $refsupp_option!="suppref_product")
  1029. {
  1030. $sql="SELECT ps.id_product,ps.id_product_attribute,pa.date_upd,p.id_supplier FROM "._DB_PREFIX_."product_supplier ps
  1031. LEFT JOIN "._DB_PREFIX_."product_attribute pa on (ps.id_product_attribute=pa.id_product_attribute)
  1032. LEFT JOIN "._DB_PREFIX_."product p on (ps.id_product=p.id_product)
  1033. WHERE ps.product_supplier_reference='".psql($search_ref)."'
  1034. ".(version_compare(_PS_VERSION_,'1.5.0.0','<') || empty($filter_supplier_id) ? '' : ' AND p.id_supplier='.$filter_supplier_id)." ".
  1035. (!empty($where_shop_list)? ' AND EXISTS (SELECT * FROM '._DB_PREFIX_.'product_shop ps WHERE pa.id_product=ps.id_product AND id_shop IN ('.psql($where_shop_list).'))' : '').
  1036. " ORDER BY id_product_attribute DESC LIMIT 1";
  1037. $res=Db::getInstance()->ExecuteS($sql);
  1038. }
  1039. if (count($res)==0)
  1040. {
  1041. $sql="SELECT p.id_product,pa.id_product_attribute,pa.date_upd,p.id_supplier FROM "._DB_PREFIX_."product p
  1042. LEFT JOIN "._DB_PREFIX_."product_attribute pa on (p.id_product=pa.id_product)
  1043. WHERE pa.supplier_reference='".psql($search_ref)."'
  1044. ".(version_compare(_PS_VERSION_,'1.5.0.0','<') || empty($filter_supplier_id) ? '' : ' AND p.id_supplier='.$filter_supplier_id)." ".
  1045. (!empty($where_shop_list)? ' AND EXISTS (SELECT * FROM '._DB_PREFIX_.'product_shop ps WHERE p.id_product=ps.id_product AND id_shop IN ('.psql($where_shop_list).'))' : '').
  1046. " ORDER BY id_product_attribute DESC LIMIT 1";
  1047. $res=Db::getInstance()->ExecuteS($sql);
  1048. }
  1049. else
  1050. $sql = "";
  1051. if (count($res)==0)
  1052. {
  1053. $sql="SELECT p.id_product,p.date_upd,p.id_supplier FROM "._DB_PREFIX_."product p
  1054. WHERE supplier_reference='".psql($search_ref)."'
  1055. ".(version_compare(_PS_VERSION_,'1.5.0.0','<') || empty($filter_supplier_id) ? '' : ' AND id_supplier='.$filter_supplier_id)."".
  1056. (!empty($where_shop_list)? ' AND EXISTS (SELECT * FROM '._DB_PREFIX_.'product_shop ps WHERE p.id_product=ps.id_product AND id_shop IN ('.psql($where_shop_list).'))' : '').
  1057. " LIMIT 1";
  1058. }
  1059. else
  1060. $sql = "";
  1061. }
  1062. }
  1063. else
  1064. $sql = "";
  1065. break;
  1066. case 'prodrefandsupref':
  1067. $search_supplier_reference = findCSVLineValue('supplier_reference');
  1068. $search_reference = findCSVLineValue('reference');
  1069. if(!empty($sear