/modules/storecommander/ead6f6fce09/SC/lib/cat/win-import/cat_win-import_process.php
PHP | 1109 lines | 989 code | 40 blank | 80 comment | 179 complexity | a54b26e1fd764fa58c0a2c82c2388f2d MD5 | raw file
- <?php
- /**
- * Store Commander
- *
- * @category administration
- * @author Store Commander - support@storecommander.com
- * @version 2015-09-15
- * @uses Prestashop modules
- * @since 2009
- * @copyright Copyright © 2009-2015, Store Commander
- * @license commercial
- * All rights reserved! Copying, duplication strictly prohibited
- *
- * *****************************************
- * * STORE COMMANDER *
- * * http://www.StoreCommander.com *
- * * V 2015-09-15 *
- * *****************************************
- *
- * Compatibility: PS version: 1.1 to 1.6.1
- *
- **/
-
- error_reporting(E_ERROR);
- @ini_set('display_errors', 'on');
-
- if (!isset($CRON)) $CRON=0;
-
- $action=Tools::getValue('action');
- $id_lang=intval(Tools::getValue('id_lang'));
- $mapping=Tools::getValue('mapping','');
- $create_categories=intval(Tools::getValue('create_categories',-1));
-
- if(!empty($CRON))
- Context::getContext()->employee = new Employee( Tools::getValue('id_employee') );
-
- if(SCAS)
- $stock_manager = StockManagerFactory::getManager();
-
- if (version_compare(_PS_VERSION_, '1.5.0.0', '<'))
- include_once(SC_PS_PATH_DIR.'images.inc.php');
-
- include_once(SC_DIR.'lib/php/parsecsv.lib.php');
- require_once(SC_DIR.'lib/cat/win-import/cat_win-import_tools.php');
-
- switch($action){
- case 'conf_delete':
- $imp_opt_files=Tools::getValue('imp_opt_files','');
- if ($imp_opt_files=='') die(_l('You should mark at least one file to delete'));
- $imp_opt_file_array=preg_split('/;/',$imp_opt_files);
- foreach($imp_opt_file_array as $imp_opt_file)
- {
- if ($imp_opt_file!='')
- {
- if (@unlink(SC_CSV_IMPORT_DIR.$imp_opt_file))
- {
- echo $imp_opt_file." "._l('deleted')."\n";
- }else{
- echo _l("Unable to delete this file, please check write permissions:")." ".$imp_opt_file."\n";
- }
- }
- }
- break;
- case 'mapping_load':
- echo loadMapping(Tools::getValue('filename',''));
- break;
- case 'mapping_delete':
- $filename=str_replace('.map.xml','',Tools::getValue('filename'));
- @unlink(SC_CSV_IMPORT_DIR.$filename.'.map.xml');
- break;
- case 'mapping_saveas':
- $filename=str_replace('.map.xml','',Tools::getValue('filename'));
- @unlink(SC_CSV_IMPORT_DIR.$filename.'.map.xml');
- $mapping=preg_split('/;/',$mapping);
- $content='<mapping><id_lang>'.(int)$sc_agent->id_lang.'</id_lang>';
- foreach($mapping AS $map)
- {
- $val=preg_split('/,/',$map);
- if (count($val)==3)
- {
- $content.='<map>';
- $content.='<csvname><![CDATA['.$val[0].']]></csvname>';
- $content.='<dbname><![CDATA['.$val[1].']]></dbname>';
- $content.='<options><![CDATA['.$val[2].']]></options>';
- $content.='</map>';
- }
- }
- $content.='</mapping>';
- file_put_contents(SC_CSV_IMPORT_DIR.$filename.'.map.xml', $content);
- echo _l('Data saved!');
- break;
- case 'addSupplier':
- $data=Tools::getValue('data','');
- if ($data!='')
- {
- addSupplier($data);
- die('<b>'._l('Supplier(s) created!').'</b>');
- }
- break;
- case 'addManufacturer':
- $data=Tools::getValue('data','');
- if ($data!='')
- {
- addManufacturer($data);
- die('<b>'._l('Manufacturer(s) created!').'</b>');
- }
- break;
- case 'addFeature':
- $data=Tools::getValue('data','');
- if ($data!='')
- {
- $features=explode("y|y",$data);
- sort($features);
- foreach($features AS $feature)
- {
- if ($feature!='')
- {
- $newFeature=new Feature();
- $newFeature->name[intval(Configuration::get('PS_LANG_DEFAULT'))]=trim(cleanQuotes(Tools::substr($feature,0,128)));
- $newFeature->save();
- }
- }
- die('<b>'._l('Feature(s) created!').'</b>');
- }
- break;
- case 'addFeatureValue':
- $data=Tools::getValue('data','');
- if ($data!='')
- {
- addFeatureValue($data);
- die('<b>'._l('Feature(s) created!').'</b>');
- }
- break;
- case 'addAttributeGroup':
- $data=Tools::getValue('data','');
- if ($data!='')
- {
- $groups=explode("y|y",$data);
- sort($groups);
- foreach($groups AS $group)
- {
- if ($group!='')
- {
- $newGroup=new AttributeGroup();
- if (version_compare(_PS_VERSION_, '1.5.0', '>='))
- {
- foreach($languages AS $lang)
- {
- $newgroup->name[$lang['id_lang']]=cleanQuotes(Tools::substr($group,0,64));
- $newgroup->public_name[$lang['id_lang']]=cleanQuotes(Tools::substr($group,0,64));
- }
- $newgroup->group_type='select';
- }
- $newGroup->save();
- }
- }
- die('<b>'._l('Attribute group(s) created!').'</b>');
- }
- break;
- case 'addAttributeValue':
- $data=Tools::getValue('data','');
- if ($data!='')
- {
- addAttributeValue($data);
- die('<b>'._l('Attribute(s) created!').'</b>');
- }
- break;
- case 'mapping_process':
- echo '<div style="width: 100%; height: 100%; overflow: auto;">';
- if (_s('APP_DEBUG_CATALOG_IMPORT'))
- $time_start = microtime(true);
-
- if (_s('APP_DEBUG_CATALOG_IMPORT'))
- {
- // Affichage des modules greffer au hook UpdateProduct
- if (version_compare(_PS_VERSION_,'1.5.0.0','>='))
- $hook_id = Hook::getIdByName("actionProductUpdate");
- else
- $hook_id = Hook::get("actionProductUpdate");
- if(!empty($hook_id))
- {
- $hook = new Hook((int)$hook_id);
- $modules = $hook->getHookModuleList();
- if(!empty($modules[(int)$hook_id]))
- {
- echo "<br/><br/>Liste des modules :";
- foreach($modules[(int)$hook_id] as $module)
- {
- echo "<br/>".$module["name"]." (".($module["active"]?"Activé":"Désactivé").")";
- }
- }
- }
- }
- checkDB();
- $scdebug=false;
- global $switchObject; // variable for custom import fields check
- $switchObject='';
- global $TODO; // actions
- $TODO=array();
- global $id_product,$id_product_attribute;
- $id_product=0; $id_product_attribute=0;
- $warehousesArray = array();
- $productsStockAdvancedTypeArray = array();
- $defaultLanguageId = intval(Configuration::get('PS_LANG_DEFAULT'));
- $defaultLanguage=new Language($defaultLanguageId);
- $getIDlangByISO=array();
-
- foreach($languages AS $lang)
- {
- $getIDlangByISO[$lang['iso_code']]=$lang['id_lang'];
- }
- $files = array_diff( scandir( SC_CSV_IMPORT_DIR ), array_merge( Array( ".", "..", "index.php", ".htaccess", SC_CSV_IMPORT_CONF)) );
- readImportConfigXML($files);
- $filename=Tools::getValue('filename',0);
- if ($create_categories <= 0) $create_categories=intval($importConfig[$filename]['createcategories']);
- $importlimit=intval(Tools::getValue('importlimit',0));
- $importlimit=($importlimit > 0 ? $importlimit : intval($importConfig[$filename]['importlimit']));
- if ($importConfig[$filename]['firstlinecontent']!='') $importlimit--;
- if ($CRON) $mapping=loadMapping($importConfig[$filename]['mapping']);
- if ($filename===0 || $mapping=='')
- die(_l('You have to select a file and a mapping.'));
-
- $mapping = str_replace("&", "&", $mapping);
- $mappingDataArray=explode(';',$mapping);
- $mappingData=array('CSVArray' => array(),'DBArray' => array(),'CSV2DB' => array(),'CSV2DBOptions' => array(),'CSV2DBOptionsMerged' => array());
- foreach($mappingDataArray AS $val)
- {
- if ($val!='')
- {
- $tmp=explode(',',$val);
- $tmp2=$tmp[0];
- escapeCharForPS($tmp2);
- $mappingData['CSVArray'][]=$tmp2;
- $mappingData['DBArray'][]=$tmp[1];
- $mappingData['CSV2DB'][$tmp[0]]=$tmp[1];
- $mappingData['CSV2DBOptions'][$tmp[0]]=$tmp[2];
- $mappingData['CSV2DBOptionsMerged'][$tmp[0]]=$tmp[1].'_'.$tmp[2];
- }
- }
- // check mapping
- switch ($importConfig[$filename]['idby']){
- case'prodname':
- if (!sc_in_array('name_'.$defaultLanguage->iso_code,$mappingData['CSV2DBOptionsMerged'],"catWinImportProcess_CSV2DBOptionsMerged"))
- die(_l('Wrong mapping, mapping should contain the field name in ').$defaultLanguage->iso_code.'<br/><br/>'.
- _l('For each line of the mapping you need to double click in the Database field column to fill the mapping.').'<br/><br/>'.
- _l('If the cell in the Options column becomes blue, you need to edit this cell and complete the mapping.'));
- break;
- case'prodref':
- if (!sc_in_array('reference',$mappingData['DBArray'],"catWinImportProcess_DBArray"))
- die(_l('Wrong mapping, mapping should contain the field reference'));
- break;
- case'prodrefthenprodname':
- if (!sc_in_array('reference',$mappingData['DBArray'],"catWinImportProcess_DBArray") || !sc_in_array('name_'.$defaultLanguage->iso_code,$mappingData['CSV2DBOptionsMerged'],"catWinImportProcess_CSV2DBOptionsMerged"))
- die(_l('Wrong mapping, mapping should contain the fields reference and name in ').$defaultLanguage->iso_code);
- break;
- case'suprefthenprodname':
- if (!sc_in_array('supplier_reference',$mappingData['DBArray'],"catWinImportProcess_DBArray") || !sc_in_array('name_'.$defaultLanguage->iso_code,$mappingData['CSV2DBOptionsMerged'],"catWinImportProcess_CSV2DBOptionsMerged"))
- die(_l('Wrong mapping, mapping should contain the fields supplier_reference and name in ').$defaultLanguage->iso_code);
- break;
- case'supref':
- if (!sc_in_array('supplier_reference',$mappingData['DBArray'],"catWinImportProcess_DBArray"))
- die(_l('Wrong mapping, mapping should contain the field supplier_reference'));
- break;
- case'prodrefandsupref':
- if (!sc_in_array('reference',$mappingData['DBArray'],"catWinImportProcess_DBArray") || !sc_in_array('supplier_reference',$mappingData['DBArray'],"catWinImportProcess_DBArray"))
- die(_l('Wrong mapping, mapping should contain the fields reference and supplier_reference'));
- break;
- case'prodnameandsupref':
- if (!sc_in_array('name_'.$defaultLanguage->iso_code,$mappingData['CSV2DBOptionsMerged'],"catWinImportProcess_CSV2DBOptionsMerged") || !sc_in_array('supplier_reference',$mappingData['DBArray'],"catWinImportProcess_DBArray"))
- die(_l('Wrong mapping, mapping should contain the fields supplier_reference and name in ').$defaultLanguage->iso_code);
- break;
- case'idproduct':
- if (!sc_in_array('id_product',$mappingData['DBArray'],"catWinImportProcess_DBArray"))
- die(_l('Wrong mapping, mapping should contain the field: id_product'));
- break;
- case'idproductattribute':
- if (!sc_in_array('id_product_attribute',$mappingData['DBArray'],"catWinImportProcess_DBArray"))
- die(_l('Wrong mapping, mapping should contain the field id_product_attribute'));
- break;
- case'ean13':
- if (!sc_in_array('EAN13',$mappingData['DBArray'],"catWinImportProcess_DBArray"))
- die(_l('Wrong mapping, mapping should contain the EAN field'));
- break;
- case'upc':
- if (!sc_in_array('upc',$mappingData['DBArray'],"catWinImportProcess_DBArray"))
- die(_l('Wrong mapping, mapping should contain the UPC field'));
- break;
- }
-
- // create TODO file
- if (substr($filename,strlen($filename)-9,9)=='.TODO.csv' && !file_exists(SC_CSV_IMPORT_DIR.$filename))
- die(_l('The TODO file has been deleted, please select the original CSV file.'));
- if (substr($filename,strlen($filename)-9,9)!='.TODO.csv')
- {
- $TODOfilename=substr($filename,0,-4).'.TODO.csv';
- if (!file_exists(SC_CSV_IMPORT_DIR.$TODOfilename))
- {
- copy(SC_CSV_IMPORT_DIR.$filename,SC_CSV_IMPORT_DIR.$TODOfilename);
- foreach($importConfig[$filename] AS $k => $v)
- {
- $importConfig[$TODOfilename][$k]=$v;
- if ($k=='name') $importConfig[$TODOfilename][$k]=$TODOfilename;
- }
- writeImportConfigXML();
- }
- }else{
- $TODOfilename=$filename;
- }
- $needSaveTODO=false;
-
- if(empty($importConfig[$TODOfilename]['fornewproduct']))
- $importConfig[$TODOfilename]['fornewproduct'] = "skip";
- if(empty($importConfig[$TODOfilename]['forfoundproduct']))
- $importConfig[$TODOfilename]['forfoundproduct'] = "skip";
-
- // open csv filename
- if ($importConfig[$TODOfilename]['fieldsep']=='dcomma') $importConfig[$TODOfilename]['fieldsep']=';';
- if ($importConfig[$TODOfilename]['fieldsep']=='dcommamac') $importConfig[$TODOfilename]['fieldsep']=';';
- // get first line
- $DATAFILE=remove_utf8_bom(file_get_contents(SC_CSV_IMPORT_DIR.$TODOfilename));
- $DATA = preg_split("/(?:\r\n|\r|\n)/", $DATAFILE);
- if ($importConfig[$TODOfilename]['firstlinecontent']!='')
- {
- $importConfig[$TODOfilename]['firstlinecontent'] = str_replace("&","&",$importConfig[$TODOfilename]['firstlinecontent']);
- $firstLineData=explode($importConfig[$TODOfilename]['fieldsep'],$importConfig[$TODOfilename]['firstlinecontent']);
- $FIRST_CONTENT_LINE=0;
- }else{
- $DATA[0] = str_replace("&","&",$DATA[0]);
- $firstLineData=explode($importConfig[$TODOfilename]['fieldsep'],$DATA[0]);
- $FIRST_CONTENT_LINE=1;
- }
- if (count($firstLineData)!=count(array_unique($firstLineData)))
- 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.'));
- foreach($firstLineData AS $key => $val)
- escapeCharForPS($firstLineData[$key]);
- $firstLineData=array_map('cleanQuotes',$firstLineData);
- if ($importConfig[$TODOfilename]['utf8'])
- utf8_encode_array($firstLineData);
-
- // CHECK FILE VALIDITY
- if (count($mappingData['CSVArray']) > count($firstLineData))
- die(_l('Error in mapping: too much field to import').' (CSVArray:'.count($mappingData['CSVArray']).' - firstLineData:'.count($firstLineData).')');
- foreach($mappingData['CSVArray'] AS $val)
- {
- if (!in_array($val,$firstLineData))
- die(_l('Error in mapping: the fields are not in the CSV file')._l(':').$val);
- }
-
- // PLACE VALUES IN CACHE
- if (
- sc_in_array('feature',$mappingData['DBArray'],"catWinImportProcess_DBArray")
- || sc_in_array('feature_custom',$mappingData['DBArray'],"catWinImportProcess_DBArray")
- || sc_in_array('feature_add',$mappingData['DBArray'],"catWinImportProcess_DBArray")
- || sc_in_array('feature_delete',$mappingData['DBArray'],"catWinImportProcess_DBArray")
- )
- {
- refreshCacheFeature();
- }
- if (isCombination())
- {
- refreshCacheAttribute();
- }
- 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"))
- {
- $sql="SELECT c.id_category,c.id_parent,cl.name,c.level_depth
- FROM "._DB_PREFIX_."category c
- LEFT JOIN "._DB_PREFIX_."category_lang cl ON (cl.id_category=c.id_category AND cl.id_lang=".intval($defaultLanguage->id).")
- GROUP BY c.id_category
- ORDER BY c.level_depth ASC";
- $res=Db::getInstance()->ExecuteS($sql);
- $categories=array();
- $categoriesProperties=array();
- $categoryNameByID=array();
- $categoryIDByPath=array();
- $categoriesFirstLevel=array();
-
- // debug pour voir les catégories qui sont parentes d'elles mêmes
- //$kk=0;
- //var_dump($res);
- foreach($res AS $categ)
- {
- 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'])));
- $categories[trim(hideCategoryPosition($categ['name']))]=array('id_category' => $categ['id_category'], 'id_parent' => $categ['id_parent']);
- $categoryNameByID[$categ['id_category']]=hideCategoryPosition($categ['name']);
- $categoriesProperties[$categ['id_category']]=array('id_category' => $categ['id_category'], 'id_parent' => $categ['id_parent']);
- $categoryIDByPath[getCategoryPath($categ['id_category'])]=$categ['id_category'];
- if ($categ['level_depth']==1) $categoriesFirstLevel[]=hideCategoryPosition($categ['name']);
- //$kk++;
- //if ($kk>=370) echo trim(hideCategoryPosition($categ['name'])).' '.$categ['id_parent'].' '.$categ['id_category'].'<br/>';
- //if ($kk==374) die('rr');
- }
- }
-
- // get carriers
- $dataDB_carrier=array();
- $dataDB_carrierByName=array();
- //$DB_carrier=Carrier::getCarriers(intval($defaultLanguage->id), false);
- $sql = 'SELECT c.*
- FROM `'._DB_PREFIX_.'carrier` c
- WHERE c.`deleted` = "0"
- GROUP BY c.`id_carrier`
- ORDER BY c.`position` ASC';
- $DB_carrier = Db::getInstance()->executeS($sql);
- foreach($DB_carrier AS $carrier)
- {
- $dataDB_manufacturer[$carrier['id_reference']]=$carrier['name'];
- $dataDB_carrierByName[$carrier['name']]=$carrier['id_reference'];
- }
-
- // VAT first check
- 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"))
- 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.'));
- $err_VAT=array();
- $dataArray_VAT=array();
- $dataArray_supplier=array();
- $dataArray_manufacturer=array();
- $dataArray_feature=array();
- $dataArray_multiplefeature=array();
- $dataArray_attributegroup=array();
- $dataArray_attributegroup=array();
- // $dataArray_attributegroupmultiple=array();
- $err='';
-
- for ($current_line = $FIRST_CONTENT_LINE; ((($current_line <= (count($DATA)-1)) && $line = parseCSVLine($importConfig[$TODOfilename]['fieldsep'],$DATA[$current_line])) && ($current_line <= $importlimit)) ; $current_line++)
- {
- if ($DATA[$current_line]=='') continue;
- if ($importConfig[$TODOfilename]['utf8']==1)
- utf8_encode_array($line);
- $line=array_map('cleanQuotes',$line);
- if (sc_in_array('VAT',$mappingData['DBArray'],"catWinImportProcess_DBArray"))
- {
- $vat=importConv2Float(findCSVLineValue('VAT'));
- if (!in_array($vat,$dataArray_VAT)) $dataArray_VAT[]=$vat;
- if ($vat < 0 || $vat > 100)
- $err_VAT[]=$current_line;
- }
- if (sc_in_array('supplier',$mappingData['DBArray'],"catWinImportProcess_DBArray"))
- {
- $dataArray_supplier[]=findCSVLineValue('supplier');
- }
- if (sc_in_array('supplier_default',$mappingData['DBArray'],"catWinImportProcess_DBArray"))
- {
- $dataArray_supplier[]=findCSVLineValue('supplier_default');
- }
- if (sc_in_array('manufacturer',$mappingData['DBArray'],"catWinImportProcess_DBArray"))
- {
- $dataArray_manufacturer[]=findCSVLineValue('manufacturer');
- }
- if (sc_in_array('feature',$mappingData['DBArray'],"catWinImportProcess_DBArray"))
- {
- findAllCSVLineValue('feature',$dataArray_feature,'id_feature',$features);
- }
- if (sc_in_array('feature_add',$mappingData['DBArray'],"catWinImportProcess_DBArray"))
- {
- findAllCSVLineValue('feature_add',$dataArray_multiplefeature,'id_feature',$features);
- }
- if (isCombination())
- {
- findAllCSVLineValue('attribute',$dataArray_attributegroup,'id_attribute_group',$attributeGroups);
- findAllCSVLineValue('attribute_multiple',$dataArray_attributegroup,'id_attribute_group',$attributeGroups);
- }
- if (count($line)!=count($firstLineData))
- $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/>";
- }
- /*echo "<pre>";
- print_r($mappingData);
- echo "############################";
- print_r($attributeGroups);
- echo "############################";
- print_r($dataArray_attributegroup);
- echo "</pre>";*/
-
- // VAT second check
- $isErr=false;
- if ($err_VAT)
- $err.=_l('Error: the VAT value should be between 0 and 100 on line(s) ').join(',',$err_VAT).'<br/>'.
- '<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/>';
- $dataDB_VAT=array();
- if (version_compare(_PS_VERSION_, '1.4.0.0', '<'))
- {
- $DB_VAT=Tax::getTaxes();
- foreach($DB_VAT as $tax)
- {
- $dataDB_VAT[]=importConv2Float($tax['rate']);
- }
- }else{
- $sql='SELECT trg.name, trg.id_tax_rules_group,t.rate
- FROM `'._DB_PREFIX_.'tax_rules_group` trg
- 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)
- LEFT JOIN `'._DB_PREFIX_.'tax` t ON (t.`id_tax` = tr.`id_tax`)
- WHERE trg.active=1';
- $DB_VAT=Db::getInstance()->ExecuteS($sql);
- foreach($DB_VAT as $tax)
- $dataDB_VAT[]=importConv2Float($tax['rate']);
- }
- $check_VAT=array_diff($dataArray_VAT,$dataDB_VAT);
- if (count($check_VAT))
- {
- foreach($check_VAT AS $tax)
- {
- if ($tax!=0)
- {
- $err.=_l('Error: tax doesn\'t exist: ').$tax.'<br/>';
- $isErr=true;
- }
- }
- }
- 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/>';
- // supplier check
- $isErr=false;
- $dataDB_supplier=array();
- $dataDB_supplierByName=array();
- //$DB_supplier=Supplier::getSuppliers(false,0,false);
- $DB_supplier = Db::getInstance()->ExecuteS('SELECT m.*
- FROM `'._DB_PREFIX_.'supplier` m
- ORDER BY m.`name` ASC');
- foreach($DB_supplier AS $supplier)
- {
- $dataDB_supplier[$supplier['id_supplier']]=$supplier['name'];
- $dataDB_supplierByName[$supplier['name']]=$supplier['id_supplier'];
- }
- $check_supplier=array_diff($dataArray_supplier,$dataDB_supplier);
- $check_supplier=arr_unique($check_supplier);
- if (count($check_supplier))
- {
- $err_unique=array();
- foreach($check_supplier AS $supplier)
- {
- if ($supplier!='')// && !in_array($supplier,$err_unique))
- {
- $err.=_l('This supplier doesn\'t exist: ').$supplier.'<br/>';
- $err_unique[]=$supplier;
- $isErr=true;
- }
- }
- }
- if ($isErr)
- {
- if ($importConfig[$TODOfilename]['createelements']==1)
- {
- addSupplier($err_unique);
- }else{
- $err.='<form name="fSupplierCreation" id="fSupplierCreation">
- <textarea name="data" style="display:none">';
- $err.=join("_|_",$err_unique);
- $err.='</textarea>';
- $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>';
- $err.='</form>';
- }
- }
- // visibility check
- $isErr=false;
- $dataDB_visibility=array();
- $dataDB_visibilityByName=array();
- $dataDB_visibility["both"]="both";
- $dataDB_visibilityByName["both"]="both";
- $dataDB_visibility["both"]=strtolower(_l('Both'));
- $dataDB_visibilityByName[strtolower(_l('Both'))]="both";
-
- $dataDB_visibility["catalog"]="catalog";
- $dataDB_visibilityByName["catalog"]="catalog";
- $dataDB_visibility["catalog"]=strtolower(_l('Catalog'));
- $dataDB_visibilityByName[strtolower(_l('Catalog'))]="catalog";
-
- $dataDB_visibility["search"]="search";
- $dataDB_visibilityByName["search"]="search";
- $dataDB_visibility["search"]=strtolower(_l('Search'));
- $dataDB_visibilityByName[strtolower(_l('Search'))]="search";
-
- $dataDB_visibility["none"]="none";
- $dataDB_visibilityByName["none"]="none";
- $dataDB_visibility["none"]=strtolower(_l('None'));
- $dataDB_visibilityByName[strtolower(_l('None'))]="none";
-
- // manufacturer check
- $isErr=false;
- $dataDB_manufacturer=array();
- $dataDB_manufacturerByName=array();
- //$DB_manufacturer=Manufacturer::getManufacturers(false,$id_lang,false);
- $DB_manufacturer = Db::getInstance()->ExecuteS('SELECT m.*
- FROM `'._DB_PREFIX_.'manufacturer` m
- ORDER BY m.`name` ASC');
- foreach($DB_manufacturer AS $manufacturer)
- {
- $dataDB_manufacturer[$manufacturer['id_manufacturer']]=$manufacturer['name'];
- $dataDB_manufacturerByName[$manufacturer['name']]=$manufacturer['id_manufacturer'];
- }
- $check_manufacturer=arrayDiffEmulation($dataArray_manufacturer,$dataDB_manufacturer);
- if (count($check_manufacturer))
- {
- $err_unique=array();
- foreach($check_manufacturer AS $manufacturer)
- {
- if ($manufacturer!='' && !in_array($manufacturer,$err_unique))
- {
- $err.=_l('This manufacturer doesn\'t exist: ').$manufacturer.'<br/>';
- $err_unique[]=$manufacturer;
- $isErr=true;
- }
- }
- }
- if ($isErr)
- {
- if ($importConfig[$TODOfilename]['createelements']==1)
- {
- addManufacturer($err_unique);
- }else{
- $err.='<form name="fManufacturerCreation" id="fManufacturerCreation">
- <textarea name="data" style="display:none">';
- $err.=join("_|_",$err_unique);
- $err.='</textarea>';
- $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>';
- $err.='</form>';
- }
- }
- // feature check
-
- $isErr=false;
- $err_unique=array();
- foreach($mappingData['CSV2DBOptions'] AS $CSVFieldName => $featureName)
- {
- if ( sc_in_array($mappingData['CSV2DB'][$CSVFieldName], array('feature','feature_custom','feature_add','feature_delete'),"catWinImportProcess_featurefields"))
- {
- if (!sc_in_array($featureName,array_keys($features),"catWinImportProcess_features") && !in_array($featureName,$err_unique))
- {
- $err.=_l('This feature doesn\'t exist: ').$featureName.'<br/>';
- $err_unique[]=$featureName;
- $isErr=true;
- }
- }
- }
-
- if ($isErr)
- {
- if ($importConfig[$TODOfilename]['createelements']==1)
- {
- $data='';
- foreach($err_unique AS $feature)
- {
- $data.=$feature."y|y";
- }
- addFeature($data);
- refreshCacheFeature();
- $isErr = false;
- //$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>';
- }else{
- $err.='<form name="fFeatureCreation" id="fFeatureCreation">
- <textarea name="data" style="display:none">';
- foreach($err_unique AS $feature)
- {
- $err.=$feature."y|y";
- }
- $err.='</textarea>';
- $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>';
- $err.='</form>';
- }
- }
-
- // feature value check
- if (!$isErr)
- {
- $isErr=false;
- $dataArray_feature_unique=array();
- // only for multiplefeature management
- foreach($dataArray_multiplefeature AS $key => $val)
- {
- $vals = explode($importConfig[$TODOfilename]['valuesep'],$val['value']);
- foreach ($vals AS $k => $uval)
- {
- $uarr = $dataArray_multiplefeature[$key];
- $uarr['value'] = $uval;
- $dataArray_feature[] = $uarr;
- }
- }
- foreach($dataArray_feature AS $f)
- {
- //echo $f['value'].'X';
- //echo $f['id_feature'].'x|x'.$f['object'].'x|x'.$f['value'].'<br/>';
- //var_dump($dataArray_feature_unique);
- //var_dump($featureValues);
- /*
- var_dump($dataArray_feature);
- die('rr');
- if ($f['value']=='CR250R'){
- if($f['value']!='') echo 'C1OK';
- if(!in_array($f['id_feature'].'_|_'.$f['value'],array_keys($featureValues))) echo 'C2OK';
- if(!in_array($f['id_feature'].'x|x'.$f['object'].'x|x'.$f['id_feature'].'_|_'.$f['value'],$dataArray_feature_unique)) echo 'C3OK';
- 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';
- echo 'XXX<br/>';
- die('rr');
- }*/
- $f['value']=trim($f['value']);
- 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))
- {
- $err.=_l('This feature doesn\'t exist: ').$f['object'].' > '.$f['value'].'<br/>';
- $dataArray_feature_unique[]=$f['id_feature'].'x|x'.$f['object'].'x|x'.$f['id_feature'].'_|_'.$f['value'];
- $isErr=true;
- }
- }
- if ($isErr)
- {
- $data='';
- foreach($dataArray_feature_unique AS $featureValue)
- {
- $fv=explode('x|x',$featureValue);
- $data.=$fv[0].'x|x'.$fv[2]."y|y";
- }
- if ($importConfig[$TODOfilename]['createelements']==1)
- {
- addFeatureValue($data);
- refreshCacheFeature();
- findAllCSVLineValue('feature',$dataArray_feature,'id_feature',$features);
- $isErr = false;
- }else{
- $err.='<form name="fFeatureCreation" id="fFeatureCreation">
- <textarea name="data" style="display:none">';
- $err.=$data;
- $err.='</textarea>';
- $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>';
- $err.='</form>';
- }
- }
- }
-
- // attribute group check
- $isErr=false;
- $err_unique=array();
- foreach($mappingData['CSV2DBOptions'] AS $CSVFieldName => $attributeGroupName)
- {
- if ($mappingData['CSV2DB'][$CSVFieldName]=='attribute' || $mappingData['CSV2DB'][$CSVFieldName]=='attribute_multiple')
- {
- if (!sc_in_array($attributeGroupName,array_keys($attributeGroups),"catWinImportProcess_attributeGroups") && !in_array($attributeGroupName,$err_unique))
- {
- $err.=_l('This attribute group doesn\'t exist: ').$attributeGroupName.'<br/>';
- $err_unique[]=$attributeGroupName;
- $isErr=true;
- }
- }
- }
- if ($isErr)
- {
- $data = "";
- foreach($err_unique AS $attributeGroup)
- {
- $data.=$attributeGroup."y|y";
- }
- if ($importConfig[$TODOfilename]['createelements']==1)
- {
- addAttributeGroup($data);
- refreshCacheAttribute();
- $isErr = false;
- //$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>';
- }else{
-
- $err.='<form name="fAttributeGroupCreation" id="fAttributeGroupCreation">
- <textarea name="data" style="display:none">'.$data.'</textarea>';
- $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>';
-
- $err.='</form>';
- }
- }
- // attribute check
- if (!$isErr)
- {
- $isErr=false;
- $dataArray_attribute_unique=array();
- foreach($dataArray_attributegroup AS $ag)
- {
- // 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/>';
- //!in_array($ag['value'],array_keys($attributeValues),true)
- 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))
- {
- $err.=_l('This attribute doesn\'t exist: ').$ag['object'].' > '.$ag['value'].'<br/>';
- $dataArray_attribute_unique[]=$ag['id_attribute_group'].'x|x'.$ag['object'].'x|x'.$ag['id_attribute_group'].'_|_'.$ag['value'].'_|_'.$ag['color_attr_options'];
- $isErr=true;
- }
- }
- if ($isErr)
- {
- $data='';
- foreach($dataArray_attribute_unique AS $attributeValue)
- {
- $av=explode('x|x',$attributeValue);
- $data.=$av[0].'x|x'.$av[2]."y|y";
- }
- if ($importConfig[$TODOfilename]['createelements']==1)
- {
- addAttributeValue($data);
- refreshCacheAttribute();
- $isErr = false;
- }else{
- $err.='<form name="fAttributeCreation" id="fAttributeCreation">
- <textarea name="data" style="display:none">';
- $err.=$data;
- $err.='</textarea>';
- $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>';
- $err.='</form>';
- }
- }
- }
-
- if ($err!='' && $importConfig[$TODOfilename]['createelements']!=1)
- die($err.'<br/><br/>'._l('The process has been stopped before any modification in the database. You need to fix these errors first.'));
-
- // CHECK IF CATEGORY EXISTS
- $categ=Db::getInstance()->getRow("
- SELECT c.id_category
- FROM `"._DB_PREFIX_."category` c
- LEFT JOIN `"._DB_PREFIX_."category_lang` cl ON (c.`id_category` = cl.`id_category`)
- WHERE `name` = '".pSQL($TODOfilename)."'
- GROUP BY c.id_category");
- if (is_array($categ) && $categ['id_category']!='')
- {
- $id_category=intval($categ['id_category']);
- }else{
- $newcategory=new Category();
- $newcategory->id_parent=Configuration::get("PS_ROOT_CATEGORY");//1;
- $newcategory->level_depth=$newcategory->calcLevelDepth();
- $newcategory->active=0;
- foreach($languages AS $lang)
- {
- $newcategory->link_rewrite[$lang['id_lang']]='import';
- $newcategory->name[$lang['id_lang']]=$TODOfilename;
- }
- if (version_compare(_PS_VERSION_, '1.4.0.0', '>='))
- {
- $newcategory->position=SCI::getLastPositionFromCategory(1);
- }
- $newcategory->save();
- //$newcategory->addGroups(array(1));
- $id_category=$newcategory->id;
- }
-
- $refsupp_option = "";
- if(sc_in_array($importConfig[$TODOfilename]['idby'], array('supref'),"catWinImportProcess_supref"))
- {
- foreach($mappingData['CSV2DB'] as $key=>$field)
- {
- if($field=="supplier_reference")
- {
- $refsupp_option = $mappingData['CSV2DBOptions'][$key];
- break;
- }
- }
- }
-
- $stats=array('created' => 0,'modified' => 0,'skipped' => 0,'no_wholesaleprice' => 0);
- $noWholesalepriceArray = array();
- $CSVDataStr = remove_utf8_bom(file_get_contents(SC_CSV_IMPORT_DIR.$TODOfilename));
- $CSVData = preg_split("/(?:\r\n|\r|\n)/", $CSVDataStr);
- $lastIdentifier='';
- $lastid_product=0;
- $updated_products = array();
- $id_shop_list=array();
- $id_shop_list_default=array(1);
- if (version_compare(_PS_VERSION_,'1.5.0.0','>='))
- {
- $id_shop_list_default=array((int)Configuration::get('PS_SHOP_DEFAULT'));
- $cache_id_shop = array();
- $cache_current_line_for_combination = array();
- }
- $imageList=array();
- $productsWithTagUpdatedList=array();
- // for ($current_line = $FIRST_CONTENT_LINE; (($current_line <= (count($DATA)-1)) && $line = explode($importConfig[$TODOfilename]['fieldsep'],$DATA[$current_line])) && $current_line <= $importlimit ; $current_line++)
- //$aa= parseCSVLine($importConfig[$TODOfilename]['fieldsep'],$DATA[1]);
- //var_dump($aa);
- for ($current_line = $FIRST_CONTENT_LINE; ((($current_line <= (count($DATA)-1)) && $line = parseCSVLine($importConfig[$TODOfilename]['fieldsep'],$DATA[$current_line])) && ($current_line <= $importlimit)) ; $current_line++)
- {
- if ($DATA[$current_line]=='') continue;
- if (_s('APP_DEBUG_CATALOG_IMPORT'))
- {
- $time_end = microtime(true);
- $time = $time_end - $time_start;
- echo "<br/><br/>Start line : $time seconds";
- }
- $extension_vars = array();
- $id_shop_list=$id_shop_list_default;
- $useSpecificPrices=false;
- $line=array_map('cleanQuotes',$line);
- if ($scdebug) echo 'line '.$current_line.': ';
- $line[count($line)-1]=rtrim($line[count($line)-1]);
- $TODO=array();
- $TODOSHOP=array();
- if ($importConfig[$TODOfilename]['utf8']==1)
- utf8_encode_array($line);
-
- $filter_supplier_id = intval($importConfig[$TODOfilename]['supplier']);
-
- $where_shop_list = "";
- if(SCMS && findCSVLineValue('id_shop_list')!='' && $importConfig[$TODOfilename]['fornewproduct']=='skip' && $importConfig[$TODOfilename]['forfoundproduct']=='update')
- $where_shop_list = findCSVLineValue('id_shop_list');
-
- $has_view = (_s('CAT_PROD_IMPORT_METHOD') && SCI::getConfigurationValue('PS_SC_IMPORT_VIEW')=="1"?true:false);
- $res=array();
- switch($importConfig[$TODOfilename]['idby'])
- {
- case 'prodname':
- $name = findCSVLineValue('name');
- if(!empty($name))
- {
- $sql = "SELECT p.id_product,p.date_upd,p.id_supplier
- FROM "._DB_PREFIX_."product p
- LEFT JOIN "._DB_PREFIX_."product_lang pl on (p.id_product=pl.id_product AND pl.id_lang=".intval($defaultLanguage->id).")
- WHERE pl.name='".psql($name)."'
- ".(version_compare(_PS_VERSION_,'1.5.0.0','<') || empty($filter_supplier_id) ? '' : ' AND p.id_supplier='.$filter_supplier_id)." ".
- (!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).'))' : '')."
- LIMIT 1";
- }
- else
- $sql = "";
- break;
- case 'idproduct':
- $id_product_find = findCSVLineValue('id_product');
- if(!empty($id_product_find))
- {
- $sql="SELECT p.id_product,p.date_upd,p.id_supplier
- FROM "._DB_PREFIX_."product p
- WHERE p.id_product='".intval($id_product_find)."'
- ".(version_compare(_PS_VERSION_,'1.5.0.0','<') || empty($filter_supplier_id) ? '' : ' AND id_supplier='.$filter_supplier_id)." ".
- (!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).'))' : '')."
- LIMIT 1";
- }
- else
- $sql = "";
- break;
- case 'idproductattribute':
- $id_product_attribute_find = findCSVLineValue('id_product_attribute');
- if(!empty($id_product_attribute_find))
- {
- if($has_view)
- {
- $sql = "SELECT id_product,id_product_attribute,date_upd,id_supplier FROM "._DB_PREFIX_."sc_import_index
- WHERE
- id_product_attribute='".intval($id_product_attribute_find)."'
- ".(version_compare(_PS_VERSION_,'1.5.0.0','<') || empty($filter_supplier_id) ? '' : ' AND id_supplier='.$filter_supplier_id)." ".
- (!empty($where_shop_list)? ' AND id_shop IN ('.psql($where_shop_list).')' : '')."
- ORDER BY id_product_attribute DESC
- LIMIT 1";
- }
- else
- {
- $sql="SELECT pa.id_product,pa.id_product_attribute,pa.date_upd,p.id_supplier
- FROM "._DB_PREFIX_."product_attribute pa
- LEFT JOIN "._DB_PREFIX_."product p on (pa.id_product=p.id_product)
- WHERE pa.id_product_attribute='".intval($id_product_attribute_find)."'
- ".(version_compare(_PS_VERSION_,'1.5.0.0','<') || empty($filter_supplier_id) ? '' : ' AND p.id_supplier='.$filter_supplier_id)." ".
- (!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).'))' : '')."
- LIMIT 1";
- }
- }
- else
- $sql = "";
- break;
- case 'ean13':
- $EAN13_find = findCSVLineValue('EAN13');
- if(!empty($EAN13_find))
- {
- $sql="SELECT p.id_product,pa.id_product_attribute,pa.date_upd,p.id_supplier
- FROM "._DB_PREFIX_."product_attribute pa
- LEFT JOIN "._DB_PREFIX_."product p on (pa.id_product=p.id_product)
- WHERE pa.ean13='".psql($EAN13_find)."'
- ".(version_compare(_PS_VERSION_,'1.5.0.0','<') || empty($filter_supplier_id) ? '' : ' AND p.id_supplier='.$filter_supplier_id)." ".
- (!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).'))' : '')."
- LIMIT 1";
- $res=Db::getInstance()->ExecuteS($sql);
- if (count($res)==0)
- {
- $sql="SELECT p.id_product,p.date_upd,p.id_supplier
- FROM "._DB_PREFIX_."product p
- WHERE p.ean13='".psql($EAN13_find)."'
- ".(version_compare(_PS_VERSION_,'1.5.0.0','<') || empty($filter_supplier_id) ? '' : ' AND p.id_supplier='.$filter_supplier_id)." ".
- (!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).'))' : '')."
- LIMIT 1";
- }
- else
- $sql = "";
- }
- else
- $sql = "";
- break;
- case 'upc':
- $upc_find = findCSVLineValue('upc');
- if(!empty($upc_find))
- {
- $sql="SELECT p.id_product,pa.id_product_attribute,pa.date_upd,p.id_supplier
- FROM "._DB_PREFIX_."product_attribute pa
- LEFT JOIN "._DB_PREFIX_."product p on (pa.id_product=p.id_product)
- WHERE pa.upc='".psql($upc_find)."'
- ".(version_compare(_PS_VERSION_,'1.5.0.0','<') || empty($filter_supplier_id) ? '' : ' AND p.id_supplier='.$filter_supplier_id)." ".
- (!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).'))' : '')."
- LIMIT 1";
- $res=Db::getInstance()->ExecuteS($sql);
- if (count($res)==0)
- {
- $sql="SELECT p.id_product,p.date_upd,p.id_supplier
- FROM "._DB_PREFIX_."product p
- WHERE p.upc='".intval($upc_find)."'
- ".(version_compare(_PS_VERSION_,'1.5.0.0','<') || empty($filter_supplier_id) ? '' : ' AND p.id_supplier='.$filter_supplier_id)." ".
- (!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).'))' : '')."
- LIMIT 1";
- }
- else
- $sql = "";
- }
- else
- $sql = "";
- break;
- case 'prodref':
- $search_reference = findCSVLineValue('reference');
- if(!empty($search_reference))
- {
- if($has_view)
- {
- $sql = "SELECT id_product,id_product_attribute,date_upd,id_supplier FROM "._DB_PREFIX_."sc_import_index
- WHERE
- ( p_reference='".psql($search_reference)."' OR pa_reference='".psql($search_reference)."' )
- ".(version_compare(_PS_VERSION_,'1.5.0.0','<') || empty($filter_supplier_id) ? '' : ' AND id_supplier='.$filter_supplier_id)." ".
- (!empty($where_shop_list)? ' AND id_shop IN ('.psql($where_shop_list).')' : '')."
- ORDER BY id_product_attribute DESC
- LIMIT 1";
- }
- else
- {
- $sql="SELECT p.id_product,pa.id_product_attribute,pa.date_upd,p.id_supplier FROM "._DB_PREFIX_."product p
- LEFT JOIN "._DB_PREFIX_."product_attribute pa on (p.id_product=pa.id_product)
- WHERE pa.reference='".psql($search_reference)."'
- ".(version_compare(_PS_VERSION_,'1.5.0.0','<') || empty($filter_supplier_id) ? '' : ' AND p.id_supplier='.$filter_supplier_id)." ".
- (!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).'))' : '').
- " LIMIT 1";
- $res=Db::getInstance()->ExecuteS($sql);
- if (count($res)==0)
- {
- $sql="SELECT p.id_product,p.date_upd,p.id_supplier
- FROM "._DB_PREFIX_."product p
- WHERE reference='".psql($search_reference)."'
- ".(version_compare(_PS_VERSION_,'1.5.0.0','<') || empty($filter_supplier_id) ? '' : ' AND id_supplier='.$filter_supplier_id)."".
- (!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).'))' : '').
- " LIMIT 1";
- }
- else
- $sql = "";
- }
- }
- else
- $sql = "";
- break;
- case 'supref':
- $search_ref = findCSVLineValue('supplier_reference');
- if(!empty($search_ref))
- {
- if($has_view)
- {
- $search_supp_ref = "";
- if(version_compare(_PS_VERSION_,'1.5.0.0','>=') && $refsupp_option!="suppref_product")
- $search_supp_ref = " OR product_supplier_reference LIKE '%||".psql($search_ref)."||%' ";
-
- $sql = "SELECT id_product,id_product_attribute,date_upd,id_supplier FROM "._DB_PREFIX_."sc_import_index
- WHERE
- ( pa_supplier_reference='".psql($search_ref)."' OR p_supplier_reference='".psql($search_ref)."' ".$search_supp_ref.")
- ".(version_compare(_PS_VERSION_,'1.5.0.0','<') || empty($filter_supplier_id) ? '' : ' AND id_supplier='.$filter_supplier_id)." ".
- (!empty($where_shop_list)? ' AND id_shop IN ('.psql($where_shop_list).')' : '')."
- ORDER BY id_product_attribute DESC
- LIMIT 1";
- }
- else
- {
- if (version_compare(_PS_VERSION_,'1.5.0.0','>=') && $refsupp_option!="suppref_product")
- {
- $sql="SELECT ps.id_product,ps.id_product_attribute,pa.date_upd,p.id_supplier FROM "._DB_PREFIX_."product_supplier ps
- LEFT JOIN "._DB_PREFIX_."product_attribute pa on (ps.id_product_attribute=pa.id_product_attribute)
- LEFT JOIN "._DB_PREFIX_."product p on (ps.id_product=p.id_product)
- WHERE ps.product_supplier_reference='".psql($search_ref)."'
- ".(version_compare(_PS_VERSION_,'1.5.0.0','<') || empty($filter_supplier_id) ? '' : ' AND p.id_supplier='.$filter_supplier_id)." ".
- (!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).'))' : '').
- " ORDER BY id_product_attribute DESC LIMIT 1";
- $res=Db::getInstance()->ExecuteS($sql);
- }
- if (count($res)==0)
- {
- $sql="SELECT p.id_product,pa.id_product_attribute,pa.date_upd,p.id_supplier FROM "._DB_PREFIX_."product p
- LEFT JOIN "._DB_PREFIX_."product_attribute pa on (p.id_product=pa.id_product)
- WHERE pa.supplier_reference='".psql($search_ref)."'
- ".(version_compare(_PS_VERSION_,'1.5.0.0','<') || empty($filter_supplier_id) ? '' : ' AND p.id_supplier='.$filter_supplier_id)." ".
- (!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).'))' : '').
- " ORDER BY id_product_attribute DESC LIMIT 1";
- $res=Db::getInstance()->ExecuteS($sql);
- }
- else
- $sql = "";
- if (count($res)==0)
- {
- $sql="SELECT p.id_product,p.date_upd,p.id_supplier FROM "._DB_PREFIX_."product p
- WHERE supplier_reference='".psql($search_ref)."'
- ".(version_compare(_PS_VERSION_,'1.5.0.0','<') || empty($filter_supplier_id) ? '' : ' AND id_supplier='.$filter_supplier_id)."".
- (!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).'))' : '').
- " LIMIT 1";
- }
- else
- $sql = "";
- }
- }
- else
- $sql = "";
-
- break;
- case 'prodrefandsupref':
- $search_supplier_reference = findCSVLineValue('supplier_reference');
- $search_reference = findCSVLineValue('reference');
- if(!empty($sear