PageRenderTime 36ms CodeModel.GetById 17ms RepoModel.GetById 1ms app.codeStats 0ms

/modules/storecommander/ead6f6fce09/SC/lib/cat/win-export/cat_win-export_process.php

https://gitlab.com/ptisky/API_prestashop
PHP | 1200 lines | 973 code | 63 blank | 164 comment | 228 complexity | d42b3780460363c02c5647d8360dd121 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. $debug=false;
  24. error_reporting(E_ALL ^ E_NOTICE);
  25. @ini_set('display_errors', 'on');
  26. if (!isset($CRON)) $CRON=0;
  27. if (!isset($CRONVERSION)) $CRONVERSION=1;
  28. if(!empty($CRON))
  29. {
  30. Context::getContext()->employee = new Employee( Tools::getValue('id_employee') );
  31. $sc_agent=new SC_Agent();
  32. }
  33. require_once(SC_DIR.'lib/cat/win-export/cat_win-export_tools.php');
  34. $action=Tools::getValue('action');
  35. $id_lang=intval(Tools::getValue('id_lang'));
  36. $mapping=Tools::getValue('mapping');
  37. $cache=array();
  38. $cacheCategory=array();
  39. $cacheCategoryPath=array();
  40. $categoriesProperties=array();
  41. $categoryNameByID=array();
  42. $cacheCarriers=array();
  43. switch($action){
  44. case 'conf_delete':
  45. $exp_opt_files=Tools::getValue('exp_opt_files','');
  46. if ($exp_opt_files=='') die(_l('You should mark at least one file to delete'));
  47. $exp_opt_files_array=preg_split('/;/',$exp_opt_files);
  48. foreach($exp_opt_files_array as $exp_opt_file)
  49. {
  50. if ($exp_opt_file!='')
  51. {
  52. if (@unlink(SC_TOOLS_DIR.'cat_export/'.$exp_opt_file.'.script.xml'))
  53. {
  54. echo $exp_opt_file." "._l('deleted')."\n";
  55. }else{
  56. echo _l("Unable to delete this file, please check write permissions:")." ".$exp_opt_file."\n";
  57. }
  58. }
  59. }
  60. break;
  61. case 'conf_add':
  62. $scriptname=Tools::getValue('scriptname','');
  63. readExportConfigXML('');
  64. writeExportConfigXML($scriptname.'.script.xml');
  65. break;
  66. case 'reset_export':
  67. $return = false;
  68. $export_id = intval(Tools::getValue('export_id', 0));
  69. if(!empty($export_id))
  70. {
  71. $sql = "UPDATE "._DB_PREFIX_."sc_export SET exporting = 0, id_next = 0, id_combination_next = 0 WHERE id_sc_export = '".intval($export_id)."'";
  72. Db::getInstance()->Execute($sql);
  73. $return = true;
  74. }
  75. if(!$return)
  76. echo '<strong style="color: #831f1f;">'._l('An error occured during reset. Please try again.').'</span>';
  77. else
  78. echo '<strong style="color: #266e00;">'._l('The export was successfully reset.').'</span>';
  79. break;
  80. case 'mapping_delete':
  81. $filename=str_replace('.map.xml','',Tools::getValue('filename'));
  82. @unlink(SC_TOOLS_DIR.'cat_export/'.$filename.'.map.xml');
  83. break;
  84. case 'mapping_saveas':
  85. $filename=str_replace('.map.xml','',Tools::getValue('filename'));
  86. $mapping=Tools::getValue('mapping');
  87. @unlink(SC_TOOLS_DIR.'cat_export/'.$filename.'.map.xml');
  88. $mapping=preg_split('/;/',$mapping);
  89. $content="<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".'<mapping version="'.SC_EXPORT_VERSION.'">';
  90. $contentArray=array();
  91. foreach($mapping AS $map)
  92. {
  93. $val=explode('|||',$map);
  94. if (count($val)==8)
  95. {
  96. $contentArray[(int)$val[1]]='<field>';
  97. $contentArray[(int)$val[1]].='<id><![CDATA['.$val[0].']]></id>';
  98. $contentArray[(int)$val[1]].='<used><![CDATA['.$val[2].']]></used>';
  99. $contentArray[(int)$val[1]].='<name><![CDATA['.$val[3].']]></name>';
  100. $contentArray[(int)$val[1]].='<lang><![CDATA['.$val[4].']]></lang>';
  101. $contentArray[(int)$val[1]].='<options><![CDATA['.$val[5].']]></options>';
  102. //$contentArray[(int)$val[1]].='<filters><![CDATA['.$val[6].']]></filters>';
  103. $contentArray[(int)$val[1]].='<modifications><![CDATA['.$val[6].']]></modifications>';
  104. $contentArray[(int)$val[1]].='<column_name><![CDATA['.$val[7].']]></column_name>';
  105. $contentArray[(int)$val[1]].='</field>'."\n";
  106. }
  107. }
  108. ksort($contentArray);
  109. $content.=join('',$contentArray).'</mapping>';
  110. file_put_contents(SC_TOOLS_DIR.'cat_export/'.$filename.'.map.xml', $content);
  111. echo _l('Data saved!');
  112. break;
  113. case 'categselection_load':
  114. $filename=str_replace('.sel.xml','',Tools::getValue('filename')).'.sel.xml';
  115. $content='';
  116. if (file_exists(SC_TOOLS_DIR.'cat_categories_sel/'.$filename) && $feed = simplexml_load_file(SC_TOOLS_DIR.'cat_categories_sel/'.$filename))
  117. foreach($feed->category AS $category)
  118. $content.=(string)$category->id.';';
  119. echo $content;
  120. break;
  121. case 'categselection_saveas':
  122. $filename=Tools::getValue('filename');
  123. $categselection=Tools::getValue('categselection');
  124. @unlink(SC_TOOLS_DIR.'cat_categories_sel/'.$filename.'.sel.xml');
  125. $categselection=preg_split('/,/',$categselection);
  126. $content="<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".'<categselection>';
  127. $contentArray=array();
  128. foreach($categselection AS $catsel)
  129. {
  130. $val=preg_split('/,/',$catsel);
  131. if (count($val)==1 && $val[0]!='')
  132. {
  133. $contentArray[(int)$val[0]]='<category>';
  134. $contentArray[(int)$val[0]].='<id><![CDATA['.$val[0].']]></id>';
  135. $contentArray[(int)$val[0]].='</category>'."\n";
  136. }
  137. }
  138. ksort($contentArray);
  139. $content.=join('',$contentArray).'</categselection>';
  140. file_put_contents(SC_TOOLS_DIR.'cat_categories_sel/'.$filename.'.sel.xml', $content);
  141. echo _l('Data saved!');
  142. break;
  143. case 'categselection_delete':
  144. $filename=Tools::getValue('filename');
  145. @unlink(SC_TOOLS_DIR.'cat_categories_sel/'.$filename.'.sel.xml');
  146. break;
  147. case 'export_process':
  148. global $switchObject,$switchObjectOption,$switchObjectLang,$p,$getIDlangByISO,$field,$id_product,$id_product_attribute; // variable for custom import fields check, used in extensions, do not remove
  149. // INIT VARS
  150. $AUTO_EXPORT=intval(Tools::getValue('auto_export',0));
  151. $export_limit=intval(Tools::getValue('export_limit',500));
  152. $first_interval=intval(Tools::getValue('first_interval',0));
  153. $time_start = microtime(true);
  154. $ALREADY_EXPORTING = false;
  155. $STOP_SCRIPT = false;
  156. $switchObject='';
  157. $switchObjectOption='';
  158. $switchObjectLang='';
  159. $link = new Link();
  160. $id_product=0;
  161. $id_product_attribute=0;
  162. $defaultLanguageId = intval(Configuration::get('PS_LANG_DEFAULT'));
  163. $defaultLanguage=new Language($defaultLanguageId);
  164. $getIDlangByISO=array();
  165. foreach($languages AS $lang)
  166. $getIDlangByISO[$lang['iso_code']]=$lang['id_lang'];
  167. $filename=Tools::getValue('filename',0);
  168. $sc_active=SCI::getConfigurationValue('SC_PLUG_DISABLECOMBINATIONS',0);
  169. $auto_filename=$filename;//str_replace(".script.xml","",$filename);
  170. if ($filename===0)
  171. {
  172. if(!$AUTO_EXPORT && !$CRON)
  173. die(_l('You have to select a file.'));
  174. elseif($CRON)
  175. {
  176. echo _l('You have to select a file.');
  177. $STOP_SCRIPT = true;
  178. }
  179. else
  180. {
  181. echo json_encode(array(
  182. "type" => "error",
  183. "stop" => 1,
  184. "content" => '<strong style="color: #831f1f;">'._l('You have to select a file.', 1).'</span>',
  185. "filename" => $auto_filename,
  186. "first_interval" => $first_interval
  187. ));
  188. die();
  189. }
  190. }
  191. if($STOP_SCRIPT)
  192. break;
  193. $arrIdAvailableLater = array();
  194. if(SCI::getConfigurationValue("SC_DELIVERYDATE_INSTALLED")=="1")
  195. {
  196. $sql = "SELECT * FROM "._DB_PREFIX_."sc_available_later";
  197. $res=Db::getInstance()->ExecuteS($sql);
  198. foreach($res as $row){
  199. $arrIdAvailableLater[$row['id_sc_available_later']][$row['id_lang']]=$row['available_later'];
  200. }
  201. }
  202. // fields to search in ps_product_lang
  203. $fields_lang=array('name','available_now','link_rewrite','meta_title','meta_description','meta_keywords','description_short','description','name_with_attributes');
  204. // fields specific to combination, should not be read in Product object
  205. $combination_fields=array('name_with_attributes');
  206. $not_auto_combination_fields=array();
  207. if(version_compare(_PS_VERSION_, '1.5.0.0', '>='))
  208. $not_auto_combination_fields[]='supplier_reference';
  209. $marginMatrix_forms=array(
  210. 0=>'{price}-{wholesale_price}',
  211. 1=>'({price}-{wholesale_price})*100/{wholesale_price}',
  212. 2=>'{price}/{wholesale_price}',
  213. 3=>'{price_inc_tax}/{wholesale_price}',
  214. 4=>'({price_inc_tax}-{wholesale_price})*100/{wholesale_price}',
  215. 5=>'({price}-{wholesale_price})*100/{price}'
  216. );
  217. $marginMatrix_form = $marginMatrix_forms[_s('CAT_PROD_GRID_MARGIN_OPERATION')];
  218. if (!$CRON && !$AUTO_EXPORT)
  219. showHeaders();
  220. if($AUTO_EXPORT || ($CRON && $CRONVERSION>=2))
  221. {
  222. $sql = "SELECT * FROM "._DB_PREFIX_."sc_export WHERE name='".pSQL($auto_filename)."'";
  223. $sc_export=Db::getInstance()->ExecuteS($sql);
  224. if(!empty($sc_export[0]["id_sc_export"]))
  225. {
  226. $sc_export = $sc_export[0];
  227. }
  228. else
  229. {
  230. $sql = "INSERT INTO "._DB_PREFIX_."sc_export (name, last_export, exporting, id_next, id_combination_next, total_lines)
  231. VALUES ('".pSQL($auto_filename)."',NULL,0,0,0,0)";
  232. Db::getInstance()->Execute($sql);
  233. $temp_id = Db::getInstance()->Insert_ID();
  234. if(!empty($temp_id))
  235. $sc_export = array("id_sc_export"=>$temp_id,"name"=>$auto_filename, "last_export"=>null, "exporting"=>0, "id_next"=>0,"id_combination_next"=>0,"total_lines"=>0);
  236. else
  237. {
  238. if($AUTO_EXPORT)
  239. {
  240. echo json_encode(array(
  241. "type" => "error",
  242. "stop" => 1,
  243. "content" => '<strong style="color: #831f1f;">'._l('Error during sc_export creation.', 1).'</span>',
  244. "debug" => $sql,
  245. "filename" => $auto_filename,
  246. "first_interval" => $first_interval
  247. ));
  248. die();
  249. }
  250. else
  251. {
  252. echo _l('Error during sc_export creation.');
  253. $STOP_SCRIPT= true;
  254. }
  255. }
  256. }
  257. }
  258. if($STOP_SCRIPT)
  259. break;
  260. /*$time_end = microtime(true);
  261. $time = $time_end - $time_start;
  262. echo "<br/><br/>after auto export : $time seconds";*/
  263. // GET MAPPING
  264. readExportConfigXML($filename);
  265. if ($exportConfig['fieldsep']=='dcomma') $exportConfig['fieldsep']=';';
  266. if ($exportConfig['fieldsep']=='dcommamac') $exportConfig['fieldsep']=';';
  267. if ($exportConfig['fieldsep']=='tab') $exportConfig['fieldsep']=' ';
  268. if ($exportConfig['enclosedby']=='quote') $exportConfig['enclosedby']='"';
  269. $selected_shops_id = (int)$exportConfig['shops'];
  270. if(empty($selected_shops_id))
  271. $selected_shops_id = SCI::getSelectedShop();
  272. if(empty($selected_shops_id))
  273. $selected_shops_id = (int)Configuration::get('PS_SHOP_DEFAULT');
  274. /* Server Params */
  275. $server_host = getHttpHost(false, true);
  276. $protocol = 'http://';
  277. $protocol_ssl = 'https://';
  278. $protocol_link = (Configuration::get('PS_SSL_ENABLED')) ? $protocol_ssl : $protocol;
  279. if (SCMS)
  280. {
  281. $shop=new Shop((int)$selected_shops_id);
  282. $_PS_BASE_URL_ = $protocol_link.$shop->domain.$shop->getBaseURI().'img/p/';
  283. }else{
  284. $_PS_BASE_URL_ = $protocol_link.$server_host._THEME_PROD_DIR_;
  285. }
  286. // READ MAPPING
  287. $fieldList=array();
  288. $mapping=array();
  289. if ($exportConfig['categoriessel']=='')
  290. {
  291. if(!$AUTO_EXPORT && !$CRON)
  292. die(_l('You have to set the category selection for the script')._l(':').' '.substr($filename,0,-11));
  293. elseif($CRON)
  294. {
  295. echo _l('You have to set the category selection for the script')._l(':').' '.substr($filename,0,-11);
  296. $STOP_SCRIPT = true;
  297. }
  298. else
  299. {
  300. echo json_encode(array(
  301. "type" => "error",
  302. "stop" => 1,
  303. "content" => '<strong style="color: #831f1f;">'._l('You have to set the category selection for the script')._l(':').' '.substr($filename,0,-11).'</span>',
  304. "filename" => $auto_filename,
  305. "first_interval" => $first_interval
  306. ));
  307. die();
  308. }
  309. }
  310. if ($exportConfig['mapping']=='')
  311. {
  312. if(!$AUTO_EXPORT && !$CRON)
  313. die(_l('You have to set the mapping for the script.')._l(':').' '.substr($filename,0,-11));
  314. elseif($CRON)
  315. {
  316. echo _l('You have to set the mapping for the script.')._l(':').' '.substr($filename,0,-11);
  317. $STOP_SCRIPT = true;
  318. }
  319. else
  320. {
  321. echo json_encode(array(
  322. "type" => "error",
  323. "stop" => 1,
  324. "content" => '<strong style="color: #831f1f;">'._l('You have to set the mapping for the script.')._l(':').' '.substr($filename,0,-11).'</span>',
  325. "filename" => $auto_filename,
  326. "first_interval" => $first_interval
  327. ));
  328. die();
  329. }
  330. }
  331. if ($exportConfig['mapping']!='' && $feed = @simplexml_load_file(SC_TOOLS_DIR.'cat_export/'.$exportConfig['mapping']))
  332. {
  333. foreach($feed->field AS $mfield)
  334. {
  335. if ((int)$mfield->used)
  336. {
  337. $mapping[]=array( 'name'=>(string)$mfield->name,
  338. 'lang'=>(string)$mfield->lang,
  339. 'options'=>(string)$mfield->options,
  340. 'filters'=>(string)$mfield->filters,
  341. 'modifications'=>(string)$mfield->modifications,
  342. 'column_name'=>(string)$mfield->column_name);
  343. $fieldList[]=(string)$mfield->name;
  344. }
  345. }
  346. }
  347. if ($exportConfig['exportfilename']=='')
  348. {
  349. if(!$AUTO_EXPORT && !$CRON)
  350. die(_l('You have to define a filename for the export.')._l(':').' '.substr($filename,0,-11));
  351. elseif($CRON)
  352. {
  353. echo _l('You have to define a filename for the export.')._l(':').' '.substr($filename,0,-11);
  354. $STOP_SCRIPT = true;
  355. }
  356. else
  357. {
  358. echo json_encode(array(
  359. "type" => "error",
  360. "stop" => 1,
  361. "content" => '<strong style="color: #831f1f;">'._l('You have to define a filename for the export.',1)._l(':',1).' '.substr($filename,0,-11).'</span>',
  362. "filename" => $auto_filename,
  363. "first_interval" => $first_interval
  364. ));
  365. die();
  366. }
  367. }
  368. if($STOP_SCRIPT)
  369. break;
  370. // CRON CHECK
  371. if($CRON && $CRONVERSION>=2)
  372. {
  373. if($sc_export["exporting"]==1)
  374. {
  375. $ALREADY_EXPORTING = true;
  376. }
  377. else
  378. {
  379. $sql = "UPDATE "._DB_PREFIX_."sc_export SET exporting = 1 WHERE name = '".pSQL($auto_filename)."'";
  380. Db::getInstance()->Execute($sql);
  381. }
  382. }
  383. /*$time_end = microtime(true);
  384. $time = $time_end - $time_start;
  385. echo "<br/><br/>after mapping : $time seconds";*/
  386. // AUTO EXPORT & FIRST INTERVAL
  387. if(($AUTO_EXPORT || ($CRON && $CRONVERSION>=2)) && $first_interval)
  388. {
  389. if($sc_export["exporting"]==0)
  390. {
  391. $sql = "UPDATE "._DB_PREFIX_."sc_export SET exporting = 1, id_next=0, id_combination_next=0, last_export='".date("Y-m-d H:i:s")."' WHERE name = '".pSQL($auto_filename)."'";
  392. Db::getInstance()->Execute($sql);
  393. // INITIALISATION
  394. $sql = "DELETE FROM "._DB_PREFIX_."sc_export_product WHERE id_sc_export = '".(int)$sc_export["id_sc_export"]."'";
  395. Db::getInstance()->Execute($sql);
  396. file_put_contents(SC_CSV_EXPORT_DIR.$exportConfig['exportfilename'], "");
  397. $sc_export["exporting"] = 0;
  398. $sc_export["id_next"] = 0;
  399. $sc_export["id_combination_next"] = 0;
  400. }
  401. else
  402. {
  403. $ALREADY_EXPORTING = true;
  404. /*echo json_encode(array(
  405. "type" => "error",
  406. "stop" => 1,
  407. "content" => '<strong style="color: #831f1f;">'._l('This export is already in progress.',1).'</span>',
  408. "filename" => $auto_filename,
  409. "first_interval" => $first_interval
  410. ));
  411. die();*/
  412. }
  413. }
  414. //die("error");
  415. // MAIN QUERIES
  416. if ($exportConfig['exportbydefaultcategory']) // by default category
  417. {
  418. // TOTAL LINES
  419. /*if($AUTO_EXPORT && $first_interval)
  420. {
  421. $sql= ' SELECT p.id_product,c.id_category';
  422. $sql.=' FROM '._DB_PREFIX_.'product p';
  423. if(SCMS && $selected_shops_id > 0)
  424. $sql.=' INNER JOIN `'._DB_PREFIX_.'product_shop` ps ON (p.id_product = ps.id_product AND ps.id_shop = "'.(int)$selected_shops_id.'")';
  425. $sql.=' LEFT JOIN '._DB_PREFIX_.'category_product pdc ON (pdc.id_category='.( SCMS && $selected_shops_id > 0 ? 'ps':'p').'.id_category_default AND pdc.id_product=p.id_product)';
  426. $sql.=' LEFT JOIN '._DB_PREFIX_.'category c ON (c.id_category=pdc.id_category)';
  427. $sql.=' WHERE 1';
  428. switch($exportConfig['categoriessel']){
  429. case 'all' :
  430. break;
  431. case 'all_enabled' :
  432. $sql.=' AND c.active=1'."\n";
  433. break;
  434. case 'all_disabled' :
  435. $sql.=' AND c.active=0'."\n";
  436. break;
  437. default:
  438. $filename=$exportConfig['categoriessel'];
  439. $categories=array();
  440. if ($feed = simplexml_load_file(SC_TOOLS_DIR.'cat_categories_sel/'.$filename))
  441. {
  442. foreach($feed->category AS $category)
  443. $categories[]=(string)$category->id;
  444. $sql.=' AND pdc.id_category IN ('.join(',',$categories).')';
  445. }
  446. break;
  447. }
  448. if(SCMS && $selected_shops_id>0)
  449. {
  450. $sql.=((int)($exportConfig['exportdisabledproducts'])?'':' AND ps.active=1');
  451. }else{
  452. $sql.=((int)($exportConfig['exportdisabledproducts'])?'':' AND p.active=1');
  453. }
  454. $sql.=' GROUP BY p.id_product,c.id_category';
  455. $total_products=Db::getInstance()->ExecuteS($sql);
  456. $sc_export["total_lines"] = count($total_products);
  457. $sql = "UPDATE "._DB_PREFIX_."sc_export SET total_lines='".(int)$sc_export["total_lines"]."' WHERE name = '".pSQL($auto_filename)."'";
  458. Db::getInstance()->Execute($sql);
  459. }*/
  460. $sql= ' SELECT p.id_product,c.id_category';
  461. $sql.=' FROM '._DB_PREFIX_.'product p';
  462. if(SCMS && $selected_shops_id > 0)
  463. $sql.=' INNER JOIN `'._DB_PREFIX_.'product_shop` ps ON (p.id_product = ps.id_product AND ps.id_shop = "'.(int)$selected_shops_id.'")';
  464. elseif(!SCMS && version_compare(_PS_VERSION_, '1.5.0.0', '>='))
  465. $sql.=' INNER JOIN `'._DB_PREFIX_.'product_shop` ps ON (p.id_product = ps.id_product AND ps.id_shop = "'.SCI::getSelectedShop().'")';
  466. $sql.=' LEFT JOIN '._DB_PREFIX_.'category_product pdc ON (pdc.id_category='.((SCMS && $selected_shops_id > 0) || (!SCMS && version_compare(_PS_VERSION_, '1.5.0.0', '>='))? 'ps':'p').'.id_category_default AND pdc.id_product=p.id_product)';
  467. $sql.=' LEFT JOIN '._DB_PREFIX_.'category c ON (c.id_category=pdc.id_category)';
  468. $sql.=' WHERE 1';
  469. switch($exportConfig['categoriessel']){
  470. case 'all' :
  471. break;
  472. case 'all_enabled' :
  473. $sql.=' AND c.active=1'."\n";
  474. break;
  475. case 'all_disabled' :
  476. $sql.=' AND c.active=0'."\n";
  477. break;
  478. default:
  479. $filename=$exportConfig['categoriessel'];
  480. $categories=array();
  481. if ($feed = simplexml_load_file(SC_TOOLS_DIR.'cat_categories_sel/'.$filename))
  482. {
  483. foreach($feed->category AS $category)
  484. $categories[]=(string)$category->id;
  485. $sql.=' AND pdc.id_category IN ('.join(',',$categories).')';
  486. }
  487. break;
  488. }
  489. if((SCMS && $selected_shops_id > 0) || (!SCMS && version_compare(_PS_VERSION_, '1.5.0.0', '>=')))
  490. {
  491. $sql.=((int)($exportConfig['exportdisabledproducts'])?'':' AND ps.active=1');
  492. }else{
  493. $sql.=((int)($exportConfig['exportdisabledproducts'])?'':' AND p.active=1');
  494. }
  495. if($AUTO_EXPORT || ($CRON && $CRONVERSION>=2))
  496. {
  497. $sql.=' AND (
  498. p.id_product NOT IN (SELECT id_product FROM '._DB_PREFIX_.'sc_export_product WHERE id_sc_export = "'.(int)$sc_export["id_sc_export"].'" AND handled=1) ';
  499. if(!empty($sc_export["id_next"]) && $exportConfig['exportcombinations'])
  500. $sql.=' OR (p.id_product = "'.$sc_export["id_next"].'") ';
  501. $sql.=' ) ';
  502. }
  503. $sql.=' GROUP BY p.id_product,c.id_category';
  504. if($AUTO_EXPORT || ($CRON && $CRONVERSION>=2))
  505. {
  506. if(!empty($sc_export["id_next"]) && $exportConfig['exportcombinations'])
  507. $sql.=' ORDER BY p.id_product ASC
  508. LIMIT '.intval($export_limit+1);
  509. else
  510. $sql.=' ORDER BY p.id_product ASC
  511. LIMIT '.intval($export_limit);
  512. }
  513. else
  514. $sql.=' ORDER BY p.id_category_default, pdc.position';
  515. }else{ // for all categories
  516. // TOTAL LINES
  517. /*if($AUTO_EXPORT && $first_interval)
  518. {
  519. $sql= ' SELECT DISTINCT cp.id_product,cp.id_category';
  520. $sql.=' FROM '._DB_PREFIX_.'category_product cp';
  521. $sql.=' LEFT JOIN '._DB_PREFIX_.'category c ON (c.id_category=cp.id_category)';
  522. $sql.=' LEFT JOIN '._DB_PREFIX_.'product p ON (p.id_product=cp.id_product)';
  523. if(SCMS && $selected_shops_id>0)
  524. {
  525. $sql.=' INNER JOIN `'._DB_PREFIX_.'product_shop` ps ON (p.id_product = ps.id_product AND ps.id_shop = "'.(int)$selected_shops_id.'")';
  526. }
  527. $sql.=' WHERE 1';
  528. switch($exportConfig['categoriessel']){
  529. case 'all' :
  530. break;
  531. case 'all_enabled' :
  532. $sql.=' AND c.active=1';
  533. break;
  534. case 'all_disabled' :
  535. $sql.=' AND c.active=0';
  536. break;
  537. default:
  538. $filename=$exportConfig['categoriessel'];
  539. $categories=array();
  540. if ($feed = simplexml_load_file(SC_TOOLS_DIR.'cat_categories_sel/'.$filename))
  541. {
  542. foreach($feed->category AS $category)
  543. $categories[]=(string)$category->id;
  544. $sql.=' AND cp.id_category IN ('.join(',',$categories).')';
  545. }
  546. break;
  547. }
  548. if(SCMS && $selected_shops_id>0)
  549. {
  550. $sql.=((int)($exportConfig['exportdisabledproducts'])?'':' AND ps.active=1');
  551. }else{
  552. $sql.=((int)($exportConfig['exportdisabledproducts'])?'':' AND p.active=1');
  553. }
  554. $sql.=' GROUP BY cp.id_product,cp.id_category';
  555. $total_products=Db::getInstance()->ExecuteS($sql);
  556. $sc_export["total_lines"] = count($total_products);
  557. $sql = "UPDATE "._DB_PREFIX_."sc_export SET total_lines='".(int)$sc_export["total_lines"]."' WHERE name = '".pSQL($auto_filename)."'";
  558. Db::getInstance()->Execute($sql);
  559. }*/
  560. $sql= ' SELECT DISTINCT(cp.id_product),cp.id_category';
  561. $sql.=' FROM '._DB_PREFIX_.'category_product cp';
  562. $sql.=' LEFT JOIN '._DB_PREFIX_.'category c ON (c.id_category=cp.id_category)';
  563. $sql.=' LEFT JOIN '._DB_PREFIX_.'product p ON (p.id_product=cp.id_product)';
  564. if(SCMS && $selected_shops_id > 0)
  565. $sql.=' INNER JOIN `'._DB_PREFIX_.'product_shop` ps ON (p.id_product = ps.id_product AND ps.id_shop = "'.(int)$selected_shops_id.'")';
  566. elseif(!SCMS && version_compare(_PS_VERSION_, '1.5.0.0', '>='))
  567. $sql.=' INNER JOIN `'._DB_PREFIX_.'product_shop` ps ON (p.id_product = ps.id_product AND ps.id_shop = "'.SCI::getSelectedShop().'")';
  568. $sql.=' WHERE 1';
  569. switch($exportConfig['categoriessel']){
  570. case 'all' :
  571. break;
  572. case 'all_enabled' :
  573. $sql.=' AND c.active=1';
  574. break;
  575. case 'all_disabled' :
  576. $sql.=' AND c.active=0';
  577. break;
  578. default:
  579. $filename=$exportConfig['categoriessel'];
  580. $categories=array();
  581. if ($feed = simplexml_load_file(SC_TOOLS_DIR.'cat_categories_sel/'.$filename))
  582. {
  583. foreach($feed->category AS $category)
  584. $categories[]=(string)$category->id;
  585. $sql.=' AND cp.id_category IN ('.join(',',$categories).')';
  586. }
  587. break;
  588. }
  589. if((SCMS && $selected_shops_id > 0) || (!SCMS && version_compare(_PS_VERSION_, '1.5.0.0', '>=')))
  590. {
  591. $sql.=((int)($exportConfig['exportdisabledproducts'])?'':' AND ps.active=1');
  592. }else{
  593. $sql.=((int)($exportConfig['exportdisabledproducts'])?'':' AND p.active=1');
  594. }
  595. if($AUTO_EXPORT || ($CRON && $CRONVERSION>=2))
  596. {
  597. $sql.=' AND (
  598. cp.id_product NOT IN (SELECT id_product FROM '._DB_PREFIX_.'sc_export_product WHERE id_sc_export = "'.(int)$sc_export["id_sc_export"].'") ';
  599. if(!empty($sc_export["id_next"]) && $exportConfig['exportcombinations'])
  600. $sql.=' OR (cp.id_product = "'.$sc_export["id_next"].'") ';
  601. $sql.=' ) ';
  602. }
  603. $sql.=' GROUP BY cp.id_product';
  604. if($AUTO_EXPORT || ($CRON && $CRONVERSION>=2))
  605. {
  606. if(!empty($sc_export["id_next"]) && $exportConfig['exportcombinations'])
  607. $sql.=' ORDER BY cp.id_product ASC
  608. LIMIT '.intval($export_limit+1);
  609. else
  610. $sql.=' ORDER BY cp.id_product ASC
  611. LIMIT '.intval($export_limit);
  612. }
  613. else
  614. $sql.=' ORDER BY cp.id_category, cp.position';
  615. }
  616. $products=Db::getInstance()->ExecuteS($sql);
  617. if (!is_array($products))
  618. {
  619. if(!$CRON)
  620. {
  621. echo json_encode(array(
  622. "type" => "error",
  623. "stop" => 1,
  624. "content" => '<strong style="color: #831f1f;">MySQL error: '.Db::getInstance()->getMsgError().'</span>',
  625. "filename" => $auto_filename,
  626. "debug" => $debug,
  627. "first_interval" => $first_interval
  628. ));
  629. exit;
  630. }
  631. }
  632. // $debug .= Db::getInstance()->getMsgError();
  633. $linecount=0;
  634. $linecountreal=0;
  635. /*$time_end = microtime(true);
  636. $time = $time_end - $time_start;
  637. echo "<br/><br/>after products : $time seconds";*/
  638. // ALREADY EXPORTING
  639. if(($AUTO_EXPORT || ($CRON && $CRONVERSION>=2)) && $ALREADY_EXPORTING && !$exportConfig['exportcombinations'])
  640. {
  641. if(!empty($products[0]["id_product"]))
  642. {
  643. $id_product_first = $products[0]["id_product"];
  644. if($id_product_first==$sc_export["id_next"])
  645. {
  646. $sql = "UPDATE "._DB_PREFIX_."sc_export SET exporting = 0 WHERE name = '".pSQL($auto_filename)."'";
  647. Db::getInstance()->Execute($sql);
  648. if($AUTO_EXPORT)
  649. {
  650. echo json_encode(array(
  651. "type" => "error",
  652. "stop" => 1,
  653. "content" => '<strong style="color: #831f1f;">'._l('An error occured during last export with product').' #'.$id_product_first.' <br/>'._l('Check this product before to try again.').'</span>',
  654. "filename" => $auto_filename,
  655. "first_interval" => $first_interval
  656. ));
  657. die();
  658. }
  659. else
  660. {
  661. $STOP_SCRIPT = true;
  662. echo _l('An error occured during last export with product').' #'.$id_product_first.' <br/>'._l('Check this product before to try again.');
  663. }
  664. }
  665. else
  666. {
  667. if($AUTO_EXPORT)
  668. {
  669. echo json_encode(array(
  670. "type" => "error",
  671. "stop" => 1,
  672. "content" => '<strong style="color: #831f1f;">'._l('This export is already in progress.',1).' - <a href="javascript: void(0);" class="reset_export" id="export_'.(int)$sc_export["id_sc_export"].'">'._l('Reset',1).'</a></span>',
  673. "filename" => $auto_filename,
  674. "first_interval" => $first_interval
  675. ));
  676. die();
  677. }
  678. else
  679. {
  680. $STOP_SCRIPT = true;
  681. echo _l('This export is already in progress.');
  682. }
  683. }
  684. }
  685. else
  686. {
  687. $sql = "UPDATE "._DB_PREFIX_."sc_export SET exporting = 0 WHERE name = '".pSQL($auto_filename)."'";
  688. Db::getInstance()->Execute($sql);
  689. if($AUTO_EXPORT)
  690. {
  691. echo json_encode(array(
  692. "type" => "error",
  693. "stop" => 1,
  694. "content" => '<strong style="color: #831f1f;">'._l('An error occured during export. Please try again.',1).'</span>',
  695. "filename" => $auto_filename,
  696. "first_interval" => $first_interval
  697. ));
  698. die();
  699. }
  700. else
  701. {
  702. $STOP_SCRIPT = true;
  703. echo _l('An error occured during export. Please try again.');
  704. }
  705. }
  706. }
  707. if($STOP_SCRIPT)
  708. break;
  709. // WRITE FILE
  710. if(($AUTO_EXPORT || ($CRON && $CRONVERSION>=2)) && $ALREADY_EXPORTING)
  711. $fp = null;
  712. elseif(($AUTO_EXPORT || ($CRON && $CRONVERSION>=2)) && !$ALREADY_EXPORTING)
  713. $fp = fopen(SC_CSV_EXPORT_DIR.$exportConfig['exportfilename'], 'a');
  714. else
  715. $fp = fopen(SC_CSV_EXPORT_DIR.$exportConfig['exportfilename'], 'w');
  716. // First line
  717. if((!$AUTO_EXPORT && !($CRON && $CRONVERSION>=2)) || (($AUTO_EXPORT || ($CRON && $CRONVERSION>=2)) && $first_interval && !$ALREADY_EXPORTING))
  718. {
  719. if ($exportConfig['firstlinecontent']!='')
  720. {
  721. if (trim($exportConfig['firstlinecontent'])!='-')
  722. fwrite($fp,((int)$exportConfig['iso']?utf8_decode($exportConfig['firstlinecontent']):$exportConfig['firstlinecontent'])."\n");
  723. }else{
  724. $fname=getExportCSVFields();
  725. $fname=array_flip($fname);
  726. $names=array();
  727. $image_link_num=1;
  728. $image_id_num=1;
  729. $image_legend_num=1;
  730. foreach($fieldList as $k => $mfield)
  731. {
  732. if(!empty($mapping[$k]['column_name']))
  733. $names[]=stripslashes($mapping[$k]['column_name']);
  734. else
  735. {
  736. if(SCAS && ($mfield=="quantity" || $mfield=="location" || $mfield=="quantity_physical" || $mfield=="quantity_usable" || $mfield=="quantity_real"))
  737. {
  738. $temp_name = $fname[$mfield];
  739. if(empty($mapping[$k]['options']) || $mapping[$k]['options']=="warehouse_none")
  740. $temp_name .= " "._l('No warehouse');
  741. else
  742. {
  743. $temp = intval(str_replace("warehouse_","",$mapping[$k]['options']));
  744. if(!empty($temp))
  745. {
  746. $warehouse = new Warehouse((int)$temp, (int)$id_lang);
  747. if(!empty($warehouse->name))
  748. $temp_name .= " "._l('Warehouse')." ".$warehouse->reference." - ".$warehouse->name;
  749. }
  750. }
  751. $names[]=stripslashes($temp_name);
  752. }
  753. elseif($mfield=="supplier_reference" || $mfield=="wholesale_price")
  754. {
  755. $temp_name = $fname[$mfield];
  756. if(empty($mapping[$k]['options']) || $mapping[$k]['options']=="supplier_none")
  757. $temp_name .= " "._l('Default values display products/combinations grids');
  758. else
  759. {
  760. $temp = ($mapping[$k]['options']);
  761. if(!empty($temp))
  762. {
  763. $temp_name .= " "._l('Supplier')." ".$temp;
  764. }
  765. }
  766. $names[]=stripslashes($temp_name);
  767. }
  768. elseif($mfield=="links_to_all_images")
  769. {
  770. $names[]=stripslashes($fname[$mfield]);
  771. }
  772. elseif($mfield=="image_link" || $mfield=="image_id" || $mfield=="image_legend")
  773. {
  774. $num = 1;
  775. if($mfield=="image_link")
  776. {
  777. $num = $image_link_num;
  778. $image_link_num++;
  779. }
  780. if($mfield=="image_id")
  781. {
  782. $num = $image_id_num;
  783. $image_id_num++;
  784. }
  785. if($mfield=="image_legend")
  786. {
  787. $num = $image_legend_num;
  788. $image_legend_num++;
  789. }
  790. $names[]=stripslashes($fname[$mfield].($mapping[$k]['options']!='' && $mapping[$k]['options']!="supplier_none"?' '.$mapping[$k]['options']:'').($mapping[$k]['lang']!=''?' '.strtoupper($mapping[$k]['lang']):'')." ".$num);
  791. }
  792. else
  793. {
  794. $names[]=stripslashes($fname[$mfield].($mapping[$k]['options']!='' && $mapping[$k]['options']!="supplier_none"?' '.$mapping[$k]['options']:'').($mapping[$k]['lang']!=''?' '.strtoupper($mapping[$k]['lang']):''));
  795. }
  796. }
  797. }
  798. fwrite($fp,((int)$exportConfig['iso']?utf8_decode(join($exportConfig['fieldsep'],$names)):join($exportConfig['fieldsep'],$names))."\n");
  799. }
  800. }
  801. // supplier
  802. if (sc_in_array('supplier_reference',$fieldList,"catWinExportProcess_fieldList") || sc_in_array('wholesale_price',$fieldList,"catWinExportProcess_fieldList"))
  803. {
  804. $suppliersListByLang=array();
  805. // DEFAULT LANG
  806. $sql='SELECT s.name,s.`id_supplier`
  807. FROM `'._DB_PREFIX_.'supplier` s
  808. '.((SCMS && $selected_shops_id>0)?' INNER JOIN `'._DB_PREFIX_.'supplier_shop` ss ON (s.`id_supplier` = ss.`id_supplier` AND ss.id_shop = "'.(int)$selected_shops_id.'") ':'').'';
  809. $suppliers=Db::getInstance()->ExecuteS($sql);
  810. foreach($suppliers AS $supplier)
  811. $suppliersListByLang[$supplier['name']]=$supplier['id_supplier'];
  812. }
  813. // PRODUCTS TREATMENT
  814. foreach($products AS $idp)
  815. {
  816. $id_product_attribute=0;
  817. $sql = "UPDATE "._DB_PREFIX_."sc_export SET id_next = '".(int)$idp['id_product']."' WHERE name = '".pSQL($auto_filename)."'";
  818. Db::getInstance()->Execute($sql);
  819. // array_diff checks if we need to load product details (more queries to handle)
  820. if(SCMS && $selected_shops_id>0)
  821. $p=new Product($idp['id_product'], (count($fieldList)!=count(array_diff($fieldList,array('supplier','manufacturer','vat','link_to_product','unity','tags'))) ? true:false), null, (int)$selected_shops_id );
  822. else
  823. $p=new Product($idp['id_product'], (count($fieldList)!=count(array_diff($fieldList,array('supplier','manufacturer','vat','link_to_product','unity','tags'))) ? true:false) );
  824. $id_product = $idp['id_product'];
  825. // features
  826. if (sc_in_array('feature',$fieldList,"catWinExportProcess_fieldList") || sc_in_array('multiple_features',$fieldList,"catWinExportProcess_fieldList"))
  827. {
  828. $featuresListByLang=array();
  829. // DEFAULT LANG
  830. $featuresListNameDefault = array();
  831. $sql='SELECT fl.name,fp.`id_feature`
  832. FROM `'._DB_PREFIX_.'feature_product` fp
  833. LEFT JOIN `'._DB_PREFIX_.'feature_lang` fl ON fp.`id_feature` = fl.`id_feature`
  834. '.((SCMS && $selected_shops_id>0)?' INNER JOIN `'._DB_PREFIX_.'feature_shop` fs ON (fp.`id_feature` = fs.`id_feature` AND fs.id_shop = "'.(int)$selected_shops_id.'") ':'').'
  835. WHERE fp.`id_product` = '.intval($idp['id_product']).'
  836. AND fl.`id_lang` = '.intval($sc_agent->id_lang);
  837. $features=Db::getInstance()->ExecuteS($sql);
  838. foreach($features AS $feature)
  839. $featuresListNameDefault[$feature['id_feature']]=$feature['name'];
  840. // OTHER LANGS
  841. $langs = Language::getLanguages();
  842. foreach($langs as $lang)
  843. {
  844. $sql='SELECT fl.name,fvl.value,fp.`id_feature`
  845. FROM `'._DB_PREFIX_.'feature_product` fp
  846. LEFT JOIN `'._DB_PREFIX_.'feature_lang` fl ON fp.`id_feature` = fl.`id_feature`
  847. LEFT JOIN `'._DB_PREFIX_.'feature_value_lang` fvl ON fp.`id_feature_value` = fvl.`id_feature_value`
  848. '.((SCMS && $selected_shops_id>0)?' INNER JOIN `'._DB_PREFIX_.'feature_shop` fs ON (fp.`id_feature` = fs.`id_feature` AND fs.id_shop = "'.(int)$selected_shops_id.'") ':'').'
  849. WHERE fp.`id_product` = '.intval($idp['id_product']).'
  850. AND fl.`id_lang` = '.intval($lang['id_lang']).'
  851. AND fvl.`id_lang` = '.intval($lang['id_lang']);
  852. $features=Db::getInstance()->ExecuteS($sql);
  853. $featuresListByLang[$lang['id_lang']]=array();
  854. foreach($features AS $feature)
  855. {
  856. $featuresListByLang[$lang['id_lang']][$featuresListNameDefault[$feature['id_feature']]]=$feature['value'];
  857. }
  858. }
  859. }
  860. // combinations
  861. if(
  862. (!$AUTO_EXPORT && !($CRON && $CRONVERSION>=2))
  863. || (($AUTO_EXPORT || ($CRON && $CRONVERSION>=2)) && $exportConfig['exportcombinations'] && $idp['id_product']!=$sc_export["id_next"])
  864. || (($AUTO_EXPORT || ($CRON && $CRONVERSION>=2)) && !$exportConfig['exportcombinations'])
  865. )
  866. $combArray=array(0 => array()); // 0: initialize array for products without combinations
  867. else
  868. $combArray=array();
  869. if ($exportConfig['exportcombinations'])
  870. {
  871. // IN DEFAULT LANG
  872. $attributesByDefaultLang = array();
  873. $sql='SELECT agl.`name` AS group_name, ag.`id_attribute_group`
  874. FROM `'._DB_PREFIX_.'attribute_group` ag
  875. LEFT JOIN `'._DB_PREFIX_.'attribute_group_lang` agl ON (ag.`id_attribute_group` = agl.`id_attribute_group`)
  876. WHERE agl.`id_lang` = '.intval($sc_agent->id_lang).'
  877. ORDER BY ag.`id_attribute_group`';
  878. $temp_attributes = Db::getInstance()->ExecuteS($sql);
  879. foreach($temp_attributes as $temp_attribute)
  880. {
  881. $attributesByDefaultLang[$temp_attribute['id_attribute_group']]=$temp_attribute['group_name'];
  882. }
  883. /* Build attributes combinaisons */
  884. $standardFields=array('price','wholesale_price','weight','reference','upc','unit_price_impact','supplier_reference','ean13','default_on','ecotax');
  885. if (version_compare(_PS_VERSION_, '1.5.0.0', '>='))
  886. $standardFields[] = 'available_date';
  887. if (!SCAS)
  888. $standardFields[] = 'location';
  889. sc_ext::readExportCSVConfigXML('addInCombiFields');
  890. //pa.id_product_attribute, pa.quantity, pa.'.(implode(", pa.", $standardFields)).'
  891. $sql='SELECT pa.*, ag.`id_attribute_group`, ag.`is_color_group`, agl.`name` AS group_name, al.`name` AS attribute_name, a.`id_attribute`, a.`color`,al.id_lang '.((version_compare(_PS_VERSION_, '1.5.0.0', '>=') && $selected_shops_id>0)?',pas.*':"").'
  892. FROM `'._DB_PREFIX_.'product_attribute` pa
  893. LEFT JOIN `'._DB_PREFIX_.'product_attribute_combination` pac ON pac.`id_product_attribute` = pa.`id_product_attribute`
  894. LEFT JOIN `'._DB_PREFIX_.'attribute` a ON a.`id_attribute` = pac.`id_attribute`
  895. LEFT JOIN `'._DB_PREFIX_.'attribute_group` ag ON ag.`id_attribute_group` = a.`id_attribute_group`
  896. LEFT JOIN `'._DB_PREFIX_.'attribute_lang` al ON (a.`id_attribute` = al.`id_attribute`)
  897. LEFT JOIN `'._DB_PREFIX_.'attribute_group_lang` agl ON (ag.`id_attribute_group` = agl.`id_attribute_group` AND al.`id_lang` = agl.`id_lang`)
  898. '.((version_compare(_PS_VERSION_, '1.5.0.0', '>=') && $selected_shops_id>0)?' INNER JOIN `'._DB_PREFIX_.'product_attribute_shop` pas ON (pa.`id_product_attribute` = pas.`id_product_attribute` AND pas.id_shop="'.(int)$selected_shops_id.'")':"").'
  899. WHERE pa.`id_product` = '.intval($p->id).' ';
  900. if($AUTO_EXPORT || ($CRON && $CRONVERSION>=2))
  901. {
  902. $sql.=' AND (
  903. pa.id_product_attribute NOT IN (SELECT id_product_attribute FROM '._DB_PREFIX_.'sc_export_product WHERE id_sc_export = "'.(int)$sc_export["id_sc_export"].'" AND id_product="'.intval($p->id).'") ';
  904. $sql.=' ) ';
  905. }
  906. $sql.=' ORDER BY pa.`id_product_attribute`';
  907. $combinaisons = Db::getInstance()->ExecuteS($sql);
  908. $groups = array();
  909. if (is_array($combinaisons))
  910. {
  911. $combinationImages = getCombinationImages((int)$p->id);
  912. foreach ($combinaisons AS $k => $combinaison)
  913. {
  914. $id_product_attribute = $combinaison['id_product_attribute'];
  915. if (!$exportConfig['exportoutofstock'])
  916. {
  917. if (version_compare(_PS_VERSION_, '1.5.0.0', '>='))
  918. $qty=StockAvailable::getQuantityAvailableByProduct($p->id, ($id_product_attribute==0 ? NULL:$id_product_attribute), (version_compare(_PS_VERSION_, '1.5.0.0', '>=') && $selected_shops_id>0?(int)$selected_shops_id:null));
  919. else
  920. $qty=intval($combinaison['quantity']);
  921. if ($qty<=0)
  922. continue;
  923. }
  924. //if (!$exportConfig['exportoutofstock'] && intval($combinaison['quantity'])==0) continue;
  925. $combArray[$combinaison['id_product_attribute']]['price_impact'] = $combinaison['price'];
  926. $combArray[$combinaison['id_product_attribute']]['pa_location'] = $combinaison['location'];
  927. $combArray[$combinaison['id_product_attribute']]['weight_impact'] = $combinaison['weight'];
  928. $combArray[$combinaison['id_product_attribute']]['attribute_color'] = $combinaison['color'];
  929. if(isset($combinaison['minimal_quantity']))
  930. $combArray[$combinaison['id_product_attribute']]['minimal_quantity'] = $combinaison['minimal_quantity'];
  931. if(!empty($sc_active))
  932. $combArray[$combinaison['id_product_attribute']]['sc_active'] = $combinaison['sc_active'];
  933. if(SCI::getConfigurationValue("SC_DELIVERYDATE_INSTALLED")=="1")
  934. $combArray[$combinaison['id_product_attribute']]['id_sc_available_later'] = $combinaison['id_sc_available_later'];
  935. $combArray[$combinaison['id_product_attribute']]['id_image'] = sc_array_key_exists($combinaison['id_product_attribute'],$combinationImages) ? $combinationImages[$combinaison['id_product_attribute']] : 0;
  936. $combArray[$combinaison['id_product_attribute']]['attributes'][$combinaison['id_lang']][] = array($combinaison['group_name'], $combinaison['attribute_name'], $combinaison['id_attribute'], $combinaison['id_attribute_group']);
  937. //$standardFields=array('price','wholesale_price','weight','reference','upc','unit_price_impact','supplier_reference','ean13','location','default_on','ecotax');
  938. foreach($standardFields AS $sfield)
  939. {
  940. if (sc_array_key_exists($sfield,$combinaison))
  941. $combArray[$combinaison['id_product_attribute']][$sfield] = $combinaison[$sfield];
  942. if (version_compare(_PS_VERSION_, '1.5.0.0', '>=') && $sfield=='supplier_reference')
  943. $combArray[$combinaison['id_product_attribute']][$sfield] = ProductSupplier::getProductSupplierReference((int)$p->id, (int)$combinaison['id_product_attribute'], (int)$p->id_supplier);
  944. }
  945. if(intval(_s("CAT_EXPORT_EAN13_COMBI"))!="1")
  946. {
  947. if(empty($combinaison['ean13']))
  948. {
  949. $combArray[$combinaison['id_product_attribute']]['ean13']="";
  950. }
  951. }
  952. if(intval(_s("CAT_EXPORT_UPC_COMBI"))!="1")
  953. {
  954. if(empty($combinaison['upc']))
  955. {
  956. $combArray[$combinaison['id_product_attribute']]['upc']="";
  957. }
  958. }
  959. if(intval(_s("CAT_EXPORT_REF_COMBI"))!="1")
  960. {
  961. if(empty($combinaison['reference']))
  962. {
  963. $combArray[$combinaison['id_product_attribute']]['reference']="";
  964. }
  965. }
  966. if ($combinaison['is_color_group'])
  967. $groups[$combinaison['id_attribute_group']] = $combinaison['group_name'];
  968. }
  969. if (count($combArray)>1) // unset products without combinations to skip next foreach
  970. unset($combArray[0]);
  971. foreach($combArray AS $id_product_attribute => $attributes)
  972. {
  973. if ($id_product_attribute!=0)
  974. foreach($attributes['attributes'] AS $id_lang => $values)
  975. {
  976. foreach($values AS $v)
  977. {
  978. if (!isset($combArray[$id_product_attribute]['name_with_attributes'][$id_lang]))
  979. $combArray[$id_product_attribute]['name_with_attributes'][$id_lang] = $p->name[intval($id_lang)].' ';
  980. $combArray[$id_product_attribute]['name_with_attributes'][$id_lang].=$v[0].':'.$v[1].' - ';
  981. if (!isset($combArray[$id_product_attribute]['attributeByGroup'][$id_lang]))
  982. $combArray[$id_product_attribute]['attributeByGroup'][$id_lang] = array();
  983. $combArray[$id_product_attribute]['attributeByGroup'][$id_lang][ $attributesByDefaultLang[$v[3]] ]=$v[1];
  984. if (!isset($combArray[$id_product_attribute]['attribute_color']))
  985. $combArray[$id_product_attribute]['attribute_color'] = '';
  986. if ($v[4]!='')
  987. $combArray[$id_product_attribute]['attribute_color'] .= ',#'.$v[4];
  988. // $group[0] : group name
  989. // $group[1] : attribute name
  990. // $group[2] : attribute id
  991. // $group[3] : id_attribute_group
  992. // $group[4] : color
  993. }
  994. }
  995. }
  996. }
  997. }
  998. // ALREADY EXPORTING
  999. if(($AUTO_EXPORT || ($CRON && $CRONVERSION>=2)) && $ALREADY_EXPORTING && $exportConfig['exportcombinations'])
  1000. {
  1001. $id_product_attribute_first = 0;
  1002. ksort($combArray);
  1003. foreach($combArray AS $id_product_attribute => $product_attribute)
  1004. {
  1005. if(!empty($id_product_attribute) && $idp['id_product']==$sc_export["id_next"])
  1006. {
  1007. $id_product_attribute_first = $id_product_attribute;
  1008. break;
  1009. }
  1010. }
  1011. if(!empty($id_product_attribute_first))
  1012. {
  1013. if($id_product_attribute_first==$sc_export["id_combination_next"])
  1014. {
  1015. $sql = "UPDATE "._DB_PREFIX_."sc_export SET exporting = 0 WHERE name = '".pSQL($auto_filename)."'";
  1016. Db::getInstance()->Execute($sql);
  1017. if($AUTO_EXPORT)
  1018. {
  1019. echo json_encode(array(
  1020. "type" => "error",
  1021. "stop" => 1,
  1022. "content" => '<strong style="color: #831f1f;">'._l('An error occured during last export with combination').' #'.$id_product_attribute_first.' '._l('from product').' #'.$idp['id_product'].'<br/>'._l('Check this combination before to try again.').'</span>',
  1023. "filename" => $auto_filename,
  1024. "first_interval" => $first_interval
  1025. ));
  1026. die();
  1027. }
  1028. else
  1029. {
  1030. $STOP_SCRIPT=true;
  1031. echo _l('An error occured during last export with combination').' #'.$id_product_attribute_first.' '._l('from product').' #'.$idp['id_product'].'<br/>'._l('Check this combination before to try again.');
  1032. }
  1033. }
  1034. else
  1035. {
  1036. if($AUTO_EXPORT)
  1037. {
  1038. echo json_encode(array(
  1039. "type" => "error",
  1040. "stop" => 1,
  1041. "content" => '<strong style="color: #831f1f;">'._l('This export is already in progress.',1).' - <a href="javascript: void(0);" class="reset_export" id="export_'.(int)$sc_export["id_sc_export"].'">'._l('Reset',1).'</a></span>',
  1042. "filename" => $auto_filename,
  1043. "first_interval" => $first_interval
  1044. ));
  1045. die();
  1046. }
  1047. else
  1048. {
  1049. $STOP_SCRIPT=true;
  1050. echo _l('This export is already in progress.');
  1051. }
  1052. }
  1053. }
  1054. else
  1055. {
  1056. $sql = "UPDATE "._DB_PREFIX_."sc_export SET exporting = 0 WHERE name = '".pSQL($auto_filename)."'";
  1057. Db::getInstance()->Execute($sql);
  1058. if($AUTO_EXPORT)
  1059. {
  1060. echo json_encode(array(
  1061. "type" => "error",
  1062. "stop" => 1,
  1063. "content" => '<strong style="color: #831f1f;">'._l('An error occured during last export with product').' #'.$idp['id_product'].' <br/>'._l('Check this product before to try again.').'</span>',
  1064. "filename" => $auto_filename,
  1065. "first_interval" => $first_interval
  1066. ));
  1067. die();
  1068. }
  1069. else
  1070. {
  1071. $STOP_SCRIPT=true;
  1072. echo _l('An error occured during last export with product').' #'.$idp['id_product'].' <br/>'._l('Check this product before to try again.');
  1073. }
  1074. }
  1075. }
  1076. if($STOP_SCRIPT)
  1077. break;
  1078. $extension_vars = array();
  1079. // COMBINATIONS TREATMENT
  1080. foreach($combArray AS $id_product_attribute => $product_attribute)
  1081. {
  1082. if(
  1083. !(
  1084. ($AUTO_EXPORT || ($CRON && $CRONVERSION>=2))
  1085. && $exportConfig['exportcombinations']
  1086. && $p->id==$sc_export["id_next"]
  1087. && !empty($id_product_attribute)
  1088. && $id_product_attribute<=$sc_export["id_combination_next"]
  1089. )
  1090. )
  1091. {
  1092. if(!empty($id_product_attribute))
  1093. {
  1094. $sql = "UPDATE "._DB_PREFIX_."sc_export SET id_combination_next = '".(int)$id_product_attribute."' WHERE name = '".pSQL($auto_filename)."'";
  1095. Db::getInstance()->Execute($sql);
  1096. }
  1097. $linecount++;
  1098. if (!$exportConfig['exportoutofstock'])
  1099. {
  1100. if (version_compare(_PS_VERSION_, '1.5.0.0', '>='))
  1101. $qty=StockAvailable::getQuantityAvailableByProduct($p->id, ($id_product_attribute==0 ? NULL:$id_product_attribute), (version_compare(_PS_VERSION_, '1.5.0.0', '>=') && $selected_shops_id>0?(int)$selected_shops_id:null));
  1102. else
  1103. $qty=$p->getQuantity($p->id,($id_product_attribute==0 ? NULL:$id_product_attribute));
  1104. if ($qty<=0)
  1105. {
  1106. if(!empty($sc_export["id_sc_export"]))
  1107. {
  1108. $sql = "
  1109. INSERT INTO "._DB_PREFIX_."sc_export_product (id_sc_export, id_product, id_product_attribute,exported)
  1110. VALUES ('".(int)$sc_export["id_sc_export"]."','".(int)$idp['id_product']."','".(int)$id_product_attribute."','0')";
  1111. Db::getInstance()->Execute($sql);
  1112. }
  1113. continue;
  1114. }
  1115. }
  1116. if(!empty($sc_export["id_sc_export"]))
  1117. {
  1118. $sql = "
  1119. INSERT INTO "._DB_PREFIX_."sc_export_product (id_sc_export, id_product, id_product_attribute,exported)
  1120. VALUES ('".(int)$sc_export["id_sc_export"]."','".(int)$idp['id_product']."','".(int)$id_product_attribute."','1')";
  1121. Db::getInstance()->Execute($sql);
  1122. }
  1123. $linecontent='';
  1124. $cacheProductImages=array();
  1125. $num_img_link = 1;
  1126. $num_img_legend = 1;
  1127. $num_img_id = 1;
  1128. $legends = array();
  1129. sc_ext::readExportCSVConfigXML('exportProcessInitRowVars');
  1130. // foreach field in mapping
  1131. foreach($mapping AS $n => $f)
  1132. {
  1133. $field='';
  1134. // extensions
  1135. $switchObject=$f['name']