* @copyright Since 2007 PrestaShop SA and Contributors * @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0) */ // Deprecated since 1.5.0.1 use Product::CUSTOMIZE_FILE define('_CUSTOMIZE_FILE_', 0); // Deprecated since 1.5.0.1 use Product::CUSTOMIZE_TEXTFIELD define('_CUSTOMIZE_TEXTFIELD_', 1); use PrestaShop\Decimal\DecimalNumber; use PrestaShop\PrestaShop\Adapter\ServiceLocator; use PrestaShop\PrestaShop\Core\Domain\Product\ProductSettings; use PrestaShop\PrestaShop\Core\Domain\Product\Stock\ValueObject\OutOfStockType; use PrestaShop\PrestaShop\Core\Domain\Product\ValueObject\Ean13; use PrestaShop\PrestaShop\Core\Domain\Product\ValueObject\Isbn; use PrestaShop\PrestaShop\Core\Domain\Product\ValueObject\ProductType; use PrestaShop\PrestaShop\Core\Domain\Product\ValueObject\RedirectType; use PrestaShop\PrestaShop\Core\Domain\Product\ValueObject\Reference; use PrestaShop\PrestaShop\Core\Domain\Product\ValueObject\Upc; use PrestaShop\PrestaShop\Core\Product\ProductInterface; use PrestaShop\PrestaShop\Core\Util\DateTime\DateTime as DateTimeUtil; class ProductCore extends ObjectModel { /** * @var string Tax name * * @deprecated Since 1.4 */ public $tax_name; /** @var float Tax rate */ public $tax_rate; /** @var int Manufacturer identifier */ public $id_manufacturer; /** @var int Supplier identifier */ public $id_supplier; /** @var int default Category identifier */ public $id_category_default; /** @var int default Shop identifier */ public $id_shop_default; /** @var string Manufacturer name */ public $manufacturer_name; /** @var string Supplier name */ public $supplier_name; /** @var string|array Name or array of names by id_lang */ public $name; /** @var string|array Long description or array of long description by id_lang */ public $description; /** @var string|array Short description or array of short description by id_lang */ public $description_short; /** * @deprecated since 1.7.8 * @see StockAvailable::$quantity instead * * @var int Quantity available */ public $quantity = 0; /** @var int Minimal quantity for add to cart */ public $minimal_quantity = 1; /** @var int|null Low stock for mail alert */ public $low_stock_threshold = null; /** @var bool Low stock mail alert activated */ public $low_stock_alert = false; /** @var string|array Text when in stock or array of text by id_lang */ public $available_now; /** @var string|array Text when not in stock but available to order or array of text by id_lang */ public $available_later; /** @var float Price */ public $price = 0; /** @var array|int|null Will be filled by reference by priceCalculation() */ public $specificPrice = 0; /** @var string Additional shipping cost */ public $additional_shipping_cost = 0; /** @var string Wholesale Price in euros */ public $wholesale_price = 0; /** @var bool on_sale */ public $on_sale = false; /** @var bool online_only */ public $online_only = false; /** @var string unity */ public $unity = null; /** @var float price for product's unity */ public $unit_price = 0; /** @var float price for product's unity ratio */ public $unit_price_ratio = 0; /** @var float Ecotax */ public $ecotax = 0; /** @var string Reference */ public $reference; /** * @var string Supplier Reference * * @deprecated since 1.7.7.0 */ public $supplier_reference; /** * @deprecated since 1.7.8 * @see StockAvailable::$location instead * * @var string Location */ public $location = ''; /** @var string|float Width in default width unit */ public $width = 0; /** @var string|float Height in default height unit */ public $height = 0; /** @var string|float Depth in default depth unit */ public $depth = 0; /** @var string|float Weight in default weight unit */ public $weight = 0; /** @var string Ean-13 barcode */ public $ean13; /** @var string ISBN */ public $isbn; /** @var string Upc barcode */ public $upc; /** @var string MPN */ public $mpn; /** @var string|array Friendly URL or array of friendly URL by id_lang */ public $link_rewrite; /** @var string|array Meta description or array of meta description by id_lang */ public $meta_description; /** * @deprecated */ public $meta_keywords; /** @var string|array Meta title or array of meta title by id_lang */ public $meta_title; /** * @var mixed * * @deprecated Unused */ public $quantity_discount = 0; /** @var bool|int Product customization */ public $customizable; /** @var bool|null Product is new */ public $new = null; /** @var int Number of uploadable files (concerning customizable products) */ public $uploadable_files; /** @var int Number of text fields */ public $text_fields; /** @var bool Product status */ public $active = true; /** * @var string Redirection type * * @see RedirectType */ public $redirect_type = RedirectType::TYPE_NOT_FOUND; /** * @var int Product identifier or Category identifier depends on redirect_type */ public $id_type_redirected = 0; /** @var bool Product available for order */ public $available_for_order = true; /** @var string Available for order date in mysql format Y-m-d */ public $available_date = DateTimeUtil::NULL_DATE; /** @var bool Will the condition select should be visible for this product ? */ public $show_condition = false; /** @var string Enumerated (enum) product condition (new, used, refurbished) */ public $condition; /** @var bool Show price of Product */ public $show_price = true; /** @var bool is the product indexed in the search index? */ public $indexed = 0; /** @var string ENUM('both', 'catalog', 'search', 'none') front office visibility */ public $visibility; /** @var string Object creation date in mysql format Y-m-d H:i:s */ public $date_add; /** @var string Object last modification date in mysql format Y-m-d H:i:s */ public $date_upd; /** @var array Tags data */ public $tags; /** @var int temporary or saved object */ public $state = self::STATE_SAVED; /** * @var float Base price of the product * * @deprecated 1.6.0.13 */ public $base_price; /** * @var int TaxRulesGroup identifier */ public $id_tax_rules_group; /** * @var int * We keep this variable for retrocompatibility for themes * * @deprecated 1.5.0 */ public $id_color_default = 0; /** * @deprecated since 1.7.8 * The advanced stock management feature is not maintained anymore * * @var bool Tells if the product uses the advanced stock management */ public $advanced_stock_management = 0; /** * @deprecated since 1.7.8 * @see StockAvailable::$out_of_stock instead * * @var int * - O Deny orders * - 1 Allow orders * - 2 Use global setting */ public $out_of_stock = OutOfStockType::OUT_OF_STOCK_DEFAULT; /** * @deprecated since 1.7.8 * This property was only relevant to advanced stock management and that feature is not maintained anymore * * @var bool */ public $depends_on_stock; /** * @var bool */ public $isFullyLoaded = false; /** * @var bool */ public $cache_is_pack; /** * @var bool */ public $cache_has_attachments; /** * @var bool */ public $is_virtual; /** * @var int */ public $id_pack_product_attribute; /** * @var int */ public $cache_default_attribute; /** * @var string|string[] If product is populated, this property contain the rewrite link of the default category */ public $category; /** * @var int tell the type of stock management to apply on the pack */ public $pack_stock_type = Pack::STOCK_TYPE_DEFAULT; /** * Type of delivery time. * * Choose which parameters use for give information delivery. * 0 - none * 1 - use default information * 2 - use product information * * @var int */ public $additional_delivery_times = 1; /** * Delivery in-stock information. * * Long description for delivery in-stock product information. * * @var string[] */ public $delivery_in_stock; /** * Delivery out-stock information. * * Long description for delivery out-stock product information. * * @var string[] */ public $delivery_out_stock; /** * For now default value remains undefined, to keep compatibility with page v1 and former products. * But once the v2 is merged the default value should be ProductType::TYPE_STANDARD * * @var string */ public $product_type = ProductType::TYPE_UNDEFINED; /** * @var int|null */ public static $_taxCalculationMethod = null; /** @var array Price cache */ protected static $_prices = []; /** @var array */ protected static $_pricesLevel2 = []; /** @var array */ protected static $_incat = []; /** @var array */ protected static $_combinations = []; /** * @deprecated Since 1.5.6.1 * * @var array */ protected static $_cart_quantity = []; /** * @deprecated Since 1.5.0.9 * * @var array */ protected static $_tax_rules_group = []; /** @var array */ protected static $_cacheFeatures = []; /** @var array */ protected static $_frontFeaturesCache = []; /** @var array */ protected static $productPropertiesCache = []; /** * @deprecated Since 1.5.0.1 Unused * * @var array cache stock data in getStock() method */ protected static $cacheStock = []; /** @var int|null */ protected static $psEcotaxTaxRulesGroupId = null; /** * Product can be temporary saved in database */ const STATE_TEMP = 0; const STATE_SAVED = 1; /** * @var array Contains object definition * * @see ObjectModel::$definition */ public static $definition = [ 'table' => 'product', 'primary' => 'id_product', 'multilang' => true, 'multilang_shop' => true, 'fields' => [ /* Classic fields */ 'id_shop_default' => ['type' => self::TYPE_INT, 'validate' => 'isUnsignedId'], 'id_manufacturer' => ['type' => self::TYPE_INT, 'validate' => 'isUnsignedId'], 'id_supplier' => ['type' => self::TYPE_INT, 'validate' => 'isUnsignedId'], 'reference' => ['type' => self::TYPE_STRING, 'validate' => 'isReference', 'size' => Reference::MAX_LENGTH], 'supplier_reference' => ['type' => self::TYPE_STRING, 'validate' => 'isReference', 'size' => 64], 'location' => ['type' => self::TYPE_STRING, 'validate' => 'isString', 'size' => 255], 'width' => ['type' => self::TYPE_FLOAT, 'validate' => 'isUnsignedFloat'], 'height' => ['type' => self::TYPE_FLOAT, 'validate' => 'isUnsignedFloat'], 'depth' => ['type' => self::TYPE_FLOAT, 'validate' => 'isUnsignedFloat'], 'weight' => ['type' => self::TYPE_FLOAT, 'validate' => 'isUnsignedFloat'], 'quantity_discount' => ['type' => self::TYPE_BOOL, 'validate' => 'isBool'], 'ean13' => ['type' => self::TYPE_STRING, 'validate' => 'isEan13', 'size' => Ean13::MAX_LENGTH], 'isbn' => ['type' => self::TYPE_STRING, 'validate' => 'isIsbn', 'size' => Isbn::MAX_LENGTH], 'upc' => ['type' => self::TYPE_STRING, 'validate' => 'isUpc', 'size' => Upc::MAX_LENGTH], 'mpn' => ['type' => self::TYPE_STRING, 'validate' => 'isMpn', 'size' => ProductSettings::MAX_MPN_LENGTH], 'cache_is_pack' => ['type' => self::TYPE_BOOL, 'validate' => 'isBool'], 'cache_has_attachments' => ['type' => self::TYPE_BOOL, 'validate' => 'isBool'], 'is_virtual' => ['type' => self::TYPE_BOOL, 'validate' => 'isBool'], 'state' => ['type' => self::TYPE_INT, 'validate' => 'isUnsignedId'], 'additional_delivery_times' => ['type' => self::TYPE_INT, 'validate' => 'isUnsignedId'], 'delivery_in_stock' => [ 'type' => self::TYPE_STRING, 'lang' => true, 'validate' => 'isGenericName', 'size' => 255, ], 'delivery_out_stock' => [ 'type' => self::TYPE_STRING, 'lang' => true, 'validate' => 'isGenericName', 'size' => 255, ], 'product_type' => [ 'type' => self::TYPE_STRING, 'validate' => 'isGenericName', // For now undefined value is still allowed, in 179 we should use ProductType::AVAILABLE_TYPES here 'values' => [ ProductType::TYPE_STANDARD, ProductType::TYPE_PACK, ProductType::TYPE_VIRTUAL, ProductType::TYPE_COMBINATIONS, ProductType::TYPE_UNDEFINED, ], // This default value should be replaced with ProductType::TYPE_STANDARD in 179 when the v2 page is fully migrated 'default' => ProductType::TYPE_UNDEFINED, ], /* Shop fields */ 'id_category_default' => ['type' => self::TYPE_INT, 'shop' => true, 'validate' => 'isUnsignedId'], 'id_tax_rules_group' => ['type' => self::TYPE_INT, 'shop' => true, 'validate' => 'isUnsignedId'], 'on_sale' => ['type' => self::TYPE_BOOL, 'shop' => true, 'validate' => 'isBool'], 'online_only' => ['type' => self::TYPE_BOOL, 'shop' => true, 'validate' => 'isBool'], 'ecotax' => ['type' => self::TYPE_FLOAT, 'shop' => true, 'validate' => 'isPrice'], 'minimal_quantity' => ['type' => self::TYPE_INT, 'shop' => true, 'validate' => 'isUnsignedInt'], 'low_stock_threshold' => ['type' => self::TYPE_INT, 'shop' => true, 'allow_null' => true, 'validate' => 'isInt'], 'low_stock_alert' => ['type' => self::TYPE_BOOL, 'shop' => true, 'validate' => 'isBool'], 'price' => ['type' => self::TYPE_FLOAT, 'shop' => true, 'validate' => 'isPrice', 'required' => true], 'wholesale_price' => ['type' => self::TYPE_FLOAT, 'shop' => true, 'validate' => 'isPrice'], 'unity' => ['type' => self::TYPE_STRING, 'shop' => true, 'validate' => 'isString'], 'unit_price_ratio' => ['type' => self::TYPE_FLOAT, 'shop' => true], 'additional_shipping_cost' => ['type' => self::TYPE_FLOAT, 'shop' => true, 'validate' => 'isPrice'], 'customizable' => ['type' => self::TYPE_INT, 'shop' => true, 'validate' => 'isUnsignedInt'], 'text_fields' => ['type' => self::TYPE_INT, 'shop' => true, 'validate' => 'isUnsignedInt'], 'uploadable_files' => ['type' => self::TYPE_INT, 'shop' => true, 'validate' => 'isUnsignedInt'], 'active' => ['type' => self::TYPE_BOOL, 'shop' => true, 'validate' => 'isBool'], 'redirect_type' => ['type' => self::TYPE_STRING, 'shop' => true, 'validate' => 'isString'], 'id_type_redirected' => ['type' => self::TYPE_INT, 'shop' => true, 'validate' => 'isUnsignedId'], 'available_for_order' => ['type' => self::TYPE_BOOL, 'shop' => true, 'validate' => 'isBool'], 'available_date' => ['type' => self::TYPE_DATE, 'shop' => true, 'validate' => 'isDateFormat'], 'show_condition' => ['type' => self::TYPE_BOOL, 'shop' => true, 'validate' => 'isBool'], 'condition' => ['type' => self::TYPE_STRING, 'shop' => true, 'validate' => 'isGenericName', 'values' => ['new', 'used', 'refurbished'], 'default' => 'new'], 'show_price' => ['type' => self::TYPE_BOOL, 'shop' => true, 'validate' => 'isBool'], 'indexed' => ['type' => self::TYPE_BOOL, 'shop' => true, 'validate' => 'isBool'], 'visibility' => ['type' => self::TYPE_STRING, 'shop' => true, 'validate' => 'isProductVisibility', 'values' => ['both', 'catalog', 'search', 'none'], 'default' => 'both'], 'cache_default_attribute' => ['type' => self::TYPE_INT, 'shop' => true], 'advanced_stock_management' => ['type' => self::TYPE_BOOL, 'shop' => true, 'validate' => 'isBool'], 'date_add' => ['type' => self::TYPE_DATE, 'shop' => true, 'validate' => 'isDate'], 'date_upd' => ['type' => self::TYPE_DATE, 'shop' => true, 'validate' => 'isDate'], 'pack_stock_type' => ['type' => self::TYPE_INT, 'shop' => true, 'validate' => 'isUnsignedInt'], /* Lang fields */ 'meta_description' => ['type' => self::TYPE_STRING, 'lang' => true, 'validate' => 'isGenericName', 'size' => 512], 'meta_keywords' => ['type' => self::TYPE_STRING, 'lang' => true, 'validate' => 'isGenericName', 'size' => 255], 'meta_title' => ['type' => self::TYPE_STRING, 'lang' => true, 'validate' => 'isGenericName', 'size' => 255], 'link_rewrite' => [ 'type' => self::TYPE_STRING, 'lang' => true, 'validate' => 'isLinkRewrite', 'required' => false, 'size' => 128, 'ws_modifier' => [ 'http_method' => WebserviceRequest::HTTP_POST, 'modifier' => 'modifierWsLinkRewrite', ], ], 'name' => ['type' => self::TYPE_STRING, 'lang' => true, 'validate' => 'isCatalogName', 'required' => false, 'size' => ProductSettings::MAX_NAME_LENGTH], 'description' => ['type' => self::TYPE_HTML, 'lang' => true, 'validate' => 'isCleanHtml'], 'description_short' => ['type' => self::TYPE_HTML, 'lang' => true, 'validate' => 'isCleanHtml'], 'available_now' => ['type' => self::TYPE_STRING, 'lang' => true, 'validate' => 'isGenericName', 'size' => ProductSettings::MAX_AVAILABLE_NOW_LABEL_LENGTH], 'available_later' => ['type' => self::TYPE_STRING, 'lang' => true, 'validate' => 'IsGenericName', 'size' => ProductSettings::MAX_AVAILABLE_LATER_LABEL_LENGTH], ], 'associations' => [ 'manufacturer' => ['type' => self::HAS_ONE], 'supplier' => ['type' => self::HAS_ONE], 'default_category' => ['type' => self::HAS_ONE, 'field' => 'id_category_default', 'object' => 'Category'], 'tax_rules_group' => ['type' => self::HAS_ONE], 'categories' => ['type' => self::HAS_MANY, 'field' => 'id_category', 'object' => 'Category', 'association' => 'category_product'], 'stock_availables' => ['type' => self::HAS_MANY, 'field' => 'id_stock_available', 'object' => 'StockAvailable', 'association' => 'stock_availables'], 'attachments' => ['type' => self::HAS_MANY, 'field' => 'id_attachment', 'object' => 'Attachment', 'association' => 'product_attachment'], ], ]; /** @var array */ protected $webserviceParameters = [ 'objectMethods' => [ 'add' => 'addWs', 'update' => 'updateWs', ], 'objectNodeNames' => 'products', 'fields' => [ 'id_manufacturer' => [ 'xlink_resource' => 'manufacturers', ], 'id_supplier' => [ 'xlink_resource' => 'suppliers', ], 'id_category_default' => [ 'xlink_resource' => 'categories', ], 'new' => [], 'cache_default_attribute' => [], 'id_default_image' => [ 'getter' => 'getCoverWs', 'setter' => 'setCoverWs', 'xlink_resource' => [ 'resourceName' => 'images', 'subResourceName' => 'products', ], ], 'id_default_combination' => [ 'getter' => 'getWsDefaultCombination', 'setter' => 'setWsDefaultCombination', 'xlink_resource' => [ 'resourceName' => 'combinations', ], ], 'id_tax_rules_group' => [ 'xlink_resource' => [ 'resourceName' => 'tax_rule_groups', ], ], 'position_in_category' => [ 'getter' => 'getWsPositionInCategory', 'setter' => 'setWsPositionInCategory', ], 'manufacturer_name' => [ 'getter' => 'getWsManufacturerName', 'setter' => false, ], 'quantity' => [ 'getter' => false, 'setter' => false, ], 'type' => [ 'getter' => 'getWsType', 'setter' => 'setWsType', ], ], 'associations' => [ 'categories' => [ 'resource' => 'category', 'fields' => [ 'id' => ['required' => true], ], ], 'images' => [ 'resource' => 'image', 'fields' => ['id' => []], ], 'combinations' => [ 'resource' => 'combination', 'fields' => [ 'id' => ['required' => true], ], ], 'product_option_values' => [ 'resource' => 'product_option_value', 'fields' => [ 'id' => ['required' => true], ], ], 'product_features' => [ 'resource' => 'product_feature', 'fields' => [ 'id' => ['required' => true], 'id_feature_value' => [ 'required' => true, 'xlink_resource' => 'product_feature_values', ], ], ], 'tags' => ['resource' => 'tag', 'fields' => [ 'id' => ['required' => true], ], ], 'stock_availables' => ['resource' => 'stock_available', 'fields' => [ 'id' => ['required' => true], 'id_product_attribute' => ['required' => true], ], 'setter' => false, ], 'attachments' => [ 'resource' => 'attachment', 'api' => 'attachments', 'fields' => [ 'id' => ['required' => true], ], ], 'accessories' => [ 'resource' => 'product', 'api' => 'products', 'fields' => [ 'id' => [ 'required' => true, 'xlink_resource' => 'products', ], ], ], 'product_bundle' => [ 'resource' => 'product', 'api' => 'products', 'fields' => [ 'id' => ['required' => true], 'id_product_attribute' => [], 'quantity' => [], ], ], ], ]; const CUSTOMIZE_FILE = 0; const CUSTOMIZE_TEXTFIELD = 1; /** * Note: prefix is "PTYPE" because TYPE_ is used in ObjectModel (definition). */ const PTYPE_SIMPLE = 0; const PTYPE_PACK = 1; const PTYPE_VIRTUAL = 2; /** * @param int|null $id_product Product identifier * @param bool $full Load with price, tax rate, manufacturer name, supplier name, tags, stocks... * @param int|null $id_lang Language identifier * @param int|null $id_shop Shop identifier * @param Context|null $context Context to use for retrieve cart */ public function __construct($id_product = null, $full = false, $id_lang = null, $id_shop = null, Context $context = null) { parent::__construct($id_product, $id_lang, $id_shop); $unitPriceRatio = new DecimalNumber((string) ($this->unit_price_ratio ?? 0)); $price = new DecimalNumber((string) ($this->price ?? 0)); if ($unitPriceRatio->isGreaterThanZero()) { $this->unit_price = (float) (string) $price->dividedBy($unitPriceRatio); } if ($full && $this->id) { if (!$context) { $context = Context::getContext(); } $this->isFullyLoaded = $full; $this->tax_name = 'deprecated'; // The applicable tax may be BOTH the product one AND the state one (moreover this variable is some deadcode) $this->manufacturer_name = Manufacturer::getNameById((int) $this->id_manufacturer); $this->supplier_name = Supplier::getNameById((int) $this->id_supplier); $address = null; if (is_object($context->cart) && $context->cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')} != null) { $address = $context->cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}; } $this->tax_rate = $this->getTaxesRate(new Address($address)); $this->new = $this->isNew(); // Keep base price $this->base_price = $this->price; $this->price = Product::getPriceStatic((int) $this->id, false, null, 6, null, false, true, 1, false, null, null, null, $this->specificPrice); $this->unit_price = ($this->unit_price_ratio != 0 ? $this->price / $this->unit_price_ratio : 0); $this->tags = Tag::getProductTags((int) $this->id); $this->loadStockData(); } if ($this->id_category_default) { $this->category = Category::getLinkRewrite((int) $this->id_category_default, (int) $id_lang); } } /** * @see ObjectModel::getFieldsShop() * * @return array */ public function getFieldsShop() { $fields = parent::getFieldsShop(); if (null === $this->update_fields || (!empty($this->update_fields['price']) && !empty($this->update_fields['unit_price']))) { if ($this->unit_price !== null) { $fields['unit_price_ratio'] = (float) $this->unit_price > 0 ? $this->price / $this->unit_price : 0; } } $fields['unity'] = pSQL($this->unity); return $fields; } /** * {@inheritdoc} */ public function add($autodate = true, $null_values = false) { if ($this->is_virtual) { $this->product_type = ProductType::TYPE_VIRTUAL; } if (!parent::add($autodate, $null_values)) { return false; } $id_shop_list = Shop::getContextListShopID(); if ($this->getType() == Product::PTYPE_VIRTUAL) { foreach ($id_shop_list as $value) { StockAvailable::setProductOutOfStock((int) $this->id, OutOfStockType::OUT_OF_STOCK_AVAILABLE, $value); } if ($this->active && !Configuration::get('PS_VIRTUAL_PROD_FEATURE_ACTIVE')) { Configuration::updateGlobalValue('PS_VIRTUAL_PROD_FEATURE_ACTIVE', '1'); } } else { foreach ($id_shop_list as $value) { StockAvailable::setProductOutOfStock((int) $this->id, OutOfStockType::OUT_OF_STOCK_DEFAULT, $value); } } $this->setGroupReduction(); Hook::exec('actionProductSave', ['id_product' => (int) $this->id, 'product' => $this]); return true; } /** * {@inheritdoc} */ public function update($null_values = false) { if ($this->is_virtual) { $this->product_type = ProductType::TYPE_VIRTUAL; } $return = parent::update($null_values); $this->setGroupReduction(); // Sync stock Reference, EAN13, MPN and UPC if (Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT') && StockAvailable::dependsOnStock($this->id, Context::getContext()->shop->id)) { Db::getInstance()->update('stock', [ 'reference' => pSQL($this->reference), 'ean13' => pSQL($this->ean13), 'isbn' => pSQL($this->isbn), 'upc' => pSQL($this->upc), 'mpn' => pSQL($this->mpn), ], 'id_product = ' . (int) $this->id . ' AND id_product_attribute = 0'); } Hook::exec('actionProductSave', ['id_product' => (int) $this->id, 'product' => $this]); Hook::exec('actionProductUpdate', ['id_product' => (int) $this->id, 'product' => $this]); if ($this->getType() == Product::PTYPE_VIRTUAL && $this->active && !Configuration::get('PS_VIRTUAL_PROD_FEATURE_ACTIVE')) { Configuration::updateGlobalValue('PS_VIRTUAL_PROD_FEATURE_ACTIVE', '1'); } return $return; } /** * Init computation of price display method (i.e. price should be including tax or not) for a customer. * If customer Id passed as null then this compute price display method with according of current group. * Otherwise a price display method will compute with according of a customer address (i.e. country). * * @see Group::getPriceDisplayMethod() * * @param int|null $id_customer Customer identifier */ public static function initPricesComputation($id_customer = null) { if ((int) $id_customer > 0) { $customer = new Customer((int) $id_customer); if (!Validate::isLoadedObject($customer)) { die(Tools::displayError()); } self::$_taxCalculationMethod = Group::getPriceDisplayMethod((int) $customer->id_default_group); $cur_cart = Context::getContext()->cart; $id_address = 0; if (Validate::isLoadedObject($cur_cart)) { $id_address = (int) $cur_cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}; } $address_infos = Address::getCountryAndState($id_address); if (self::$_taxCalculationMethod != PS_TAX_EXC && !empty($address_infos['vat_number']) && $address_infos['id_country'] != Configuration::get('VATNUMBER_COUNTRY') && Configuration::get('VATNUMBER_MANAGEMENT')) { self::$_taxCalculationMethod = PS_TAX_EXC; } } else { self::$_taxCalculationMethod = Group::getPriceDisplayMethod(Group::getCurrent()->id); } } /** * Returns price display method for a customer (i.e. price should be including tax or not). * * @see initPricesComputation() * * @param int|null $id_customer Customer identifier * * @return int Returns 0 (PS_TAX_INC) if tax should be included, otherwise 1 (PS_TAX_EXC) - tax should be excluded */ public static function getTaxCalculationMethod($id_customer = null) { if (self::$_taxCalculationMethod === null || $id_customer !== null) { Product::initPricesComputation($id_customer); } return (int) self::$_taxCalculationMethod; } /** * Move a product inside its category. * * @param bool $way Up (1) or Down (0) * @param int $position * * @return bool Update result */ public function updatePosition($way, $position) { if (!$res = Db::getInstance()->executeS(' SELECT cp.`id_product`, cp.`position`, cp.`id_category` FROM `' . _DB_PREFIX_ . 'category_product` cp WHERE cp.`id_category` = ' . (int) Tools::getValue('id_category', 1) . ' ORDER BY cp.`position` ASC') ) { return false; } foreach ($res as $product) { if ((int) $product['id_product'] == (int) $this->id) { $moved_product = $product; } } if (!isset($moved_product) || !isset($position)) { return false; } // < and > statements rather than BETWEEN operator // since BETWEEN is treated differently according to databases $result = ( Db::getInstance()->execute(' UPDATE `' . _DB_PREFIX_ . 'category_product` cp INNER JOIN `' . _DB_PREFIX_ . 'product` p ON (p.`id_product` = cp.`id_product`) ' . Shop::addSqlAssociation('product', 'p') . ' SET cp.`position`= `position` ' . ($way ? '- 1' : '+ 1') . ', p.`date_upd` = "' . date('Y-m-d H:i:s') . '", product_shop.`date_upd` = "' . date('Y-m-d H:i:s') . '" WHERE cp.`position` ' . ($way ? '> ' . (int) $moved_product['position'] . ' AND `position` <= ' . (int) $position : '< ' . (int) $moved_product['position'] . ' AND `position` >= ' . (int) $position) . ' AND `id_category`=' . (int) $moved_product['id_category']) && Db::getInstance()->execute(' UPDATE `' . _DB_PREFIX_ . 'category_product` cp INNER JOIN `' . _DB_PREFIX_ . 'product` p ON (p.`id_product` = cp.`id_product`) ' . Shop::addSqlAssociation('product', 'p') . ' SET cp.`position` = ' . (int) $position . ', p.`date_upd` = "' . date('Y-m-d H:i:s') . '", product_shop.`date_upd` = "' . date('Y-m-d H:i:s') . '" WHERE cp.`id_product` = ' . (int) $moved_product['id_product'] . ' AND cp.`id_category`=' . (int) $moved_product['id_category']) ); Hook::exec('actionProductUpdate', ['id_product' => (int) $this->id, 'product' => $this]); return $result; } /** * Reorder product position in category $id_category. * Call it after deleting a product from a category. * * @param int $id_category Category identifier * @param int $position * * @return bool */ public static function cleanPositions($id_category, $position = 0) { $return = true; if (!(int) $position) { $result = Db::getInstance()->executeS(' SELECT `id_product` FROM `' . _DB_PREFIX_ . 'category_product` WHERE `id_category` = ' . (int) $id_category . ' ORDER BY `position` '); $total = count($result); for ($i = 0; $i < $total; ++$i) { $return &= Db::getInstance()->update( 'category_product', ['position' => $i], '`id_category` = ' . (int) $id_category . ' AND `id_product` = ' . (int) $result[$i]['id_product'] ); $return &= Db::getInstance()->execute( 'UPDATE `' . _DB_PREFIX_ . 'product` p' . Shop::addSqlAssociation('product', 'p') . ' SET p.`date_upd` = "' . date('Y-m-d H:i:s') . '", product_shop.`date_upd` = "' . date('Y-m-d H:i:s') . '" WHERE p.`id_product` = ' . (int) $result[$i]['id_product'] ); } } else { $result = Db::getInstance()->executeS(' SELECT `id_product` FROM `' . _DB_PREFIX_ . 'category_product` WHERE `id_category` = ' . (int) $id_category . ' AND `position` > ' . (int) $position . ' ORDER BY `position` '); $total = count($result); $return &= Db::getInstance()->update( 'category_product', ['position' => ['type' => 'sql', 'value' => '`position`-1']], '`id_category` = ' . (int) $id_category . ' AND `position` > ' . (int) $position ); for ($i = 0; $i < $total; ++$i) { $return &= Db::getInstance()->execute( 'UPDATE `' . _DB_PREFIX_ . 'product` p' . Shop::addSqlAssociation('product', 'p') . ' SET p.`date_upd` = "' . date('Y-m-d H:i:s') . '", product_shop.`date_upd` = "' . date('Y-m-d H:i:s') . '" WHERE p.`id_product` = ' . (int) $result[$i]['id_product'] ); } } return $return; } /** * Get the default attribute for a product. * * @param int $id_product Product identifier * @param int $minimum_quantity * @param bool $reset * * @return int Attributes list */ public static function getDefaultAttribute($id_product, $minimum_quantity = 0, $reset = false) { if (!Combination::isFeatureActive()) { return 0; } if ($reset && isset(static::$_combinations[$id_product])) { unset(static::$_combinations[$id_product]); } if (!isset(static::$_combinations[$id_product])) { static::$_combinations[$id_product] = []; } if (isset(static::$_combinations[$id_product][$minimum_quantity])) { return static::$_combinations[$id_product][$minimum_quantity]; } $sql = 'SELECT product_attribute_shop.id_product_attribute FROM ' . _DB_PREFIX_ . 'product_attribute pa ' . Shop::addSqlAssociation('product_attribute', 'pa') . ' WHERE pa.id_product = ' . (int) $id_product; $result_no_filter = Db::getInstance()->getValue($sql); if (!$result_no_filter) { static::$_combinations[$id_product][$minimum_quantity] = 0; return 0; } $sql = 'SELECT product_attribute_shop.id_product_attribute FROM ' . _DB_PREFIX_ . 'product_attribute pa ' . Shop::addSqlAssociation('product_attribute', 'pa') . ' ' . ($minimum_quantity > 0 ? Product::sqlStock('pa', 'pa') : '') . ' WHERE product_attribute_shop.default_on = 1 ' . ($minimum_quantity > 0 ? ' AND IFNULL(stock.quantity, 0) >= ' . (int) $minimum_quantity : '') . ' AND pa.id_product = ' . (int) $id_product; $result = Db::getInstance()->getValue($sql); if (!$result) { $sql = 'SELECT product_attribute_shop.id_product_attribute FROM ' . _DB_PREFIX_ . 'product_attribute pa ' . Shop::addSqlAssociation('product_attribute', 'pa') . ' ' . ($minimum_quantity > 0 ? Product::sqlStock('pa', 'pa') : '') . ' WHERE pa.id_product = ' . (int) $id_product . ($minimum_quantity > 0 ? ' AND IFNULL(stock.quantity, 0) >= ' . (int) $minimum_quantity : ''); $result = Db::getInstance()->getValue($sql); } if (!$result) { $sql = 'SELECT product_attribute_shop.id_product_attribute FROM ' . _DB_PREFIX_ . 'product_attribute pa ' . Shop::addSqlAssociation('product_attribute', 'pa') . ' WHERE product_attribute_shop.`default_on` = 1 AND pa.id_product = ' . (int) $id_product; $result = Db::getInstance()->getValue($sql); } if (!$result) { $result = $result_no_filter; } static::$_combinations[$id_product][$minimum_quantity] = $result; return $result; } /** * @param string $available_date Date in mysql format Y-m-d * * @return bool */ public function setAvailableDate($available_date = '0000-00-00') { if (Validate::isDateFormat($available_date) && $this->available_date != $available_date) { $this->available_date = $available_date; return $this->update(); } return false; } /** * For a given id_product and id_product_attribute, return available date. * * @param int $id_product Product identifier * @param int|null $id_product_attribute Attribute identifier * * @return string|null */ public static function getAvailableDate($id_product, $id_product_attribute = null) { $sql = 'SELECT'; if ($id_product_attribute === null) { $sql .= ' p.`available_date`'; } else { $sql .= ' pa.`available_date`'; } $sql .= ' FROM `' . _DB_PREFIX_ . 'product` p'; if ($id_product_attribute !== null) { $sql .= ' LEFT JOIN `' . _DB_PREFIX_ . 'product_attribute` pa ON (pa.`id_product` = p.`id_product`)'; } $sql .= Shop::addSqlAssociation('product', 'p'); if ($id_product_attribute !== null) { $sql .= Shop::addSqlAssociation('product_attribute', 'pa'); } $sql .= ' WHERE p.`id_product` = ' . (int) $id_product; if ($id_product_attribute !== null) { $sql .= ' AND pa.`id_product` = ' . (int) $id_product . ' AND pa.`id_product_attribute` = ' . (int) $id_product_attribute; } $result = Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue($sql); if ($result == '0000-00-00') { $result = null; } return $result; } /** * @param int $id_product Product identifier * @param bool $is_virtual */ public static function updateIsVirtual($id_product, $is_virtual = true) { $isVirtual = (bool) $is_virtual; $updateData = [ 'is_virtual' => $isVirtual, ]; // We only update the type if we are sure it is virtual if ($isVirtual) { $updateData['product_type'] = ProductType::TYPE_VIRTUAL; } Db::getInstance()->update('product', $updateData, 'id_product = ' . (int) $id_product); } /** * @see ObjectModel::resetStaticCache() * * reset static cache (eg unit testing purpose). */ public static function resetStaticCache() { static::$loaded_classes = []; static::$productPropertiesCache = []; static::$_cacheFeatures = []; static::$_frontFeaturesCache = []; static::$_prices = []; static::$_pricesLevel2 = []; static::$_incat = []; static::$_combinations = []; static::$psEcotaxTaxRulesGroupId = null; } /** * {@inheritdoc} */ public function validateField($field, $value, $id_lang = null, $skip = [], $human_errors = false) { if ($field == 'description_short') { // The legacy validation is basic, so the idea here is to adapt the allowed limit so that it takes into // account the difference between the raw text and the html text (since actually the limit is only about // the raw text) This is a bit ugly the real validation should only be performed by TinyMceMaxLengthValidator // but we have to deal with this for now. $limit = (int) Configuration::get('PS_PRODUCT_SHORT_DESC_LIMIT'); if ($limit <= 0) { $limit = 800; } $replaceArray = [ "\n", "\r", "\n\r", "\r\n", ]; $str = str_replace($replaceArray, [''], strip_tags($value)); $size_without_html = iconv_strlen($str); $size_with_html = Tools::strlen($value); $adaptedLimit = $limit + $size_with_html - $size_without_html; $this->def['fields']['description_short']['size'] = $adaptedLimit; } return parent::validateField($field, $value, $id_lang, $skip, $human_errors); } /** * {@inheritdoc} */ public function delete() { /* * @since 1.5.0 * It is NOT possible to delete a product if there are currently: * - physical stock for this product * - supply order(s) for this product */ if (Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT') && $this->advanced_stock_management) { $stock_manager = StockManagerFactory::getManager(); $physical_quantity = $stock_manager->getProductPhysicalQuantities($this->id, 0); $real_quantity = $stock_manager->getProductRealQuantities($this->id, 0); if ($physical_quantity > 0) { return false; } if ($real_quantity > $physical_quantity) { return false; } $warehouse_product_locations = ServiceLocator::get('\\PrestaShop\\PrestaShop\\Core\\Foundation\\Database\\EntityManager')->getRepository('WarehouseProductLocation')->findByIdProduct($this->id); foreach ($warehouse_product_locations as $warehouse_product_location) { $warehouse_product_location->delete(); } $stocks = ServiceLocator::get('\\PrestaShop\\PrestaShop\\Core\\Foundation\\Database\\EntityManager')->getRepository('Stock')->findByIdProduct($this->id); foreach ($stocks as $stock) { $stock->delete(); } } $result = parent::delete(); // Removes the product from StockAvailable, for the current shop StockAvailable::removeProductFromStockAvailable($this->id); $result &= ($this->deleteProductAttributes() && $this->deleteImages()); // If there are still entries in product_shop, don't remove completely the product if ($this->hasMultishopEntries()) { return true; } Hook::exec('actionProductDelete', ['id_product' => (int) $this->id, 'product' => $this]); if (!$result || !GroupReduction::deleteProductReduction($this->id) || !$this->deleteCategories(true) || !$this->deleteProductFeatures() || !$this->deleteTags() || !$this->deleteCartProducts() || !$this->deleteAttributesImpacts() || !$this->deleteAttachments(false) || !$this->deleteCustomization() || !SpecificPrice::deleteByProductId((int) $this->id) || !$this->deletePack() || !$this->deleteProductSale() || !$this->deleteSearchIndexes() || !$this->deleteAccessories() || !$this->deleteFromAccessories() || !$this->deleteFromSupplier() || !$this->deleteDownload() || !$this->deleteFromCartRules()) { return false; } return true; } /** * @param array $products Product identifiers * * @return bool|int */ public function deleteSelection($products) { $return = 1; if (is_array($products) && ($count = count($products))) { // Deleting products can be quite long on a cheap server. Let's say 1.5 seconds by product (I've seen it!). if ((int) (ini_get('max_execution_time')) < round($count * 1.5)) { ini_set('max_execution_time', round($count * 1.5)); } foreach ($products as $id_product) { $product = new Product((int) $id_product); $return &= $product->delete(); } } return $return; } /** * @return bool */ public function deleteFromCartRules() { CartRule::cleanProductRuleIntegrity('products', $this->id); return true; } /** * @return bool */ public function deleteFromSupplier() { return Db::getInstance()->delete('product_supplier', 'id_product = ' . (int) $this->id); } /** * addToCategories add this product to the category/ies if not exists. * * @param int|int[] $categories id_category or array of id_category * * @return bool true if succeed */ public function addToCategories($categories = []) { if (empty($categories)) { return false; } if (!is_array($categories)) { $categories = [$categories]; } if (!count($categories)) { return false; } $categories = array_map('intval', $categories); $current_categories = $this->getCategories(); $current_categories = array_map('intval', $current_categories); // for new categ, put product at last position $res_categ_new_pos = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS(' SELECT id_category, MAX(position)+1 newPos FROM `' . _DB_PREFIX_ . 'category_product` WHERE `id_category` IN(' . implode(',', $categories) . ') GROUP BY id_category'); foreach ($res_categ_new_pos as $array) { $new_categories[(int) $array['id_category']] = (int) $array['newPos']; } $new_categ_pos = []; // The first position must be 1 instead of 0 foreach ($categories as $id_category) { $new_categ_pos[$id_category] = isset($new_categories[$id_category]) ? $new_categories[$id_category] : 1; } $product_cats = []; foreach ($categories as $new_id_categ) { if (!in_array($new_id_categ, $current_categories)) { $product_cats[] = [ 'id_category' => (int) $new_id_categ, 'id_product' => (int) $this->id, 'position' => (int) $new_categ_pos[$new_id_categ], ]; } } Db::getInstance()->insert('category_product', $product_cats); Cache::clean('Product::getProductCategories_' . (int) $this->id); return true; } /** * Update categories to index product into. * * @param int[] $categories Categories list to index product into * @param bool $keeping_current_pos (deprecated, no more used) * * @return bool Update/insertion result */ public function updateCategories($categories, $keeping_current_pos = false) { if (empty($categories)) { return false; } $result = Db::getInstance()->executeS( ' SELECT c.`id_category` FROM `' . _DB_PREFIX_ . 'category_product` cp LEFT JOIN `' . _DB_PREFIX_ . 'category` c ON (c.`id_category` = cp.`id_category`) ' . Shop::addSqlAssociation('category', 'c', true, null, true) . ' WHERE cp.`id_category` NOT IN (' . implode(',', array_map('intval', $categories)) . ') AND cp.id_product = ' . (int) $this->id ); // if none are found, it's an error if (!is_array($result)) { return false; } foreach ($result as $categ_to_delete) { $this->deleteCategory($categ_to_delete['id_category']); } if (!$this->addToCategories($categories)) { return false; } SpecificPriceRule::applyAllRules([(int) $this->id]); Cache::clean('Product::getProductCategories_' . (int) $this->id); return true; } /** * deleteCategory delete this product from the category $id_category. * * @param int $id_category Category identifier * @param bool $clean_positions * * @return bool */ public function deleteCategory($id_category, $clean_positions = true) { $result = Db::getInstance()->executeS( 'SELECT `id_category`, `position` FROM `' . _DB_PREFIX_ . 'category_product` WHERE `id_product` = ' . (int) $this->id . ' AND id_category = ' . (int) $id_category ); $return = Db::getInstance()->delete('category_product', 'id_product = ' . (int) $this->id . ' AND id_category = ' . (int) $id_category); if ($clean_positions === true) { foreach ($result as $row) { static::cleanPositions((int) $row['id_category'], (int) $row['position']); } } SpecificPriceRule::applyAllRules([(int) $this->id]); Cache::clean('Product::getProductCategories_' . (int) $this->id); return $return; } /** * Delete all association to category where product is indexed. * * @param bool $clean_positions clean category positions after deletion * * @return bool Deletion result */ public function deleteCategories($clean_positions = false) { if ($clean_positions === true) { $result = Db::getInstance()->executeS( 'SELECT `id_category`, `position` FROM `' . _DB_PREFIX_ . 'category_product` WHERE `id_product` = ' . (int) $this->id ); } $return = Db::getInstance()->delete('category_product', 'id_product = ' . (int) $this->id); if ($clean_positions === true && is_array($result)) { foreach ($result as $row) { $return &= static::cleanPositions((int) $row['id_category'], (int) $row['position']); } } Cache::clean('Product::getProductCategories_' . (int) $this->id); return $return; } /** * Delete products tags entries. * * @return bool Deletion result */ public function deleteTags() { return Tag::deleteTagsForProduct((int) $this->id); } /** * Delete product from cart. * * @return bool Deletion result */ public function deleteCartProducts() { return Db::getInstance()->delete('cart_product', 'id_product = ' . (int) $this->id); } /** * Delete product images from database. * * @return bool success */ public function deleteImages() { $result = Db::getInstance()->executeS( ' SELECT `id_image` FROM `' . _DB_PREFIX_ . 'image` WHERE `id_product` = ' . (int) $this->id ); $status = true; if ($result) { foreach ($result as $row) { $image = new Image($row['id_image']); $status &= $image->delete(); } } return $status; } /** * Get all available products. * * @param int $id_lang Language identifier * @param int $start Start number * @param int $limit Number of products to return * @param string $order_by Field for ordering * @param string $order_way Way for ordering (ASC or DESC) * @param int|false $id_category Category identifier * @param bool $only_active * @param Context|null $context * * @return array Products details */ public static function getProducts( $id_lang, $start, $limit, $order_by, $order_way, $id_category = false, $only_active = false, Context $context = null ) { if (!$context) { $context = Context::getContext(); } $front = true; if (!in_array($context->controller->controller_type, ['front', 'modulefront'])) { $front = false; } if (!Validate::isOrderBy($order_by) || !Validate::isOrderWay($order_way)) { die(Tools::displayError()); } if ($order_by == 'id_product' || $order_by == 'price' || $order_by == 'date_add' || $order_by == 'date_upd') { $order_by_prefix = 'p'; } elseif ($order_by == 'name') { $order_by_prefix = 'pl'; } elseif ($order_by == 'position') { $order_by_prefix = 'c'; } if (strpos($order_by, '.') > 0) { $order_by = explode('.', $order_by); $order_by_prefix = $order_by[0]; $order_by = $order_by[1]; } $sql = 'SELECT p.*, product_shop.*, pl.* , m.`name` AS manufacturer_name, s.`name` AS supplier_name FROM `' . _DB_PREFIX_ . 'product` p ' . Shop::addSqlAssociation('product', 'p') . ' LEFT JOIN `' . _DB_PREFIX_ . 'product_lang` pl ON (p.`id_product` = pl.`id_product` ' . Shop::addSqlRestrictionOnLang('pl') . ') LEFT JOIN `' . _DB_PREFIX_ . 'manufacturer` m ON (m.`id_manufacturer` = p.`id_manufacturer`) LEFT JOIN `' . _DB_PREFIX_ . 'supplier` s ON (s.`id_supplier` = p.`id_supplier`)' . ($id_category ? 'LEFT JOIN `' . _DB_PREFIX_ . 'category_product` c ON (c.`id_product` = p.`id_product`)' : '') . ' WHERE pl.`id_lang` = ' . (int) $id_lang . ($id_category ? ' AND c.`id_category` = ' . (int) $id_category : '') . ($front ? ' AND product_shop.`visibility` IN ("both", "catalog")' : '') . ($only_active ? ' AND product_shop.`active` = 1' : '') . ' ORDER BY ' . (isset($order_by_prefix) ? pSQL($order_by_prefix) . '.' : '') . '`' . pSQL($order_by) . '` ' . pSQL($order_way) . ($limit > 0 ? ' LIMIT ' . (int) $start . ',' . (int) $limit : ''); $rq = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($sql); if ($order_by == 'price') { Tools::orderbyPrice($rq, $order_way); } foreach ($rq as &$row) { $row = Product::getTaxesInformations($row); } return $rq; } /** * @param int $id_lang Language identifier * @param Context|null $context * * @return array */ public static function getSimpleProducts($id_lang, Context $context = null) { if (!$context) { $context = Context::getContext(); } $front = true; if (!in_array($context->controller->controller_type, ['front', 'modulefront'])) { $front = false; } $sql = 'SELECT p.`id_product`, pl.`name` FROM `' . _DB_PREFIX_ . 'product` p ' . Shop::addSqlAssociation('product', 'p') . ' LEFT JOIN `' . _DB_PREFIX_ . 'product_lang` pl ON (p.`id_product` = pl.`id_product` ' . Shop::addSqlRestrictionOnLang('pl') . ') WHERE pl.`id_lang` = ' . (int) $id_lang . ' ' . ($front ? ' AND product_shop.`visibility` IN ("both", "catalog")' : '') . ' ORDER BY pl.`name`'; return Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($sql); } /** * @return bool */ public function isNew() { $nbDaysNewProduct = Configuration::get('PS_NB_DAYS_NEW_PRODUCT'); if (!Validate::isUnsignedInt($nbDaysNewProduct)) { $nbDaysNewProduct = 20; } $query = 'SELECT COUNT(p.id_product) FROM `' . _DB_PREFIX_ . 'product` p ' . Shop::addSqlAssociation('product', 'p') . ' WHERE p.id_product = ' . (int) $this->id . ' AND DATEDIFF("' . date('Y-m-d') . ' 00:00:00", product_shop.`date_add`) < ' . $nbDaysNewProduct; return (bool) Db::getInstance()->getValue($query, false); } /** * @param int[] $attributes_list Attribute identifier(s) * @param int|false $current_product_attribute Attribute identifier * @param Context|null $context * @param bool $all_shops * @param bool $return_id * * @return bool|int|string Attribute exist or Attribute identifier if return_id = true */ public function productAttributeExists($attributes_list, $current_product_attribute = false, Context $context = null, $all_shops = false, $return_id = false) { if (!Combination::isFeatureActive()) { return false; } if ($context === null) { $context = Context::getContext(); } $result = Db::getInstance()->executeS( 'SELECT pac.`id_attribute`, pac.`id_product_attribute` FROM `' . _DB_PREFIX_ . 'product_attribute` pa JOIN `' . _DB_PREFIX_ . 'product_attribute_shop` pas ON (pas.id_product_attribute = pa.id_product_attribute) LEFT JOIN `' . _DB_PREFIX_ . 'product_attribute_combination` pac ON (pac.`id_product_attribute` = pa.`id_product_attribute`) WHERE 1 ' . (!$all_shops ? ' AND pas.id_shop =' . (int) $context->shop->id : '') . ' AND pa.`id_product` = ' . (int) $this->id . ($all_shops ? ' GROUP BY pac.id_attribute, pac.id_product_attribute ' : '') ); /* If something's wrong */ if (!$result || empty($result)) { return false; } /* Product attributes simulation */ $product_attributes = []; foreach ($result as $product_attribute) { $product_attributes[$product_attribute['id_product_attribute']][] = $product_attribute['id_attribute']; } /* Checking product's attribute existence */ foreach ($product_attributes as $key => $product_attribute) { if (count($product_attribute) == count($attributes_list)) { $diff = false; for ($i = 0; $diff == false && isset($product_attribute[$i]); ++$i) { if (!in_array($product_attribute[$i], $attributes_list) || $key == $current_product_attribute) { $diff = true; } } if (!$diff) { if ($return_id) { return $key; } return true; } } } return false; } /** * addProductAttribute is deprecated. * * The quantity params now set StockAvailable for the current shop with the specified quantity * The supplier_reference params now set the supplier reference of the default supplier of the product if possible * * @deprecated since 1.5.0 * @see StockManager if you want to manage real stock * @see StockAvailable if you want to manage available quantities for sale on your shop(s) * @see ProductSupplier for manage supplier reference(s) * * @param float $price Additional price * @param float $weight Additional weight * @param float $unit_impact * @param float $ecotax Additional ecotax * @param int $quantity * @param int[] $id_images Image ids * @param string $reference Reference * @param int $id_supplier Supplier identifier * @param string $ean13 * @param bool $default Is default attribute for product * @param string $location * @param string $upc * @param int $minimal_quantity * @param string $isbn * @param int|null $low_stock_threshold Low stock for mail alert * @param bool $low_stock_alert Low stock mail alert activated * @param string|null $mpn * * @return int|false Attribute identifier if success, false if it fail */ public function addProductAttribute( $price, $weight, $unit_impact, $ecotax, $quantity, $id_images, $reference, $id_supplier, $ean13, $default, $location, $upc, $minimal_quantity, $isbn, $low_stock_threshold = null, $low_stock_alert = false, $mpn = null ) { Tools::displayAsDeprecated(); $id_product_attribute = $this->addAttribute( $price, $weight, $unit_impact, $ecotax, $id_images, $reference, $ean13, $default, $location, $upc, $minimal_quantity, [], null, 0, $isbn, $low_stock_threshold, $low_stock_alert, $mpn ); if (!$id_product_attribute) { return false; } StockAvailable::setQuantity($this->id, $id_product_attribute, $quantity); //Try to set the default supplier reference $this->addSupplierReference($id_supplier, $id_product_attribute); return $id_product_attribute; } /** * @param array $combinations * @param array $attributes * @param bool $resetExistingCombination * * @return bool */ public function generateMultipleCombinations($combinations, $attributes, $resetExistingCombination = true) { $res = true; foreach ($combinations as $key => $combination) { $id_combination = (int) $this->productAttributeExists($attributes[$key], false, null, true, true); if ($id_combination && !$resetExistingCombination) { continue; } $obj = new Combination($id_combination); if ($id_combination) { $obj->minimal_quantity = 1; $obj->available_date = '0000-00-00'; } foreach ($combination as $field => $value) { $obj->$field = $value; } $obj->default_on = 0; $this->setAvailableDate(); $obj->save(); if (!$id_combination) { $attribute_list = []; foreach ($attributes[$key] as $id_attribute) { $attribute_list[] = [ 'id_product_attribute' => (int) $obj->id, 'id_attribute' => (int) $id_attribute, ]; } $res &= Db::getInstance()->insert('product_attribute_combination', $attribute_list); } } return $res; } /** * @param int[] $combinations * @param $langId * * @return array */ public function sortCombinationByAttributePosition($combinations, $langId) { $attributes = []; foreach ($combinations as $combinationId) { $attributeCombination = $this->getAttributeCombinationsById($combinationId, $langId); $attributes[$attributeCombination[0]['position']][$combinationId] = $attributeCombination[0]; } ksort($attributes); return $attributes; } /** * @param float $wholesale_price * @param float $price Additional price * @param float $weight Additional weight * @param float $unit_impact * @param float $ecotax Additional ecotax * @param int $quantity deprecated * @param int[] $id_images Image ids * @param string $reference Reference * @param int $id_supplier Supplier identifier * @param string $ean13 * @param bool $default Is default attribute for product * @param string|null $location * @param string|null $upc * @param int $minimal_quantity * @param array $id_shop_list * @param string|null $available_date Date in mysql format Y-m-d * @param string $isbn * @param int|null $low_stock_threshold Low stock for mail alert * @param bool $low_stock_alert Low stock mail alert activated * @param string|null $mpn * * @return int|false Attribute identifier if success, false if it fail */ public function addCombinationEntity( $wholesale_price, $price, $weight, $unit_impact, $ecotax, $quantity, $id_images, $reference, $id_supplier, $ean13, $default, $location = null, $upc = null, $minimal_quantity = 1, array $id_shop_list = [], $available_date = null, $isbn = '', $low_stock_threshold = null, $low_stock_alert = false, $mpn = null ) { $id_product_attribute = $this->addAttribute( $price, $weight, $unit_impact, $ecotax, $id_images, $reference, $ean13, $default, $location, $upc, $minimal_quantity, $id_shop_list, $available_date, 0, $isbn, $low_stock_threshold, $low_stock_alert, $mpn ); $this->addSupplierReference($id_supplier, $id_product_attribute); $result = ObjectModel::updateMultishopTable('Combination', [ 'wholesale_price' => (float) $wholesale_price, ], 'a.id_product_attribute = ' . (int) $id_product_attribute); if (!$id_product_attribute || !$result) { return false; } return $id_product_attribute; } /** * @deprecated 1.5.5.0 * * @param array $attributes * @param bool $set_default * * @return array */ public function addProductAttributeMultiple($attributes, $set_default = true) { Tools::displayAsDeprecated(); $return = []; $default_value = 1; foreach ($attributes as $attribute) { $obj = new Combination(); foreach ($attribute as $key => $value) { $obj->$key = $value; } if ($set_default) { $obj->default_on = $default_value; $default_value = 0; // if we add a combination for this shop and this product does not use the combination feature in other shop, // we clone the default combination in every shop linked to this product if (!$this->hasAttributesInOtherShops()) { $id_shop_list_array = Product::getShopsByProduct($this->id); $id_shop_list = []; foreach ($id_shop_list_array as $array_shop) { $id_shop_list[] = $array_shop['id_shop']; } $obj->id_shop_list = $id_shop_list; } } $obj->add(); $return[] = $obj->id; } return $return; } /** * Delete all default attributes for product. * * @return bool */ public function deleteDefaultAttributes() { return ObjectModel::updateMultishopTable('Combination', [ 'default_on' => null, ], 'a.`id_product` = ' . (int) $this->id); } /** * @param int $id_product_attribute Attribute identifier * * @return bool */ public function setDefaultAttribute($id_product_attribute) { // We only update the type when we know it has combinations if (!empty($id_product_attribute)) { $this->product_type = ProductType::TYPE_COMBINATIONS; } $result = ObjectModel::updateMultishopTable('Combination', [ 'default_on' => 1, ], 'a.`id_product` = ' . (int) $this->id . ' AND a.`id_product_attribute` = ' . (int) $id_product_attribute); $result &= ObjectModel::updateMultishopTable('product', [ 'cache_default_attribute' => (int) $id_product_attribute, 'product_type' => $this->product_type, ], 'a.`id_product` = ' . (int) $this->id); $this->cache_default_attribute = (int) $id_product_attribute; return $result; } /** * @param int $id_product Product identifier * * @return int|false Default Attribute identifier if success, false if it false */ public static function updateDefaultAttribute($id_product) { $id_default_attribute = (int) Product::getDefaultAttribute($id_product, 0, true); $result = Db::getInstance()->update('product_shop', [ 'cache_default_attribute' => $id_default_attribute, ], 'id_product = ' . (int) $id_product . Shop::addSqlRestriction()); // We only update the type when we know it has combinations $updateData = [ 'cache_default_attribute' => $id_default_attribute, ]; if (!empty($id_default_attribute)) { $updateData['product_type'] = ProductType::TYPE_COMBINATIONS; } $result &= Db::getInstance()->update('product', $updateData, 'id_product = ' . (int) $id_product); if ($result && $id_default_attribute) { return $id_default_attribute; } else { return $result; } } /** * Update a product attribute. * * @deprecated since 1.5 * @see updateAttribute() to use instead * @see ProductSupplier for manage supplier reference(s) * * @param int $id_product_attribute Attribute identifier * @param float $wholesale_price * @param float $price Additional price * @param float $weight Additional weight * @param float $unit * @param float $ecotax Additional ecotax * @param int[] $id_images Image ids * @param string $reference * @param int $id_supplier Supplier identifier * @param string $ean13 * @param bool $default Is default attribute for product * @param string $location * @param string $upc * @param int $minimal_quantity * @param string $available_date Date in mysql format Y-m-d * @param string $isbn * @param int|null $low_stock_threshold Low stock for mail alert * @param bool $low_stock_alert Low stock mail alert activated * @param string|null $mpn * * @return array */ public function updateProductAttribute( $id_product_attribute, $wholesale_price, $price, $weight, $unit, $ecotax, $id_images, $reference, $id_supplier, $ean13, $default, $location, $upc, $minimal_quantity, $available_date, $isbn = '', $low_stock_threshold = null, $low_stock_alert = false, $mpn = null ) { Tools::displayAsDeprecated('Use updateAttribute() instead'); $return = $this->updateAttribute( $id_product_attribute, $wholesale_price, $price, $weight, $unit, $ecotax, $id_images, $reference, $ean13, $default, $location = null, $upc = null, $minimal_quantity, $available_date, true, [], $isbn, $low_stock_threshold, $low_stock_alert, $mpn = null ); $this->addSupplierReference($id_supplier, $id_product_attribute); return $return; } /** * Sets or updates Supplier Reference. * * @param int $id_supplier Supplier identifier * @param int $id_product_attribute Attribute identifier * @param string|null $supplier_reference * @param float|null $price * @param int|null $id_currency Currency identifier */ public function addSupplierReference($id_supplier, $id_product_attribute, $supplier_reference = null, $price = null, $id_currency = null) { //in some case we need to add price without supplier reference if ($supplier_reference === null) { $supplier_reference = ''; } //Try to set the default supplier reference if (($id_supplier > 0) && ($this->id > 0)) { $id_product_supplier = (int) ProductSupplier::getIdByProductAndSupplier($this->id, $id_product_attribute, $id_supplier); $product_supplier = new ProductSupplier($id_product_supplier); if (!$id_product_supplier) { $product_supplier->id_product = (int) $this->id; $product_supplier->id_product_attribute = (int) $id_product_attribute; $product_supplier->id_supplier = (int) $id_supplier; } $product_supplier->product_supplier_reference = pSQL($supplier_reference); $product_supplier->product_supplier_price_te = null !== $price ? (float) $price : (float) $product_supplier->product_supplier_price_te; $product_supplier->id_currency = null !== $id_currency ? (int) $id_currency : (int) $product_supplier->id_currency; $product_supplier->save(); } } /** * Update a product attribute. * * @param int $id_product_attribute Product attribute id * @param float $wholesale_price Wholesale price * @param float $price Additional price * @param float $weight Additional weight * @param float $unit Additional unit price * @param float $ecotax Additional ecotax * @param int[] $id_images Image identifiers * @param string $reference Reference * @param string $ean13 Ean-13 barcode * @param bool $default Is default attribute for product * @param string|null $location * @param string $upc Upc barcode * @param int|null $minimal_quantity Minimal quantity * @param string|null $available_date Date in mysql format Y-m-d * @param bool $update_all_fields * @param int[] $id_shop_list * @param string $isbn ISBN reference * @param int|null $low_stock_threshold Low stock for mail alert * @param bool $low_stock_alert Low stock mail alert activated * @param string $mpn MPN * * @return bool Update result */ public function updateAttribute( $id_product_attribute, $wholesale_price, $price, $weight, $unit, $ecotax, $id_images, $reference, $ean13, $default, $location = null, $upc = null, $minimal_quantity = null, $available_date = null, $update_all_fields = true, array $id_shop_list = [], $isbn = '', $low_stock_threshold = null, $low_stock_alert = false, $mpn = null ) { $combination = new Combination($id_product_attribute); if (!$update_all_fields) { $combination->setFieldsToUpdate([ 'price' => null !== $price, 'wholesale_price' => null !== $wholesale_price, 'ecotax' => null !== $ecotax, 'weight' => null !== $weight, 'unit_price_impact' => null !== $unit, 'default_on' => null !== $default, 'minimal_quantity' => null !== $minimal_quantity, 'available_date' => null !== $available_date, ]); } $price = str_replace(',', '.', $price); $weight = str_replace(',', '.', $weight); $combination->price = (float) $price; $combination->wholesale_price = (float) $wholesale_price; $combination->ecotax = (float) $ecotax; $combination->weight = (float) $weight; $combination->unit_price_impact = (float) $unit; $combination->reference = pSQL($reference); $combination->location = pSQL($location); $combination->ean13 = pSQL($ean13); $combination->isbn = pSQL($isbn); $combination->upc = pSQL($upc); $combination->mpn = pSQL($mpn); $combination->default_on = (int) $default; $combination->minimal_quantity = (int) $minimal_quantity; $combination->low_stock_threshold = empty($low_stock_threshold) && '0' != $low_stock_threshold ? null : (int) $low_stock_threshold; $combination->low_stock_alert = !empty($low_stock_alert); $combination->available_date = $available_date ? pSQL($available_date) : '0000-00-00'; if (count($id_shop_list)) { $combination->id_shop_list = $id_shop_list; } $combination->save(); if (is_array($id_images) && count($id_images)) { $combination->setImages($id_images); } $id_default_attribute = (int) Product::updateDefaultAttribute($this->id); if ($id_default_attribute) { $this->cache_default_attribute = $id_default_attribute; } // Sync stock Reference, EAN13, ISBN, MPN and UPC for this attribute if (Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT') && StockAvailable::dependsOnStock($this->id, Context::getContext()->shop->id)) { Db::getInstance()->update('stock', [ 'reference' => pSQL($reference), 'ean13' => pSQL($ean13), 'isbn' => pSQL($isbn), 'upc' => pSQL($upc), 'mpn' => pSQL($mpn), ], 'id_product = ' . $this->id . ' AND id_product_attribute = ' . (int) $id_product_attribute); } Hook::exec('actionProductAttributeUpdate', ['id_product_attribute' => (int) $id_product_attribute]); Tools::clearColorListCache($this->id); return true; } /** * Add a product attribute. * * @since 1.5.0.1 * * @param float $price Additional price * @param float $weight Additional weight * @param float $unit_impact Additional unit price * @param float $ecotax Additional ecotax * @param int[] $id_images Image ids * @param string $reference Reference * @param string $ean13 Ean-13 barcode * @param bool $default Is default attribute for product * @param string $location Location * @param string|null $upc * @param int $minimal_quantity Minimal quantity to add to cart * @param int[] $id_shop_list * @param string|null $available_date Date in mysql format Y-m-d * @param int $quantity * @param string $isbn ISBN reference * @param int|null $low_stock_threshold Low stock for mail alert * @param bool $low_stock_alert Low stock mail alert activated * @param string|null $mpn * * @return int|false|void Attribute identifier if success, false if failed to add Combination, void if Product identifier not set */ public function addAttribute( $price, $weight, $unit_impact, $ecotax, $id_images, $reference, $ean13, $default, $location = null, $upc = null, $minimal_quantity = 1, array $id_shop_list = [], $available_date = null, $quantity = 0, $isbn = '', $low_stock_threshold = null, $low_stock_alert = false, $mpn = null ) { if (!$this->id) { return; } $price = str_replace(',', '.', $price); $weight = str_replace(',', '.', $weight); $combination = new Combination(); $combination->id_product = (int) $this->id; $combination->price = (float) $price; $combination->ecotax = (float) $ecotax; $combination->quantity = (int) $quantity; $combination->weight = (float) $weight; $combination->unit_price_impact = (float) $unit_impact; $combination->reference = pSQL($reference); $combination->location = pSQL($location); $combination->ean13 = pSQL($ean13); $combination->isbn = pSQL($isbn); $combination->upc = pSQL($upc); $combination->mpn = pSQL($mpn); $combination->default_on = (int) $default; $combination->minimal_quantity = (int) $minimal_quantity; $combination->low_stock_threshold = empty($low_stock_threshold) && '0' != $low_stock_threshold ? null : (int) $low_stock_threshold; $combination->low_stock_alert = !empty($low_stock_alert); $combination->available_date = $available_date; if (count($id_shop_list)) { $combination->id_shop_list = array_unique($id_shop_list); } $combination->add(); if (!$combination->id) { return false; } $total_quantity = (int) Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue( ' SELECT SUM(quantity) as quantity FROM ' . _DB_PREFIX_ . 'stock_available WHERE id_product = ' . (int) $this->id . ' AND id_product_attribute <> 0 ' ); if (!$total_quantity) { Db::getInstance()->update('stock_available', ['quantity' => 0], '`id_product` = ' . $this->id); } $id_default_attribute = Product::updateDefaultAttribute($this->id); if ($id_default_attribute) { $this->cache_default_attribute = $id_default_attribute; if (!$combination->available_date) { $this->setAvailableDate(); } } $this->product_type = ProductType::TYPE_COMBINATIONS; if (!empty($id_images)) { $combination->setImages($id_images); } Tools::clearColorListCache($this->id); if (Configuration::get('PS_DEFAULT_WAREHOUSE_NEW_PRODUCT') != 0 && Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT')) { $warehouse_location_entity = new WarehouseProductLocation(); $warehouse_location_entity->id_product = $this->id; $warehouse_location_entity->id_product_attribute = (int) $combination->id; $warehouse_location_entity->id_warehouse = Configuration::get('PS_DEFAULT_WAREHOUSE_NEW_PRODUCT'); $warehouse_location_entity->location = pSQL(''); $warehouse_location_entity->save(); } return (int) $combination->id; } /** * @deprecated since 1.5.0 * * @return bool */ public function updateQuantityProductWithAttributeQuantity() { Tools::displayAsDeprecated(); return Db::getInstance()->execute(' UPDATE `' . _DB_PREFIX_ . 'product` SET `quantity` = IFNULL( ( SELECT SUM(`quantity`) FROM `' . _DB_PREFIX_ . 'product_attribute` WHERE `id_product` = ' . (int) $this->id . ' ), \'0\') WHERE `id_product` = ' . (int) $this->id); } /** * Delete product attributes. * * @return bool Deletion result */ public function deleteProductAttributes() { Hook::exec('actionProductAttributeDelete', ['id_product_attribute' => 0, 'id_product' => (int) $this->id, 'deleteAllAttributes' => true]); $result = true; $combinations = new PrestaShopCollection('Combination'); $combinations->where('id_product', '=', $this->id); foreach ($combinations as $combination) { $result &= $combination->delete(); } SpecificPriceRule::applyAllRules([(int) $this->id]); Tools::clearColorListCache($this->id); return $result; } /** * Delete product attributes impacts. * * @return bool */ public function deleteAttributesImpacts() { return Db::getInstance()->execute( 'DELETE FROM `' . _DB_PREFIX_ . 'attribute_impact` WHERE `id_product` = ' . (int) $this->id ); } /** * Delete product features. * * @return bool Deletion result */ public function deleteProductFeatures() { SpecificPriceRule::applyAllRules([(int) $this->id]); return $this->deleteFeatures(); } /** * @param int $id_product Product identifier * * @return bool */ public static function updateCacheAttachment($id_product) { $value = (bool) Db::getInstance()->getValue(' SELECT id_attachment FROM ' . _DB_PREFIX_ . 'product_attachment WHERE id_product=' . (int) $id_product); return Db::getInstance()->update( 'product', ['cache_has_attachments' => (int) $value], 'id_product = ' . (int) $id_product ); } /** * Delete product attachments. * * @param bool $update_attachment_cache If set to true attachment cache will be updated * * @return bool Deletion result */ public function deleteAttachments($update_attachment_cache = true) { $res = Db::getInstance()->execute( ' DELETE FROM `' . _DB_PREFIX_ . 'product_attachment` WHERE `id_product` = ' . (int) $this->id ); if (isset($update_attachment_cache) && (bool) $update_attachment_cache === true) { Product::updateCacheAttachment((int) $this->id); } return $res; } /** * Delete product customizations. * * @return bool Deletion result */ public function deleteCustomization() { return Db::getInstance()->execute( 'DELETE FROM `' . _DB_PREFIX_ . 'customization_field` WHERE `id_product` = ' . (int) $this->id ) && Db::getInstance()->execute( 'DELETE `' . _DB_PREFIX_ . 'customization_field_lang` FROM `' . _DB_PREFIX_ . 'customization_field_lang` LEFT JOIN `' . _DB_PREFIX_ . 'customization_field` ON (' . _DB_PREFIX_ . 'customization_field.id_customization_field = ' . _DB_PREFIX_ . 'customization_field_lang.id_customization_field) WHERE ' . _DB_PREFIX_ . 'customization_field.id_customization_field IS NULL' ); } /** * Delete product pack details. * * @return bool Deletion result */ public function deletePack() { return Db::getInstance()->execute( 'DELETE FROM `' . _DB_PREFIX_ . 'pack` WHERE `id_product_pack` = ' . (int) $this->id . ' OR `id_product_item` = ' . (int) $this->id ); } /** * Delete product sales. * * @return bool Deletion result */ public function deleteProductSale() { return Db::getInstance()->execute( 'DELETE FROM `' . _DB_PREFIX_ . 'product_sale` WHERE `id_product` = ' . (int) $this->id ); } /** * Delete product indexed words. * * @return bool Deletion result */ public function deleteSearchIndexes() { return Db::getInstance()->execute( 'DELETE FROM `' . _DB_PREFIX_ . 'search_index` WHERE `id_product` = ' . (int) $this->id ) && Db::getInstance()->execute( 'DELETE sw FROM `' . _DB_PREFIX_ . 'search_word` sw LEFT JOIN `' . _DB_PREFIX_ . 'search_index` si ON (sw.id_word=si.id_word) WHERE si.id_word IS NULL;' ); } /** * Add a product attributes combinaison. * * @deprecated since 1.5.0.7 * * @param int $id_product_attribute Attribute identifier * @param array $attributes Attributes to forge combinaison * * @return bool Insertion result */ public function addAttributeCombinaison($id_product_attribute, $attributes) { Tools::displayAsDeprecated(); if (!is_array($attributes)) { die(Tools::displayError()); } if (!count($attributes)) { return false; } $combination = new Combination((int) $id_product_attribute); return $combination->setAttributes($attributes); } /** * @deprecated 1.5.5.0 * * @param array $id_attributes * @param array $combinations * * @return bool * * @throws PrestaShopDatabaseException */ public function addAttributeCombinationMultiple($id_attributes, $combinations) { Tools::displayAsDeprecated(); $attributes_list = []; foreach ($id_attributes as $nb => $id_product_attribute) { if (isset($combinations[$nb])) { foreach ($combinations[$nb] as $id_attribute) { $attributes_list[] = [ 'id_product_attribute' => (int) $id_product_attribute, 'id_attribute' => (int) $id_attribute, ]; } } } return Db::getInstance()->insert('product_attribute_combination', $attributes_list); } /** * Delete a product attributes combination. * * @param int $id_product_attribute Attribute identifier * * @return bool Deletion result */ public function deleteAttributeCombination($id_product_attribute) { if (!$this->id || !$id_product_attribute || !is_numeric($id_product_attribute)) { return false; } Hook::exec( 'deleteProductAttribute', [ 'id_product_attribute' => $id_product_attribute, 'id_product' => $this->id, 'deleteAllAttributes' => false, ] ); $combination = new Combination($id_product_attribute); $res = $combination->delete(); SpecificPriceRule::applyAllRules([(int) $this->id]); return $res; } /** * Delete features. * * @return bool */ public function deleteFeatures() { $all_shops = Context::getContext()->shop->getContext() == Shop::CONTEXT_ALL ? true : false; // List products features $features = Db::getInstance()->executeS( ' SELECT p.*, f.* FROM `' . _DB_PREFIX_ . 'feature_product` as p LEFT JOIN `' . _DB_PREFIX_ . 'feature_value` as f ON (f.`id_feature_value` = p.`id_feature_value`) ' . (!$all_shops ? 'LEFT JOIN `' . _DB_PREFIX_ . 'feature_shop` fs ON (f.`id_feature` = fs.`id_feature`)' : null) . ' WHERE `id_product` = ' . (int) $this->id . (!$all_shops ? ' AND fs.`id_shop` = ' . (int) Context::getContext()->shop->id : '') ); foreach ($features as $tab) { // Delete product custom features if ($tab['custom']) { Db::getInstance()->execute('DELETE FROM `' . _DB_PREFIX_ . 'feature_value` WHERE `id_feature_value` = ' . (int) $tab['id_feature_value']); Db::getInstance()->execute('DELETE FROM `' . _DB_PREFIX_ . 'feature_value_lang` WHERE `id_feature_value` = ' . (int) $tab['id_feature_value']); } } // Delete product features $result = Db::getInstance()->execute(' DELETE `' . _DB_PREFIX_ . 'feature_product` FROM `' . _DB_PREFIX_ . 'feature_product` WHERE `id_product` = ' . (int) $this->id . (!$all_shops ? ' AND `id_feature` IN ( SELECT `id_feature` FROM `' . _DB_PREFIX_ . 'feature_shop` WHERE `id_shop` = ' . (int) Context::getContext()->shop->id . ' )' : '')); SpecificPriceRule::applyAllRules([(int) $this->id]); return $result; } /** * Get all available product attributes resume. * * @param int $id_lang Language identifier * @param string $attribute_value_separator * @param string $attribute_separator * * @return array Product attributes combinations */ public function getAttributesResume($id_lang, $attribute_value_separator = ' - ', $attribute_separator = ', ') { if (!Combination::isFeatureActive()) { return []; } $combinations = Db::getInstance()->executeS('SELECT pa.*, product_attribute_shop.* FROM `' . _DB_PREFIX_ . 'product_attribute` pa ' . Shop::addSqlAssociation('product_attribute', 'pa') . ' WHERE pa.`id_product` = ' . (int) $this->id . ' GROUP BY pa.`id_product_attribute` ORDER BY pa.`id_product_attribute`'); if (!$combinations) { return false; } $product_attributes = []; foreach ($combinations as $combination) { $product_attributes[] = (int) $combination['id_product_attribute']; } $lang = Db::getInstance()->executeS('SELECT pac.id_product_attribute, GROUP_CONCAT(agl.`name`, \'' . pSQL($attribute_value_separator) . '\',al.`name` ORDER BY agl.`id_attribute_group` SEPARATOR \'' . pSQL($attribute_separator) . '\') as attribute_designation FROM `' . _DB_PREFIX_ . 'product_attribute_combination` pac LEFT JOIN `' . _DB_PREFIX_ . 'attribute` a ON a.`id_attribute` = pac.`id_attribute` LEFT JOIN `' . _DB_PREFIX_ . 'attribute_group` ag ON ag.`id_attribute_group` = a.`id_attribute_group` LEFT JOIN `' . _DB_PREFIX_ . 'attribute_lang` al ON (a.`id_attribute` = al.`id_attribute` AND al.`id_lang` = ' . (int) $id_lang . ') LEFT JOIN `' . _DB_PREFIX_ . 'attribute_group_lang` agl ON (ag.`id_attribute_group` = agl.`id_attribute_group` AND agl.`id_lang` = ' . (int) $id_lang . ') WHERE pac.id_product_attribute IN (' . implode(',', $product_attributes) . ') GROUP BY pac.id_product_attribute ORDER BY pac.id_product_attribute'); foreach ($lang as $k => $row) { $combinations[$k]['attribute_designation'] = $row['attribute_designation']; } $computingPrecision = Context::getContext()->getComputingPrecision(); //Get quantity of each variations foreach ($combinations as $key => $row) { $cache_key = $row['id_product'] . '_' . $row['id_product_attribute'] . '_quantity'; if (!Cache::isStored($cache_key)) { $result = StockAvailable::getQuantityAvailableByProduct($row['id_product'], $row['id_product_attribute']); Cache::store( $cache_key, $result ); $combinations[$key]['quantity'] = $result; } else { $combinations[$key]['quantity'] = Cache::retrieve($cache_key); } $ecotax = (float) $combinations[$key]['ecotax'] ?? 0; $combinations[$key]['ecotax_tax_excluded'] = $ecotax; $combinations[$key]['ecotax_tax_included'] = Tools::ps_round($ecotax * (1 + Tax::getProductEcotaxRate() / 100), $computingPrecision); } return $combinations; } /** * Get all available product attributes combinations. * * @param int|null $id_lang Language identifier * @param bool $groupByIdAttributeGroup * * @return array Product attributes combinations */ public function getAttributeCombinations($id_lang = null, $groupByIdAttributeGroup = true) { if (!Combination::isFeatureActive()) { return []; } if (null === $id_lang) { $id_lang = Context::getContext()->language->id; } $sql = 'SELECT pa.*, product_attribute_shop.*, ag.`id_attribute_group`, ag.`is_color_group`, agl.`name` AS group_name, al.`name` AS attribute_name, a.`id_attribute` FROM `' . _DB_PREFIX_ . 'product_attribute` pa ' . Shop::addSqlAssociation('product_attribute', 'pa') . ' LEFT JOIN `' . _DB_PREFIX_ . 'product_attribute_combination` pac ON pac.`id_product_attribute` = pa.`id_product_attribute` LEFT JOIN `' . _DB_PREFIX_ . 'attribute` a ON a.`id_attribute` = pac.`id_attribute` LEFT JOIN `' . _DB_PREFIX_ . 'attribute_group` ag ON ag.`id_attribute_group` = a.`id_attribute_group` LEFT JOIN `' . _DB_PREFIX_ . 'attribute_lang` al ON (a.`id_attribute` = al.`id_attribute` AND al.`id_lang` = ' . (int) $id_lang . ') LEFT JOIN `' . _DB_PREFIX_ . 'attribute_group_lang` agl ON (ag.`id_attribute_group` = agl.`id_attribute_group` AND agl.`id_lang` = ' . (int) $id_lang . ') WHERE pa.`id_product` = ' . (int) $this->id . ' GROUP BY pa.`id_product_attribute`' . ($groupByIdAttributeGroup ? ',ag.`id_attribute_group`' : '') . ' ORDER BY pa.`id_product_attribute`'; $res = Db::getInstance()->executeS($sql); //Get quantity of each variations foreach ($res as $key => $row) { $cache_key = $row['id_product'] . '_' . $row['id_product_attribute'] . '_quantity'; if (!Cache::isStored($cache_key)) { Cache::store( $cache_key, StockAvailable::getQuantityAvailableByProduct($row['id_product'], $row['id_product_attribute']) ); } $res[$key]['quantity'] = Cache::retrieve($cache_key); } return $res; } /** * Get product attribute combination by id_product_attribute. * * @param int $id_product_attribute Attribute identifier * @param int $id_lang Language identifier * @param bool $groupByIdAttributeGroup * * @return array Product attribute combination by id_product_attribute */ public function getAttributeCombinationsById($id_product_attribute, $id_lang, $groupByIdAttributeGroup = true) { if (!Combination::isFeatureActive()) { return []; } $sql = 'SELECT pa.*, product_attribute_shop.*, ag.`id_attribute_group`, ag.`is_color_group`, agl.`name` AS group_name, al.`name` AS attribute_name, a.`id_attribute`, a.`position` FROM `' . _DB_PREFIX_ . 'product_attribute` pa ' . Shop::addSqlAssociation('product_attribute', 'pa') . ' LEFT JOIN `' . _DB_PREFIX_ . 'product_attribute_combination` pac ON pac.`id_product_attribute` = pa.`id_product_attribute` LEFT JOIN `' . _DB_PREFIX_ . 'attribute` a ON a.`id_attribute` = pac.`id_attribute` LEFT JOIN `' . _DB_PREFIX_ . 'attribute_group` ag ON ag.`id_attribute_group` = a.`id_attribute_group` LEFT JOIN `' . _DB_PREFIX_ . 'attribute_lang` al ON (a.`id_attribute` = al.`id_attribute` AND al.`id_lang` = ' . (int) $id_lang . ') LEFT JOIN `' . _DB_PREFIX_ . 'attribute_group_lang` agl ON (ag.`id_attribute_group` = agl.`id_attribute_group` AND agl.`id_lang` = ' . (int) $id_lang . ') WHERE pa.`id_product` = ' . (int) $this->id . ' AND pa.`id_product_attribute` = ' . (int) $id_product_attribute . ' GROUP BY pa.`id_product_attribute`' . ($groupByIdAttributeGroup ? ',ag.`id_attribute_group`' : '') . ' ORDER BY pa.`id_product_attribute`'; $res = Db::getInstance()->executeS($sql); $computingPrecision = Context::getContext()->getComputingPrecision(); //Get quantity of each variations foreach ($res as $key => $row) { $cache_key = $row['id_product'] . '_' . $row['id_product_attribute'] . '_quantity'; if (!Cache::isStored($cache_key)) { $result = StockAvailable::getQuantityAvailableByProduct($row['id_product'], $row['id_product_attribute']); Cache::store( $cache_key, $result ); $res[$key]['quantity'] = $result; } else { $res[$key]['quantity'] = Cache::retrieve($cache_key); } $ecotax = (float) $res[$key]['ecotax'] ?? 0; $res[$key]['ecotax_tax_excluded'] = $ecotax; $res[$key]['ecotax_tax_included'] = Tools::ps_round($ecotax * (1 + Tax::getProductEcotaxRate() / 100), $computingPrecision); } return $res; } /** * @param int $id_lang Language identifier * * @return array|false */ public function getCombinationImages($id_lang) { if (!Combination::isFeatureActive()) { return false; } $product_attributes = Db::getInstance()->executeS( 'SELECT `id_product_attribute` FROM `' . _DB_PREFIX_ . 'product_attribute` WHERE `id_product` = ' . (int) $this->id ); if (!$product_attributes) { return false; } $ids = []; foreach ($product_attributes as $product_attribute) { $ids[] = (int) $product_attribute['id_product_attribute']; } $result = Db::getInstance()->executeS( ' SELECT pai.`id_image`, pai.`id_product_attribute`, il.`legend` FROM `' . _DB_PREFIX_ . 'product_attribute_image` pai LEFT JOIN `' . _DB_PREFIX_ . 'image_lang` il ON (il.`id_image` = pai.`id_image`) LEFT JOIN `' . _DB_PREFIX_ . 'image` i ON (i.`id_image` = pai.`id_image`) WHERE pai.`id_product_attribute` IN (' . implode(', ', $ids) . ') AND il.`id_lang` = ' . (int) $id_lang . ' ORDER by i.`position`' ); if (!$result) { return false; } $images = []; foreach ($result as $row) { $images[$row['id_product_attribute']][] = $row; } return $images; } /** * @param int $id_product_attribute Attribute identifier * @param int $id_lang Language identifier * * @return array|false */ public static function getCombinationImageById($id_product_attribute, $id_lang) { if (!Combination::isFeatureActive() || !$id_product_attribute) { return false; } $result = Db::getInstance()->executeS( ' SELECT pai.`id_image`, pai.`id_product_attribute`, il.`legend` FROM `' . _DB_PREFIX_ . 'product_attribute_image` pai LEFT JOIN `' . _DB_PREFIX_ . 'image_lang` il ON (il.`id_image` = pai.`id_image`) LEFT JOIN `' . _DB_PREFIX_ . 'image` i ON (i.`id_image` = pai.`id_image`) WHERE pai.`id_product_attribute` = ' . (int) $id_product_attribute . ' AND il.`id_lang` = ' . (int) $id_lang . ' ORDER by i.`position` LIMIT 1' ); if (!$result) { return false; } return $result[0]; } /** * Check if product has attributes combinations. * * @return int Attributes combinations number */ public function hasAttributes() { if (!Combination::isFeatureActive()) { return 0; } return Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue( ' SELECT COUNT(*) FROM `' . _DB_PREFIX_ . 'product_attribute` pa ' . Shop::addSqlAssociation('product_attribute', 'pa') . ' WHERE pa.`id_product` = ' . (int) $this->id ); } /** * Get new products. * * @param int $id_lang Language identifier * @param int $page_number Start from * @param int $nb_products Number of products to return * @param bool $count * @param string|null $order_by * @param string|null $order_way * @param Context|null $context * * @return array|int|false New products, total of product if $count is true, false if it fail */ public static function getNewProducts($id_lang, $page_number = 0, $nb_products = 10, $count = false, $order_by = null, $order_way = null, Context $context = null) { $now = date('Y-m-d') . ' 00:00:00'; if (!$context) { $context = Context::getContext(); } $front = true; if (!in_array($context->controller->controller_type, ['front', 'modulefront'])) { $front = false; } if ($page_number < 1) { $page_number = 1; } if ($nb_products < 1) { $nb_products = 10; } if (empty($order_by) || $order_by == 'position') { $order_by = 'date_add'; } if (empty($order_way)) { $order_way = 'DESC'; } if ($order_by == 'id_product' || $order_by == 'price' || $order_by == 'date_add' || $order_by == 'date_upd') { $order_by_prefix = 'product_shop'; } elseif ($order_by == 'name') { $order_by_prefix = 'pl'; } if (!Validate::isOrderBy($order_by) || !Validate::isOrderWay($order_way)) { die(Tools::displayError()); } $sql_groups = ''; if (Group::isFeatureActive()) { $groups = FrontController::getCurrentCustomerGroups(); $sql_groups = ' AND EXISTS(SELECT 1 FROM `' . _DB_PREFIX_ . 'category_product` cp JOIN `' . _DB_PREFIX_ . 'category_group` cg ON (cp.id_category = cg.id_category AND cg.`id_group` ' . (count($groups) ? 'IN (' . implode(',', $groups) . ')' : '=' . (int) Group::getCurrent()->id) . ') WHERE cp.`id_product` = p.`id_product`)'; } if (strpos($order_by, '.') > 0) { $order_by = explode('.', $order_by); $order_by_prefix = $order_by[0]; $order_by = $order_by[1]; } $nb_days_new_product = (int) Configuration::get('PS_NB_DAYS_NEW_PRODUCT'); if ($count) { $sql = 'SELECT COUNT(p.`id_product`) AS nb FROM `' . _DB_PREFIX_ . 'product` p ' . Shop::addSqlAssociation('product', 'p') . ' WHERE product_shop.`active` = 1 AND DATEDIFF(product_shop.`date_add`, DATE_SUB("' . $now . '", INTERVAL ' . $nb_days_new_product . ' DAY)) > 0 ' . ($front ? ' AND product_shop.`visibility` IN ("both", "catalog")' : '') . ' ' . $sql_groups; return (int) Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue($sql); } $sql = new DbQuery(); $sql->select( 'p.*, product_shop.*, stock.out_of_stock, IFNULL(stock.quantity, 0) as quantity, pl.`description`, pl.`description_short`, pl.`link_rewrite`, pl.`meta_description`, pl.`meta_keywords`, pl.`meta_title`, pl.`name`, pl.`available_now`, pl.`available_later`, image_shop.`id_image` id_image, il.`legend`, m.`name` AS manufacturer_name, (DATEDIFF(product_shop.`date_add`, DATE_SUB( "' . $now . '", INTERVAL ' . $nb_days_new_product . ' DAY ) ) > 0) as new' ); $sql->from('product', 'p'); $sql->join(Shop::addSqlAssociation('product', 'p')); $sql->leftJoin( 'product_lang', 'pl', ' p.`id_product` = pl.`id_product` AND pl.`id_lang` = ' . (int) $id_lang . Shop::addSqlRestrictionOnLang('pl') ); $sql->leftJoin('image_shop', 'image_shop', 'image_shop.`id_product` = p.`id_product` AND image_shop.cover=1 AND image_shop.id_shop=' . (int) $context->shop->id); $sql->leftJoin('image_lang', 'il', 'image_shop.`id_image` = il.`id_image` AND il.`id_lang` = ' . (int) $id_lang); $sql->leftJoin('manufacturer', 'm', 'm.`id_manufacturer` = p.`id_manufacturer`'); $sql->where('product_shop.`active` = 1'); if ($front) { $sql->where('product_shop.`visibility` IN ("both", "catalog")'); } $sql->where('DATEDIFF(product_shop.`date_add`, DATE_SUB( "' . $now . '", INTERVAL ' . $nb_days_new_product . ' DAY ) ) > 0'); if (Group::isFeatureActive()) { $groups = FrontController::getCurrentCustomerGroups(); $sql->where('EXISTS(SELECT 1 FROM `' . _DB_PREFIX_ . 'category_product` cp JOIN `' . _DB_PREFIX_ . 'category_group` cg ON (cp.id_category = cg.id_category AND cg.`id_group` ' . (count($groups) ? 'IN (' . implode(',', $groups) . ')' : '=' . (int) Group::getCurrent()->id) . ') WHERE cp.`id_product` = p.`id_product`)'); } if ($order_by !== 'price') { $sql->orderBy((isset($order_by_prefix) ? pSQL($order_by_prefix) . '.' : '') . '`' . pSQL($order_by) . '` ' . pSQL($order_way)); $sql->limit($nb_products, (int) (($page_number - 1) * $nb_products)); } if (Combination::isFeatureActive()) { $sql->select('product_attribute_shop.minimal_quantity AS product_attribute_minimal_quantity, IFNULL(product_attribute_shop.id_product_attribute,0) id_product_attribute'); $sql->leftJoin('product_attribute_shop', 'product_attribute_shop', 'p.`id_product` = product_attribute_shop.`id_product` AND product_attribute_shop.`default_on` = 1 AND product_attribute_shop.id_shop=' . (int) $context->shop->id); } $sql->join(Product::sqlStock('p', 0)); $result = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($sql); if (!$result) { return false; } if ($order_by === 'price') { Tools::orderbyPrice($result, $order_way); $result = array_slice($result, (int) (($page_number - 1) * $nb_products), (int) $nb_products); } $products_ids = []; foreach ($result as $row) { $products_ids[] = $row['id_product']; } // Thus you can avoid one query per product, because there will be only one query for all the products of the cart Product::cacheFrontFeatures($products_ids, $id_lang); return Product::getProductsProperties((int) $id_lang, $result); } /** * @param string $beginning Date in mysql format Y-m-d * @param string $ending Date in mysql format Y-m-d * @param Context|null $context * @param bool $with_combination * * @return array */ protected static function _getProductIdByDate($beginning, $ending, Context $context = null, $with_combination = false) { if (!$context) { $context = Context::getContext(); } $id_address = $context->cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}; $ids = Address::getCountryAndState($id_address); $id_country = isset($ids['id_country']) ? (int) $ids['id_country'] : (int) Configuration::get('PS_COUNTRY_DEFAULT'); return SpecificPrice::getProductIdByDate( $context->shop->id, $context->currency->id, $id_country, $context->customer->id_default_group, $beginning, $ending, 0, $with_combination ); } /** * Get a random special. * * @param int $id_lang Language identifier * @param string|false $beginning Date in mysql format Y-m-d * @param string|false $ending Date in mysql format Y-m-d * @param Context|null $context * * @return array|false Special */ public static function getRandomSpecial($id_lang, $beginning = false, $ending = false, Context $context = null) { if (!$context) { $context = Context::getContext(); } $front = true; if (!in_array($context->controller->controller_type, ['front', 'modulefront'])) { $front = false; } $current_date = date('Y-m-d H:i:00'); $product_reductions = Product::_getProductIdByDate((!$beginning ? $current_date : $beginning), (!$ending ? $current_date : $ending), $context, true); if ($product_reductions) { $ids_products = ''; foreach ($product_reductions as $product_reduction) { $ids_products .= '(' . (int) $product_reduction['id_product'] . ',' . ($product_reduction['id_product_attribute'] ? (int) $product_reduction['id_product_attribute'] : '0') . '),'; } $ids_products = rtrim($ids_products, ','); Db::getInstance()->execute('CREATE TEMPORARY TABLE `' . _DB_PREFIX_ . 'product_reductions` (id_product INT UNSIGNED NOT NULL DEFAULT 0, id_product_attribute INT UNSIGNED NOT NULL DEFAULT 0) ENGINE=MEMORY', false); if ($ids_products) { Db::getInstance()->execute('INSERT INTO `' . _DB_PREFIX_ . 'product_reductions` VALUES ' . $ids_products, false); } $groups = FrontController::getCurrentCustomerGroups(); $sql_groups = ' AND EXISTS(SELECT 1 FROM `' . _DB_PREFIX_ . 'category_product` cp JOIN `' . _DB_PREFIX_ . 'category_group` cg ON (cp.id_category = cg.id_category AND cg.`id_group` ' . (count($groups) ? 'IN (' . implode(',', $groups) . ')' : '=' . (int) Group::getCurrent()->id) . ') WHERE cp.`id_product` = p.`id_product`)'; // Please keep 2 distinct queries because RAND() is an awful way to achieve this result $sql = 'SELECT product_shop.id_product, IFNULL(product_attribute_shop.id_product_attribute,0) id_product_attribute FROM `' . _DB_PREFIX_ . 'product_reductions` pr, `' . _DB_PREFIX_ . 'product` p ' . Shop::addSqlAssociation('product', 'p') . ' LEFT JOIN `' . _DB_PREFIX_ . 'product_attribute_shop` product_attribute_shop ON (p.`id_product` = product_attribute_shop.`id_product` AND product_attribute_shop.`default_on` = 1 AND product_attribute_shop.id_shop=' . (int) $context->shop->id . ') WHERE p.id_product=pr.id_product AND (pr.id_product_attribute = 0 OR product_attribute_shop.id_product_attribute = pr.id_product_attribute) AND product_shop.`active` = 1 ' . $sql_groups . ' ' . ($front ? ' AND product_shop.`visibility` IN ("both", "catalog")' : '') . ' ORDER BY RAND()'; $result = Db::getInstance()->getRow($sql); Db::getInstance()->execute('DROP TEMPORARY TABLE `' . _DB_PREFIX_ . 'product_reductions`', false); if (!$id_product = $result['id_product']) { return false; } // no group by needed : there's only one attribute with cover=1 for a given id_product + shop $sql = 'SELECT p.*, product_shop.*, stock.`out_of_stock` out_of_stock, pl.`description`, pl.`description_short`, pl.`link_rewrite`, pl.`meta_description`, pl.`meta_keywords`, pl.`meta_title`, pl.`name`, pl.`available_now`, pl.`available_later`, p.`ean13`, p.`isbn`, p.`upc`, p.`mpn`, image_shop.`id_image` id_image, il.`legend`, DATEDIFF(product_shop.`date_add`, DATE_SUB("' . date('Y-m-d') . ' 00:00:00", INTERVAL ' . (Validate::isUnsignedInt(Configuration::get('PS_NB_DAYS_NEW_PRODUCT')) ? Configuration::get('PS_NB_DAYS_NEW_PRODUCT') : 20) . ' DAY)) > 0 AS new FROM `' . _DB_PREFIX_ . 'product` p LEFT JOIN `' . _DB_PREFIX_ . 'product_lang` pl ON ( p.`id_product` = pl.`id_product` AND pl.`id_lang` = ' . (int) $id_lang . Shop::addSqlRestrictionOnLang('pl') . ' ) ' . Shop::addSqlAssociation('product', 'p') . ' LEFT JOIN `' . _DB_PREFIX_ . 'image_shop` image_shop ON (image_shop.`id_product` = p.`id_product` AND image_shop.cover=1 AND image_shop.id_shop=' . (int) $context->shop->id . ') LEFT JOIN `' . _DB_PREFIX_ . 'image_lang` il ON (image_shop.`id_image` = il.`id_image` AND il.`id_lang` = ' . (int) $id_lang . ') ' . Product::sqlStock('p', 0) . ' WHERE p.id_product = ' . (int) $id_product; $row = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow($sql); if (!$row) { return false; } $row['id_product_attribute'] = (int) $result['id_product_attribute']; return Product::getProductProperties($id_lang, $row); } else { return false; } } /** * Get prices drop. * * @param int $id_lang Language identifier * @param int $page_number Start from * @param int $nb_products Number of products to return * @param bool $count Only in order to get total number * @param string|null $order_by * @param string|null $order_way * @param string|false $beginning Date in mysql format Y-m-d * @param string|false $ending Date in mysql format Y-m-d * @param Context|null $context * * @return array|false */ public static function getPricesDrop( $id_lang, $page_number = 0, $nb_products = 10, $count = false, $order_by = null, $order_way = null, $beginning = false, $ending = false, Context $context = null ) { if (!Validate::isBool($count)) { die(Tools::displayError()); } if (!$context) { $context = Context::getContext(); } if ($page_number < 1) { $page_number = 1; } if ($nb_products < 1) { $nb_products = 10; } if (empty($order_by) || $order_by == 'position') { $order_by = 'price'; } if (empty($order_way)) { $order_way = 'DESC'; } if ($order_by == 'id_product' || $order_by == 'price' || $order_by == 'date_add' || $order_by == 'date_upd') { $order_by_prefix = 'product_shop'; } elseif ($order_by == 'name') { $order_by_prefix = 'pl'; } if (!Validate::isOrderBy($order_by) || !Validate::isOrderWay($order_way)) { die(Tools::displayError()); } $current_date = date('Y-m-d H:i:00'); $ids_product = Product::_getProductIdByDate((!$beginning ? $current_date : $beginning), (!$ending ? $current_date : $ending), $context); $tab_id_product = []; foreach ($ids_product as $product) { if (is_array($product)) { $tab_id_product[] = (int) $product['id_product']; } else { $tab_id_product[] = (int) $product; } } $front = true; if (!in_array($context->controller->controller_type, ['front', 'modulefront'])) { $front = false; } $sql_groups = ''; if (Group::isFeatureActive()) { $groups = FrontController::getCurrentCustomerGroups(); $sql_groups = ' AND EXISTS(SELECT 1 FROM `' . _DB_PREFIX_ . 'category_product` cp JOIN `' . _DB_PREFIX_ . 'category_group` cg ON (cp.id_category = cg.id_category AND cg.`id_group` ' . (count($groups) ? 'IN (' . implode(',', $groups) . ')' : '=' . (int) Group::getCurrent()->id) . ') WHERE cp.`id_product` = p.`id_product`)'; } if ($count) { return Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue(' SELECT COUNT(DISTINCT p.`id_product`) FROM `' . _DB_PREFIX_ . 'product` p ' . Shop::addSqlAssociation('product', 'p') . ' WHERE product_shop.`active` = 1 AND product_shop.`show_price` = 1 ' . ($front ? ' AND product_shop.`visibility` IN ("both", "catalog")' : '') . ' ' . ((!$beginning && !$ending) ? 'AND p.`id_product` IN(' . ((is_array($tab_id_product) && count($tab_id_product)) ? implode(', ', $tab_id_product) : 0) . ')' : '') . ' ' . $sql_groups); } if (strpos($order_by, '.') > 0) { $order_by = explode('.', $order_by); $order_by = pSQL($order_by[0]) . '.`' . pSQL($order_by[1]) . '`'; } $sql = ' SELECT p.*, product_shop.*, stock.out_of_stock, IFNULL(stock.quantity, 0) as quantity, pl.`description`, pl.`description_short`, pl.`available_now`, pl.`available_later`, IFNULL(product_attribute_shop.id_product_attribute, 0) id_product_attribute, pl.`link_rewrite`, pl.`meta_description`, pl.`meta_keywords`, pl.`meta_title`, pl.`name`, image_shop.`id_image` id_image, il.`legend`, m.`name` AS manufacturer_name, DATEDIFF( p.`date_add`, DATE_SUB( "' . date('Y-m-d') . ' 00:00:00", INTERVAL ' . (Validate::isUnsignedInt(Configuration::get('PS_NB_DAYS_NEW_PRODUCT')) ? Configuration::get('PS_NB_DAYS_NEW_PRODUCT') : 20) . ' DAY ) ) > 0 AS new FROM `' . _DB_PREFIX_ . 'product` p ' . Shop::addSqlAssociation('product', 'p') . ' LEFT JOIN `' . _DB_PREFIX_ . 'product_attribute_shop` product_attribute_shop ON (p.`id_product` = product_attribute_shop.`id_product` AND product_attribute_shop.`default_on` = 1 AND product_attribute_shop.id_shop=' . (int) $context->shop->id . ') ' . Product::sqlStock('p', 0, false, $context->shop) . ' LEFT JOIN `' . _DB_PREFIX_ . 'product_lang` pl ON ( p.`id_product` = pl.`id_product` AND pl.`id_lang` = ' . (int) $id_lang . Shop::addSqlRestrictionOnLang('pl') . ' ) LEFT JOIN `' . _DB_PREFIX_ . 'image_shop` image_shop ON (image_shop.`id_product` = p.`id_product` AND image_shop.cover=1 AND image_shop.id_shop=' . (int) $context->shop->id . ') LEFT JOIN `' . _DB_PREFIX_ . 'image_lang` il ON (image_shop.`id_image` = il.`id_image` AND il.`id_lang` = ' . (int) $id_lang . ') LEFT JOIN `' . _DB_PREFIX_ . 'manufacturer` m ON (m.`id_manufacturer` = p.`id_manufacturer`) WHERE product_shop.`active` = 1 AND product_shop.`show_price` = 1 ' . ($front ? ' AND product_shop.`visibility` IN ("both", "catalog")' : '') . ' ' . ((!$beginning && !$ending) ? ' AND p.`id_product` IN (' . ((is_array($tab_id_product) && count($tab_id_product)) ? implode(', ', $tab_id_product) : 0) . ')' : '') . ' ' . $sql_groups; if ($order_by != 'price') { $sql .= ' ORDER BY ' . (isset($order_by_prefix) ? pSQL($order_by_prefix) . '.' : '') . pSQL($order_by) . ' ' . pSQL($order_way) . ' LIMIT ' . (int) (($page_number - 1) * $nb_products) . ', ' . (int) $nb_products; } $result = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($sql); if (!$result) { return false; } if ($order_by === 'price') { Tools::orderbyPrice($result, $order_way); $result = array_slice($result, (int) (($page_number - 1) * $nb_products), (int) $nb_products); } return Product::getProductsProperties($id_lang, $result); } /** * getProductCategories return an array of categories which this product belongs to. * * @param int|string $id_product Product identifier * * @return array Category identifiers */ public static function getProductCategories($id_product = '') { $cache_id = 'Product::getProductCategories_' . (int) $id_product; if (!Cache::isStored($cache_id)) { $ret = []; $row = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS( ' SELECT `id_category` FROM `' . _DB_PREFIX_ . 'category_product` WHERE `id_product` = ' . (int) $id_product ); if ($row) { foreach ($row as $val) { $ret[] = $val['id_category']; } } Cache::store($cache_id, $ret); return $ret; } return Cache::retrieve($cache_id); } /** * @param int|string $id_product Product identifier * @param int|null $id_lang Language identifier * * @return array */ public static function getProductCategoriesFull($id_product = '', $id_lang = null) { if (!$id_lang) { $id_lang = Context::getContext()->language->id; } $ret = []; $row = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS( ' SELECT cp.`id_category`, cl.`name`, cl.`link_rewrite` FROM `' . _DB_PREFIX_ . 'category_product` cp LEFT JOIN `' . _DB_PREFIX_ . 'category` c ON (c.id_category = cp.id_category) LEFT JOIN `' . _DB_PREFIX_ . 'category_lang` cl ON (cp.`id_category` = cl.`id_category`' . Shop::addSqlRestrictionOnLang('cl') . ') ' . Shop::addSqlAssociation('category', 'c') . ' WHERE cp.`id_product` = ' . (int) $id_product . ' AND cl.`id_lang` = ' . (int) $id_lang ); foreach ($row as $val) { $ret[$val['id_category']] = $val; } return $ret; } /** * getCategories return an array of categories which this product belongs to. * * @return array of categories */ public function getCategories() { return Product::getProductCategories($this->id); } /** * Gets carriers assigned to the product. * * @return array */ public function getCarriers() { return Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS(' SELECT c.* FROM `' . _DB_PREFIX_ . 'product_carrier` pc INNER JOIN `' . _DB_PREFIX_ . 'carrier` c ON (c.`id_reference` = pc.`id_carrier_reference` AND c.`deleted` = 0) WHERE pc.`id_product` = ' . (int) $this->id . ' AND pc.`id_shop` = ' . (int) $this->id_shop); } /** * Sets carriers assigned to the product. * * @param int[] $carrier_list */ public function setCarriers($carrier_list) { $data = []; foreach ($carrier_list as $carrier) { $data[] = [ 'id_product' => (int) $this->id, 'id_carrier_reference' => (int) $carrier, 'id_shop' => (int) $this->id_shop, ]; } Db::getInstance()->execute( 'DELETE FROM `' . _DB_PREFIX_ . 'product_carrier` WHERE id_product = ' . (int) $this->id . ' AND id_shop = ' . (int) $this->id_shop ); $unique_array = []; foreach ($data as $sub_array) { if (!in_array($sub_array, $unique_array)) { $unique_array[] = $sub_array; } } if (count($unique_array)) { Db::getInstance()->insert('product_carrier', $unique_array, false, true, Db::INSERT_IGNORE); } } /** * Get product images and legends. * * @param int $id_lang Language identifier * @param Context|null $context * * @return array Product images and legends */ public function getImages($id_lang, Context $context = null) { return Db::getInstance()->executeS( ' SELECT image_shop.`cover`, i.`id_image`, il.`legend`, i.`position` FROM `' . _DB_PREFIX_ . 'image` i ' . Shop::addSqlAssociation('image', 'i') . ' LEFT JOIN `' . _DB_PREFIX_ . 'image_lang` il ON (i.`id_image` = il.`id_image` AND il.`id_lang` = ' . (int) $id_lang . ') WHERE i.`id_product` = ' . (int) $this->id . ' ORDER BY `position`' ); } /** * Get product cover image. * * @param int $id_product Product identifier * @param Context|null $context * * @return array Product cover image */ public static function getCover($id_product, Context $context = null) { if (!$context) { $context = Context::getContext(); } $cache_id = 'Product::getCover_' . (int) $id_product . '-' . (int) $context->shop->id; if (!Cache::isStored($cache_id)) { $sql = 'SELECT image_shop.`id_image` FROM `' . _DB_PREFIX_ . 'image` i ' . Shop::addSqlAssociation('image', 'i') . ' WHERE i.`id_product` = ' . (int) $id_product . ' AND image_shop.`cover` = 1'; $result = Db::getInstance()->getRow($sql); Cache::store($cache_id, $result); return $result; } return Cache::retrieve($cache_id); } /** * Returns product price. * * @param int $id_product Product identifier * @param bool $usetax With taxes or not (optional) * @param int|null $id_product_attribute Attribute identifier (optional). * If set to false, do not apply the combination price impact. * NULL does apply the default combination price impact * @param int $decimals Number of decimals (optional) * @param int|null $divisor Useful when paying many time without fees (optional) * @param bool $only_reduc Returns only the reduction amount * @param bool $usereduc Set if the returned amount will include reduction * @param int $quantity Required for quantity discount application (default value: 1) * @param bool $force_associated_tax DEPRECATED - NOT USED Force to apply the associated tax. * Only works when the parameter $usetax is true * @param int|null $id_customer Customer identifier (for customer group reduction) * @param int|null $id_cart Cart identifier Required when the cookie is not accessible * (e.g., inside a payment module, a cron task...) * @param int|null $id_address Address identifier of Customer. Required for price (tax included) * calculation regarding the guest localization * @param array|null $specific_price_output If a specific price applies regarding the previous parameters, * this variable is filled with the corresponding SpecificPrice data * @param bool $with_ecotax insert ecotax in price output * @param bool $use_group_reduction * @param Context $context * @param bool $use_customer_price * @param int|null $id_customization Customization identifier * * @return float Product price */ public static function getPriceStatic( $id_product, $usetax = true, $id_product_attribute = null, $decimals = 6, $divisor = null, $only_reduc = false, $usereduc = true, $quantity = 1, $force_associated_tax = false, $id_customer = null, $id_cart = null, $id_address = null, &$specific_price_output = null, $with_ecotax = true, $use_group_reduction = true, Context $context = null, $use_customer_price = true, $id_customization = null ) { if (!$context) { $context = Context::getContext(); } $cur_cart = $context->cart; if ($divisor !== null) { Tools::displayParameterAsDeprecated('divisor'); } if (!Validate::isBool($usetax) || !Validate::isUnsignedId($id_product)) { die(Tools::displayError()); } // Initializations $id_group = null; if ($id_customer) { $id_group = Customer::getDefaultGroupId((int) $id_customer); } if (!$id_group) { $id_group = (int) Group::getCurrent()->id; } // If there is cart in context or if the specified id_cart is different from the context cart id if (!is_object($cur_cart) || (Validate::isUnsignedInt($id_cart) && $id_cart && $cur_cart->id != $id_cart)) { /* * When a user (e.g., guest, customer, Google...) is on PrestaShop, he has already its cart as the global (see /init.php) * When a non-user calls directly this method (e.g., payment module...) is on PrestaShop, he does not have already it BUT knows the cart ID * When called from the back office, cart ID can be inexistant */ if (!$id_cart && !isset($context->employee)) { die(Tools::displayError()); } $cur_cart = new Cart($id_cart); // Store cart in context to avoid multiple instantiations in BO if (!Validate::isLoadedObject($context->cart)) { $context->cart = $cur_cart; } } $cart_quantity = 0; if ((int) $id_cart) { $cache_id = 'Product::getPriceStatic_' . (int) $id_product . '-' . (int) $id_cart; if (!Cache::isStored($cache_id) || ($cart_quantity = Cache::retrieve($cache_id) != (int) $quantity)) { $sql = 'SELECT SUM(`quantity`) FROM `' . _DB_PREFIX_ . 'cart_product` WHERE `id_product` = ' . (int) $id_product . ' AND `id_cart` = ' . (int) $id_cart; $cart_quantity = (int) Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue($sql); Cache::store($cache_id, $cart_quantity); } else { $cart_quantity = Cache::retrieve($cache_id); } } $id_currency = Validate::isLoadedObject($context->currency) ? (int) $context->currency->id : (int) Configuration::get('PS_CURRENCY_DEFAULT'); if (!$id_address && Validate::isLoadedObject($cur_cart)) { $id_address = $cur_cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}; } // retrieve address informations $address = Address::initialize($id_address, true); $id_country = (int) $address->id_country; $id_state = (int) $address->id_state; $zipcode = $address->postcode; if (Tax::excludeTaxeOption()) { $usetax = false; } if ($usetax != false && !empty($address->vat_number) && $address->id_country != Configuration::get('VATNUMBER_COUNTRY') && Configuration::get('VATNUMBER_MANAGEMENT')) { $usetax = false; } if (null === $id_customer && Validate::isLoadedObject($context->customer)) { $id_customer = $context->customer->id; } $return = Product::priceCalculation( $context->shop->id, $id_product, $id_product_attribute, $id_country, $id_state, $zipcode, $id_currency, $id_group, $quantity, $usetax, $decimals, $only_reduc, $usereduc, $with_ecotax, $specific_price_output, $use_group_reduction, $id_customer, $use_customer_price, $id_cart, $cart_quantity, $id_customization ); return $return; } /** * Price calculation / Get product price. * * @param int $id_shop Shop identifier * @param int $id_product Product identifier * @param int $id_product_attribute Attribute identifier * @param int $id_country Country identifier * @param int $id_state State identifier * @param string $zipcode * @param int $id_currency Currency identifier * @param int $id_group Group identifier * @param int $quantity Quantity Required for Specific prices : quantity discount application * @param bool $use_tax with (1) or without (0) tax * @param int $decimals Number of decimals returned * @param bool $only_reduc Returns only the reduction amount * @param bool $use_reduc Set if the returned amount will include reduction * @param bool $with_ecotax insert ecotax in price output * @param array|null $specific_price If a specific price applies regarding the previous parameters, * this variable is filled with the corresponding SpecificPrice data * @param bool $use_group_reduction * @param int $id_customer Customer identifier * @param bool $use_customer_price * @param int $id_cart Cart identifier * @param int $real_quantity * @param int $id_customization Customization identifier * * @return float|void Product price, void if not found in cache $_pricesLevel2 */ public static function priceCalculation( $id_shop, $id_product, $id_product_attribute, $id_country, $id_state, $zipcode, $id_currency, $id_group, $quantity, $use_tax, $decimals, $only_reduc, $use_reduc, $with_ecotax, &$specific_price, $use_group_reduction, $id_customer = 0, $use_customer_price = true, $id_cart = 0, $real_quantity = 0, $id_customization = 0 ) { static $address = null; static $context = null; if ($context == null) { $context = Context::getContext()->cloneContext(); } if ($address === null) { if (is_object($context->cart) && $context->cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')} != null) { $id_address = $context->cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}; $address = new Address($id_address); } else { $address = new Address(); } } if ($id_shop !== null && $context->shop->id != (int) $id_shop) { $context->shop = new Shop((int) $id_shop); } if (!$use_customer_price) { $id_customer = 0; } if ($id_product_attribute === null) { $id_product_attribute = Product::getDefaultAttribute($id_product); } $cache_id = (int) $id_product . '-' . (int) $id_shop . '-' . (int) $id_currency . '-' . (int) $id_country . '-' . $id_state . '-' . $zipcode . '-' . (int) $id_group . '-' . (int) $quantity . '-' . (int) $id_product_attribute . '-' . (int) $id_customization . '-' . (int) $with_ecotax . '-' . (int) $id_customer . '-' . (int) $use_group_reduction . '-' . (int) $id_cart . '-' . (int) $real_quantity . '-' . ($only_reduc ? '1' : '0') . '-' . ($use_reduc ? '1' : '0') . '-' . ($use_tax ? '1' : '0') . '-' . (int) $decimals; // reference parameter is filled before any returns $specific_price = SpecificPrice::getSpecificPrice( (int) $id_product, $id_shop, $id_currency, $id_country, $id_group, $quantity, $id_product_attribute, $id_customer, $id_cart, $real_quantity ); if (isset(self::$_prices[$cache_id])) { return self::$_prices[$cache_id]; } // fetch price & attribute price $cache_id_2 = $id_product . '-' . $id_shop; // We need to check the cache for this price AND attribute, if absent the whole product cache needs update // This can happen if the cache was filled before the combination was created for example if (!isset(self::$_pricesLevel2[$cache_id_2][(int) $id_product_attribute])) { $sql = new DbQuery(); $sql->select('product_shop.`price`, product_shop.`ecotax`'); $sql->from('product', 'p'); $sql->innerJoin('product_shop', 'product_shop', '(product_shop.id_product=p.id_product AND product_shop.id_shop = ' . (int) $id_shop . ')'); $sql->where('p.`id_product` = ' . (int) $id_product); if (Combination::isFeatureActive()) { $sql->select('IFNULL(product_attribute_shop.id_product_attribute,0) id_product_attribute, product_attribute_shop.`price` AS attribute_price, product_attribute_shop.default_on, product_attribute_shop.`ecotax` AS attribute_ecotax'); $sql->leftJoin('product_attribute_shop', 'product_attribute_shop', '(product_attribute_shop.id_product = p.id_product AND product_attribute_shop.id_shop = ' . (int) $id_shop . ')'); } else { $sql->select('0 as id_product_attribute'); } $res = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($sql); if (is_array($res) && count($res)) { foreach ($res as $row) { $array_tmp = [ 'price' => $row['price'], 'ecotax' => $row['ecotax'], 'attribute_price' => $row['attribute_price'] ?? null, 'attribute_ecotax' => $row['attribute_ecotax'] ?? null, ]; self::$_pricesLevel2[$cache_id_2][(int) $row['id_product_attribute']] = $array_tmp; if (isset($row['default_on']) && $row['default_on'] == 1) { self::$_pricesLevel2[$cache_id_2][0] = $array_tmp; } } } } if (!isset(self::$_pricesLevel2[$cache_id_2][(int) $id_product_attribute])) { return; } $result = self::$_pricesLevel2[$cache_id_2][(int) $id_product_attribute]; // echo '
' . print_r( $specific_price , true) . ''; if (!$specific_price || $specific_price['price'] < 0) { $price = (float) $result['price']; } else { $price = (float) $specific_price['price']; } // convert only if the specific price is in the default currency (id_currency = 0) if ( !$specific_price || !( $specific_price['price'] >= 0 && $specific_price['id_currency'] && $id_currency !== $specific_price['id_currency'] ) ) { $price = Tools::convertPrice($price, $id_currency); if (isset($specific_price['price']) && $specific_price['price'] >= 0) { $specific_price['price'] = $price; } } // Attribute price if (is_array($result) && (!$specific_price || !$specific_price['id_product_attribute'] || $specific_price['price'] < 0)) { $attribute_price = Tools::convertPrice($result['attribute_price'] !== null ? (float) $result['attribute_price'] : 0, $id_currency); // If you want the default combination, please use NULL value instead if ($id_product_attribute !== false) { $price += $attribute_price; } } // Customization price if ((int) $id_customization) { $price += Tools::convertPrice(Customization::getCustomizationPrice($id_customization), $id_currency); } // Tax $address->id_country = $id_country; $address->id_state = $id_state; $address->postcode = $zipcode; $tax_manager = TaxManagerFactory::getManager($address, Product::getIdTaxRulesGroupByIdProduct((int) $id_product, $context)); $product_tax_calculator = $tax_manager->getTaxCalculator(); // Add Tax if ($use_tax) { $price = $product_tax_calculator->addTaxes($price); } // Eco Tax if (($result['ecotax'] || isset($result['attribute_ecotax'])) && $with_ecotax) { $ecotax = $result['ecotax']; if (isset($result['attribute_ecotax']) && $result['attribute_ecotax'] > 0) { $ecotax = $result['attribute_ecotax']; } if ($id_currency) { $ecotax = Tools::convertPrice($ecotax, $id_currency); } if ($use_tax) { if (self::$psEcotaxTaxRulesGroupId === null) { self::$psEcotaxTaxRulesGroupId = (int) Configuration::get('PS_ECOTAX_TAX_RULES_GROUP_ID'); } // reinit the tax manager for ecotax handling $tax_manager = TaxManagerFactory::getManager( $address, self::$psEcotaxTaxRulesGroupId ); $ecotax_tax_calculator = $tax_manager->getTaxCalculator(); $price += $ecotax_tax_calculator->addTaxes($ecotax); } else { $price += $ecotax; } } // Reduction $specific_price_reduction = 0; if (($only_reduc || $use_reduc) && $specific_price) { if ($specific_price['reduction_type'] == 'amount') { $reduction_amount = $specific_price['reduction']; if (!$specific_price['id_currency']) { $reduction_amount = Tools::convertPrice($reduction_amount, $id_currency); } $specific_price_reduction = $reduction_amount; // Adjust taxes if required if (!$use_tax && $specific_price['reduction_tax']) { $specific_price_reduction = $product_tax_calculator->removeTaxes($specific_price_reduction); } if ($use_tax && !$specific_price['reduction_tax']) { $specific_price_reduction = $product_tax_calculator->addTaxes($specific_price_reduction); } } else { $specific_price_reduction = $price * $specific_price['reduction']; } } if ($use_reduc) { $price -= $specific_price_reduction; } // Zaokrąglanie w górę tylko gdy mamy redukcję if ($specific_price && $specific_price['reduction'] > 0) { $price = Tools::ps_round($price); } // Group reduction if ($use_group_reduction) { $reduction_from_category = GroupReduction::getValueForProduct($id_product, $id_group); if ($reduction_from_category !== false) { $group_reduction = $price * (float) $reduction_from_category; } else { // apply group reduction if there is no group reduction for this category $group_reduction = (($reduc = Group::getReductionByIdGroup($id_group)) != 0) ? ($price * $reduc / 100) : 0; } $price -= $group_reduction; } if ($only_reduc) { return Tools::ps_round($specific_price_reduction, $decimals); } $price = Tools::ps_round($price, $decimals); if ($price < 0) { $price = 0; } self::$_prices[$cache_id] = $price; return self::$_prices[$cache_id]; } /** * @param int $orderId * @param int $productId * @param int $combinationId * @param bool $withTaxes * @param bool $useReduction * @param bool $withEcoTax * * @return float|null * * @throws PrestaShopDatabaseException */ public static function getPriceFromOrder( int $orderId, int $productId, int $combinationId, bool $withTaxes, bool $useReduction, bool $withEcoTax ): ?float { $sql = new DbQuery(); $sql->select('od.*, t.rate AS tax_rate'); $sql->from('order_detail', 'od'); $sql->where('od.`id_order` = ' . $orderId); $sql->where('od.`product_id` = ' . $productId); if (Combination::isFeatureActive()) { $sql->where('od.`product_attribute_id` = ' . $combinationId); } $sql->leftJoin('order_detail_tax', 'odt', 'odt.id_order_detail = od.id_order_detail'); $sql->leftJoin('tax', 't', 't.id_tax = odt.id_tax'); $res = Db::getInstance((bool) _PS_USE_SQL_SLAVE_)->executeS($sql); if (!is_array($res) || empty($res)) { return null; } $orderDetail = $res[0]; if ($useReduction) { // If we want price with reduction it is already the one stored in OrderDetail $price = $withTaxes ? $orderDetail['unit_price_tax_incl'] : $orderDetail['unit_price_tax_excl']; } else { // Without reduction we use the original product price to compute the original price $tax_rate = $withTaxes ? (1 + ($orderDetail['tax_rate'] / 100)) : 1; $price = $orderDetail['original_product_price'] * $tax_rate; } if (!$withEcoTax) { // Remove the ecotax as the order detail contains already ecotax in the price $price -= ($withTaxes ? $orderDetail['ecotax'] * (1 + $orderDetail['ecotax_tax_rate']) : $orderDetail['ecotax']); } return $price; } /** * @param float $price * @param Currency|false $currency * @param Context|null $context * * @return string */ public static function convertAndFormatPrice($price, $currency = false, Context $context = null) { if (!$context) { $context = Context::getContext(); } if (!$currency) { $currency = $context->currency; } return $context->getCurrentLocale()->formatPrice(Tools::convertPrice($price, $currency), $currency->iso_code); } /** * @param int $id_product Product identifier * @param int $quantity * @param Context|null $context * * @return bool */ public static function isDiscounted($id_product, $quantity = 1, Context $context = null) { if (!$context) { $context = Context::getContext(); } $id_group = $context->customer->id_default_group; $cart_quantity = !$context->cart ? 0 : Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue( ' SELECT SUM(`quantity`) FROM `' . _DB_PREFIX_ . 'cart_product` WHERE `id_product` = ' . (int) $id_product . ' AND `id_cart` = ' . (int) $context->cart->id ); $quantity = $cart_quantity ? $cart_quantity : $quantity; $id_currency = (int) $context->currency->id; $ids = Address::getCountryAndState((int) $context->cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}); $id_country = (int) ($ids['id_country'] ?? Configuration::get('PS_COUNTRY_DEFAULT')); return (bool) SpecificPrice::getSpecificPrice((int) $id_product, $context->shop->id, $id_currency, $id_country, $id_group, $quantity, null, 0, 0, $quantity); } /** * Get product price * Same as static function getPriceStatic, no need to specify product id. * * @param bool $tax With taxes or not (optional) * @param int|null $id_product_attribute Attribute identifier * @param int $decimals Number of decimals * @param int|null $divisor Util when paying many time without fees * @param bool $only_reduc * @param bool $usereduc * @param int $quantity * * @return float Product price in euros */ public function getPrice( $tax = true, $id_product_attribute = null, $decimals = 6, $divisor = null, $only_reduc = false, $usereduc = true, $quantity = 1 ) { return Product::getPriceStatic((int) $this->id, $tax, $id_product_attribute, $decimals, $divisor, $only_reduc, $usereduc, $quantity); } /** * @param bool $tax With taxes or not (optional) * @param int|null $id_product_attribute Attribute identifier * @param int $decimals Number of decimals * @param null $divisor Util when paying many time without fees * @param bool $only_reduc * @param bool $usereduc * @param int $quantity * * @return float */ public function getPublicPrice( $tax = true, $id_product_attribute = null, $decimals = 6, $divisor = null, $only_reduc = false, $usereduc = true, $quantity = 1 ) { $specific_price_output = null; return Product::getPriceStatic( (int) $this->id, $tax, $id_product_attribute, $decimals, $divisor, $only_reduc, $usereduc, $quantity, false, null, null, null, $specific_price_output, true, true, null, false ); } /** * @return int */ public function getIdProductAttributeMostExpensive() { if (!Combination::isFeatureActive()) { return 0; } return (int) Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue(' SELECT pa.`id_product_attribute` FROM `' . _DB_PREFIX_ . 'product_attribute` pa ' . Shop::addSqlAssociation('product_attribute', 'pa') . ' WHERE pa.`id_product` = ' . (int) $this->id . ' ORDER BY product_attribute_shop.`price` DESC'); } /** * @return int */ public function getDefaultIdProductAttribute() { if (!Combination::isFeatureActive()) { return 0; } return (int) Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue( ' SELECT pa.`id_product_attribute` FROM `' . _DB_PREFIX_ . 'product_attribute` pa ' . Shop::addSqlAssociation('product_attribute', 'pa') . ' WHERE pa.`id_product` = ' . (int) $this->id . ' AND product_attribute_shop.default_on = 1' ); } /** * @param bool $notax With taxes or not (optional) * @param int|null $id_product_attribute Attribute identifier * @param int $decimals Number of decimals * * @return float */ public function getPriceWithoutReduct($notax = false, $id_product_attribute = null, $decimals = 6) { return Product::getPriceStatic((int) $this->id, !$notax, $id_product_attribute, $decimals, null, false, false); } /** * Display price with right format and currency. * * @param array $params Params * @param object $smarty Smarty object (DEPRECATED) * * @return string Price with right format and currency */ public static function convertPrice($params, &$smarty) { return Context::getContext()->getCurrentLocale()->formatPrice($params['price'], Context::getContext()->currency->iso_code); } /** * Convert price with currency. * * @param array $params * @param object $smarty Smarty object (DEPRECATED) * * @return string Ambigous