PageRenderTime 51ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 1ms

/modules/simpleimportproduct/import.php

https://gitlab.com/ptisky/API_prestashop
PHP | 978 lines | 865 code | 109 blank | 4 comment | 216 complexity | 74e2c8ba17e71a630c64ab8db74892e4 MD5 | raw file
  1. <?php
  2. class importProducts
  3. {
  4. private $_context;
  5. private $_idShop;
  6. private $_idShopGroup;
  7. private $_idLang;
  8. private $_format;
  9. private $_cover = 'no';
  10. private $_model;
  11. private $_delimiter;
  12. private $_typeImport;
  13. private $_parser;
  14. private $ids_images = array();
  15. private $_importFieldsBase;
  16. private $_importFieldsCategories;
  17. private $_importFieldsCombinations;
  18. private $_importFieldsDiscount;
  19. private $_importFieldsFeatures;
  20. private $_importProducts = 0;
  21. private $_productsForImport = 0;
  22. private $_PHPExcelFactory;
  23. private $selected_countries = array();
  24. private $selected_states = array();
  25. private $errors = array();
  26. public function __construct($fields, $id_shop, $idShopGroup){
  27. Context::getContext()->shop->id = $id_shop;
  28. Context::getContext()->shop->id_shop_group = $idShopGroup;
  29. Context::getContext()->shop->save();
  30. include_once(_PS_MODULE_DIR_ . 'simpleimportproduct/libraries/PHPExcel_1.7.9/Classes/PHPExcel.php');
  31. include_once(_PS_MODULE_DIR_ . 'simpleimportproduct/libraries/PHPExcel_1.7.9/Classes/PHPExcel/IOFactory.php');
  32. include_once(_PS_MODULE_DIR_ . 'simpleimportproduct/datamodel.php');
  33. require_once(dirname(__FILE__).'/simpleimportproduct.php');
  34. ini_set('memory_limit', '-1');
  35. ini_set('max_execution_time', "0");
  36. $config_step_one = Tools::unserialize(Configuration::get('GOMAKOIL_CONFIG_IMPORT_PRODUCTS', null, $idShopGroup, $id_shop));
  37. $this->_simpleimportproduct = new Simpleimportproduct();
  38. $this->_model = new importProductData();
  39. $this->_context = Context::getContext();
  40. $this->_idShop = $id_shop;
  41. $this->_idShopGroup = $idShopGroup;
  42. $this->_idLang = $config_step_one['id_lang'];
  43. $this->_format = $config_step_one['format_file'];
  44. $this->_delimiter = $config_step_one['delimiter_val'];
  45. $this->_typeImport = $config_step_one['import_type_val'];
  46. $this->_parser = $config_step_one['parser_import_val'];
  47. $this->_importFieldsBase = $fields['base_field'];
  48. $this->_importFieldsCategories = $fields['field_category'];
  49. $this->_importFieldsCombinations = $fields['field_combinations'];
  50. $this->_importFieldsDiscount = $fields['field_discount'];
  51. $this->_importFieldsFeatures = $fields['field_featured'];
  52. }
  53. public function import()
  54. {
  55. $this->_clearErrorFile();
  56. $this->_copyFile();
  57. $this->_importData();
  58. if( $this->_importProducts != $this->_productsForImport ){
  59. $res = array(
  60. 'message' => sprintf(Module::getInstanceByName('simpleimportproduct')->l('Successfully imported %1s products from: %2s'), $this->_importProducts, $this->_productsForImport),
  61. 'error_logs' => _PS_BASE_URL_.__PS_BASE_URI__.'modules/simpleimportproduct/error/error_logs.csv',
  62. );
  63. return $res;
  64. }
  65. $rez = array(
  66. 'message' => sprintf(Module::getInstanceByName('simpleimportproduct')->l('Successfully imported %s products!'), $this->_importProducts),
  67. 'error_logs' => false
  68. );
  69. return $rez;
  70. }
  71. private function _clearErrorFile()
  72. {
  73. $write_fd = fopen('error/error_logs.csv', 'w');
  74. fwrite($write_fd, 'product_name,error'."\r\n");
  75. fclose($write_fd);
  76. }
  77. private function _copyFile()
  78. {
  79. if($this->_format == 'xlsx'){
  80. $this->_PHPExcelFactory = PHPExcel_IOFactory::load("data/import_products.xls");
  81. }
  82. elseif($this->_format == 'csv'){
  83. $reader = PHPExcel_IOFactory::createReader("CSV");
  84. $reader->setDelimiter($this->_delimiter);
  85. $this->_PHPExcelFactory = $reader->load("data/import_products.csv");
  86. }
  87. }
  88. private function _importData()
  89. {
  90. foreach ($this->_PHPExcelFactory->getWorksheetIterator() as $worksheet) {
  91. $highestRow = $worksheet->getHighestRow(); // e.g. 10
  92. $highestColumn = $worksheet->getHighestColumn(); // e.g 'F'
  93. $highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
  94. $fileFields = array();
  95. for ($row = 1; $row <= $highestRow; ++ $row) {
  96. $product = array();
  97. for ($col = 0; $col < $highestColumnIndex; ++ $col) {
  98. $cell = $worksheet->getCellByColumnAndRow($col, $row);
  99. $val = $cell->getValue();
  100. if($row == 1){
  101. if( !$val ){
  102. continue;
  103. }
  104. $fileFields[$col] = $val;
  105. }
  106. else{
  107. if(!isset($fileFields[$col])){
  108. continue;
  109. }
  110. $product[$fileFields[$col]] = $val;
  111. }
  112. }
  113. if( $product ){
  114. $productData = array();
  115. foreach( $this->_importFieldsBase as $key => $value){
  116. if($value !== 'no'){
  117. $productData['main'][$key] = $product[$value];
  118. }
  119. }
  120. if($this->_importFieldsCategories){
  121. foreach( $this->_importFieldsCategories as $key => $value){
  122. $category = array();
  123. foreach( $value as $k => $v ){
  124. if($v !== 'no' && $v !== 'undefined'){
  125. $category[] = $product[$v];
  126. }
  127. }
  128. $productData['categories'][$key] = $category;
  129. }
  130. }
  131. if($this->_importFieldsCombinations){
  132. foreach( $this->_importFieldsCombinations as $key => $value){
  133. $combinations = array();
  134. foreach( $value as $k => $v ){
  135. if($v !== 'no' && $k !== 'undefined'){
  136. $combinations[$k] = $product[$v];
  137. }
  138. }
  139. $productData['combinations'][$key] = $combinations;
  140. }
  141. }
  142. else{
  143. $productData['combinations'] = false;
  144. }
  145. if($this->_importFieldsDiscount){
  146. foreach( $this->_importFieldsDiscount as $key => $value){
  147. $discount = array();
  148. foreach( $value as $k => $v ){
  149. if($v !== 'no' && $k !== 'undefined'){
  150. $discount[$k] = $product[$v];
  151. }
  152. }
  153. $productData['discount'][$key] = $discount;
  154. }
  155. }
  156. else{
  157. $productData['discount'] = false;
  158. }
  159. if($this->_importFieldsFeatures){
  160. foreach( $this->_importFieldsFeatures as $key => $value){
  161. $features = array();
  162. foreach( $value as $k => $v ){
  163. if($v !== 'no' && $k !== 'undefined'){
  164. $features[$k] = $product[$v];
  165. }
  166. }
  167. $productData['features'][$key] = $features;
  168. }
  169. }
  170. else{
  171. $productData['features'] = false;
  172. }
  173. $this->_productsForImport++;
  174. if(!$this->_importProduct( $productData )){
  175. continue;
  176. }
  177. }
  178. }
  179. }
  180. }
  181. private function _importProduct( $productData )
  182. {
  183. if($this->_typeImport == 'Add/update'){
  184. $where = '';
  185. if(!$productData['main'][$this->_parser]){
  186. return false;
  187. }
  188. if($this->_parser == 'name'){
  189. $where .= " AND pl.name = '".pSQL($productData['main']['name'])."'";
  190. }
  191. elseif($this->_parser == 'reference'){
  192. $where .= " AND p.reference = '".pSQL($productData['main']['reference'])."'";
  193. }
  194. else{
  195. $where .= " AND pl.link_rewrite = '".pSQL($productData['main']['link_rewrite'])."'";
  196. }
  197. $id_product = $this->_model->getProductId($where, $this->_idShop, $this->_idLang);
  198. return $this->_saveNewProduct($id_product['id_product'], $productData);
  199. }
  200. elseif($this->_typeImport == 'Add'){
  201. if(!$productData['main']['name']){
  202. return false;
  203. }
  204. return $this->_saveNewProduct(false, $productData);
  205. }
  206. }
  207. private function _saveNewProduct($id_product, $productData ){
  208. $this->ids_images = array();
  209. $this->_cover = 'no';
  210. $main = $productData['main'];
  211. $categories = $productData['categories'];
  212. $combinations = $productData['combinations'];
  213. if( $combinations ){
  214. foreach( $combinations as $key => $comb ){
  215. if( !$comb['attribute'] ){
  216. unset($combinations[$key]);
  217. }
  218. }
  219. }
  220. $discount = $productData['discount'];
  221. $features = $productData['features'];
  222. if($this->_typeImport == 'Add/update' && $id_product){
  223. $object = new Product($id_product, false, $this->_idLang);
  224. }
  225. else{
  226. $object = new Product();
  227. }
  228. if(isset($main['manufacturer']) && $main['manufacturer']){
  229. $id_manufacturer = $this->_productManufacturer($main['manufacturer'], $main['name']);
  230. if(!$id_manufacturer){ return false; }
  231. }
  232. $object->name = $this->_createMultiLangField( $main['name'] );
  233. if(isset( $main['reference']) && $main['reference']){
  234. $object->reference = $main['reference'];
  235. }
  236. if(isset( $main['available_for_order']) && $main['available_for_order'] !== ''){
  237. $object->available_for_order = (string)$main['available_for_order'] == '0' ? 0 : 1;
  238. }
  239. if(isset( $main['active']) && $main['active'] !== ''){
  240. $object->active = (string)$main['active'] == '0' ? 0 : 1;
  241. }
  242. else{
  243. $object->active = 1;
  244. }
  245. if(isset( $main['condition']) && $main['condition']){
  246. $object->condition = $main['condition'];
  247. }
  248. if(isset( $main['visibility']) && $main['visibility'] !== ''){
  249. $object->visibility = $main['visibility'];
  250. }
  251. if(isset( $main['link_rewrite']) && $main['link_rewrite']){
  252. $object->link_rewrite = $this->_createMultiLangField( Tools::link_rewrite($main['link_rewrite']) );
  253. }
  254. else{
  255. $object->link_rewrite = $this->_createMultiLangField( Tools::link_rewrite($main['name']) );
  256. }
  257. if(isset( $main['meta_description']) && $main['meta_description']){
  258. $object->meta_description = $this->_createMultiLangField( $main['meta_description']);
  259. }
  260. if(isset( $main['meta_keywords']) && $main['meta_keywords']){
  261. $object->meta_keywords = $this->_createMultiLangField( $main['meta_keywords']);
  262. }
  263. if(isset( $main['meta_title']) && $main['meta_title']){
  264. $object->meta_title = $this->_createMultiLangField( $main['meta_title']);
  265. }
  266. if(isset( $main['on_sale']) && $main['on_sale'] !== ''){
  267. $object->on_sale = $main['on_sale'];
  268. }
  269. if(isset( $main['min_quantity']) && $main['min_quantity'] !== ''){
  270. $object->minimal_quantity = (int)$main['min_quantity'];
  271. }
  272. if(isset( $main['show_price']) && $main['show_price'] !== ''){
  273. $object->show_price = (string)$main['show_price'] == '0' ? 0 : 1;
  274. }
  275. if(isset( $main['unit_price']) && $main['unit_price']){
  276. $main['unit_price'] = str_replace(',','.', $main['unit_price']);
  277. $main['unit_price'] = number_format($main['unit_price'], 4, '.', '');
  278. $object->unit_price = $main['unit_price'];
  279. }
  280. if(isset( $main['price']) && $main['price'] !== ''){
  281. $main['price'] = str_replace(',','.', $main['price']);
  282. $main['price'] = number_format($main['price'], 4, '.', '');
  283. $object->price = $main['price'];
  284. }
  285. if(isset( $main['wholesale_price']) && $main['wholesale_price'] !== ''){
  286. $main['wholesale_price'] = str_replace(',','.', $main['wholesale_price']);
  287. $main['wholesale_price'] = number_format($main['wholesale_price'], 4, '.', '');
  288. $object->wholesale_price = (float)$main['wholesale_price'];
  289. }
  290. if(isset( $main['ean13']) && $main['ean13']){
  291. $object->ean13 = $main['ean13'];
  292. }
  293. if(isset( $main['ecotax']) && $main['ecotax']){
  294. $object->ecotax = (float)$main['ecotax'];
  295. }
  296. if(isset( $main['upc']) && $main['upc']){
  297. $object->upc = $main['upc'];
  298. }
  299. if(isset($main['manufacturer']) && $main['manufacturer']){
  300. $object->id_manufacturer = $id_manufacturer;
  301. }
  302. if(isset($main['width']) && $main['width']){
  303. $object->width = $main['width'];
  304. }
  305. if(isset($main['height']) && $main['height']){
  306. $object->height = $main['height'];
  307. }
  308. if(isset($main['depth']) && $main['depth']){
  309. $object->depth = $main['depth'];
  310. }
  311. if(isset($main['weight']) && $main['weight']){
  312. $object->weight = $main['weight'];
  313. }
  314. if(isset($main['short_description']) && $main['short_description']){
  315. $object->description_short = $this->_createMultiLangField( $main['short_description'] );
  316. }
  317. if(isset($main['description']) && $main['description']){
  318. $object->description = $this->_createMultiLangField( $main['description'] );
  319. }
  320. if(isset($main['available_now']) && $main['available_now']){
  321. $object->available_now = $main['available_now'] ;
  322. }
  323. if(isset($main['available_later']) && $main['available_later']){
  324. $object->available_later = $main['available_later'];
  325. }
  326. if(isset( $main['tax']) && $main['tax']){
  327. $name_tax = 'Import module tax ('. $main['tax'] .'%)';
  328. $tax = new Tax();
  329. $id_tax = $tax->getTaxIdByName($name_tax);
  330. if($id_tax){
  331. $tax_rule_group = new TaxRulesGroupCore();
  332. $tax_rule_group_id = $tax_rule_group->getIdByName($name_tax);
  333. $object->id_tax_rules_group = $tax_rule_group_id;
  334. }
  335. else{
  336. if((float)$main['tax']>0 && (float)$main['tax']<100){
  337. $tax->name = array( $this->_idLang => $name_tax);
  338. $tax->rate = (float)$main['tax'];
  339. $tax->active = 1;
  340. $tax->save();
  341. $tax_rule_group = new TaxRulesGroup();
  342. $tax_rule_group->name = $name_tax;
  343. $tax_rule_group->active = 1;
  344. $tax_rule_group->save();
  345. $tax_rule_group->save();
  346. $this->_createRule($tax->id, $tax_rule_group->id);
  347. $object->id_tax_rules_group = $tax_rule_group->id;
  348. }
  349. }
  350. }
  351. if( ( $error = $object->validateFields(false, true) ) !== true ){
  352. $this->_createErrorsFile($error,$main['name']);
  353. return false;
  354. }
  355. if( ( $error = $object->validateFieldsLang(false, true) ) !== true ){
  356. $this->_createErrorsFile($error,$main['name']);
  357. return false;
  358. }
  359. $object->save();
  360. $productId = $object->id;
  361. if(isset($categories) && $categories){
  362. $id_category = $this->_productCategories($categories);
  363. $object->deleteCategories();
  364. $id_category = array_unique($id_category);
  365. Cache::clean('Product::getProductCategories_'.(int)$id_product);
  366. $object->addToCategories($id_category);
  367. }
  368. if(isset($main['default_category']) && $main['default_category']){
  369. $category_def = $this->_model->getCategoryByName(trim($main['default_category']), $this->_idLang, false);
  370. if($category_def){
  371. $object->id_category_default = $category_def;
  372. }
  373. else{
  374. $object->id_category_default = 2;
  375. }
  376. }
  377. if(isset($main['tags']) && $main['tags']){
  378. Tag::deleteTagsForProduct($productId);
  379. Tag::addTags($this->_idLang, $productId, $main['tags']);
  380. }
  381. if(isset($main['quantity']) && $main['quantity'] !== ''){
  382. StockAvailable::setQuantity($productId, null, (int)$main['quantity']);
  383. }
  384. if(isset($main['supplier']) && $main['supplier']){
  385. $suppliers = explode(",", $main['supplier']);
  386. $object->deleteFromSupplier();
  387. foreach($suppliers as $supplier){
  388. $rez = $this->_productSuppliers($supplier, $productId);
  389. }
  390. }
  391. if(isset($main['supplier_default']) && $main['supplier_default']){
  392. $isset_supplier_dafault = $this->_model->getSupplier(trim($main['supplier_default']));
  393. if($isset_supplier_dafault){
  394. $object->id_supplier = $isset_supplier_dafault['id_supplier'];
  395. }
  396. }
  397. $img_attr = false;
  398. if(isset($combinations) && $combinations){
  399. foreach($combinations as $combination){
  400. if(isset($combination['images_combination']) && $combination['images_combination']){
  401. $img_attr = true;
  402. }
  403. }
  404. }
  405. if((isset($main['images_url']) && $main['images_url']) || $img_attr){
  406. foreach($object->getImages($this->_idLang) as $img_del){
  407. if($img_del){
  408. $image_del = new Image($img_del['id_image']);
  409. $image_del->delete();
  410. }
  411. }
  412. if(isset($main['images_url']) && $main['images_url']){
  413. $img_products = explode(",", $main['images_url']);
  414. if(isset($main['images_alt']) && $main['images_alt']){
  415. $img_alt = explode(",", $main['images_alt']);
  416. }
  417. else{
  418. $img_alt = false;
  419. }
  420. foreach($img_products as $kay => $url_img){
  421. if(!isset($img_alt[$kay])){
  422. $img_alt[$kay] = $main['name'];
  423. }
  424. $ids_images = $this->ids_images;
  425. if(!isset($ids_images[$url_img]) || !$ids_images[$url_img]){
  426. $rez = $this->_productImages($productId, $url_img, $img_alt[$kay], $kay);
  427. }
  428. }
  429. }
  430. if($img_attr){
  431. if(isset($combinations) && $combinations){
  432. foreach($combinations as $k => $combination){
  433. if(isset($combination['images_combination']) && $combination['images_combination']){
  434. $img_products = explode(",", $combination['images_combination']);
  435. foreach($img_products as $kay => $url_img){
  436. if(!isset($img_alt[$kay])){
  437. $img_alt[$kay] = $main['name'];
  438. }
  439. $ids_images = $this->ids_images;
  440. if(!isset($ids_images[$url_img]) || !$ids_images[$url_img]){
  441. $rez = $this->_productImages($productId, $url_img, $img_alt[$kay], false);
  442. }
  443. }
  444. }
  445. }
  446. }
  447. }
  448. }
  449. if(isset($combinations) && $combinations){
  450. $object->deleteProductAttributes();
  451. $rez = $this->_productCombinations($combinations, $productId);
  452. $attributes = $rez['attributes'];
  453. $values = $rez['values'];
  454. $id_images = $rez['id_images'];
  455. $object->generateMultipleCombinations($values, $attributes);
  456. $attributesAll = Product::getProductAttributesIds($productId, true);
  457. foreach ($attributesAll as $key => $attribute){
  458. StockAvailable::setQuantity($productId, $attribute['id_product_attribute'], (int)$values[$key]['quantity']);
  459. $combination = new Combinationcore($attribute['id_product_attribute']);
  460. if (!empty($id_images[$key])) {
  461. $combination->setImages($id_images[$key]);
  462. }
  463. }
  464. }
  465. if($discount){
  466. $rez = $this->_productDiscount($discount, $productId);
  467. }
  468. if($features){
  469. foreach($features as $featur){
  470. if(isset($featur['features_name']) && $featur['features_name'] && $featur['features_value'] && isset($featur['features_value'])){
  471. $rez = $this->_productFeatures($featur);
  472. $object->addFeatureProductImport($productId, $rez['id_feature'], $rez['id_feature_val']);
  473. }
  474. }
  475. }
  476. if( ( $error = $object->validateFields(false, true) ) !== true ){
  477. $this->_createErrorsFile($error,$main['name']);
  478. return false;
  479. }
  480. $object->save();
  481. $this->_importProducts++;
  482. Configuration::updateValue('GOMAKOIL_IMPORT_PRODUCTS_COUNT', (int)$this->_importProducts, false, $this->_idShopGroup, $this->_idShop);
  483. return true;
  484. }
  485. private function _createRule($id_tax, $id_tax_rules_group)
  486. {
  487. $zip_code = 0;
  488. $id_rule = (int)0;
  489. $behavior = (int)0;
  490. $description = "";
  491. $countries = Country::getCountries(Context::getContext()->language->id);
  492. $this->selected_countries = array();
  493. foreach ($countries as $country) {
  494. $this->selected_countries[] = (int)$country['id_country'];
  495. }
  496. if (empty($this->selected_states) || count($this->selected_states) == 0) {
  497. $this->selected_states = array(0);
  498. }
  499. $tax_rules_group = new TaxRulesGroup((int)$id_tax_rules_group);
  500. foreach ($this->selected_countries as $id_country) {
  501. $first = true;
  502. foreach ($this->selected_states as $id_state) {
  503. if ($tax_rules_group->hasUniqueTaxRuleForCountry($id_country, $id_state, $id_rule)) {
  504. $this->errors[] = Tools::displayError('A tax rule already exists for this country/state with tax only behavior.');
  505. continue;
  506. }
  507. $tr = new TaxRule();
  508. // update or creation?
  509. if (isset($id_rule) && $first) {
  510. $tr->id = $id_rule;
  511. $first = false;
  512. }
  513. $tr->id_tax = $id_tax;
  514. $tax_rules_group = new TaxRulesGroup((int)$id_tax_rules_group);
  515. $tr->id_tax_rules_group = (int)$tax_rules_group->id;
  516. $tr->id_country = (int)$id_country;
  517. $tr->id_state = (int)$id_state;
  518. list($tr->zipcode_from, $tr->zipcode_to) = $tr->breakDownZipCode($zip_code);
  519. // Construct Object Country
  520. $country = new Country((int)$id_country, (int)Context::getContext()->language->id);
  521. if ($zip_code && $country->need_zip_code) {
  522. if ($country->zip_code_format) {
  523. foreach (array($tr->zipcode_from, $tr->zipcode_to) as $zip_code) {
  524. if ($zip_code) {
  525. if (!$country->checkZipCode($zip_code)) {
  526. $this->errors[] = sprintf(
  527. Tools::displayError('The Zip/postal code is invalid. It must be typed as follows: %s for %s.'),
  528. str_replace('C', $country->iso_code, str_replace('N', '0', str_replace('L', 'A', $country->zip_code_format))), $country->name
  529. );
  530. }
  531. }
  532. }
  533. }
  534. }
  535. $tr->behavior = (int)$behavior;
  536. $tr->description = $description;
  537. $this->tax_rule = $tr;
  538. if (count($this->errors) == 0) {
  539. $tax_rules_group = $this->updateTaxRulesGroup($tax_rules_group);
  540. // $tr->id = (int)$tax_rules_group->getIdTaxRuleGroupFromHistorizedId((int)$tr->id);
  541. // $tr->id_tax_rules_group = (int)$tax_rules_group->id;
  542. if (!$tr->save()) {
  543. $this->errors[] = Tools::displayError('An error has occurred: Cannot save the current tax rule.');
  544. }
  545. }
  546. }
  547. }
  548. }
  549. protected function updateTaxRulesGroup($object)
  550. {
  551. static $tax_rules_group = null;
  552. if ($tax_rules_group === null) {
  553. $object->update();
  554. $tax_rules_group = $object;
  555. }
  556. return $tax_rules_group;
  557. }
  558. private function _productImages($productId, $url_img, $img_alt, $kay){
  559. $url_img = trim($url_img);
  560. $img_alt = trim($img_alt);
  561. if(@getimagesize($url_img)){
  562. $path_parts_prod = pathinfo($url_img);
  563. $name_img = $path_parts_prod['basename'];
  564. $newpath_prod = dirname(__FILE__).'/upload/';
  565. if (PHP_VERSION_ID < 50300)
  566. clearstatcache();
  567. else
  568. clearstatcache(true, $newpath_prod.$name_img);
  569. if ( copy($url_img, $newpath_prod.$name_img) ) {
  570. $image = new Image();
  571. $image->id_product = $productId;
  572. $image->legend = @trim($img_alt);
  573. if( $this->_cover == 'no'){
  574. $image->cover = 1;
  575. $image->position = 1;
  576. $this->_cover = 'yes';
  577. }
  578. $image->add();
  579. $all_img = $this->ids_images;
  580. $all_img[$url_img] = $image->id;
  581. $this->ids_images = $all_img;
  582. $new_path = $image->getPathForCreation();
  583. if( !ImageManager::resize($newpath_prod.$name_img, $new_path.'.'.$image->image_format, null, null, 'jpg', false) ){
  584. return false;
  585. }
  586. $imagesTypes = ImageType::getImagesTypes('products');
  587. foreach ($imagesTypes as $imageType)
  588. {
  589. ImageManager::resize($newpath_prod.$name_img, $new_path.'-'. Tools::stripslashes($imageType['name']).'.'.$image->image_format, $imageType['width'], $imageType['height'], $image->image_format);
  590. }
  591. $image->update();
  592. if( file_exists($newpath_prod.$name_img) ){
  593. unlink($newpath_prod.$name_img);
  594. }
  595. }
  596. }
  597. }
  598. private function _productSuppliers($supplier, $productId){
  599. $supplier = trim($supplier);
  600. $id_shop_list = Shop::getContextListShopID();
  601. $isset_supplier = $this->_model->getSupplier($supplier);
  602. if(!$isset_supplier && $supplier){
  603. $supplier_obj = new Supplier();
  604. $supplier_obj->name = $supplier;
  605. $supplier_obj->id_shop_list = $id_shop_list;
  606. $supplier_obj->active = 1;
  607. $supplier_obj->save();
  608. Db::getInstance()->insert('product_supplier', array('id_product' => (int)$productId, 'id_supplier' => (int)$supplier_obj->id));
  609. }
  610. else{
  611. Db::getInstance()->insert('product_supplier', array('id_product' => (int)$productId, 'id_supplier' => (int)$isset_supplier['id_supplier']));
  612. }
  613. }
  614. private function _productFeatures($features){
  615. $rez = array();
  616. $id_shop_list = Shop::getContextListShopID();
  617. $feature_name = trim($features['features_name']);
  618. $isset_feature = $this->_model->getFeatures($feature_name, $this->_idLang, $this->_idShop);
  619. if(!$isset_feature){
  620. $feature= new Feature();
  621. $feature->name = $this->_createMultiLangField( $feature_name );
  622. $feature->id_shop_list = $id_shop_list;
  623. $feature->save();
  624. $id_feature = $feature->id;
  625. }
  626. else{
  627. $id_feature = $isset_feature;
  628. }
  629. $feature_value = trim($features['features_value']);
  630. $isset_feature_val = $this->_model->getFeaturesValue($feature_value, $id_feature, $this->_idLang);
  631. if(!$isset_feature_val){
  632. $feature_val= new FeatureValue();
  633. $feature_val->id_feature = $id_feature;
  634. $feature_val->value = $this->_createMultiLangField( $feature_value );
  635. $feature_val->save();
  636. $id_feature_val = $feature_val->id;
  637. }
  638. else{
  639. $id_feature_val = $isset_feature_val;
  640. }
  641. $rez['id_feature'] = $id_feature;
  642. $rez['id_feature_val'] = $id_feature_val;
  643. return $rez;
  644. }
  645. private function _productDiscount($discounts, $productId){
  646. foreach ($discounts as $discount)
  647. {
  648. $reduction_type = trim($discount['reduction_type']);
  649. if($reduction_type == 'amount'){
  650. $reduction = $discount['reduction'];
  651. }
  652. else if($reduction_type == 'percentage'){
  653. $reduction = $discount['reduction']/100;
  654. }
  655. else{
  656. $reduction = 0;
  657. $reduction_type = 0;
  658. }
  659. $reduction_from = trim($discount['reduction_from']);
  660. $reduction_to = trim($discount['reduction_to']);
  661. $price = trim($discount['fixed_price']);
  662. if(!$price){
  663. $price = -1;
  664. }
  665. else{
  666. $reduction_type = 'amount';
  667. }
  668. $from_quantity = trim($discount['from_quantity']);
  669. if(!$from_quantity){
  670. $from_quantity = 1;
  671. }
  672. $isst_specific_price = $this->_model->getSpecificPrice($productId, $this->_idShop);
  673. if ($isst_specific_price){
  674. $specific_price = new SpecificPrice((int)$isst_specific_price);
  675. }
  676. else
  677. {
  678. $specific_price = new SpecificPrice();
  679. }
  680. if( (float)$price > 0 ){
  681. $price = str_replace(',','.', $price);
  682. $price = number_format($price, 4, '.', '');
  683. }
  684. $specific_price->id_product = (int)$productId;
  685. $specific_price->id_specific_price_rule = 0;
  686. $specific_price->id_shop = $this->_idShop;
  687. $specific_price->id_currency = 0;
  688. $specific_price->id_country = 0;
  689. $specific_price->id_group = 0;
  690. $specific_price->price = $price;
  691. $specific_price->id_customer = 0;
  692. $specific_price->from_quantity = (int)$from_quantity;
  693. $specific_price->reduction = $reduction;
  694. $specific_price->reduction_type = $reduction_type;
  695. $specific_price->from = (isset($reduction_from) && Validate::isDate($reduction_from)) ? $reduction_from : '0000-00-00 00:00:00';
  696. $specific_price->to = (isset($reduction_to) && Validate::isDate($reduction_to)) ? $reduction_to : '0000-00-00 00:00:00';
  697. $specific_price->save();
  698. }
  699. }
  700. private function _productCombinations($combinations_all, $productId){
  701. $attributes = array();
  702. $values = array();
  703. $img_attr= array();
  704. foreach($combinations_all as $k => $combinations){
  705. $attribut = array();
  706. $attribut = explode(",", $combinations['attribute']);
  707. $attribut_val = explode(",",$combinations['value']);
  708. $id_attributes = array();
  709. foreach($attribut as $key => $a){
  710. $val_name = array();
  711. $val_name = explode(":", $a);
  712. if( !$val_name[0] || !trim($attribut_val[$key]) ){
  713. continue;
  714. }
  715. $isset_group = $this->_model->getGroupAttribute($val_name[0], $val_name[1], $this->_idLang);
  716. if(!$isset_group){
  717. if($val_name[1] !== 'select' && $val_name[1] !== 'radio' && $val_name[1] !== 'color'){
  718. $type = 'select';
  719. }
  720. else{
  721. $type = $val_name[1];
  722. }
  723. $obj = new AttributeGroup();
  724. $obj->name[$this->_idLang] = $val_name[0];
  725. $obj->public_name[$this->_idLang] = $val_name[0];
  726. $obj->group_type = $type;
  727. if($type == 'color'){
  728. $obj->is_color_group = 1;
  729. }
  730. else{
  731. $obj->is_color_group = 0;
  732. }
  733. $obj->save();
  734. $id_attribute_group = $obj->id;
  735. }
  736. else{
  737. $id_attribute_group = $isset_group;
  738. }
  739. $isset_attribute = $this->_model->getAttribute(trim($attribut_val[$key]), $id_attribute_group, $this->_idLang);
  740. if(!$isset_attribute){
  741. $attribute = new Attribute();
  742. $attribute->id_attribute_group = $id_attribute_group;
  743. $attribute->name[$this->_idLang] = trim($attribut_val[$key]);
  744. $attribute->save();
  745. $id_attributes[] = $attribute->id;
  746. }
  747. else{
  748. $id_attributes[] = $isset_attribute;
  749. }
  750. }
  751. if( $id_attributes ){
  752. $attributes[] = $id_attributes;
  753. if($combinations['impact_price']){
  754. $combinations['impact_price'] = str_replace(',','.', $combinations['impact_price']);
  755. $combinations['impact_price'] = number_format($combinations['impact_price'], 4, '.', '');
  756. }
  757. if($combinations['wholesale_price_combination']){
  758. $combinations['wholesale_price_combination'] = str_replace(',','.', $combinations['wholesale_price_combination']);
  759. $combinations['wholesale_price_combination'] = number_format($combinations['wholesale_price_combination'], 4, '.', '');
  760. }
  761. if(isset($combinations['images_combination']) && $combinations['images_combination']){
  762. $img_products = explode(",", $combinations['images_combination']);
  763. foreach($img_products as $kay => $url_img){
  764. $ids_images = $this->ids_images;
  765. if(isset($ids_images[$url_img]) && $ids_images[$url_img]){
  766. $img_attr[$k][] = $ids_images[$url_img];
  767. }
  768. }
  769. }
  770. $values[] = array(
  771. 'id_product' => $productId,
  772. 'price' => (float)$combinations['impact_price'],
  773. 'weight' => (float)$combinations['impact_weight'],
  774. 'ecotax' => (float)$combinations['ecotax_combination'],
  775. 'ean13' => $combinations['ean13_combination'],
  776. 'upc' => $combinations['upc_combination'],
  777. 'wholesale_price' => $combinations['wholesale_price_combination'],
  778. 'min_quantity' => $combinations['min_quantity_combination'],
  779. 'quantity' => $combinations['quantity_combination'],
  780. 'reference' => pSQL($combinations['reference_combination']),
  781. 'default_on' => (int)$combinations['default'],
  782. 'available_date' => '0000-00-00',
  783. );
  784. }
  785. }
  786. $rez = array();
  787. $rez['attributes'] = $attributes;
  788. $rez['values'] = $values;
  789. $rez['id_images'] = $img_attr;
  790. return $rez;
  791. }
  792. private function _productCategories($categories){
  793. $id_category = array();
  794. foreach($categories as $category){
  795. $count_cat = count($category);
  796. $parent_cat = 2;
  797. for($i = 0; $i < $count_cat; $i++){
  798. $cat = trim($category[$i]);
  799. if($cat){
  800. if($i == 0){
  801. $isset_cat = $this->_model->getCategoryByName($cat, $this->_idLang, $this->_idShop, $parent_cat);
  802. if(!$isset_cat){
  803. $obj_cat = new Category(null, null, $this->_idShop);
  804. $obj_cat->name = $this->_createMultiLangField( $cat );
  805. $obj_cat->link_rewrite = $this->_createMultiLangField( Tools::link_rewrite( $cat ));
  806. $obj_cat->id_parent = $parent_cat;
  807. $obj_cat->save();
  808. $parent_cat = $obj_cat->id;
  809. }
  810. else{
  811. $parent_cat = $isset_cat;
  812. }
  813. }
  814. else{
  815. $isset_cat = $this->_model->getCategoryByName($cat, $this->_idLang, $this->_idShop, $parent_cat );
  816. if(!$isset_cat){
  817. $obj_cat = new Category(null, null, $this->_idShop);
  818. $obj_cat->name = $this->_createMultiLangField( $cat );
  819. $obj_cat->link_rewrite = $this->_createMultiLangField( Tools::link_rewrite( $cat ));
  820. $obj_cat->id_parent = $parent_cat;
  821. $obj_cat->save();
  822. $parent_cat = $obj_cat->id;
  823. }
  824. else{
  825. $parent_cat = $isset_cat;
  826. }
  827. }
  828. $id_category[] = $parent_cat;
  829. }
  830. }
  831. }
  832. return $id_category;
  833. }
  834. private function _productManufacturer($manufacturer, $nameProduct)
  835. {
  836. $manufacturer = trim($manufacturer);
  837. $isset_manufacturer = $this->_model->getManufacturer($manufacturer);
  838. if(!$isset_manufacturer && $manufacturer){
  839. $manufacturer_obj = new Manufacturer();
  840. $manufacturer_obj->name = $manufacturer;
  841. $manufacturer_obj->active = 1;
  842. if( ( $error = $manufacturer_obj->validateFields(false, true) ) !== true ){
  843. $this->_createErrorsFile($error,$nameProduct);
  844. return false;
  845. }
  846. $manufacturer_obj->save();
  847. return $manufacturer_obj->id;
  848. }
  849. else{
  850. return $isset_manufacturer['id_manufacturer'];
  851. }
  852. }
  853. private function _createErrorsFile($error, $nameProduct)
  854. {
  855. $write_fd = fopen('error/error_logs.csv', 'a+');
  856. if (@$write_fd !== false){
  857. fwrite($write_fd, $nameProduct . ',' . $error . "\r\n");
  858. }
  859. fclose($write_fd);
  860. }
  861. private function _createMultiLangField($field)
  862. {
  863. $languages = Language::getLanguages(false);
  864. $res = array();
  865. foreach ($languages as $lang)
  866. $res[$lang['id_lang']] = $field;
  867. return $res;
  868. }
  869. }