protected function generateProductsData() { $delimiter = ';'; $titles = array(); $id_lang = $this->use_lang; $new_path = new Sampledatainstall(); $f = fopen($new_path->sendPath() . 'output/products.vsc', 'w'); foreach ($this->product_fields as $field => $array) { $titles[] = $array['label']; } fputcsv($f, $titles, $delimiter, '"'); $products = Product::getProducts($id_lang, 0, 0, 'id_product', 'ASC', false, true); foreach ($products as $product) { $line = array(); $p = new Product($product['id_product'], true, $id_lang, 1); foreach ($this->product_fields as $field => $array) { $line[$field] = property_exists('Product', $field) && !is_array($p->{$field}) && !Tools::isEmpty($p->{$field}) ? $p->{$field} : ''; } $cats = $p->getProductCategoriesFull($p->id, 1); $cat_array = array(); foreach ($cats as $cat) { $cat_array[] = $cat['id_category']; } $line['categories'] = implode(',', $cat_array); $line['price_tex'] = $p->getPrice(false); $line['price_tin'] = $p->getPrice(true); $line['upc'] = $p->upc ? $p->upc : ''; $line['features'] = ''; $features = $p->getFrontFeatures($id_lang); $position = 1; $devider = ''; foreach ($features as $feature) { $sql = 'SELECT `id_feature` FROM ' . _DB_PREFIX_ . 'feature_lang WHERE `name` = "' . pSql($feature['name']) . '"'; $sql1 = 'SELECT `id_feature_value` FROM ' . _DB_PREFIX_ . 'feature_value_lang WHERE `value` = "' . pSql($feature['value']) . '"'; $id_feature = Db::getInstance()->getValue($sql); $id_feature_value = Db::getInstance()->getValue($sql1); $line['features'] .= $devider . $id_feature . ':' . $id_feature_value . ':' . $position; $devider = ','; $position++; } $specificPrice = SpecificPrice::getSpecificPrice($p->id, 1, 0, 0, 0, 0); $line['reduction_price'] = ''; $line['reduction_percent'] = ''; $line['reduction_from'] = ''; $line['reduction_to'] = ''; if ($specificPrice) { if ($specificPrice['reduction_type'] == 'amount') { $line['reduction_price'] = $specificPrice['reduction']; } elseif ($specificPrice['reduction_type'] == 'percent') { $line['reduction_percent'] = $specificPrice['reduction']; } if ($line['reduction_price'] !== '' || $line['reduction_percent'] !== '') { $line['reduction_from'] = $specificPrice['from']; $line['reduction_to'] = $specificPrice['to']; } } $tags = $p->getTags($id_lang); $line['tags'] = $tags; $link = new Link(); $imagelinks = array(); $images = $p->getImages($id_lang); foreach ($images as $image) { $imagelink = Tools::getShopProtocol() . $link->getImageLink($p->link_rewrite, $p->id . '-' . $image['id_image']); $this->copyConverFileName($imagelink); $imagelinks[] = $imagelink; } $line['image'] = implode(',', $imagelinks); $line['delete_existing_images'] = 0; $line['shop'] = 1; $warehouses = Warehouse::getWarehousesByProductId($p->id); $line['warehouse'] = ''; if (!empty($warehouses)) { $line['warehouse'] = implode(',', array_map("{$this->getWarehouses}", $warehouses)); } $values = array(); $accesories = $p->getAccessories($id_lang); if (isset($accesories) && $accesories && count($accesories)) { foreach ($accesories as $accesorie) { $values[] = $accesorie['id_product']; } } $line['accessories'] = $values ? implode(',', $values) : ''; $values = array(); $carriers = $p->getCarriers(); if (isset($carriers) && $carriers && count($carriers)) { foreach ($carriers as $carrier) { $values[] = $carrier['id_carrier']; } } $line['carriers'] = $values ? implode(',', $values) : ''; $values = array(); $customization_fields_ids = $p->getCustomizationFieldIds(); if (class_exists('CustomizationField') && isset($customization_fields_ids) && $customization_fields_ids && count($customization_fields_ids)) { foreach ($customization_fields_ids as $customization_field_id) { $cf = new CustomizationField($customization_field_id['id_customization_field'], $this->use_lang); $values[] = $cf->id . ':' . $cf->type . ':' . $cf->required . ':' . $cf->name; } } $line['customization_fields_ids'] = $values ? implode(',', $values) : ''; $values = array(); $attachments = $p->getAttachments($this->use_lang); if (isset($attachments) && $attachments && count($attachments)) { foreach ($attachments as $attachment) { $values[] = $attachment['id_attachment']; } } $line['attachments'] = $values ? implode(',', $values) : ''; if (!property_exists('Product', 'base_price')) { // for versions < 1.6.0.13 $line['base_price'] = !is_array($p->base_price) && !Tools::isEmpty($p->base_price) ? $p->base_price : ''; } if (!$line[$field]) { $line[$field] = ''; } fputcsv($f, $line, $delimiter, '"'); } fclose($f); }
private function getImages() { $images = $this->product->getImages((int) $this->context->language->id); $link = $this->context->link; $jsonImages = array(); if ($images && count($images)) { foreach ($images as $image) { $jsonImages[] = array('name' => $image['legend'], 'url' => $link->getImageLink($this->product->link_rewrite, $this->product->id . '-' . $image['id_image'])); } } return $jsonImages; }
/** * Assign template vars related to images */ protected function assignImages() { $images = $this->product->getImages((int) $this->context->cookie->id_lang); $product_images = array(); if (isset($images[0])) { $this->context->smarty->assign('mainImage', $images[0]); } foreach ($images as $k => $image) { if ($image['cover']) { $this->context->smarty->assign('mainImage', $image); $cover = $image; $cover['id_image'] = Configuration::get('PS_LEGACY_IMAGES') ? $this->product->id . '-' . $image['id_image'] : $image['id_image']; $cover['id_image_only'] = (int) $image['id_image']; } $product_images[(int) $image['id_image']] = $image; } if (!isset($cover)) { if (isset($images[0])) { $cover = $images[0]; $cover['id_image'] = Configuration::get('PS_LEGACY_IMAGES') ? $this->product->id . '-' . $images[0]['id_image'] : $images[0]['id_image']; $cover['id_image_only'] = (int) $images[0]['id_image']; } else { $cover = array('id_image' => $this->context->language->iso_code . '-default', 'legend' => 'No picture', 'title' => 'No picture'); } } $size = Image::getSize(ImageType::getFormatedName('large')); $this->context->smarty->assign(array('have_image' => isset($cover['id_image']) && (int) $cover['id_image'] ? array((int) $cover['id_image']) : Product::getCover((int) Tools::getValue('id_product')), 'cover' => $cover, 'imgWidth' => (int) $size['width'], 'mediumSize' => Image::getSize(ImageType::getFormatedName('medium')), 'largeSize' => Image::getSize(ImageType::getFormatedName('large')), 'homeSize' => Image::getSize(ImageType::getFormatedName('home')), 'cartSize' => Image::getSize(ImageType::getFormatedName('cart')), 'col_img_dir' => _PS_COL_IMG_DIR_)); if (count($product_images)) { $this->context->smarty->assign('images', $product_images); } }
public function hookDisplayTmHoverImage($params) { if (!$this->isCached('tmimagehover.tpl', $this->getCacheId($params['id_product']))) { $id_lang = $this->context->language->id; $obj = new Product((int) $params['id_product'], false, $id_lang); $images = $obj->getImages($this->context->language->id); $_images = array(); if (!empty($images)) { foreach ($images as $k => $image) { if (!$image['cover']) { $_images[] = $obj->id . '-' . $image['id_image']; } } } $this->smarty->assign(array('link_rewrite' => $params['link_rewrite'], 'images' => $_images)); } return $this->display(__FILE__, 'tmimagehover.tpl', $this->getCacheId($params['id_product'])); }
private function getOfferInfo(Product $model) { $res = ''; $res .= CHtml::tag('url', [], $model->getUrl(true)); $res .= CHtml::tag('price', [], $model->price); $res .= CHtml::tag('currencyId', [], 'RUR'); $res .= CHtml::tag('categoryId', [], $model->category_id); // tag market_category $imageCount = 0; if ($model->image) { $res .= CHtml::tag('picture', [], $model->getImageUrl()); $imageCount++; } foreach ($model->getImages() as $image) { if ($imageCount > 10) { break; } $res .= CHtml::tag('picture', [], $image->getImageUrl()); $imageCount++; } // tag store // tag pickup // tag delivery // tag local_delivery_cost // tag typePrefix $res .= CHtml::tag('vendor', [], $model->producer->name); // tag vendorCode $res .= CHtml::tag('model', [], htmlspecialchars(strip_tags($model->name))); $res .= CHtml::tag('description', [], htmlspecialchars(strip_tags($model->description))); // tag sales_notes // tag manufacturer_warranty // tag seller_warranty // tag country_of_origin // tag downloadable // tag adult // tag age // tag barcode // tag cpa // tag rec // tag expiry // tag weight // tag dimensions // tag param return $res; }
public function attributeImport() { $default_language = Configuration::get('PS_LANG_DEFAULT'); $groups = array(); foreach (AttributeGroup::getAttributesGroups($default_language) as $group) { $groups[$group['name']] = (int) $group['id_attribute_group']; } $attributes = array(); foreach (Attribute::getAttributes($default_language) as $attribute) { $attributes[$attribute['attribute_group'] . '_' . $attribute['name']] = (int) $attribute['id_attribute']; } $this->receiveTab(); $handle = $this->openCsvFile(); AdminImportController::setLocale(); for ($current_line = 0; $line = fgetcsv($handle, MAX_LINE_SIZE, $this->separator); $current_line++) { if (count($line) == 1 && empty($line[0])) { continue; } if (Tools::getValue('convert')) { $line = $this->utf8EncodeArray($line); } $info = AdminImportController::getMaskedRow($line); $info = array_map('trim', $info); AdminImportController::setDefaultValues($info); if (!Shop::isFeatureActive()) { $info['shop'] = 1; } elseif (!isset($info['shop']) || empty($info['shop'])) { $info['shop'] = implode($this->multiple_value_separator, Shop::getContextListShopID()); } // Get shops for each attributes $info['shop'] = explode($this->multiple_value_separator, $info['shop']); $id_shop_list = array(); foreach ($info['shop'] as $shop) { if (!is_numeric($shop)) { $id_shop_list[] = Shop::getIdByName($shop); } else { $id_shop_list[] = $shop; } } if (isset($info['id_product'])) { $product = new Product((int) $info['id_product'], false, $default_language); } else { continue; } $id_image = null; //delete existing images if "delete_existing_images" is set to 1 if (array_key_exists('delete_existing_images', $info) && $info['delete_existing_images'] && !isset($this->cache_image_deleted[(int) $product->id])) { $product->deleteImages(); $this->cache_image_deleted[(int) $product->id] = true; } if (isset($info['image_url']) && $info['image_url']) { $product_has_images = (bool) Image::getImages($this->context->language->id, $product->id); $url = $info['image_url']; $image = new Image(); $image->id_product = (int) $product->id; $image->position = Image::getHighestPosition($product->id) + 1; $image->cover = !$product_has_images ? true : false; $field_error = $image->validateFields(UNFRIENDLY_ERROR, true); $lang_field_error = $image->validateFieldsLang(UNFRIENDLY_ERROR, true); if ($field_error === true && $lang_field_error === true && $image->add()) { $image->associateTo($id_shop_list); if (!AdminImportController::copyImg($product->id, $image->id, $url)) { $this->warnings[] = sprintf(Tools::displayError('Error copying image: %s'), $url); $image->delete(); } else { $id_image = array($image->id); } } else { $this->warnings[] = sprintf(Tools::displayError('%s cannot be saved'), isset($image->id_product) ? ' (' . $image->id_product . ')' : ''); $this->errors[] = ($field_error !== true ? $field_error : '') . (isset($lang_field_error) && $lang_field_error !== true ? $lang_field_error : '') . mysql_error(); } } elseif (isset($info['image_position']) && $info['image_position']) { $images = $product->getImages($default_language); if ($images) { foreach ($images as $row) { if ($row['position'] == (int) $info['image_position']) { $id_image = array($row['id_image']); break; } } } if (!$id_image) { $this->warnings[] = sprintf(Tools::displayError('No image was found for combination with id_product = %s and image position = %s.'), $product->id, (int) $info['image_position']); } } $id_attribute_group = 0; // groups $groups_attributes = array(); if (isset($info['group'])) { foreach (explode($this->multiple_value_separator, $info['group']) as $key => $group) { $tab_group = explode(':', $group); $group = trim($tab_group[0]); if (!isset($tab_group[1])) { $type = 'select'; } else { $type = trim($tab_group[1]); } // sets group $groups_attributes[$key]['group'] = $group; // if position is filled if (isset($tab_group[2])) { $position = trim($tab_group[2]); } else { $position = false; } if (!isset($groups[$group])) { $obj = new AttributeGroup(); $obj->is_color_group = false; $obj->group_type = pSQL($type); $obj->name[$default_language] = $group; $obj->public_name[$default_language] = $group; $obj->position = !$position ? AttributeGroup::getHigherPosition() + 1 : $position; if (($field_error = $obj->validateFields(UNFRIENDLY_ERROR, true)) === true && ($lang_field_error = $obj->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true) { $obj->add(); $obj->associateTo($id_shop_list); $groups[$group] = $obj->id; } else { $this->errors[] = ($field_error !== true ? $field_error : '') . (isset($lang_field_error) && $lang_field_error !== true ? $lang_field_error : ''); } // fils groups attributes $id_attribute_group = $obj->id; $groups_attributes[$key]['id'] = $id_attribute_group; } else { $id_attribute_group = $groups[$group]; $groups_attributes[$key]['id'] = $id_attribute_group; } } } // inits attribute $id_product_attribute = 0; $id_product_attribute_update = false; $attributes_to_add = array(); // for each attribute if (isset($info['attribute'])) { foreach (explode($this->multiple_value_separator, $info['attribute']) as $key => $attribute) { $tab_attribute = explode(':', $attribute); $attribute = trim($tab_attribute[0]); // if position is filled if (isset($tab_attribute[1])) { $position = trim($tab_attribute[1]); } else { $position = false; } if (isset($groups_attributes[$key])) { $group = $groups_attributes[$key]['group']; if (!isset($attributes[$group . '_' . $attribute]) && count($groups_attributes[$key]) == 2) { $id_attribute_group = $groups_attributes[$key]['id']; $obj = new Attribute(); // sets the proper id (corresponding to the right key) $obj->id_attribute_group = $groups_attributes[$key]['id']; $obj->name[$default_language] = str_replace('\\n', '', str_replace('\\r', '', $attribute)); $obj->position = !$position && isset($groups[$group]) ? Attribute::getHigherPosition($groups[$group]) + 1 : $position; if (($field_error = $obj->validateFields(UNFRIENDLY_ERROR, true)) === true && ($lang_field_error = $obj->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true) { $obj->add(); $obj->associateTo($id_shop_list); $attributes[$group . '_' . $attribute] = $obj->id; } else { $this->errors[] = ($field_error !== true ? $field_error : '') . (isset($lang_field_error) && $lang_field_error !== true ? $lang_field_error : ''); } } $info['minimal_quantity'] = isset($info['minimal_quantity']) && $info['minimal_quantity'] ? (int) $info['minimal_quantity'] : 1; $info['wholesale_price'] = str_replace(',', '.', $info['wholesale_price']); $info['price'] = str_replace(',', '.', $info['price']); $info['ecotax'] = str_replace(',', '.', $info['ecotax']); $info['weight'] = str_replace(',', '.', $info['weight']); // if a reference is specified for this product, get the associate id_product_attribute to UPDATE if (isset($info['reference']) && !empty($info['reference'])) { $id_product_attribute = Combination::getIdByReference($product->id, strval($info['reference'])); // updates the attribute if ($id_product_attribute) { // gets all the combinations of this product $attribute_combinations = $product->getAttributeCombinations($default_language); foreach ($attribute_combinations as $attribute_combination) { if ($id_product_attribute && in_array($id_product_attribute, $attribute_combination)) { $product->updateAttribute($id_product_attribute, (double) $info['wholesale_price'], (double) $info['price'], (double) $info['weight'], 0, (double) $info['ecotax'], $id_image, strval($info['reference']), strval($info['ean13']), (int) $info['default_on'], 0, strval($info['upc']), (int) $info['minimal_quantity'], 0, null, $id_shop_list); $id_product_attribute_update = true; } } } } // if no attribute reference is specified, creates a new one if (!$id_product_attribute) { $id_product_attribute = $product->addCombinationEntity((double) $info['wholesale_price'], (double) $info['price'], (double) $info['weight'], 0, (double) $info['ecotax'], (int) $info['quantity'], $id_image, strval($info['reference']), 0, strval($info['ean13']), (int) $info['default_on'], 0, strval($info['upc']), (int) $info['minimal_quantity'], $id_shop_list); } // fills our attributes array, in order to add the attributes to the product_attribute afterwards if (isset($attributes[$group . '_' . $attribute])) { $attributes_to_add[] = (int) $attributes[$group . '_' . $attribute]; } // after insertion, we clean attribute position and group attribute position $obj = new Attribute(); $obj->cleanPositions((int) $id_attribute_group, false); AttributeGroup::cleanPositions(); } } } $product->checkDefaultAttributes(); if (!$product->cache_default_attribute) { Product::updateDefaultAttribute($product->id); } if ($id_product_attribute) { // now adds the attributes in the attribute_combination table if ($id_product_attribute_update) { Db::getInstance()->execute(' DELETE FROM ' . _DB_PREFIX_ . 'product_attribute_combination WHERE id_product_attribute = ' . (int) $id_product_attribute); } foreach ($attributes_to_add as $attribute_to_add) { Db::getInstance()->execute(' INSERT IGNORE INTO ' . _DB_PREFIX_ . 'product_attribute_combination (id_attribute, id_product_attribute) VALUES (' . (int) $attribute_to_add . ',' . (int) $id_product_attribute . ')'); } StockAvailable::setQuantity($product->id, $id_product_attribute, (int) $info['quantity']); } } $this->closeCsvFile($handle); }
function addProducts($client, $ids = array()) { //update currency // update_currency(); $default_tz = date_default_timezone_get(); date_default_timezone_set('UTC'); $category = new Category(1, 1); $sql = "select p.id_product, DATEDIFF(NOW(), p.`date_add`) as 'age'\n from ps_product p\n where p.price > 0 and p.active = 1"; $productScores = array(); $products = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS($sql); foreach ($products as $product) { $productScores[$product['id_product']] = array('age' => $product['age'], 'week_sold' => 0, 'month_sales' => 0, 'year_sales' => 0); } $sql = "select p.`id_product`, sum(od.product_quantity) as 'quantity'\n from `ps_product` p\n inner join `ps_order_detail` od on od.product_id = p.id_product\n inner join ps_orders o on o.id_order = od.id_order\n where p.price > 0 \n and p.active = 1\n and o.date_add > now() - INTERVAL 7 DAY\n group by p.id_product"; $week_quantities = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS($sql); foreach ($week_quantities as $week_quantity) { $productScores[$week_quantity['id_product']]['week_sold'] = $week_quantity['quantity']; } $sql = "select p.`id_product`, round(sum(od.product_quantity * od.product_price * 55 / o.`conversion_rate`)) as 'month_revenue'\n from `ps_product` p\n inner join `ps_order_detail` od on od.product_id = p.id_product\n inner join ps_orders o on o.id_order = od.id_order\n where p.price > 0 and p.active = 1\n and o.date_add > now() - INTERVAL 30 DAY\n group by p.id_product"; $month_sales = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS($sql); foreach ($month_sales as $month_sale) { $productScores[$month_sale['id_product']]['month_sales'] = $month_sale['month_revenue']; } $sql = "select p.`id_product`, round(sum(od.product_quantity * od.product_price * 55 / o.`conversion_rate`)) as 'year_revenue'\n from `ps_product` p\n inner join `ps_order_detail` od on od.product_id = p.id_product\n inner join ps_orders o on o.id_order = od.id_order\n where p.price > 0 and p.active = 1\n and o.date_add > now() - INTERVAL 365 DAY\n group by p.id_product"; $year_sales = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS($sql); foreach ($year_sales as $year_sale) { $productScores[$year_sale['id_product']]['year_sales'] = $year_sale['year_revenue']; } foreach ($products as $product) { $productScores[$product['id_product']]['score'] = getWeekSalesScore($productScores[$product['id_product']]['week_sold']) + getAgeScore($productScores[$product['id_product']]['age']) + getMonthScore($productScores[$product['id_product']]['month_sales']) + getYearScore($productScores[$product['id_product']]['year_sales']); } $docs = array(); $link = new Link(); $count = 0; $update = $client->createUpdate(); foreach ($products as $product) { if (!empty($ids) && !in_array((int) $product['id_product'], $ids)) { continue; } $productObj = new Product((int) $product['id_product'], true, 1); print_r('\\n' . 'reindexing ' . $product['id_product']); if (!$productObj->active) { deleteProduct($productObj->id, $client); continue; } $doc = $update->createDocument(); $doc->id_product = $productObj->id; $doc->reference = $productObj->reference; $doc->name = $productObj->name; $doc->description = preg_replace('@[\\x00-\\x08\\x0B\\x0C\\x0E-\\x1F]@', ' ', $productObj->description); $doc->description_short = preg_replace('@[\\x00-\\x08\\x0B\\x0C\\x0E-\\x1F]@', ' ', $productObj->description_short); $doc->brand_id = $productObj->id_manufacturer; $doc->brand_name = $productObj->manufacturer_name; $doc->style_tips = $productObj->description_short; $doc->alphaNameSort = $productObj->name; $dbresult = $productObj->getWsCategories(); $catIds = array(); foreach ($dbresult as $catIdRow) { $catIds[] = $catIdRow['id']; } $category_names = array(); foreach ($catIds as $catID) { $category = new Category((int) $catID); $category_names[] = $category->getName(1); } $doc->cat_name = $category_names; $doc->cat_id = $catIds; $doc->tags = $productObj->getTags(1); $doc->shipping_sla = $productObj->shipping_sla ? $productObj->shipping_sla : 0; $doc->weight = $productObj->weight ? $productObj->weight : 0.5; if (isset($productObj->work_type)) { $doc->work_type = preg_replace('@[\\x00-\\x08\\x0B\\x0C\\x0E-\\x1F]@', ' ', $productObj->work_type ? $productObj->work_type : ''); } if (isset($productObj->garment_type)) { $doc->garment_type = preg_replace('@[\\x00-\\x08\\x0B\\x0C\\x0E-\\x1F]@', ' ', $productObj->garment_type ? $productObj->garment_type : ''); } if (isset($productObj->blouse_length)) { $doc->blouse_length = $productObj->blouse_length ? $productObj->blouse_length : ''; } $doc->height = $productObj->height; $doc->width = $productObj->width; $atributeQty = Attribute::getAttributeQty($productObj->id); if ($productObj->quantity > 0 || $atributeQty > 0) { $doc->inStock = true; } else { $doc->inStock = false; } $doc->isPlusSize = $productObj->is_plussize ? true : false; $doc->isRTS = $productObj->is_rts ? true : false; $doc->quantity = $productObj->quantity ? $productObj->quantity : ($atributeQty ? $atributeQty : 0); //Indian Price $doc->offer_price_in = Product::getPriceStatic($productObj->id, true, NULL, 6, NULL, false, true, 1, false, NULL, NULL, IND_ADDRESS_ID); $doc->offer_price_in_rs = Tools::convertPrice($doc->offer_price_in, 4); $doc->mrp_in = Product::getPriceStatic($productObj->id, true, NULL, 6, NULL, false, false, 1, false, NULL, NULL, IND_ADDRESS_ID); if ($doc->mrp_in > $doc->offer_price_in) { $doc->discount_in = Tools::ps_round(($doc->mrp_in - $doc->offer_price_in) / $doc->mrp_in * 100); } //Worldwide Price $doc->offer_price = $productObj->getPrice(); $doc->offer_price_rs = Tools::convertPrice($doc->offer_price, 4); $doc->mrp = $productObj->getPriceWithoutReduct(); if ($doc->mrp > $doc->offer_price) { $doc->discount = Tools::ps_round(($doc->mrp - $doc->offer_price) / $doc->mrp * 100); } $date = DateTime::createFromFormat('Y-m-d H:i:s', $productObj->date_add); $doc->date_add = $date->format("Y-m-d\\TG:i:s\\Z"); $doc->product_link = $productObj->getLink(); $idImage = $productObj->getCoverWs(); if ($idImage) { $idImage = $productObj->id . '-' . $idImage; } else { $idImage = Language::getIsoById(1) . '-default'; } $doc->image_link_list = $link->getImageLink($productObj->link_rewrite, $idImage, 'list'); $doc->image_link_medium = $link->getImageLink($productObj->link_rewrite, $idImage, 'medium'); $doc->image_link_large = $link->getImageLink($productObj->link_rewrite, $idImage, 'large'); $images = $productObj->getImages(1); $productImages = array(); foreach ($images as $k => $image) { $productImages[] = $link->getImageLink($productObj->link_rewrite, $image['id_image'], 'large'); } $doc->image_links = $productImages; $doc->sales = $productScores[$product['id_product']]['score']; $productObj->fabric = trim($productObj->fabric); $productObj->fabric = preg_replace('/\\s+/', '-', $productObj->fabric); $doc->fabric = strtolower($productObj->fabric); $doc->is_customizable = $productObj->is_customizable; if (isset($productObj->generic_color) && !empty($productObj->generic_color)) { $colors = explode(',', $productObj->generic_color); $indexed_colors = array(); foreach ($colors as $color) { $indexed_colors[] = strtolower(preg_replace('/\\s+/', '-', trim($color))); } $doc->color = $indexed_colors; } if (isset($productObj->stone) && !empty($productObj->stone)) { $stones = explode(',', $productObj->stone); $indexed_stones = array(); foreach ($stones as $stone) { $indexed_stones[] = strtolower(preg_replace('/\\s+/', '-', trim($stone))); } $doc->stone = $indexed_stones; } if (isset($productObj->plating) && !empty($productObj->plating)) { $platings = explode(',', $productObj->plating); $indexed_platings = array(); foreach ($platings as $plating) { $indexed_platings[] = strtolower(preg_replace('/\\s+/', '-', trim($plating))); } $doc->plating = $indexed_platings; } if (isset($productObj->material) && !empty($productObj->material)) { $materials = explode(',', $productObj->material); $indexed_materials = array(); foreach ($materials as $material) { $indexed_materials[] = strtolower(preg_replace('/\\s+/', '-', trim($material))); } $doc->material = $indexed_materials; } if (isset($productObj->look) && !empty($productObj->look)) { $looks = explode(',', $productObj->look); $indexed_looks = array(); foreach ($looks as $look) { $indexed_looks[] = strtolower(preg_replace('/\\s+/', '-', trim($look))); } $doc->look = $indexed_looks; } if (isset($productObj->handbag_occasion) && !empty($productObj->handbag_occasion)) { $handbag_occasions = explode(',', $productObj->handbag_occasion); $indexed_handbag_occasions = array(); foreach ($handbag_occasions as $handbag_occasion) { $indexed_handbag_occasions[] = strtolower(preg_replace('/\\s+/', '-', trim($handbag_occasion))); } $doc->handbag_occasion = $indexed_handbag_occasions; } if (isset($productObj->handbag_style) && !empty($productObj->handbag_style)) { $handbag_styles = explode(',', $productObj->handbag_style); $indexed_handbag_styles = array(); foreach ($handbag_styles as $handbag_style) { $indexed_handbag_styles[] = strtolower(preg_replace('/\\s+/', '-', trim($handbag_style))); } $doc->handbag_style = $indexed_handbag_styles; } if (isset($productObj->handbag_material) && !empty($productObj->handbag_material)) { $handbag_materials = explode(',', $productObj->handbag_material); $indexed_handbag_materials = array(); foreach ($handbag_materials as $handbag_material) { $indexed_handbag_materials[] = strtolower(preg_replace('/\\s+/', '-', trim($handbag_material))); } $doc->handbag_material = $indexed_handbag_materials; } $combinaisons = $productObj->getAttributeCombinaisons(1); $indexed_sizes = array(); foreach ($combinaisons as $k => $combinaison) { if ($combinaison['group_name'] == 'size' || $combinaison['group_name'] == 'Size') { $indexed_sizes[] = $combinaison['attribute_name']; } } $doc->size = $indexed_sizes; $doc->cashback_percentage = $productObj->cashback_percentage; $docs[] = $doc; if (++$count == 300) { $update->addDocuments($docs); $result = $client->update($update); echo 'Update query executed' . PHP_EOL; echo 'Query status: ' . $result->getStatus() . PHP_EOL; echo 'Query time: ' . $result->getQueryTime() . PHP_EOL; $count = 0; $docs = array(); $update = $client->createUpdate(); } } $update->addDocuments($docs); date_default_timezone_set($default_tz); $result = $client->update($update); $sql = "update ps_product set indexed = 1 where indexed = 0"; Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS($sql); }
public function attributeImport() { global $cookie; $defaultLanguage = Configuration::get('PS_LANG_DEFAULT'); $groups = array(); foreach (AttributeGroup::getAttributesGroups($defaultLanguage) as $group) { $groups[$group['name']] = (int) $group['id_attribute_group']; } $attributes = array(); foreach (Attribute::getAttributes($defaultLanguage) as $attribute) { $attributes[$attribute['attribute_group'] . '_' . $attribute['name']] = (int) $attribute['id_attribute']; } $this->receiveTab(); $handle = $this->openCsvFile(); $fsep = (is_null(Tools::getValue('multiple_value_separator')) or trim(Tools::getValue('multiple_value_separator')) == '') ? ',' : Tools::getValue('multiple_value_separator'); self::setLocale(); for ($current_line = 0; $line = fgetcsv($handle, MAX_LINE_SIZE, Tools::getValue('separator')); $current_line++) { if (Tools::getValue('convert')) { $line = $this->utf8_encode_array($line); } $info = self::getMaskedRow($line); $info = array_map('trim', $info); self::setDefaultValues($info); $product = new Product((int) $info['id_product'], false, $defaultLanguage); $id_image = null; if (isset($info['image_url']) && $info['image_url']) { $productHasImages = (bool) Image::getImages((int) $cookie->id_lang, (int) $product->id); $url = $info['image_url']; $image = new Image(); $image->id_product = (int) $product->id; $image->position = Image::getHighestPosition($product->id) + 1; $image->cover = !$productHasImages ? true : false; $image->legend = self::createMultiLangField($product->name); if (($fieldError = $image->validateFields(UNFRIENDLY_ERROR, true)) === true and ($langFieldError = $image->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true and $image->add()) { if (!self::copyImg($product->id, $image->id, $url)) { $this->_warnings[] = Tools::displayError('Error copying image: ') . $url; } else { $id_image = array($image->id); } } else { $this->_warnings[] = $image->legend[$defaultLanguageId] . (isset($image->id_product) ? ' (' . $image->id_product . ')' : '') . ' ' . Tools::displayError('Cannot be saved'); $this->_errors[] = ($fieldError !== true ? $fieldError : '') . ($langFieldError !== true ? $langFieldError : '') . mysql_error(); } } elseif (isset($info['image_position']) && $info['image_position']) { $images = $product->getImages($defaultLanguage); if ($images) { foreach ($images as $row) { if ($row['position'] == (int) $info['image_position']) { $id_image = array($row['id_image']); break; } } } if (!$id_image) { $this->_warnings[] = sprintf(Tools::displayError('No image found for combination with id_product = %s and image position = %s.'), $product->id, (int) $info['image_position']); } } $id_product_attribute = $product->addProductAttribute((double) $info['price'], (double) $info['weight'], 0, (double) $info['ecotax'], (int) $info['quantity'], $id_image, strval($info['reference']), strval($info['supplier_reference']), strval($info['ean13']), (int) $info['default_on'], strval($info['upc'])); foreach (explode($fsep, $info['options']) as $option) { list($group, $attribute) = array_map('trim', explode(':', $option)); if (!isset($groups[$group])) { $obj = new AttributeGroup(); $obj->is_color_group = false; $obj->name[$defaultLanguage] = $group; $obj->public_name[$defaultLanguage] = $group; if (($fieldError = $obj->validateFields(UNFRIENDLY_ERROR, true)) === true and ($langFieldError = $obj->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true) { $obj->add(); $groups[$group] = $obj->id; } else { $this->_errors[] = ($fieldError !== true ? $fieldError : '') . ($langFieldError !== true ? $langFieldError : ''); } } if (!isset($attributes[$group . '_' . $attribute])) { $obj = new Attribute(); $obj->id_attribute_group = $groups[$group]; $obj->name[$defaultLanguage] = str_replace('\\n', '', str_replace('\\r', '', $attribute)); if (($fieldError = $obj->validateFields(UNFRIENDLY_ERROR, true)) === true and ($langFieldError = $obj->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true) { $obj->add(); $attributes[$group . '_' . $attribute] = $obj->id; } else { $this->_errors[] = ($fieldError !== true ? $fieldError : '') . ($langFieldError !== true ? $langFieldError : ''); } } Db::getInstance()->Execute('INSERT INTO ' . _DB_PREFIX_ . 'product_attribute_combination (id_attribute, id_product_attribute) VALUES (' . (int) $attributes[$group . '_' . $attribute] . ',' . (int) $id_product_attribute . ')'); } } $this->closeCsvFile($handle); }
public function hookProductFooter($params) { $product = new Product((int) Tools::getValue('id_product')); $lang_id = (int) (int) $this->context->cookie->id_lang; $images = $product->getImages($lang_id); foreach ($images as $image) { if ($image['cover']) { $cover = $image; $cover['id_image'] = Configuration::get('PS_LEGACY_IMAGES') ? $this->product->id . '-' . $image['id_image'] : $image['id_image']; } } if (!isset($cover)) { $cover = array('id_image' => $this->context->language->iso_code . '-default'); } $prod = new stdClass(); $prod->name = $product->name[$lang_id]; $prod->description = $product->description[$lang_id]; $prod->link_rewrite = $product->link_rewrite[$lang_id]; $prod->price = $product->price; $this->context->smarty->assign(array('product' => $prod, 'cover' => $cover['id_image'])); return $this->display(__FILE__, 'product.tpl'); }
/** * Updates a product on Prestashop. * * @param array $product_attributes * @param integer $id_product * @param string $url_photo * @param array $triple_cod_col_siz * @param integer $language * @param array $array_combinations * @return array * @see $this->isOldNameProductEgualToNewNameProduct * @see $this->isOldOrNewValueForProduct * @see $this->controlCategoriesForActivateTheir * @see $this->updateCombinantionsForPrestashop * */ public function updateProductForPrestashop($product_attributes = array(), $id_product, $url_photo, $triple_cod_col_siz, $array_combinations, $language = 1) { $product = new Product($id_product); $is_change_product = false; $new_name_product = trim($product_attributes["Nome"]); if (!$this->isOldNameProductEgualToNewNameProduct($product->name, $new_name_product)) { $product->name = $this->setArrayElementForLinkRewrite($new_name_product, true, $language); $product->meta_keywords = $new_name_product; $product->link_rewrite = $this->setArrayElementForLinkRewrite($new_name_product, false, $language); $is_change_product = true; } $new_price = (double) $product_attributes["Prezzo"]; if (!$this->isOldOrNewValueForProduct((double) $product->price, $new_price)) { $product->price = $new_price; $is_change_product = true; } $new_active = (int) $product_attributes["Attivo"]; $control_category = $this->isOldOrNewValueForProduct((int) $product->active, $new_active); if (!$control_category) { $product->active = $new_active; $is_change_product = true; } $new_minimal_quantity = (int) $product_attributes["Qta_min"]; if (!$this->isOldOrNewValueForProduct((int) $product->minimal_quantity, $new_minimal_quantity)) { $product->minimal_quantity = $new_minimal_quantity; $is_change_product = true; } $new_quantity = (int) $product_attributes["Qta"]; if (!$this->isOldOrNewValueForProduct((int) $product->getQuantity($id_product), $new_quantity)) { StockAvailable::setQuantity($id_product, 0, $new_quantity); } $array_old_features = $product->getFeatures(); $array_features = $product_attributes["Feature"]; $height = false; $width = false; foreach ($array_old_features as $array_old_single_features) { $feature = new FeatureCore((int) $array_old_single_features['id_feature']); $tmp_feature = $feature->name; $single_old_feature = $tmp_feature[$language]; $feature_value = new FeatureValueCore((int) $array_old_single_features["id_feature_value"]); $tmp_feature_value = $feature_value->value; $single_old_feature_value = $tmp_feature_value[$language]; if ($this->isOldOrNewValueForProduct("Altezza", $single_old_feature)) { if (!$this->isOldOrNewValueForProduct($single_old_feature_value, $array_features["Altezza"] . " cm")) { $feature_value->value = array($language => $array_features["Altezza"] . " cm"); $feature_value->update(); $height = true; $is_change_product = true; } } if ($this->isOldOrNewValueForProduct("Larghezza", $single_old_feature)) { if (!$this->isOldOrNewValueForProduct($single_old_feature_value, $array_features["Larghezza"] . " cm")) { $feature_value->value = array($language => $array_features["Larghezza"] . " cm"); $feature_value->update(); $width = true; $is_change_product = true; } } if ($this->isOldOrNewValueForProduct("Lunghezza", $single_old_feature)) { if (!$this->isOldOrNewValueForProduct($single_old_feature_value, $array_features["Lunghezza"] . " cm")) { $feature_value->value = array($language => $array_features["Lunghezza"] . " cm"); $feature_value->update(); $is_change_product = true; } } if ($this->isOldOrNewValueForProduct("Modello", $single_old_feature)) { if (!$this->isOldOrNewValueForProduct($single_old_feature_value, $array_features["Modello"])) { $feature_value->value = array($language => $array_features["Modello"]); $feature_value->update(); $is_change_product = true; } } if ($this->isOldOrNewValueForProduct("Linea", $single_old_feature)) { if (!$this->isOldOrNewValueForProduct($single_old_feature_value, $array_features["Linea"])) { $feature_value->value = array($language => $array_features["Linea"]); $feature_value->update(); $is_change_product = true; } } } if ($height) { $product->height = (double) $array_features["Altezza"]; $is_change_product = true; } if ($width) { $product->width = (double) $array_features["Larghezza"]; $is_change_product = true; } if ($is_change_product) { $product->update(); } if (!$control_category) { $ids_categories_array = $product->getWsCategories(); $this->controlCategoriesForActivateTheir($ids_categories_array); } $change_new_image = $this->updateCombinantionsForPrestashop($id_product, $url_photo, $triple_cod_col_siz, $array_combinations, $language); $string_triple = array(); $return = array(); array_push($return, $product->id); $array_images_combinations_of_the_product = $product->getImages($language); $element = array(); foreach ($array_images_combinations_of_the_product as $array_combo_image) { $name_of_the_image = $array_combo_image['legend']; $id_image_of_the_product = $array_combo_image['id_image']; array_push($element, $id_image_of_the_product . ";" . $name_of_the_image); } array_push($return, $element); foreach ($change_new_image as $array_combo_image) { $fetch_tmp = explode(";", $array_combo_image); $fetch_jpg = explode(".jpg", $fetch_tmp[1]); $fetch_image_name = explode(",", $fetch_jpg[0]); array_push($string_triple, $fetch_image_name[2]); } array_push($return, $change_new_image); array_push($return, $string_triple); return $return; }
public function postProcess() { if (Tools::isSubmit('submitExport')) { $delimiter = Tools::getValue('export_delimiter'); $id_lang = Tools::getValue('export_language'); $id_shop = (int) $this->context->shop->id; set_time_limit(0); $fileName = 'products_' . date("Y_m_d_H_i_s") . '.csv'; header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); header('Content-Description: File Transfer'); header("Content-type: text/csv"); header("Content-Disposition: attachment; filename={$fileName}"); header("Expires: 0"); header("Pragma: public"); $f = fopen('php://output', 'w'); foreach ($this->available_fields as $field => $array) { $titles[] = $array['label']; } fputcsv($f, $titles, $delimiter, '"'); $export_active = Tools::getValue('export_active') == 0 ? false : true; $export_category = Tools::getValue('export_category') == 99999 ? false : Tools::getValue('export_category'); $products = Product::getProducts($id_lang, 0, 0, 'id_product', 'ASC', $export_category, $export_active); foreach ($products as $product) { $line = array(); $p = new Product($product['id_product'], true, $id_lang, $id_shop); $p->loadStockData(); foreach ($this->available_fields as $field => $array) { if (isset($p->{$field}) && !is_array($p->{$field})) { $line[$field] = $p->{$field} ? $p->{$field} : ' '; } else { switch ($field) { case 'categories': $cats = $p->getProductCategoriesFull($p->id, $id_lang); $cat_array = array(); foreach ($cats as $cat) { $cat_array[] = $cat['name']; } $line['categories'] = implode(",", $cat_array); break; case 'price_tex': $line['price_tex'] = $p->getPrice(false); $line['price_tin'] = $p->getPrice(true); break; case 'upc': $line['upc'] = $p->upc ? $p->upc : ' '; break; case 'features': $line['features'] = ''; $features = $p->getFrontFeatures($id_lang); $position = 1; foreach ($features as $feature) { $line['features'] .= $feature['name'] . ':' . $feature['value'] . ':' . $position; $position++; } break; case 'reduction_price': $specificPrice = SpecificPrice::getSpecificPrice($p->id, $id_shop, 0, 0, 0, 0); $line['reduction_price'] = ''; $line['reduction_percent'] = ''; $line['reduction_from'] = ''; $line['reduction_to'] = ''; if ($specificPrice['reduction_type'] == "amount") { $line['reduction_price'] = $specificPrice['reduction']; } elseif ($specificPrice['reduction_type'] == "percent") { $line['reduction_percent'] = $specificPrice['reduction']; } if ($line['reduction_price'] !== '' || $line['reduction_percent'] !== '') { $line['reduction_from'] = date_format(date_create($specificPrice['from']), "Y-m-d"); $line['reduction_to'] = date_format(date_create($specificPrice['to']), "Y-m-d"); } break; case 'tags': $tags = $p->getTags($id_lang); $line['tags'] = $tags; break; case 'image': $link = new Link(); $imagelinks = array(); $images = $p->getImages($id_lang); foreach ($images as $image) { $imagelinks[] = Tools::getShopProtocol() . $link->getImageLink($p->link_rewrite, $p->id . '-' . $image['id_image']); } $line['image'] = implode(",", $imagelinks); break; case 'delete_existing_images': $line['delete_existing_images'] = 0; break; case 'shop': $line['shop'] = $id_shop; break; case 'warehouse': $warehouses = Warehouse::getWarehousesByProductId($p->id); $line['warehouse'] = ''; if (!empty($warehouses)) { $line['warehouse'] = implode(',', array_map("{$this->getWarehouses}", $warehouses)); } break; case 'date_added': $date = new DateTime($p->date_add); $line['date_add'] = $date->format("Y-m-d"); break; } } } if (!$line[$field]) { $line[$field] = ''; } fputcsv($f, $line, $delimiter, '"'); } fclose($f); die; } }
/** * */ public function hookActionProductListModifier($products) { $playout = $this->getConfigValue('product_layout'); if (($playout == 'swap' || $playout == 'gallery') && $products['cat_products']) { foreach ($products['cat_products'] as $key => $product) { $obj = new Product($product['id_product'], true, $this->context->language->id, $this->context->shop->id); $images = $obj->getImages((int) $this->context->cookie->id_lang); $product['ptsimages'] = $images; $product['swapimage'] = count($images) > 1 ? $images[1] : ''; $products['cat_products'][$key] = $product; } } }
/** * @param Solarium_Query_Update $update * @param Link $link * @param Product $productObj * @return Solarium_Document_ReadWrite */ private static function getProductDoc($update, $link, $productObj) { $doc = $update->createDocument(); $doc->id_product = $productObj->id; $doc->reference = $productObj->reference; $doc->name = $productObj->name; //$doc->description = $productObj->description; $doc->description = preg_replace('@[\\x00-\\x08\\x0B\\x0C\\x0E-\\x1F]@', ' ', $productObj->description); $doc->description_short = preg_replace('@[\\x00-\\x08\\x0B\\x0C\\x0E-\\x1F]@', ' ', $productObj->description_short); $doc->brand_id = $productObj->id_manufacturer; $doc->brand_name = $productObj->manufacturer_name; $doc->style_tips = preg_replace('@[\\x00-\\x08\\x0B\\x0C\\x0E-\\x1F]@', ' ', $productObj->description_short); $doc->alphaNameSort = $productObj->name; $dbresult = $productObj->getWsCategories(); $catIds = array(); foreach ($dbresult as $catIdRow) { $catIds[] = $catIdRow['id']; } $category_names = array(); foreach ($catIds as $catID) { $category = new Category((int) $catID); $category_names[] = $category->getName(1); } $doc->cat_name = $category_names; $doc->cat_id = $catIds; $doc->tags = $productObj->getTags(1); $doc->shipping_sla = $productObj->shipping_sla; $doc->weight = $productObj->weight ? $productObj->weight : 0.5; $doc->cashback_percentage = $productObj->cashback_percentage; if (isset($productObj->work_type)) { $doc->work_type = preg_replace('@[\\x00-\\x08\\x0B\\x0C\\x0E-\\x1F]@', ' ', $productObj->work_type ? $productObj->work_type : ''); } if (isset($productObj->garment_type)) { $doc->garment_type = preg_replace('@[\\x00-\\x08\\x0B\\x0C\\x0E-\\x1F]@', ' ', $productObj->garment_type ? $productObj->garment_type : ''); } if (isset($productObj->blouse_length)) { $doc->blouse_length = $productObj->blouse_length ? $productObj->blouse_length : ''; } $doc->height = $productObj->height; $doc->width = $productObj->width; $atributeQty = Attribute::getAttributeQty($productObj->id); if ($productObj->quantity > 0 || $atributeQty > 0) { $doc->inStock = true; } else { $doc->inStock = false; } $doc->isPlusSize = $productObj->is_plussize ? true : false; $doc->isRTS = $productObj->is_rts ? true : false; $doc->quantity = $productObj->quantity ? $productObj->quantity : ($atributeQty ? $atributeQty : 0); $date = DateTime::createFromFormat('Y-m-d H:i:s', $productObj->date_add); $doc->date_add = $date->format("Y-m-d\\TG:i:s\\Z"); $productObj->fabric = trim($productObj->fabric); $productObj->fabric = preg_replace('/\\s+/', '-', $productObj->fabric); $doc->fabric = strtolower($productObj->fabric); $doc->is_customizable = $productObj->is_customizable; if (isset($productObj->generic_color) && !empty($productObj->generic_color)) { $colors = explode(',', $productObj->generic_color); $indexed_colors = array(); foreach ($colors as $color) { $indexed_colors[] = strtolower(preg_replace('/\\s+/', '-', trim($color))); } $doc->color = $indexed_colors; } if (isset($productObj->stone) && !empty($productObj->stone)) { $stones = explode(',', $productObj->stone); $indexed_stones = array(); foreach ($stones as $stone) { $indexed_stones[] = strtolower(preg_replace('/\\s+/', '-', trim($stone))); } $doc->stone = $indexed_stones; } if (isset($productObj->plating) && !empty($productObj->plating)) { $platings = explode(',', $productObj->plating); $indexed_platings = array(); foreach ($platings as $plating) { $indexed_platings[] = strtolower(preg_replace('/\\s+/', '-', trim($plating))); } $doc->plating = $indexed_platings; } if (isset($productObj->material) && !empty($productObj->material)) { $materials = explode(',', $productObj->material); $indexed_materials = array(); foreach ($materials as $material) { $indexed_materials[] = strtolower(preg_replace('/\\s+/', '-', trim($material))); } $doc->material = $indexed_materials; } if (isset($productObj->look) && !empty($productObj->look)) { $looks = explode(',', $productObj->look); $indexed_looks = array(); foreach ($looks as $look) { $indexed_looks[] = strtolower(preg_replace('/\\s+/', '-', trim($look))); } $doc->look = $indexed_looks; } if (isset($productObj->handbag_occasion) && !empty($productObj->handbag_occasion)) { $handbag_occasions = explode(',', $productObj->handbag_occasion); $indexed_handbag_occasions = array(); foreach ($handbag_occasions as $handbag_occasion) { $indexed_handbag_occasions[] = strtolower(preg_replace('/\\s+/', '-', trim($handbag_occasion))); } $doc->handbag_occasion = $indexed_handbag_occasions; } if (isset($productObj->handbag_style) && !empty($productObj->handbag_style)) { $handbag_styles = explode(',', $productObj->handbag_style); $indexed_handbag_styles = array(); foreach ($handbag_styles as $handbag_style) { $indexed_handbag_styles[] = strtolower(preg_replace('/\\s+/', '-', trim($handbag_style))); } $doc->handbag_style = $indexed_handbag_styles; } if (isset($productObj->handbag_material) && !empty($productObj->handbag_material)) { $handbag_materials = explode(',', $productObj->handbag_material); $indexed_handbag_materials = array(); foreach ($handbag_materials as $handbag_material) { $indexed_handbag_materials[] = strtolower(preg_replace('/\\s+/', '-', trim($handbag_material))); } $doc->handbag_material = $indexed_handbag_materials; } $combinaisons = $productObj->getAttributeCombinaisons(1); $indexed_sizes = array(); foreach ($combinaisons as $k => $combinaison) { if ($combinaison['group_name'] == 'size' || $combinaison['group_name'] == 'Size') { $indexed_sizes[] = $combinaison['attribute_name']; } } $doc->size = $indexed_sizes; //Indian Price $doc->offer_price_in = Product::getPriceStatic($productObj->id, true, NULL, 6, NULL, false, true, 1, false, NULL, NULL, IND_ADDRESS_ID); $doc->offer_price_in_rs = Tools::convertPrice($doc->offer_price_in, 4); $doc->mrp_in = Product::getPriceStatic($productObj->id, true, NULL, 6, NULL, false, false, 1, false, NULL, NULL, IND_ADDRESS_ID); if ($doc->mrp_in > $doc->offer_price_in) { $doc->discount_in = Tools::ps_round(($doc->mrp_in - $doc->offer_price_in) / $doc->mrp_in * 100); } //Worldwide Price $doc->offer_price = $productObj->getPrice(); $doc->offer_price_rs = Tools::convertPrice($doc->offer_price, 4); $doc->mrp = $productObj->getPriceWithoutReduct(); if ($doc->mrp > $doc->offer_price) { $doc->discount = Tools::ps_round(($doc->mrp - $doc->offer_price) / $doc->mrp * 100); } $doc->product_link = $productObj->getLink(); $idImage = $productObj->getCoverWs(); if ($idImage) { $idImage = $productObj->id . '-' . $idImage; } else { $idImage = Language::getIsoById(1) . '-default'; } $doc->image_link_list = $link->getImageLink($productObj->link_rewrite, $idImage, 'list'); $doc->image_link_medium = $link->getImageLink($productObj->link_rewrite, $idImage, 'medium'); $doc->image_link_large = $link->getImageLink($productObj->link_rewrite, $idImage, 'large'); $images = $productObj->getImages(1); $productImages = array(); foreach ($images as $k => $image) { $productImages[] = $link->getImageLink($productObj->link_rewrite, $image['id_image'], 'large'); } $doc->image_links = $productImages; return $doc; }
public function parseTemplateStandard($output, $smarty) { $output = self::prepareOutput($output); if (Configuration::get('PS_FORCE_SMARTY_2') === "0") { //Smarty v3 template engine //$currentTemplate = substr(basename($smarty->_current_file), 0, -4); $currentTemplate = substr(basename($smarty->template_resource), 0, -4); if ($currentTemplate == 'breadcrumb') { $currentTemplate = 'product'; } elseif ($currentTemplate == 'pagination') { $currentTemplate = 'category'; } $getTemplateVars = 'getTemplateVars'; } else { //Smarty v2 template engine $currentTemplate = $smarty->currentTemplate; $getTemplateVars = 'get_template_vars'; } switch ($currentTemplate) { case 'manufacturer': $currentTemplate = 'manufacturer'; break; case 'best-sales': $currentTemplate = 'bestsellerspage'; break; case 'new-products': $currentTemplate = 'newproductpage'; break; case 'prices-drop': $currentTemplate = 'specialspage'; break; } $tool = $this->loadTool(); if (!$tool->params->profileExists($currentTemplate) || $tool->params->checkValue('enable-effect', 'No', $currentTemplate)) { return self::prepareOutput($output); } $tool->params->setProfile($currentTemplate); global $link; $cookie =& $GLOBALS['magictoolbox']['magiczoomplus']['cookie']; if (method_exists($link, 'getImageLink')) { $_link =& $link; } else { //for Prestashop ver 1.1 $_link =& $this; } switch ($currentTemplate) { case 'homefeatured': $GLOBALS['magictoolbox']['magiczoomplus']['headers'] = true; $category = new Category(1); $nb = intval(Configuration::get('HOME_FEATURED_NBR')); //Number of product displayed $products = $category->getProducts(intval($cookie->id_lang), 1, $nb ? $nb : 10); foreach ($products as $product) { $lrw = $product['link_rewrite']; if (!$tool->params->checkValue('link-to-product-page', 'No')) { $lnk = $link->getProductLink($product['id_product'], $lrw); } else { $lnk = false; } $thumb = $_link->getImageLink($lrw, $product['id_image'], $tool->params->getValue('thumb-image')); $image = $tool->getMainTemplate(array('id' => 'homefeatured' . $product['id_image'], 'group' => 'homefeatured', 'link' => $lnk, 'img' => $_link->getImageLink($lrw, $product['id_image'], $tool->params->getValue('large-image')), 'thumb' => $thumb, 'title' => $product['name'], 'shortDescription' => $product['description_short'], 'description' => $product['description'])); //need a.product_image > img for blockcart module $image = '<div class="MagicToolboxContainer"><div style="width:0px;height:1px;overflow:hidden;visibility:hidden;"><a class="product_image" href="#"><img src="' . $thumb . '" /></a></div>' . $image . '</div>'; //$image = '<div class="MagicToolboxContainer">' . $image . '</div>'; $pattern = '<img src="[^"]*?' . preg_quote($_link->getImageLink($lrw, $product['id_image'], 'home'), '/') . '"[^>]*?>'; $pattern = '(?:<a[^>]*?href="[^"]*?"[^>]*>\\s*)?' . $pattern . '(?:\\s*<\\/a>)?'; $output = preg_replace('/' . $pattern . '/is', $image, $output); } break; case 'category': case 'manufacturer': case 'newproductpage': case 'bestsellerspage': case 'specialspage': //global $p, $n, $orderBy, $orderWay; //$category = new Category(intval(Tools::getValue('id_category')), intval($cookie->id_lang)); //$products = $category->getProducts(intval($cookie->id_lang), intval($p), intval($n), $orderBy, $orderWay); $GLOBALS['magictoolbox']['magiczoomplus']['headers'] = true; $products = $smarty->{$getTemplateVars}('products'); foreach ($products as $product) { $lrw = $product['link_rewrite']; if (!$tool->params->checkValue('link-to-product-page', 'No')) { $lnk = $link->getProductLink($product['id_product'], $lrw); } else { $lnk = false; } $thumb = $_link->getImageLink($lrw, $product['id_image'], $tool->params->getValue('thumb-image')); $image = $tool->getMainTemplate(array('id' => 'category' . $product['id_image'], 'group' => 'category', 'link' => $lnk, 'img' => $_link->getImageLink($lrw, $product['id_image'], $tool->params->getValue('large-image')), 'thumb' => $thumb, 'title' => $product['name'], 'shortDescription' => $product['description_short'], 'description' => $product['description'])); //$image = preg_replace('/<a class="MagicZoomPlus"/is', '<a class="MagicZoomPlus product_img_link"', $image); $image_suffix = $tool->params->getValue('thumb-image') ? '-' . $tool->params->getValue('thumb-image') : ''; $file_path = _PS_PROD_IMG_DIR_ . $product['id_image'] . $image_suffix . '.jpg'; if (!file_exists($file_path)) { $split_ids = explode('-', $product['id_image']); $id_image = isset($split_ids[1]) ? $split_ids[1] : $split_ids[0]; $folders = implode('/', str_split((string) $id_image)) . '/'; $file_path = _PS_PROD_IMG_DIR_ . $folders . $id_image . $image_suffix . '.jpg'; } $size = getimagesize($file_path); //need a.product_img_link > img for blockcart module $image = '<div class="MagicToolboxContainer" style="float: left; width: ' . $size[0] . 'px; margin-right: 0.6em;" ><div style="width:0px;height:1px;overflow:hidden;visibility:hidden;"><a class="product_img_link" href="#"><img src="' . $thumb . '" /></a></div>' . $image . '</div>'; //$image = '<div class="MagicToolboxContainer" style="float: left; width: '.$size[0].'px; margin-right: 0.6em;" >'.$image.'</div>'; $pattern = '<img src="[^"]*?' . preg_quote($_link->getImageLink($lrw, $product['id_image'], 'home'), '/') . '"[^>]*?>'; $pattern = '(<a[^>]*?href="[^"]*?"[^>]*>\\s*)?' . $pattern . '(\\s*<\\/a>)?'; $output = preg_replace('/' . $pattern . '/is', $image, $output); } break; case 'product': if (!isset($GLOBALS['magictoolbox']['magiczoomplus']['product'])) { //for skip loyalty module product.tpl return self::prepareOutput($output); } //$product = new Product(intval($smarty->$tpl_vars['product']->id), true, intval($cookie->id_lang)); //get some data from $GLOBALS for compatible with Prestashop modules which reset the $product smarty variable $product = new Product(intval($GLOBALS['magictoolbox']['magiczoomplus']['product']['id']), true, intval($cookie->id_lang)); $lrw = $product->link_rewrite; $pid = $product->id; $images = $product->getImages(intval($cookie->id_lang)); $productImages = array(); foreach ($images as $image) { if ($image['cover']) { $cover = $image; $cover['id_image'] = intval($product->id) . '-' . $cover['id_image']; } $productImages[intval($image['id_image'])] = $image; } if (!isset($cover)) { // ensure that we have the image return self::prepareOutput($output); } $GLOBALS['magictoolbox']['magiczoomplus']['headers'] = true; $thumb = $_link->getImageLink($lrw, $cover['id_image'], $tool->params->getValue('thumb-image')); $image = $tool->getMainTemplate(array('id' => 'MainImage', 'img' => $_link->getImageLink($lrw, $cover['id_image'], $tool->params->getValue('large-image')), 'thumb' => $thumb, 'title' => $product->name, 'shortDescription' => $product->description_short, 'description' => $product->description)); $iTypes = $this->getImagesTypes(); $selectors = array(); if (count($productImages) > 0) { $pattern = '<img[^>]*?src="[^"]*?{medium}"[^>]*>'; //$pattern = '(<a[^>]*?href="[^"]*?{thickbox}"[^>]*>\s*)?' . $pattern . '(\s*<\/a>)?'; $pattern = '(<a[^>]*?href="[^"]*"[^>]*>\\s*)?' . $pattern . '(\\s*<\\/a>)?'; foreach ($productImages as $i) { $s = $tool->getSelectorTemplate(array('id' => 'MainImage', 'img' => $_link->getImageLink($lrw, $pid . '-' . $i['id_image'], $tool->params->getValue('large-image')), 'medium' => $_link->getImageLink($lrw, $pid . '-' . $i['id_image'], $tool->params->getValue('thumb-image')), 'thumb' => $_link->getImageLink($lrw, $pid . '-' . $i['id_image'], $tool->params->getValue('selector-image')), 'title' => $i['legend'])); $s = str_replace('<img ', '<img id="thumb_' . $i['id_image'] . '" ', $s); $s = str_replace('<a ', '<a class="magicthickbox" ', $s); //$p = str_replace('{thickbox}', preg_quote($_link->getImageLink($lrw, $pid . '-' . $i['id_image'], 'thickbox'), '/'), $pattern); //$p = str_replace('{medium}', preg_quote($_link->getImageLink($lrw, $pid . '-' . $i['id_image'], 'medium'), '/'), $p); $p = str_replace('{medium}', preg_quote($_link->getImageLink($lrw, $pid . '-' . $i['id_image'], 'medium'), '/'), $pattern); $replaced = 0; if ($tool->params->checkValue('template', 'original')) { // append selector in their preserved place $output = preg_replace('/' . $p . '/is', $s, $output, -1, $replaced); if (!$replaced) { $p = '(<a[^>]*?href="[^"]*"[^>]*>\\s*)?<img[^>]*?id="thumb_' . $i['id_image'] . '"[^>]*>(\\s*<\\/a>)?'; $output = preg_replace('/' . $p . '/is', $s, $output, -1, $replaced); } } else { // remove selector from contents $output = preg_replace('/' . $p . '/is', '', $output, -1, $replaced); if (!$replaced) { $p = '(<a[^>]*?href="[^"]*"[^>]*>\\s*)?<img[^>]*?id="thumb_' . $i['id_image'] . '"[^>]*>(\\s*<\\/a>)?'; $output = preg_replace('/' . $p . '/is', $s, $output, -1, $replaced); } $selectors[] = $s; } } } // append selectors if (!$tool->params->checkValue('template', 'original')) { //remove selectors from contents $pattern = '<div id="thumbs_list">.*?<\\/div>'; $output = preg_replace('/<div id="thumbs_list">.*?<\\/div>/is', '', $output); $output = preg_replace('/<\\!-- thumbnails -->\\s*<div id="views_block"\\s*>.*?<\\/div>/is', '<!-- thumbnails -->', $output); $output = preg_replace('/<\\!-- thumbnails -->\\s*<p[^>]*><a[^>]+reset[^>]+>.*?<\\/a><\\/p>/is', '<!-- thumbnails -->', $output); //remove "View full size" link $output = preg_replace('/<li>[^<]*?<span[^>]*?id="view_full_size"[^>]*?>[^<]*?<\\/span>[^<]*?<\\/li>/is', '', $output); } else { $tool->params->setValue('template', 'bottom'); } // we need this sizes for template renderer $sql = 'SELECT name,width,height FROM `' . _DB_PREFIX_ . 'image_type` WHERE name in (\'' . $tool->params->getValue('thumb-image') . '\',\'' . $tool->params->getValue('selector-image') . '\')'; $result = Db::getInstance()->ExecuteS($sql); $result[$result[0]['name']] = $result[0]; $result[$result[1]['name']] = $result[1]; $tool->params->setValue('thumb-max-width', $result[$tool->params->getValue('thumb-image')]['width']); $tool->params->setValue('thumb-max-height', $result[$tool->params->getValue('thumb-image')]['height']); $tool->params->setValue('selector-max-width', $result[$tool->params->getValue('selector-image')]['width']); $tool->params->setValue('selector-max-height', $result[$tool->params->getValue('selector-image')]['height']); require_once dirname(__FILE__) . DIRECTORY_SEPARATOR . 'magictoolbox.templatehelper.class.php'; MagicToolboxTemplateHelperClass::setPath(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'templates'); MagicToolboxTemplateHelperClass::setOptions($tool->params); $html = MagicToolboxTemplateHelperClass::render(array('main' => $image, 'thumbs' => $selectors, 'pid' => $pid)); //need img#bigpic for blockcart module $html = preg_replace('/(<div class="MagicToolboxContainer"[^>]*>)/is', '$1<div style="width:0px;height:1px;overflow:hidden;visibility:hidden;"><img id="bigpic" src="' . $thumb . '" /></div>', $html); // append main image $replaced = 0; $pattern = '<img src="[^"]*?' . preg_quote($_link->getImageLink($lrw, $cover['id_image'], 'large'), '/') . '".*?>'; $output = preg_replace('/' . $pattern . '/is', $html, $output, -1, $replaced); if (!$replaced) { $iTypes = $this->getImagesTypes(); foreach ($iTypes as $iType) { if ($iType != 'large') { $pattern = '<img src="[^"]*?' . preg_quote($_link->getImageLink($lrw, $cover['id_image'], $iType), '/') . '".*?>'; $output = preg_replace('/' . $pattern . '/is', $html, $output, -1, $replaced); if ($replaced) { break; } } } } break; case 'blockspecials': $GLOBALS['magictoolbox']['magiczoomplus']['headers'] = true; //$product = $smarty->get_template_vars('special'); $product = $smarty->{$getTemplateVars}('special'); $lrw = $product['link_rewrite']; if (!$tool->params->checkValue('link-to-product-page', 'No') && (!isset($_GET['id_product']) || $_GET['id_product'] != $product['id_product'])) { $lnk = $link->getProductLink($product['id_product'], $lrw); } else { $lnk = false; } $image = $tool->getMainTemplate(array('id' => 'blockspecials' . $product['id_image'], 'group' => 'blockspecials', 'link' => $lnk, 'img' => $_link->getImageLink($lrw, $product['id_image'], $tool->params->getValue('large-image')), 'thumb' => $_link->getImageLink($lrw, $product['id_image'], $tool->params->getValue('thumb-image')), 'title' => $product['name'], 'shortDescription' => $product['description_short'], 'description' => $product['description'])); $image = '<div class="MagicToolboxContainer">' . $image . '</div>'; $pattern = '<img src="[^"]*?' . preg_quote($_link->getImageLink($lrw, $product['id_image'], 'medium'), '/') . '"[^>]*?>'; $pattern = '(<a[^>]*?href="[^"]*?"[^>]*>\\s*)?' . $pattern . '(\\s*<\\/a>)?'; $output = preg_replace('/' . $pattern . '/is', $image, $output); break; case 'blockviewed': $productsViewed = array_slice($GLOBALS['magictoolbox']['magiczoomplus']['productsViewed'], 0, Configuration::get('PRODUCTS_VIEWED_NBR')); if (sizeof($productsViewed)) { foreach ($productsViewed as $id_product) { $productViewedObj = new Product(intval($id_product), false, intval($cookie->id_lang)); if (!Validate::isLoadedObject($productViewedObj) or !$productViewedObj->active) { continue; } else { $GLOBALS['magictoolbox']['magiczoomplus']['headers'] = true; $images = $productViewedObj->getImages(intval($cookie->id_lang)); foreach ($images as $image) { if ($image['cover']) { $productViewedObj->cover = $productViewedObj->id . '-' . $image['id_image']; $productViewedObj->legend = $image['legend']; break; } } if (!isset($productViewedObj->cover)) { $productViewedObj->cover = Language::getIsoById($cookie->id_lang) . '-default'; $productViewedObj->legend = ''; } $lrw = $productViewedObj->link_rewrite; if (!$tool->params->checkValue('link-to-product-page', 'No') && (!isset($_GET['id_product']) || $_GET['id_product'] != $id_product)) { $lnk = $link->getProductLink($id_product, $lrw); } else { $lnk = false; } $image = $tool->getMainTemplate(array('id' => 'blockviewed' . $id_product, 'group' => 'blockviewed', 'link' => $lnk, 'img' => $_link->getImageLink($lrw, $productViewedObj->cover, $tool->params->getValue('large-image')), 'thumb' => $_link->getImageLink($lrw, $productViewedObj->cover, $tool->params->getValue('thumb-image')), 'title' => $productViewedObj->name, 'shortDescription' => $productViewedObj->description_short, 'description' => $productViewedObj->description)); $image_suffix = $tool->params->getValue('thumb-image') ? '-' . $tool->params->getValue('thumb-image') : ''; $file_path = _PS_PROD_IMG_DIR_ . $productViewedObj->cover . $image_suffix . '.jpg'; if (!file_exists($file_path)) { $split_ids = explode('-', $productViewedObj->cover); $id_image = isset($split_ids[1]) ? $split_ids[1] : $split_ids[0]; $folders = implode('/', str_split((string) $id_image)) . '/'; $file_path = _PS_PROD_IMG_DIR_ . $folders . $id_image . $image_suffix . '.jpg'; } $size = getimagesize($file_path); $image = '<div class="MagicToolboxContainer" style="float: left; width: ' . $size[0] . 'px;">' . $image . '</div>'; $pattern = '<img src="[^"]*?' . preg_quote($_link->getImageLink($lrw, $productViewedObj->cover, 'medium'), '/') . '"[^>]*?>'; $pattern = '(<a[^>]*?href="[^"]*?"[^>]*>\\s*)?' . $pattern . '(\\s*<\\/a>)?'; $output = preg_replace('/' . $pattern . '/is', $image, $output); } } } break; case 'blockbestsellers': $blockbestsellers = true; case 'blocknewproducts': if (isset($blockbestsellers)) { //$products = $smarty->$getTemplateVars('best_sellers'); //to get with description etc. $products = ProductSale::getBestSales(intval($cookie->id_lang), 0, 4); } else { $products = $smarty->{$getTemplateVars}('new_products'); } $pCount = count($products); if ($pCount) { $GLOBALS['magictoolbox']['magiczoomplus']['headers'] = true; for ($i = 0; $i < 2 && $i < $pCount; $i++) { $lrw = $products[$i]['link_rewrite']; if (!$tool->params->checkValue('link-to-product-page', 'No') && (!isset($_GET['id_product']) || $_GET['id_product'] != $products[$i]['id_product'])) { $lnk = $link->getProductLink($products[$i]['id_product'], $lrw); } else { $lnk = false; } $image = $tool->getMainTemplate(array('id' => $currentTemplate . $products[$i]['id_image'], 'group' => $currentTemplate, 'link' => $lnk, 'img' => $_link->getImageLink($lrw, $products[$i]['id_image'], $tool->params->getValue('large-image')), 'thumb' => $_link->getImageLink($lrw, $products[$i]['id_image'], $tool->params->getValue('thumb-image')), 'title' => $products[$i]['name'], 'shortDescription' => $products[$i]['description_short'], 'description' => $products[$i]['description'])); $image = '<div class="MagicToolboxContainer">' . $image . '</div>'; $pattern = '<img src="[^"]*?' . preg_quote($_link->getImageLink($lrw, $products[$i]['id_image'], 'medium'), '/') . '"[^>]*?>'; $pattern = '(<a[^>]*?href="[^"]*?"[^>]*>\\s*)?' . $pattern . '(\\s*<\\/a>)?'; $output = preg_replace('/' . $pattern . '/is', $image, $output); } } break; } return self::prepareOutput($output); }
public function attributeImport() { $default_language = Configuration::get('PS_LANG_DEFAULT'); $groups = array(); foreach (AttributeGroup::getAttributesGroups($default_language) as $group) { $groups[$group['name']] = (int) $group['id_attribute_group']; } $attributes = array(); foreach (Attribute::getAttributes($default_language) as $attribute) { $attributes[$attribute['attribute_group'] . '_' . $attribute['name']] = (int) $attribute['id_attribute']; } $this->receiveTab(); $handle = $this->openCsvFile(); AdminImportController::setLocale(); for ($current_line = 0; $line = fgetcsv($handle, MAX_LINE_SIZE, $this->separator); $current_line++) { if (count($line) == 1 && empty($line[0])) { continue; } if (Tools::getValue('convert')) { $line = $this->utf8EncodeArray($line); } $info = AdminImportController::getMaskedRow($line); $info = array_map('trim', $info); if (self::ignoreRow($info)) { continue; } AdminImportController::setDefaultValues($info); if (!Shop::isFeatureActive()) { $info['shop'] = 1; } elseif (!isset($info['shop']) || empty($info['shop'])) { $info['shop'] = implode($this->multiple_value_separator, Shop::getContextListShopID()); } $info['shop'] = explode($this->multiple_value_separator, $info['shop']); $id_shop_list = array(); if (is_array($info['shop']) && count($info['shop'])) { foreach ($info['shop'] as $shop) { if (!empty($shop) && !is_numeric($shop)) { $id_shop_list[] = Shop::getIdByName($shop); } elseif (!empty($shop)) { $id_shop_list[] = $shop; } } } if (isset($info['id_product']) && is_string($info['id_product'])) { $prod = self::findProductByName($default_language, $info['id_product']); if ($prod['id_product']) { $info['id_product'] = $prod['id_product']; } else { unset($info['id_product']); } } if (!isset($info['id_product']) && Tools::getValue('match_ref') && isset($info['product_reference']) && $info['product_reference']) { $datas = Db::getInstance()->getRow(' SELECT p.`id_product` FROM `' . _DB_PREFIX_ . 'product` p ' . Shop::addSqlAssociation('product', 'p') . ' WHERE p.`reference` = "' . pSQL($info['product_reference']) . '" '); if (isset($datas['id_product']) && $datas['id_product']) { $info['id_product'] = $datas['id_product']; } } if (isset($info['id_product'])) { $product = new Product((int) $info['id_product'], false, $default_language); } else { continue; } $id_image = array(); if (array_key_exists('delete_existing_images', $info) && $info['delete_existing_images'] && !isset($this->cache_image_deleted[(int) $product->id])) { $product->deleteImages(); $this->cache_image_deleted[(int) $product->id] = true; } if (isset($info['image_url']) && $info['image_url']) { $info['image_url'] = explode(',', $info['image_url']); if (is_array($info['image_url']) && count($info['image_url'])) { foreach ($info['image_url'] as $url) { $url = trim($url); $product_has_images = (bool) Image::getImages($this->context->language->id, $product->id); $image = new Image(); $image->id_product = (int) $product->id; $image->position = Image::getHighestPosition($product->id) + 1; $image->cover = !$product_has_images ? true : false; $field_error = $image->validateFields(UNFRIENDLY_ERROR, true); $lang_field_error = $image->validateFieldsLang(UNFRIENDLY_ERROR, true); if ($field_error === true && $lang_field_error === true && $image->add()) { $image->associateTo($id_shop_list); if (!AdminImportController::copyImg($product->id, $image->id, $url, 'products', !Tools::getValue('regenerate'))) { $this->warnings[] = sprintf(Tools::displayError('Error copying image: %s'), $url); $image->delete(); } else { $id_image[] = (int) $image->id; } } else { $this->warnings[] = sprintf(Tools::displayError('%s cannot be saved'), isset($image->id_product) ? ' (' . $image->id_product . ')' : ''); $this->errors[] = ($field_error !== true ? $field_error : '') . (isset($lang_field_error) && $lang_field_error !== true ? $lang_field_error : '') . mysql_error(); } } } } elseif (isset($info['image_position']) && $info['image_position']) { $info['image_position'] = explode(',', $info['image_position']); if (is_array($info['image_position']) && count($info['image_position'])) { foreach ($info['image_position'] as $position) { $images = $product->getImages($default_language); if ($images) { foreach ($images as $row) { if ($row['position'] == (int) $position) { $id_image[] = (int) $row['id_image']; break; } } } if (empty($id_image)) { $this->warnings[] = sprintf(Tools::displayError('No image was found for combination with id_product = %s and image position = %s.'), $product->id, (int) $position); } } } } $id_attribute_group = 0; $groups_attributes = array(); if (isset($info['group'])) { foreach (explode($this->multiple_value_separator, $info['group']) as $key => $group) { if (empty($group)) { continue; } $tab_group = explode(':', $group); $group = trim($tab_group[0]); if (!isset($tab_group[1])) { $type = 'select'; } else { $type = trim($tab_group[1]); } $groups_attributes[$key]['group'] = $group; if (isset($tab_group[2])) { $position = trim($tab_group[2]); } else { $position = false; } if (!isset($groups[$group])) { $obj = new AttributeGroup(); $obj->is_color_group = false; $obj->group_type = pSQL($type); $obj->name[$default_language] = $group; $obj->public_name[$default_language] = $group; $obj->position = !$position ? AttributeGroup::getHigherPosition() + 1 : $position; if (($field_error = $obj->validateFields(UNFRIENDLY_ERROR, true)) === true && ($lang_field_error = $obj->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true) { $obj->add(); $obj->associateTo($id_shop_list); $groups[$group] = $obj->id; } else { $this->errors[] = ($field_error !== true ? $field_error : '') . (isset($lang_field_error) && $lang_field_error !== true ? $lang_field_error : ''); } $id_attribute_group = $obj->id; $groups_attributes[$key]['id'] = $id_attribute_group; } else { $id_attribute_group = $groups[$group]; $groups_attributes[$key]['id'] = $id_attribute_group; } } } $id_product_attribute = 0; $id_product_attribute_update = false; $attributes_to_add = array(); if (isset($info['attribute'])) { foreach (explode($this->multiple_value_separator, $info['attribute']) as $key => $attribute) { if (empty($attribute)) { continue; } $tab_attribute = explode(':', $attribute); $attribute = trim($tab_attribute[0]); if (isset($tab_attribute[1])) { $position = trim($tab_attribute[1]); } else { $position = false; } if (isset($groups_attributes[$key])) { $group = $groups_attributes[$key]['group']; if (!isset($attributes[$group . '_' . $attribute]) && count($groups_attributes[$key]) == 2) { $id_attribute_group = $groups_attributes[$key]['id']; $obj = new Attribute(); $obj->id_attribute_group = $groups_attributes[$key]['id']; $obj->name[$default_language] = str_replace('\\n', '', str_replace('\\r', '', $attribute)); $obj->position = !$position && isset($groups[$group]) ? Attribute::getHigherPosition($groups[$group]) + 1 : $position; if (($field_error = $obj->validateFields(UNFRIENDLY_ERROR, true)) === true && ($lang_field_error = $obj->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true) { $obj->add(); $obj->associateTo($id_shop_list); $attributes[$group . '_' . $attribute] = $obj->id; } else { $this->errors[] = ($field_error !== true ? $field_error : '') . (isset($lang_field_error) && $lang_field_error !== true ? $lang_field_error : ''); } } $info['minimal_quantity'] = isset($info['minimal_quantity']) && $info['minimal_quantity'] ? (int) $info['minimal_quantity'] : 1; $info['wholesale_price'] = str_replace(',', '.', $info['wholesale_price']); $info['price'] = str_replace(',', '.', $info['price']); $info['ecotax'] = str_replace(',', '.', $info['ecotax']); $info['weight'] = str_replace(',', '.', $info['weight']); $info['available_date'] = Validate::isDate($info['available_date']) ? $info['available_date'] : null; if (!Validate::isEan13($info['ean13'])) { $this->warnings[] = sprintf(Tools::displayError('EAN13 "%1s" has incorrect value for product with id %2d.'), $info['ean13'], $product->id); $info['ean13'] = ''; } if ($info['default_on']) { $product->deleteDefaultAttributes(); } if (isset($info['reference']) && !empty($info['reference'])) { $id_product_attribute = Combination::getIdByReference($product->id, (string) $info['reference']); if ($id_product_attribute) { $attribute_combinations = $product->getAttributeCombinations($default_language); foreach ($attribute_combinations as $attribute_combination) { if ($id_product_attribute && in_array($id_product_attribute, $attribute_combination)) { $product->updateAttribute($id_product_attribute, (double) $info['wholesale_price'], (double) $info['price'], (double) $info['weight'], 0, Configuration::get('PS_USE_ECOTAX') ? (double) $info['ecotax'] : 0, $id_image, (string) $info['reference'], (string) $info['ean13'], (int) $info['default_on'], 0, (string) $info['upc'], (int) $info['minimal_quantity'], $info['available_date'], null, $id_shop_list); $id_product_attribute_update = true; if (isset($info['supplier_reference']) && !empty($info['supplier_reference'])) { $product->addSupplierReference($product->id_supplier, $id_product_attribute, $info['supplier_reference']); } } } } } if (!$id_product_attribute) { $id_product_attribute = $product->addCombinationEntity((double) $info['wholesale_price'], (double) $info['price'], (double) $info['weight'], 0, Configuration::get('PS_USE_ECOTAX') ? (double) $info['ecotax'] : 0, (int) $info['quantity'], $id_image, (string) $info['reference'], 0, (string) $info['ean13'], (int) $info['default_on'], 0, (string) $info['upc'], (int) $info['minimal_quantity'], $id_shop_list, $info['available_date']); if (isset($info['supplier_reference']) && !empty($info['supplier_reference'])) { $product->addSupplierReference($product->id_supplier, $id_product_attribute, $info['supplier_reference']); } } if (isset($attributes[$group . '_' . $attribute])) { $attributes_to_add[] = (int) $attributes[$group . '_' . $attribute]; } $obj = new Attribute(); $obj->cleanPositions((int) $id_attribute_group, false); AttributeGroup::cleanPositions(); } } } $product->checkDefaultAttributes(); if (!$product->cache_default_attribute) { Product::updateDefaultAttribute($product->id); } if ($id_product_attribute) { if ($id_product_attribute_update) { Db::getInstance()->execute(' DELETE FROM ' . _DB_PREFIX_ . 'product_attribute_combination WHERE id_product_attribute = ' . (int) $id_product_attribute); } foreach ($attributes_to_add as $attribute_to_add) { Db::getInstance()->execute(' INSERT IGNORE INTO ' . _DB_PREFIX_ . 'product_attribute_combination (id_attribute, id_product_attribute) VALUES (' . (int) $attribute_to_add . ',' . (int) $id_product_attribute . ')'); } if (isset($info['advanced_stock_management'])) { if ($info['advanced_stock_management'] != 1 && $info['advanced_stock_management'] != 0) { $this->warnings[] = sprintf(Tools::displayError('Advanced stock management has incorrect value. Not set for product with id %d.'), $product->id); } elseif (!Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT') && $info['advanced_stock_management'] == 1) { $this->warnings[] = sprintf(Tools::displayError('Advanced stock management is not enabled, cannot enable on product with id %d.'), $product->id); } else { $product->setAdvancedStockManagement($info['advanced_stock_management']); } if (StockAvailable::dependsOnStock($product->id) == 1 && $info['advanced_stock_management'] == 0) { StockAvailable::setProductDependsOnStock($product->id, 0, null, $id_product_attribute); } } if (isset($info['warehouse']) && $info['warehouse']) { if (!Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT')) { $this->warnings[] = sprintf(Tools::displayError('Advanced stock management is not enabled, warehouse is not set on product with id %d.'), $product->id); } else { if (Warehouse::exists($info['warehouse'])) { $warehouse_location_entity = new WarehouseProductLocation(); $warehouse_location_entity->id_product = $product->id; $warehouse_location_entity->id_product_attribute = $id_product_attribute; $warehouse_location_entity->id_warehouse = $info['warehouse']; if (WarehouseProductLocation::getProductLocation($product->id, $id_product_attribute, $info['warehouse']) !== false) { $warehouse_location_entity->update(); } else { $warehouse_location_entity->save(); } StockAvailable::synchronize($product->id); } else { $this->warnings[] = sprintf(Tools::displayError('Warehouse did not exist, cannot set on product %1$s.'), $product->name[$default_language]); } } } if (isset($info['depends_on_stock'])) { if ($info['depends_on_stock'] != 0 && $info['depends_on_stock'] != 1) { $this->warnings[] = sprintf(Tools::displayError('Incorrect value for depends on stock for product %1$s '), $product->name[$default_language]); } elseif ((!$info['advanced_stock_management'] || $info['advanced_stock_management'] == 0) && $info['depends_on_stock'] == 1) { $this->warnings[] = sprintf(Tools::displayError('Advanced stock management is not enabled, cannot set depends on stock %1$s '), $product->name[$default_language]); } else { StockAvailable::setProductDependsOnStock($product->id, $info['depends_on_stock'], null, $id_product_attribute); } if (isset($info['quantity']) && $info['quantity']) { if ($info['depends_on_stock'] == 1) { $stock_manager = StockManagerFactory::getManager(); $price = str_replace(',', '.', $info['wholesale_price']); if ($price == 0) { $price = 1.0E-6; } $price = round((double) $price, 6); $warehouse = new Warehouse($info['warehouse']); if ($stock_manager->addProduct((int) $product->id, $id_product_attribute, $warehouse, $info['quantity'], 1, $price, true)) { StockAvailable::synchronize((int) $product->id); } } else { if (Shop::isFeatureActive()) { foreach ($id_shop_list as $shop) { StockAvailable::setQuantity((int) $product->id, $id_product_attribute, $info['quantity'], (int) $shop); } } else { StockAvailable::setQuantity((int) $product->id, $id_product_attribute, $info['quantity'], $this->context->shop->id); } } } } else { if (Shop::isFeatureActive()) { foreach ($id_shop_list as $shop) { StockAvailable::setQuantity((int) $product->id, $id_product_attribute, (int) $info['quantity'], (int) $shop); } } else { StockAvailable::setQuantity((int) $product->id, $id_product_attribute, (int) $info['quantity'], $this->context->shop->id); } } } } $this->closeCsvFile($handle); }
$doc->product_link = $productObj->getLink(); $idImage = $productObj->getCoverWs(); if ($idImage) { $idImage = $productObj->id . '-' . $idImage; } else { $idImage = Language::getIsoById(1) . '-default'; } $thickbox_image = $link->getImageLink($productObj->link_rewrite, $idImage, 'thickbox'); $large_image = $link->getImageLink($productObj->link_rewrite, $idImage, 'large'); $id_manufacturer = $productObj->id_manufacturer; $manufacturer = ''; if (!empty($id_manufacturer)) { $manufacturer = Manufacturer::getNameById($id_manufacturer); } $productRec = array($id_product, $productObj->reference, $productObj->supplier_reference, $productObj->name, $productObj->getLink(), $productObj->getPriceWithoutReduct(), round($productObj->getPrice()), round($mrp_in_rs), round($offer_price_in_rs), strip_tags($productObj->description), '0', $availability, $manufacturer, $category, $categories, $color, $fabric, (int) $productObj->active === 1 ? 'ACTIVE' : 'INACTIVE', $quantity, $productObj->shipping_sla, $productObj->is_customizable, $large_image, $thickbox_image, date('Y-m-d', strtotime($productObj->date_add))); $images = $productObj->getImages(1); foreach ($images as $image) { $oImage = $link->getImageLink($productObj->link_rewrite, $image['id_image'], 'thickbox'); if ($thickbox_image !== $oImage) { array_push($productRec, $oImage); } } //echo '"'.implode($productRec,'","').'"'; //echo PHP_EOL; fputcsv($outstream, $productRec, ',', '"'); ob_flush(); flush(); } fclose($outstream); } elseif (Tools::getValue('getPartnerProducts')) { ini_set('max_execution_time', 600);
protected function attributeImportOne($info, $default_language, &$groups, &$attributes, $regenerate, $shop_is_feature_active, $validateOnly = false) { AdminImportController::setDefaultValues($info); if (!$shop_is_feature_active) { $info['shop'] = 1; } elseif (!isset($info['shop']) || empty($info['shop'])) { $info['shop'] = implode($this->multiple_value_separator, Shop::getContextListShopID()); } // Get shops for each attributes $info['shop'] = explode($this->multiple_value_separator, $info['shop']); $id_shop_list = array(); if (is_array($info['shop']) && count($info['shop'])) { foreach ($info['shop'] as $shop) { if (!empty($shop) && !is_numeric($shop)) { $id_shop_list[] = Shop::getIdByName($shop); } elseif (!empty($shop)) { $id_shop_list[] = $shop; } } } if (isset($info['id_product']) && $info['id_product']) { $product = new Product((int) $info['id_product'], false, $default_language); } elseif (Tools::getValue('match_ref') && isset($info['product_reference']) && $info['product_reference']) { $datas = Db::getInstance()->getRow(' SELECT p.`id_product` FROM `' . _DB_PREFIX_ . 'product` p ' . Shop::addSqlAssociation('product', 'p') . ' WHERE p.`reference` = "' . pSQL($info['product_reference']) . '" ', false); if (isset($datas['id_product']) && $datas['id_product']) { $product = new Product((int) $datas['id_product'], false, $default_language); } } else { return; } $id_image = array(); if (isset($info['image_url']) && $info['image_url']) { $info['image_url'] = explode($this->multiple_value_separator, $info['image_url']); if (is_array($info['image_url']) && count($info['image_url'])) { foreach ($info['image_url'] as $key => $url) { $url = trim($url); $product_has_images = (bool) Image::getImages($this->context->language->id, $product->id); $image = new Image(); $image->id_product = (int) $product->id; $image->position = Image::getHighestPosition($product->id) + 1; $image->cover = !$product_has_images ? true : false; if (isset($info['image_alt'])) { $alt = self::split($info['image_alt']); if (isset($alt[$key]) && strlen($alt[$key]) > 0) { $alt = self::createMultiLangField($alt[$key]); $image->legend = $alt; } } $field_error = $image->validateFields(UNFRIENDLY_ERROR, true); $lang_field_error = $image->validateFieldsLang(UNFRIENDLY_ERROR, true); if ($field_error === true && $lang_field_error === true && !$validateOnly && $image->add()) { $image->associateTo($id_shop_list); // FIXME: 2s/image ! if (!AdminImportController::copyImg($product->id, $image->id, $url, 'products', !$regenerate)) { $this->warnings[] = sprintf($this->trans('Error copying image: %s', array(), 'Admin.Parameters.Notification'), $url); $image->delete(); } else { $id_image[] = (int) $image->id; } // until here } else { if (!$validateOnly) { $this->warnings[] = sprintf($this->trans('%s cannot be saved', array(), 'Admin.Parameters.Notification'), isset($image->id_product) ? ' (' . $image->id_product . ')' : ''); } if ($field_error !== true || $lang_field_error !== true) { $this->errors[] = ($field_error !== true ? $field_error : '') . (isset($lang_field_error) && $lang_field_error !== true ? $lang_field_error : '') . mysql_error(); } } } } } elseif (isset($info['image_position']) && $info['image_position']) { $info['image_position'] = explode($this->multiple_value_separator, $info['image_position']); if (is_array($info['image_position']) && count($info['image_position'])) { foreach ($info['image_position'] as $position) { // choose images from product by position $images = $product->getImages($default_language); if ($images) { foreach ($images as $row) { if ($row['position'] == (int) $position) { $id_image[] = (int) $row['id_image']; break; } } } if (empty($id_image)) { $this->warnings[] = sprintf($this->trans('No image was found for combination with id_product = %s and image position = %s.', array(), 'Admin.Parameters.Notification'), $product->id, (int) $position); } } } } $id_attribute_group = 0; // groups $groups_attributes = array(); if (isset($info['group'])) { foreach (explode($this->multiple_value_separator, $info['group']) as $key => $group) { if (empty($group)) { continue; } $tab_group = explode(':', $group); $group = trim($tab_group[0]); if (!isset($tab_group[1])) { $type = 'select'; } else { $type = trim($tab_group[1]); } // sets group $groups_attributes[$key]['group'] = $group; // if position is filled if (isset($tab_group[2])) { $position = trim($tab_group[2]); } else { $position = false; } if (!isset($groups[$group])) { $obj = new AttributeGroup(); $obj->is_color_group = false; $obj->group_type = pSQL($type); $obj->name[$default_language] = $group; $obj->public_name[$default_language] = $group; $obj->position = !$position ? AttributeGroup::getHigherPosition() + 1 : $position; if (($field_error = $obj->validateFields(UNFRIENDLY_ERROR, true)) === true && ($lang_field_error = $obj->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true) { // here, cannot avoid attributeGroup insertion to avoid an error during validation step. //if (!$validateOnly) { $obj->add(); $obj->associateTo($id_shop_list); $groups[$group] = $obj->id; //} } else { $this->errors[] = ($field_error !== true ? $field_error : '') . (isset($lang_field_error) && $lang_field_error !== true ? $lang_field_error : ''); } // fills groups attributes $id_attribute_group = $obj->id; $groups_attributes[$key]['id'] = $id_attribute_group; } else { // already exists $id_attribute_group = $groups[$group]; $groups_attributes[$key]['id'] = $id_attribute_group; } } } // inits attribute $id_product_attribute = 0; $id_product_attribute_update = false; $attributes_to_add = array(); // for each attribute if (isset($info['attribute'])) { foreach (explode($this->multiple_value_separator, $info['attribute']) as $key => $attribute) { if (empty($attribute)) { continue; } $tab_attribute = explode(':', $attribute); $attribute = trim($tab_attribute[0]); // if position is filled if (isset($tab_attribute[1])) { $position = trim($tab_attribute[1]); } else { $position = false; } if (isset($groups_attributes[$key])) { $group = $groups_attributes[$key]['group']; if (!isset($attributes[$group . '_' . $attribute]) && count($groups_attributes[$key]) == 2) { $id_attribute_group = $groups_attributes[$key]['id']; $obj = new Attribute(); // sets the proper id (corresponding to the right key) $obj->id_attribute_group = $groups_attributes[$key]['id']; $obj->name[$default_language] = str_replace('\\n', '', str_replace('\\r', '', $attribute)); $obj->position = !$position && isset($groups[$group]) ? Attribute::getHigherPosition($groups[$group]) + 1 : $position; if (($field_error = $obj->validateFields(UNFRIENDLY_ERROR, true)) === true && ($lang_field_error = $obj->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true) { if (!$validateOnly) { $obj->add(); $obj->associateTo($id_shop_list); $attributes[$group . '_' . $attribute] = $obj->id; } } else { $this->errors[] = ($field_error !== true ? $field_error : '') . (isset($lang_field_error) && $lang_field_error !== true ? $lang_field_error : ''); } } $info['minimal_quantity'] = isset($info['minimal_quantity']) && $info['minimal_quantity'] ? (int) $info['minimal_quantity'] : 1; $info['wholesale_price'] = str_replace(',', '.', $info['wholesale_price']); $info['price'] = str_replace(',', '.', $info['price']); $info['ecotax'] = str_replace(',', '.', $info['ecotax']); $info['weight'] = str_replace(',', '.', $info['weight']); $info['available_date'] = Validate::isDate($info['available_date']) ? $info['available_date'] : null; if (!Validate::isEan13($info['ean13'])) { $this->warnings[] = sprintf($this->trans('EAN13 "%1s" has incorrect value for product with id %2d.', array(), 'Admin.Parameters.Notification'), $info['ean13'], $product->id); $info['ean13'] = ''; } if ($info['default_on'] && !$validateOnly) { $product->deleteDefaultAttributes(); } // if a reference is specified for this product, get the associate id_product_attribute to UPDATE if (isset($info['reference']) && !empty($info['reference'])) { $id_product_attribute = Combination::getIdByReference($product->id, strval($info['reference'])); // updates the attribute if ($id_product_attribute && !$validateOnly) { // gets all the combinations of this product $attribute_combinations = $product->getAttributeCombinations($default_language); foreach ($attribute_combinations as $attribute_combination) { if ($id_product_attribute && in_array($id_product_attribute, $attribute_combination)) { // FIXME: ~3s/declinaison $product->updateAttribute($id_product_attribute, (double) $info['wholesale_price'], (double) $info['price'], (double) $info['weight'], 0, Configuration::get('PS_USE_ECOTAX') ? (double) $info['ecotax'] : 0, $id_image, strval($info['reference']), strval($info['ean13']), (int) $info['default_on'], 0, strval($info['upc']), (int) $info['minimal_quantity'], $info['available_date'], null, $id_shop_list); $id_product_attribute_update = true; if (isset($info['supplier_reference']) && !empty($info['supplier_reference'])) { $product->addSupplierReference($product->id_supplier, $id_product_attribute, $info['supplier_reference']); } // until here } } } } // if no attribute reference is specified, creates a new one if (!$id_product_attribute && !$validateOnly) { $id_product_attribute = $product->addCombinationEntity((double) $info['wholesale_price'], (double) $info['price'], (double) $info['weight'], 0, Configuration::get('PS_USE_ECOTAX') ? (double) $info['ecotax'] : 0, (int) $info['quantity'], $id_image, strval($info['reference']), 0, strval($info['ean13']), (int) $info['default_on'], 0, strval($info['upc']), (int) $info['minimal_quantity'], $id_shop_list, $info['available_date']); if (isset($info['supplier_reference']) && !empty($info['supplier_reference'])) { $product->addSupplierReference($product->id_supplier, $id_product_attribute, $info['supplier_reference']); } } // fills our attributes array, in order to add the attributes to the product_attribute afterwards if (isset($attributes[$group . '_' . $attribute])) { $attributes_to_add[] = (int) $attributes[$group . '_' . $attribute]; } // after insertion, we clean attribute position and group attribute position if (!$validateOnly) { $obj = new Attribute(); $obj->cleanPositions((int) $id_attribute_group, false); AttributeGroup::cleanPositions(); } } } } $product->checkDefaultAttributes(); if (!$product->cache_default_attribute && !$validateOnly) { Product::updateDefaultAttribute($product->id); } if ($id_product_attribute) { if (!$validateOnly) { // now adds the attributes in the attribute_combination table if ($id_product_attribute_update) { Db::getInstance()->execute(' DELETE FROM ' . _DB_PREFIX_ . 'product_attribute_combination WHERE id_product_attribute = ' . (int) $id_product_attribute); } foreach ($attributes_to_add as $attribute_to_add) { Db::getInstance()->execute(' INSERT IGNORE INTO ' . _DB_PREFIX_ . 'product_attribute_combination (id_attribute, id_product_attribute) VALUES (' . (int) $attribute_to_add . ',' . (int) $id_product_attribute . ')', false); } } // set advanced stock managment if (isset($info['advanced_stock_management'])) { if ($info['advanced_stock_management'] != 1 && $info['advanced_stock_management'] != 0) { $this->warnings[] = sprintf($this->trans('Advanced stock management has incorrect value. Not set for product with id %d.', array(), 'Admin.Parameters.Notification'), $product->id); } elseif (!Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT') && $info['advanced_stock_management'] == 1) { $this->warnings[] = sprintf($this->trans('Advanced stock management is not enabled, cannot enable on product with id %d.', array(), 'Admin.Parameters.Notification'), $product->id); } elseif (!$validateOnly) { $product->setAdvancedStockManagement($info['advanced_stock_management']); } // automaticly disable depends on stock, if a_s_m set to disabled if (!$validateOnly && StockAvailable::dependsOnStock($product->id) == 1 && $info['advanced_stock_management'] == 0) { StockAvailable::setProductDependsOnStock($product->id, 0, null, $id_product_attribute); } } // Check if warehouse exists if (isset($info['warehouse']) && $info['warehouse']) { if (!Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT')) { $this->warnings[] = sprintf($this->trans('Advanced stock management is not enabled, warehouse is not set on product with id %d.', array(), 'Admin.Parameters.Notification'), $product->id); } else { if (Warehouse::exists($info['warehouse'])) { $warehouse_location_entity = new WarehouseProductLocation(); $warehouse_location_entity->id_product = $product->id; $warehouse_location_entity->id_product_attribute = $id_product_attribute; $warehouse_location_entity->id_warehouse = $info['warehouse']; if (!$validateOnly) { if (WarehouseProductLocation::getProductLocation($product->id, $id_product_attribute, $info['warehouse']) !== false) { $warehouse_location_entity->update(); } else { $warehouse_location_entity->save(); } StockAvailable::synchronize($product->id); } } else { $this->warnings[] = sprintf($this->trans('Warehouse did not exist, cannot set on product %1$s.', array(), 'Admin.Parameters.Notification'), $product->name[$default_language]); } } } // stock available if (isset($info['depends_on_stock'])) { if ($info['depends_on_stock'] != 0 && $info['depends_on_stock'] != 1) { $this->warnings[] = sprintf($this->trans('Incorrect value for "Depends on stock" for product %1$s ', array(), 'Admin.Notifications.Error'), $product->name[$default_language]); } elseif ((!$info['advanced_stock_management'] || $info['advanced_stock_management'] == 0) && $info['depends_on_stock'] == 1) { $this->warnings[] = sprintf($this->trans('Advanced stock management is not enabled, cannot set "Depends on stock" for product %1$s ', array(), 'Admin.Parameters.Notification'), $product->name[$default_language]); } elseif (!$validateOnly) { StockAvailable::setProductDependsOnStock($product->id, $info['depends_on_stock'], null, $id_product_attribute); } // This code allows us to set qty and disable depends on stock if (isset($info['quantity']) && (int) $info['quantity']) { // if depends on stock and quantity, add quantity to stock if ($info['depends_on_stock'] == 1) { $stock_manager = StockManagerFactory::getManager(); $price = str_replace(',', '.', $info['wholesale_price']); if ($price == 0) { $price = 1.0E-6; } $price = round(floatval($price), 6); $warehouse = new Warehouse($info['warehouse']); if (!$validateOnly && $stock_manager->addProduct((int) $product->id, $id_product_attribute, $warehouse, (int) $info['quantity'], 1, $price, true)) { StockAvailable::synchronize((int) $product->id); } } elseif (!$validateOnly) { if ($shop_is_feature_active) { foreach ($id_shop_list as $shop) { StockAvailable::setQuantity((int) $product->id, $id_product_attribute, (int) $info['quantity'], (int) $shop); } } else { StockAvailable::setQuantity((int) $product->id, $id_product_attribute, (int) $info['quantity'], $this->context->shop->id); } } } } elseif (!$validateOnly) { // if not depends_on_stock set, use normal qty if ($shop_is_feature_active) { foreach ($id_shop_list as $shop) { StockAvailable::setQuantity((int) $product->id, $id_product_attribute, (int) $info['quantity'], (int) $shop); } } else { StockAvailable::setQuantity((int) $product->id, $id_product_attribute, (int) $info['quantity'], $this->context->shop->id); } } } }
public function hookDisplayShoppingCartFooter($params) { if (Configuration::get('CUSTOMGIFT_PRODUCTID') < 1) { return; } $produit = new Product(Configuration::get('CUSTOMGIFT_PRODUCTID'), true, (int) $this->context->cookie->id_lang); if (!$produit) { return; } $fields = $produit->getCustomizationFieldIds(); $index = $fields[0]['id_customization_field']; $images = $produit->getImages((int) $this->context->cookie->id_lang); foreach ($images as $i) { if ($i['cover']) { $image_id = $i['id_image']; } } $image = new Image($image_id); $image_url = '/shop/img/p/' . $image->getImgPath() . '.jpg'; //print_r( $image_url ); die(); $products = $this->context->cart->getProducts(); //print_r( $products ); die(); foreach ($products as $p) { //echo $p['id_product']; if ($p['id_product'] == Configuration::get('CUSTOMGIFT_PRODUCTID')) { $custom = $this->context->cart->getProductCustomization($p['id_product']); if (empty($custom)) { $this->smarty->assign('nmcustomgift_title', $this->l('Gift customization')); $this->smarty->assign('nmcustomgift_info', $this->l('Write text to put on the back of the card.')); $this->smarty->assign('nmcustomgift_info2', $this->l('Package included !')); $this->smarty->assign('nmcustomgift_save', $this->l('Save')); $this->smarty->assign('nmcustomgift_image_url', $image_url); $this->context->controller->addCSS($this->_path . 'css/nmcustomgift.css', 'all'); return $this->display(__FILE__, 'nmcustomgift.tpl'); } else { $this->smarty->assign('customgift_id', Configuration::get('CUSTOMGIFT_PRODUCTID')); $this->smarty->assign('customgist_customization', $custom[0]['id_customization']); $this->smarty->assign('gift', $this->l('Gift !')); return $this->display(__FILE__, 'nmcustomgiftcartmodify.tpl'); } //print_r( $this->context->cart->getProductCustomization( $p['product_id'] ) ); } } //die(); //$products = $this->context->cart->getProducts() ; //print_r( $products ); die(); //$context=Context::getContext(); /* header( 'Content-type: text/html'); echo "<html><script type='text/javascript'>var data = ".json_encode( $this->context->cart->getSummaryDetails() )."</script></html>"; die(); //echo json_encode( $context ); die(); return "<h3>GROS TEST</h3>"; */ /* $this->context->smarty->assign( array( 'my_module_name' => Configuration::get('MYMODULE_NAME'), 'my_module_link' => $this->context->link->getModuleLink('mymodule', 'display') ) ); return $this->display(__FILE__, 'mymodule.tpl'); */ }
/** * @param \Product $product * * @return string * @throws \Exception * @author Panagiotis Vagenas <*****@*****.**> * @since 150213 */ protected function getProductImageLink(\Product &$product) { $link = new \Link(); $imageLink = null; if ($this->Options->getValue('map_image') == 1) { $images = $product->getImages($this->defaultLang); if (!empty($images)) { shuffle($images); $imageLink = $link->getImageLink($product->link_rewrite, end($images)['id_image']); } } else { $coverImage = \Image::getCover($product->id); if ($coverImage && !empty($coverImage) && isset($coverImage['id_image'])) { $imageLink = $link->getImageLink($product->link_rewrite, $coverImage['id_image']); } } return empty($imageLink) ? '' : urldecode($this->addHttp($imageLink)); }
if ($product->add()) { if (!$product->updateCategories($_POST['categoryBox']) or !$product->addToTags($_POST['tags']) or !$product->updateAttribute($_POST['attribute_items'])) { $product->_errors = '添加产品内容时发生了一个错误'; } } if (is_array($product->_errors) and count($product->_errors) > 0) { $errors = $product->_errors; } else { $_GET['id'] = $product->id; echo '<div class="conf">添加产品成功</div>'; } } if (isset($_GET['id'])) { $id = (int) $_GET['id']; $obj = new Product($id); $images = $obj->getImages($id); } if (isset($_POST['sveProduct']) && Tools::getRequest('sveProduct') == 'edit') { if (Validate::isLoadedObject($obj)) { $obj->copyFromPost(); if ($obj->update()) { if (!$obj->updateCategories($_POST['categoryBox']) or !$obj->addToTags($_POST['tags']) or !$obj->updateAttribute($_POST['attribute_items']) or !$obj->updateFeature(Tools::P('id_feature_value'))) { $obj->_errors = '更新产品内容时发生了一个错误'; } } } if (is_array($obj->_errors) and count($obj->_errors) > 0) { $errors = $obj->_errors; } else { echo '<div class="alert alert-success" role="alert">更新产品内容成功</div>'; }