Пример #1
1
    /**
     * Get product accessories
     *
     * @param integer $id_lang Language id
     * @return array Product accessories
     */
    public static function getItems($iIdProduct, $id_lang, $active = true, Context $context = null)
    {
        if (!$context) {
            $context = Context::getContext();
        }
        $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`,
					MAX(image_shop.`id_image`) id_image, il.`legend`, m.`name` as manufacturer_name, cl.`name` AS category_default,
					DATEDIFF(
						p.`date_add`,
						DATE_SUB(
							NOW(),
							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_ . 'now_ideas_or_tips`
				LEFT JOIN `' . _DB_PREFIX_ . 'product` p ON p.`id_product` = `id_product_2`
				' . Shop::addSqlAssociation('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') . '
				)
				LEFT JOIN `' . _DB_PREFIX_ . 'category_lang` cl ON (
					product_shop.`id_category_default` = cl.`id_category`
					AND cl.`id_lang` = ' . (int) $id_lang . Shop::addSqlRestrictionOnLang('cl') . '
				)
				LEFT JOIN `' . _DB_PREFIX_ . 'image` i ON (i.`id_product` = p.`id_product`)' . Shop::addSqlAssociation('image', 'i', false, 'image_shop.cover=1') . '
				LEFT JOIN `' . _DB_PREFIX_ . 'image_lang` il ON (i.`id_image` = il.`id_image` AND il.`id_lang` = ' . (int) $id_lang . ')
				LEFT JOIN `' . _DB_PREFIX_ . 'manufacturer` m ON (p.`id_manufacturer`= m.`id_manufacturer`)
				' . Product::sqlStock('p', 0) . '
				WHERE `id_product_1` = ' . (int) $iIdProduct . ($active ? ' AND product_shop.`active` = 1 AND product_shop.`visibility` != \'none\'' : '') . '
				GROUP BY product_shop.id_product';
        if (!($result = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($sql))) {
            return false;
        }
        foreach ($result as &$row) {
            $row['id_product_attribute'] = Product::getDefaultAttribute((int) $row['id_product']);
        }
        return Product::getProductsProperties($id_lang, $result);
    }
Пример #2
0
 /**
  * For a given id_product and id_product_attribute updates the quantity available
  *
  * @param int $id_product
  * @param int $id_product_attribute Optional
  * @param int $delta_quantity The delta quantity to update
  * @param int $id_shop Optional
  */
 public static function updateQuantity($id_product, $id_product_attribute, $delta_quantity, $id_shop = null)
 {
     if (!Validate::isUnsignedId($id_product)) {
         return false;
     }
     $id_stock_available = StockAvailable::getStockAvailableIdByProductId($id_product, $id_product_attribute, $id_shop);
     if (!$id_stock_available) {
         return false;
     }
     // Update quantity of the pack products
     if (Pack::isPack($id_product)) {
         $products_pack = Pack::getItems($id_product, (int) Configuration::get('PS_LANG_DEFAULT'));
         foreach ($products_pack as $product_pack) {
             $pack_id_product_attribute = Product::getDefaultAttribute($product_pack->id, 1);
             StockAvailable::updateQuantity($product_pack->id, $pack_id_product_attribute, $product_pack->pack_quantity * $delta_quantity, $id_shop);
         }
     }
     $stock_available = new StockAvailable($id_stock_available);
     $stock_available->quantity = $stock_available->quantity + $delta_quantity;
     $stock_available->update();
     Hook::exec('actionUpdateQuantity', array('id_product' => $id_product, 'id_product_attribute' => $id_product_attribute, 'quantity' => $stock_available->quantity));
 }
Пример #3
0
 public static function calcProductDisplayPrice($product, $product_properties = null, $price = null, $mode = null)
 {
     $key = null;
     $product_object = self::productAsObject($product);
     if ($product_object != null) {
         if ($product_properties === null) {
             $product_properties = PP::getProductProperties($product_object);
         }
         $display_retail_price = ($product_properties['pp_display_mode'] & 2) == 2 && (($product_properties['pp_display_mode'] & 1) == 1 && $mode != 'unit_price' || !(($product_properties['pp_display_mode'] & 1) == 1) && $mode == 'unit_price');
         if ($display_retail_price) {
             $price = Product::getRetailPrice($product_object);
         } elseif (($product_properties['pp_display_mode'] & 1) == 1) {
             if ($product_object->unit_price_ratio > 0) {
                 if ($price === null) {
                     $price = self::calcProductPrice($product_object);
                 }
                 if ($mode == 'unit_price') {
                     $price = Tools::ps_round((double) $price * $product_object->unit_price_ratio, _PS_PRICE_COMPUTE_PRECISION_);
                 } else {
                     if (is_array($product) && isset($product['price_tax_exc']) && $product['price_tax_exc'] > 0 && round($price, 8) > round($product['price_tax_exc'], 8)) {
                         $tax = $price / $product['price_tax_exc'];
                     }
                     // we use $product_object->price because unit price is calculated based on the base price, without attribute impact on the price
                     $price = Tools::ps_round($product_object->price / $product_object->unit_price_ratio, _PS_PRICE_COMPUTE_PRECISION_);
                     if (($attribute = Product::getDefaultAttribute($product_object->id)) > 0) {
                         $combination = $product_object->getAttributeCombinationsById($attribute, Context::getContext()->language->id);
                         $price += Tools::ps_round($combination[0]['unit_price_impact'], _PS_PRICE_COMPUTE_PRECISION_);
                     }
                     if (isset($tax)) {
                         $price = Tools::ps_round($price * $tax, _PS_PRICE_COMPUTE_PRECISION_);
                     }
                 }
             }
         }
         if (($product_properties['pp_display_mode'] & 1) == 1) {
             if ($mode == 'unit_price') {
                 if (!empty($product_properties['pp_price_text'])) {
                     $key = 'pp_price_text';
                 }
             } else {
                 if (!empty($product_properties['pp_unity_text'])) {
                     $key = 'pp_unity_text';
                 }
             }
         } else {
             if ($mode == 'unit_price') {
                 if (!empty($product_properties['pp_unity_text'])) {
                     $key = 'pp_unity_text';
                 }
             } else {
                 if (!empty($product_properties['pp_price_text'])) {
                     $key = 'pp_price_text';
                 }
             }
         }
         if ($price === null) {
             $price = self::calcProductPrice($product_object);
         }
     }
     return array($key, $price);
 }
Пример #4
0
    /**
     * @see StockManagerInterface::removeProduct()
     */
    public function removeProduct($id_product, $id_product_attribute = null, Warehouse $warehouse, $quantity, $id_stock_mvt_reason, $is_usable = true, $id_order = null)
    {
        $return = array();
        if (!Validate::isLoadedObject($warehouse) || !$quantity || !$id_product) {
            return $return;
        }
        if (!StockMvtReason::exists($id_stock_mvt_reason)) {
            $id_stock_mvt_reason = Configuration::get('PS_STOCK_MVT_DEC_REASON_DEFAULT');
        }
        $context = Context::getContext();
        // Special case of a pack
        if (Pack::isPack((int) $id_product)) {
            // Gets items
            $products_pack = Pack::getItems((int) $id_product, (int) Configuration::get('PS_LANG_DEFAULT'));
            // Foreach item
            foreach ($products_pack as $product_pack) {
                $pack_id_product_attribute = Product::getDefaultAttribute($product_pack->id, 1);
                if ($product_pack->advanced_stock_management == 1) {
                    $this->removeProduct($product_pack->id, $pack_id_product_attribute, $warehouse, $product_pack->pack_quantity * $quantity, $id_stock_mvt_reason, $is_usable, $id_order);
                }
            }
        } else {
            // gets total quantities in stock for the current product
            $physical_quantity_in_stock = (int) $this->getProductPhysicalQuantities($id_product, $id_product_attribute, array($warehouse->id), false);
            $usable_quantity_in_stock = (int) $this->getProductPhysicalQuantities($id_product, $id_product_attribute, array($warehouse->id), true);
            // check quantity if we want to decrement unusable quantity
            if (!$is_usable) {
                $quantity_in_stock = $physical_quantity_in_stock - $usable_quantity_in_stock;
            } else {
                $quantity_in_stock = $usable_quantity_in_stock;
            }
            // checks if it's possible to remove the given quantity
            if ($quantity_in_stock < $quantity) {
                return $return;
            }
            $stock_collection = $this->getStockCollection($id_product, $id_product_attribute, $warehouse->id);
            $stock_collection->getAll();
            // check if the collection is loaded
            if (count($stock_collection) <= 0) {
                return $return;
            }
            $stock_history_qty_available = array();
            $mvt_params = array();
            $stock_params = array();
            $quantity_to_decrement_by_stock = array();
            $global_quantity_to_decrement = $quantity;
            // switch on MANAGEMENT_TYPE
            switch ($warehouse->management_type) {
                // case CUMP mode
                case 'WA':
                    // There is one and only one stock for a given product in a warehouse in this mode
                    $stock = $stock_collection->current();
                    $mvt_params = array('id_stock' => $stock->id, 'physical_quantity' => $quantity, 'id_stock_mvt_reason' => $id_stock_mvt_reason, 'id_order' => $id_order, 'price_te' => $stock->price_te, 'last_wa' => $stock->price_te, 'current_wa' => $stock->price_te, 'id_employee' => $context->employee->id, 'employee_firstname' => $context->employee->firstname, 'employee_lastname' => $context->employee->lastname, 'sign' => -1);
                    $stock_params = array('physical_quantity' => $stock->physical_quantity - $quantity, 'usable_quantity' => $is_usable ? $stock->usable_quantity - $quantity : $stock->usable_quantity);
                    // saves stock in warehouse
                    $stock->hydrate($stock_params);
                    $stock->update();
                    // saves stock mvt
                    $stock_mvt = new StockMvt();
                    $stock_mvt->hydrate($mvt_params);
                    $stock_mvt->save();
                    $return[$stock->id]['quantity'] = $quantity;
                    $return[$stock->id]['price_te'] = $stock->price_te;
                    break;
                case 'LIFO':
                case 'FIFO':
                    // for each stock, parse its mvts history to calculate the quantities left for each positive mvt,
                    // according to the instant available quantities for this stock
                    foreach ($stock_collection as $stock) {
                        $left_quantity_to_check = $stock->physical_quantity;
                        if ($left_quantity_to_check <= 0) {
                            continue;
                        }
                        $resource = Db::getInstance(_PS_USE_SQL_SLAVE_)->query('
							SELECT sm.`id_stock_mvt`, sm.`date_add`, sm.`physical_quantity`,
								IF ((sm2.`physical_quantity` is null), sm.`physical_quantity`, (sm.`physical_quantity` - SUM(sm2.`physical_quantity`))) as qty
							FROM `' . _DB_PREFIX_ . 'stock_mvt` sm
							LEFT JOIN `' . _DB_PREFIX_ . 'stock_mvt` sm2 ON sm2.`referer` = sm.`id_stock_mvt`
							WHERE sm.`sign` = 1
							AND sm.`id_stock` = ' . (int) $stock->id . '
							GROUP BY sm.`id_stock_mvt`
							ORDER BY sm.`date_add` DESC');
                        while ($row = Db::getInstance()->nextRow($resource)) {
                            // break - in FIFO mode, we have to retreive the oldest positive mvts for which there are left quantities
                            if ($warehouse->management_type == 'FIFO') {
                                if ($row['qty'] == 0) {
                                    break;
                                }
                            }
                            // converts date to timestamp
                            $date = new DateTime($row['date_add']);
                            $timestamp = $date->format('U');
                            // history of the mvt
                            $stock_history_qty_available[$timestamp] = array('id_stock' => $stock->id, 'id_stock_mvt' => (int) $row['id_stock_mvt'], 'qty' => (int) $row['qty']);
                            // break - in LIFO mode, checks only the necessary history to handle the global quantity for the current stock
                            if ($warehouse->management_type == 'LIFO') {
                                $left_quantity_to_check -= (int) $row['physical_quantity'];
                                if ($left_quantity_to_check <= 0) {
                                    break;
                                }
                            }
                        }
                    }
                    if ($warehouse->management_type == 'LIFO') {
                        // orders stock history by timestamp to get newest history first
                        krsort($stock_history_qty_available);
                    } else {
                        // orders stock history by timestamp to get oldest history first
                        ksort($stock_history_qty_available);
                    }
                    // checks each stock to manage the real quantity to decrement for each of them
                    foreach ($stock_history_qty_available as $entry) {
                        if ($entry['qty'] >= $global_quantity_to_decrement) {
                            $quantity_to_decrement_by_stock[$entry['id_stock']][$entry['id_stock_mvt']] = $global_quantity_to_decrement;
                            $global_quantity_to_decrement = 0;
                        } else {
                            $quantity_to_decrement_by_stock[$entry['id_stock']][$entry['id_stock_mvt']] = $entry['qty'];
                            $global_quantity_to_decrement -= $entry['qty'];
                        }
                        if ($global_quantity_to_decrement <= 0) {
                            break;
                        }
                    }
                    // for each stock, decrements it and logs the mvts
                    foreach ($stock_collection as $stock) {
                        if (array_key_exists($stock->id, $quantity_to_decrement_by_stock) && is_array($quantity_to_decrement_by_stock[$stock->id])) {
                            $total_quantity_for_current_stock = 0;
                            foreach ($quantity_to_decrement_by_stock[$stock->id] as $id_mvt_referrer => $qte) {
                                $mvt_params = array('id_stock' => $stock->id, 'physical_quantity' => $qte, 'id_stock_mvt_reason' => $id_stock_mvt_reason, 'id_order' => $id_order, 'price_te' => $stock->price_te, 'sign' => -1, 'referer' => $id_mvt_referrer, 'id_employee' => $context->employee->id);
                                // saves stock mvt
                                $stock_mvt = new StockMvt();
                                $stock_mvt->hydrate($mvt_params);
                                $stock_mvt->save();
                                $total_quantity_for_current_stock += $qte;
                            }
                            $stock_params = array('physical_quantity' => $stock->physical_quantity - $total_quantity_for_current_stock, 'usable_quantity' => $is_usable ? $stock->usable_quantity - $total_quantity_for_current_stock : $stock->usable_quantity);
                            $return[$stock->id]['quantity'] = $total_quantity_for_current_stock;
                            $return[$stock->id]['price_te'] = $stock->price_te;
                            // saves stock in warehouse
                            $stock->hydrate($stock_params);
                            $stock->update();
                        }
                    }
                    break;
            }
        }
        // if we remove a usable quantity, exec hook
        if ($is_usable) {
            Hook::exec('actionProductCoverage', array('id_product' => $id_product, 'id_product_attribute' => $id_product_attribute, 'warehouse' => $warehouse));
        }
        return $return;
    }
Пример #5
0
 /**
  * This process add or update a product in the cart
  */
 protected function processChangeProductInCart()
 {
     $mode = Tools::getIsset('update') && $this->id_product ? 'update' : 'add';
     if ($this->qty == 0) {
         $this->errors[] = Tools::displayError('Null quantity.', !Tools::getValue('ajax'));
     } elseif (!$this->id_product) {
         $this->errors[] = Tools::displayError('Product not found', !Tools::getValue('ajax'));
     }
     $product = new Product($this->id_product, true, $this->context->language->id);
     if (!$product->id || !$product->active || !$product->checkAccess($this->context->cart->id_customer)) {
         $this->errors[] = Tools::displayError('This product is no longer available.', !Tools::getValue('ajax'));
         return;
     }
     $qty_to_check = $this->qty;
     $cart_products = $this->context->cart->getProducts();
     if (is_array($cart_products)) {
         foreach ($cart_products as $cart_product) {
             if ((!isset($this->id_product_attribute) || $cart_product['id_product_attribute'] == $this->id_product_attribute) && (isset($this->id_product) && $cart_product['id_product'] == $this->id_product)) {
                 $qty_to_check = $cart_product['cart_quantity'];
                 if (Tools::getValue('op', 'up') == 'down') {
                     $qty_to_check -= $this->qty;
                 } else {
                     $qty_to_check += $this->qty;
                 }
                 break;
             }
         }
     }
     // Check product quantity availability
     if ($this->id_product_attribute) {
         if (!Product::isAvailableWhenOutOfStock($product->out_of_stock) && !Attribute::checkAttributeQty($this->id_product_attribute, $qty_to_check)) {
             $this->errors[] = Tools::displayError('There isn\'t enough product in stock.', !Tools::getValue('ajax'));
         }
     } elseif ($product->hasAttributes()) {
         $minimumQuantity = $product->out_of_stock == 2 ? !Configuration::get('PS_ORDER_OUT_OF_STOCK') : !$product->out_of_stock;
         $this->id_product_attribute = Product::getDefaultAttribute($product->id, $minimumQuantity);
         // @todo do something better than a redirect admin !!
         if (!$this->id_product_attribute) {
             Tools::redirectAdmin($this->context->link->getProductLink($product));
         } elseif (!Product::isAvailableWhenOutOfStock($product->out_of_stock) && !Attribute::checkAttributeQty($this->id_product_attribute, $qty_to_check)) {
             $this->errors[] = Tools::displayError('There isn\'t enough product in stock.', !Tools::getValue('ajax'));
         }
     } elseif (!$product->checkQty($qty_to_check)) {
         $this->errors[] = Tools::displayError('There isn\'t enough product in stock.', !Tools::getValue('ajax'));
     }
     // If no errors, process product addition
     if (!$this->errors && $mode == 'add') {
         // Add cart if no cart found
         if (!$this->context->cart->id) {
             if (Context::getContext()->cookie->id_guest) {
                 $guest = new Guest(Context::getContext()->cookie->id_guest);
                 $this->context->cart->mobile_theme = $guest->mobile_theme;
             }
             $this->context->cart->add();
             if ($this->context->cart->id) {
                 $this->context->cookie->id_cart = (int) $this->context->cart->id;
             }
         }
         // Check customizable fields
         if (!$product->hasAllRequiredCustomizableFields() && !$this->customization_id) {
             $this->errors[] = Tools::displayError('Please fill in all of the required fields, and then save your customizations.', !Tools::getValue('ajax'));
         }
         if (!$this->errors) {
             $cart_rules = $this->context->cart->getCartRules();
             $available_cart_rules = CartRule::getCustomerCartRules($this->context->language->id, isset($this->context->customer->id) ? $this->context->customer->id : 0, true, true, true, $this->context->cart, false, true);
             $update_quantity = $this->context->cart->updateQty($this->qty, $this->id_product, $this->id_product_attribute, $this->customization_id, Tools::getValue('op', 'up'), $this->id_address_delivery);
             if ($update_quantity < 0) {
                 // If product has attribute, minimal quantity is set with minimal quantity of attribute
                 $minimal_quantity = $this->id_product_attribute ? Attribute::getAttributeMinimalQty($this->id_product_attribute) : $product->minimal_quantity;
                 $this->errors[] = sprintf(Tools::displayError('You must add %d minimum quantity', !Tools::getValue('ajax')), $minimal_quantity);
             } elseif (!$update_quantity) {
                 $this->errors[] = Tools::displayError('You already have the maximum quantity available for this product.', !Tools::getValue('ajax'));
             } elseif ((int) Tools::getValue('allow_refresh')) {
                 // If the cart rules has changed, we need to refresh the whole cart
                 $cart_rules2 = $this->context->cart->getCartRules();
                 if (count($cart_rules2) != count($cart_rules)) {
                     $this->ajax_refresh = true;
                 } elseif (count($cart_rules2)) {
                     $rule_list = array();
                     foreach ($cart_rules2 as $rule) {
                         $rule_list[] = $rule['id_cart_rule'];
                     }
                     foreach ($cart_rules as $rule) {
                         if (!in_array($rule['id_cart_rule'], $rule_list)) {
                             $this->ajax_refresh = true;
                             break;
                         }
                     }
                 } else {
                     $available_cart_rules2 = CartRule::getCustomerCartRules($this->context->language->id, isset($this->context->customer->id) ? $this->context->customer->id : 0, true, true, true, $this->context->cart, false, true);
                     if (count($available_cart_rules2) != count($available_cart_rules)) {
                         $this->ajax_refresh = true;
                     } elseif (count($available_cart_rules2)) {
                         $rule_list = array();
                         foreach ($available_cart_rules2 as $rule) {
                             $rule_list[] = $rule['id_cart_rule'];
                         }
                         foreach ($cart_rules2 as $rule) {
                             if (!in_array($rule['id_cart_rule'], $rule_list)) {
                                 $this->ajax_refresh = true;
                                 break;
                             }
                         }
                     }
                 }
             }
         }
     }
     $removed = CartRule::autoRemoveFromCart();
     CartRule::autoAddToCart();
     if (count($removed) && (int) Tools::getValue('allow_refresh')) {
         $this->ajax_refresh = true;
     }
 }
Пример #6
0
    public static function buildXML()
    {
        global $country_infos;
        $context = Context::getContext();
        $country_infos = array('id_group' => 0, 'id_tax' => 1);
        $html = '<products>' . "\n";
        /* First line, columns */
        $columns = array('id', 'name', 'smallimage', 'bigimage', 'producturl', 'description', 'price', 'retailprice', 'discount', 'recommendable', 'instock');
        /* Setting parameters */
        $conf = Configuration::getMultiple(array('PS_REWRITING_SETTINGS', 'PS_LANG_DEFAULT', 'PS_SHIPPING_FREE_PRICE', 'PS_SHIPPING_HANDLING', 'PS_SHIPPING_METHOD', 'PS_SHIPPING_FREE_WEIGHT', 'PS_COUNTRY_DEFAULT', 'PS_SHOP_NAME', 'PS_CURRENCY_DEFAULT', 'PS_CARRIER_DEFAULT'));
        /* Searching for products */
        $result = Db::getInstance()->executeS('
		SELECT DISTINCT p.`id_product`, i.`id_image`
		FROM `' . _DB_PREFIX_ . 'product` p
		JOIN `' . _DB_PREFIX_ . 'category_product` cp ON (cp.id_product = p.id_product)
		LEFT JOIN `' . _DB_PREFIX_ . 'image` i ON (i.id_product = p.id_product)
		WHERE p.`active` = 1 AND i.id_image IS NOT NULL
		GROUP BY p.id_product');
        foreach ($result as $k => $row) {
            if (Pack::isPack(intval($row['id_product']))) {
                continue;
            }
            $product = new Product(intval($row['id_product']), true);
            if (Validate::isLoadedObject($product)) {
                $imageObj = new Image($row['id_image']);
                $imageObj->id_product = intval($product->id);
                $line = array();
                $line[] = $product->manufacturer_name . ' - ' . $product->name[intval($conf['PS_LANG_DEFAULT'])];
                $line[] = Tools::getProtocol() . $_SERVER['HTTP_HOST'] . _THEME_PROD_DIR_ . $imageObj->getExistingImgPath() . '-small.jpg';
                $line[] = Tools::getProtocol() . $_SERVER['HTTP_HOST'] . _THEME_PROD_DIR_ . $imageObj->getExistingImgPath() . '-thickbox.jpg';
                $line[] = $context->link->getProductLink(intval($product->id), $product->link_rewrite[intval($conf['PS_LANG_DEFAULT'])], $product->ean13) . '&utm_source=criteo&aff=criteo';
                $line[] = str_replace(array("\n", "\r", "\t", '|'), '', strip_tags(html_entity_decode($product->description_short[intval($conf['PS_LANG_DEFAULT'])], ENT_COMPAT, 'UTF-8')));
                $price = $product->getPrice(true, intval(Product::getDefaultAttribute($product->id)));
                $line[] = number_format($price, 2, '.', '');
                $line[] = number_format($product->getPrice(true, intval(Product::getDefaultAttribute(intval($product->id))), 6, NULL, false, false), 2, '.', '');
                $line[] = $product->getPrice(true, NULL, 2, NULL, true);
                $line[] = '1';
                $line[] = '1';
                $cptXML = 1;
                $html .= "\t" . '<product id="' . $product->id . '">' . "\n";
                foreach ($line as $column) {
                    $html .= "\t\t" . '<' . $columns[$cptXML] . '>' . $column . '</' . $columns[$cptXML] . '>' . "\n";
                    $cptXML++;
                }
                $html .= "\t" . '</product>' . "\n";
            }
        }
        $html .= '</products>' . "\n";
        echo $html;
    }
Пример #7
0
 public static function getProductProperties($id_lang, $row)
 {
     if (!$row['id_product']) {
         return false;
     }
     // Product::getDefaultAttribute is only called if id_product_attribute is missing from the SQL query at the origin of it: consider adding it in order to avoid unnecessary queries
     $row['allow_oosp'] = Product::isAvailableWhenOutOfStock($row['out_of_stock']);
     if ((!isset($row['id_product_attribute']) or !$row['id_product_attribute']) and (isset($row['cache_default_attribute']) and ($ipa_default = $row['cache_default_attribute']) !== NULL or $ipa_default = Product::getDefaultAttribute($row['id_product'], !$row['allow_oosp']))) {
         $row['id_product_attribute'] = $ipa_default;
     }
     if (!isset($row['id_product_attribute'])) {
         $row['id_product_attribute'] = 0;
     }
     // Tax
     $usetax = Tax::excludeTaxeOption();
     $cacheKey = $row['id_product'] . '-' . $row['id_product_attribute'] . '-' . $id_lang . '-' . (int) $usetax;
     if (array_key_exists($cacheKey, self::$producPropertiesCache)) {
         return self::$producPropertiesCache[$cacheKey];
     }
     // Datas
     $link = new Link();
     $row['category'] = Category::getLinkRewrite((int) $row['id_category_default'], (int) $id_lang);
     $row['link'] = $link->getProductLink((int) $row['id_product'], $row['link_rewrite'], $row['category'], $row['ean13']);
     $row['attribute_price'] = (isset($row['id_product_attribute']) and $row['id_product_attribute']) ? (double) Product::getProductAttributePrice($row['id_product_attribute']) : 0;
     $row['price_tax_exc'] = Product::getPriceStatic((int) $row['id_product'], false, (isset($row['id_product_attribute']) and !empty($row['id_product_attribute'])) ? (int) $row['id_product_attribute'] : NULL, self::$_taxCalculationMethod == PS_TAX_EXC ? 2 : 6);
     if (self::$_taxCalculationMethod == PS_TAX_EXC) {
         $row['price_tax_exc'] = Tools::ps_round($row['price_tax_exc'], 2);
         $row['price'] = Product::getPriceStatic((int) $row['id_product'], true, (isset($row['id_product_attribute']) and !empty($row['id_product_attribute'])) ? (int) $row['id_product_attribute'] : NULL, 6);
         $row['price_without_reduction'] = Product::getPriceStatic((int) $row['id_product'], false, (isset($row['id_product_attribute']) and !empty($row['id_product_attribute'])) ? (int) $row['id_product_attribute'] : NULL, 2, NULL, false, false);
     } else {
         $row['price'] = Tools::ps_round(Product::getPriceStatic((int) $row['id_product'], true, (isset($row['id_product_attribute']) and !empty($row['id_product_attribute'])) ? (int) $row['id_product_attribute'] : NULL, 2), 2);
         $row['price_without_reduction'] = Product::getPriceStatic((int) $row['id_product'], true, (isset($row['id_product_attribute']) and !empty($row['id_product_attribute'])) ? (int) $row['id_product_attribute'] : NULL, 6, NULL, false, false);
     }
     $row['reduction'] = Product::getPriceStatic((int) $row['id_product'], (bool) $usetax, (int) $row['id_product_attribute'], 6, NULL, true, true, 1, true, NULL, NULL, NULL, $specific_prices);
     $row['specific_prices'] = $specific_prices;
     if ($row['id_product_attribute']) {
         $row['quantity_all_versions'] = $row['quantity'];
         $row['quantity'] = Product::getQuantity((int) $row['id_product'], $row['id_product_attribute'], isset($row['cache_is_pack']) ? $row['cache_is_pack'] : NULL);
     }
     $row['id_image'] = Product::defineProductImage($row, $id_lang);
     $row['features'] = Product::getFrontFeaturesStatic((int) $id_lang, $row['id_product']);
     $row['attachments'] = (!isset($row['cache_has_attachments']) or $row['cache_has_attachments']) ? Product::getAttachmentsStatic((int) $id_lang, $row['id_product']) : array();
     // Pack management
     $row['pack'] = !isset($row['cache_is_pack']) ? Pack::isPack($row['id_product']) : (int) $row['cache_is_pack'];
     $row['packItems'] = $row['pack'] ? Pack::getItemTable($row['id_product'], $id_lang) : array();
     $row['nopackprice'] = $row['pack'] ? Pack::noPackPrice($row['id_product']) : 0;
     if ($row['pack'] and !Pack::isInStock($row['id_product'])) {
         $row['quantity'] = 0;
     }
     self::$producPropertiesCache[$cacheKey] = $row;
     return self::$producPropertiesCache[$cacheKey];
 }
Пример #8
0
 public function hookDisplayProductPriceBlock($params)
 {
     if (!isset($params['product'])) {
         return;
     }
     if ($params['product'] instanceof Product) {
         $id_product = (int) $params['product']->id;
     } else {
         $id_product = (int) $params['product']['id_product'];
     }
     $cache_key = $this->name . '_' . $params['type'] . '_' . $id_product;
     if (!$this->isCached('displayProductPriceBlock.tpl', $this->getCacheId($cache_key))) {
         $weight = 0;
         $combination_weight = 0;
         $id_product = 0;
         $allow_oosp = 0;
         if ($params['product'] instanceof Product) {
             $id_product_attribute = Product::getDefaultAttribute($id_product);
             $weight = (double) $params['product']->weight;
             $allow_oosp = $params['product']->isAvailableWhenOutOfStock((int) $params['product']->out_of_stock);
         } else {
             $id_product_attribute = Product::getDefaultAttribute($id_product);
             if (!isset($params['product']['weight'])) {
                 $product = new Product((int) $id_product);
                 $params['product']['weight'] = $product->weight;
             }
             $weight = (double) $params['product']['weight'];
             $allow_oosp = $params['product']['allow_oosp'];
         }
         if ($id_product_attribute) {
             $combination = new Combination($id_product_attribute);
             $combination_weight = $combination->weight;
         }
         $this->smarty->assign(array('is_object' => (bool) ($params['product'] instanceof Product), 'product' => $params['product'], 'weight' => $weight, 'allow_oosp' => $allow_oosp, 'combination_weight' => $combination_weight, 'priceDisplay' => Product::getTaxCalculationMethod((int) $this->context->cookie->id_customer), 'priceDisplayPrecision' => _PS_PRICE_DISPLAY_PRECISION_, 'php_self' => $this->context->controller->php_self, 'tax_enabled' => Configuration::get('PS_TAX'), 'cms_id_shipping' => Configuration::get('LEGAL_CMS_ID_SHIPPING'), 'template_type' => $params['type'], 'weight_unit' => Configuration::get('PS_WEIGHT_UNIT'), 'show_weights' => Configuration::get('LEGAL_SHOW_WEIGHTS'), 'show_fancy' => Configuration::get('LEGAL_SHOW_FANCY'), 'seo_active' => Configuration::get('PS_REWRITING_SETTINGS')));
     }
     return $this->display(__FILE__, 'displayProductPriceBlock.tpl', $this->getCacheId($cache_key));
 }
Пример #9
0
 public function renderExpressCheckoutForm($type)
 {
     if (!Configuration::get('PAYPAL_EXPRESS_CHECKOUT_SHORTCUT') && !$this->useMobile() || !in_array(ECS, $this->getPaymentMethods()) || (int) Configuration::get('PAYPAL_BUSINESS') == 1 && (int) Configuration::get('PAYPAL_PAYMENT_METHOD') == HSS && !$this->useMobile()) {
         return;
     }
     $id_product = (int) Tools::getValue('id_product');
     $id_product_attribute = (int) Product::getDefaultAttribute($id_product);
     if ($id_product_attribute) {
         $minimal_quantity = Attribute::getAttributeMinimalQty($id_product_attribute);
     } else {
         $product = new Product($id_product);
         $minimal_quantity = $product->minimal_quantity;
     }
     $this->context->smarty->assign(array('PayPal_payment_type' => $type, 'PayPal_current_page' => $this->getCurrentUrl(), 'id_product_attribute' => $id_product_attribute, 'product_minimal_quantity' => $minimal_quantity, 'PayPal_tracking_code' => $this->getTrackingCode((int) Configuration::get('PAYPAL_PAYMENT_METHOD'))));
     return $this->fetchTemplate('express_checkout_shortcut_form.tpl');
 }
 public function process()
 {
     global $cart, $currency;
     parent::process();
     if (!Validate::isLoadedObject($this->product)) {
         $this->errors[] = Tools::displayError('Product not found');
     } else {
         if (!$this->product->active and Tools::getValue('adtoken') != Tools::encrypt('PreviewProduct' . $this->product->id) || !file_exists(dirname(__FILE__) . '/../' . Tools::getValue('ad') . '/ajax.php')) {
             header('HTTP/1.1 404 page not found');
             $this->errors[] = Tools::displayError('Product is no longer available.');
         } elseif (!$this->product->checkAccess((int) self::$cookie->id_customer)) {
             $this->errors[] = Tools::displayError('You do not have access to this product.');
         } else {
             self::$smarty->assign('virtual', ProductDownload::getIdFromIdProduct((int) $this->product->id));
             if (!$this->product->active) {
                 self::$smarty->assign('adminActionDisplay', true);
             }
             /* Product pictures management */
             require_once 'images.inc.php';
             if ($this->product->customizable) {
                 self::$smarty->assign('customizationFormTarget', Tools::safeOutput(urldecode($_SERVER['REQUEST_URI'])));
                 if (Tools::isSubmit('submitCustomizedDatas')) {
                     $this->pictureUpload($this->product, $cart);
                     $this->textRecord($this->product, $cart);
                     $this->formTargetFormat();
                 } elseif (isset($_GET['deletePicture']) and !$cart->deletePictureToProduct((int) $this->product->id, (int) Tools::getValue('deletePicture'))) {
                     $this->errors[] = Tools::displayError('An error occurred while deleting the selected picture');
                 }
                 $files = self::$cookie->getFamily('pictures_' . (int) $this->product->id);
                 $textFields = self::$cookie->getFamily('textFields_' . (int) $this->product->id);
                 foreach ($textFields as $key => $textField) {
                     $textFields[$key] = str_replace('<br />', "\n", $textField);
                 }
                 self::$smarty->assign(array('pictures' => $files, 'textFields' => $textFields));
             }
             /* Features / Values */
             $features = $this->product->getFrontFeatures((int) self::$cookie->id_lang);
             $attachments = $this->product->cache_has_attachments ? $this->product->getAttachments((int) self::$cookie->id_lang) : array();
             /* Category */
             $category = false;
             if (isset($_SERVER['HTTP_REFERER']) and preg_match('!^(.*)\\/([0-9]+)\\-(.*[^\\.])|(.*)id_category=([0-9]+)(.*)$!', $_SERVER['HTTP_REFERER'], $regs) and !strstr($_SERVER['HTTP_REFERER'], '.html')) {
                 if (isset($regs[2]) and is_numeric($regs[2])) {
                     if (Product::idIsOnCategoryId((int) $this->product->id, array('0' => array('id_category' => (int) $regs[2])))) {
                         $category = new Category((int) $regs[2], (int) self::$cookie->id_lang);
                     }
                 } elseif (isset($regs[5]) and is_numeric($regs[5])) {
                     if (Product::idIsOnCategoryId((int) $this->product->id, array('0' => array('id_category' => (int) $regs[5])))) {
                         $category = new Category((int) $regs[5], (int) self::$cookie->id_lang);
                     }
                 }
             }
             if (!$category) {
                 $category = new Category($this->product->id_category_default, (int) self::$cookie->id_lang);
             }
             if (isset($category) and Validate::isLoadedObject($category)) {
                 self::$smarty->assign(array('path' => Tools::getPath((int) $category->id, $this->product->name, true), 'category' => $category, 'subCategories' => $category->getSubCategories((int) self::$cookie->id_lang, true), 'id_category_current' => (int) $category->id, 'id_category_parent' => (int) $category->id_parent, 'return_category_name' => Tools::safeOutput($category->name)));
             } else {
                 self::$smarty->assign('path', Tools::getPath((int) $this->product->id_category_default, $this->product->name));
             }
             self::$smarty->assign('return_link', (isset($category->id) and $category->id) ? Tools::safeOutput(self::$link->getCategoryLink($category)) : 'javascript: history.back();');
             if (Pack::isPack((int) $this->product->id) and !Pack::isInStock((int) $this->product->id)) {
                 $this->product->quantity = 0;
             }
             $id_customer = (isset(self::$cookie->id_customer) and self::$cookie->id_customer) ? (int) self::$cookie->id_customer : 0;
             $id_group = $id_customer ? (int) Customer::getDefaultGroupId($id_customer) : _PS_DEFAULT_CUSTOMER_GROUP_;
             $id_country = (int) ($id_customer ? Customer::getCurrentCountry($id_customer) : Configuration::get('PS_COUNTRY_DEFAULT'));
             $group_reduction = GroupReduction::getValueForProduct($this->product->id, $id_group);
             if ($group_reduction == 0) {
                 $group_reduction = Group::getReduction((int) self::$cookie->id_customer) / 100;
             }
             // Tax
             $tax = (double) Tax::getProductTaxRate((int) $this->product->id, $cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
             self::$smarty->assign('tax_rate', $tax);
             $productPriceWithTax = Product::getPriceStatic($this->product->id, true, NULL, 6);
             if (Product::$_taxCalculationMethod == PS_TAX_INC) {
                 $productPriceWithTax = Tools::ps_round($productPriceWithTax, 2);
             }
             $productPriceWithoutEcoTax = (double) ($productPriceWithTax - $this->product->ecotax);
             $ecotax_rate = (double) Tax::getProductEcotaxRate($cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
             $ecotaxTaxAmount = Tools::ps_round($this->product->ecotax, 2);
             if (Product::$_taxCalculationMethod == PS_TAX_INC && (int) Configuration::get('PS_TAX')) {
                 $ecotaxTaxAmount = Tools::ps_round($ecotaxTaxAmount * (1 + $ecotax_rate / 100), 2);
             }
             self::$smarty->assign(array('quantity_discounts' => $this->formatQuantityDiscounts(SpecificPrice::getQuantityDiscounts((int) $this->product->id, (int) Shop::getCurrentShop(), (int) self::$cookie->id_currency, $id_country, $id_group), $this->product->getPrice(Product::$_taxCalculationMethod == PS_TAX_INC, false), (double) $tax), 'product' => $this->product, 'ecotax_tax_inc' => $ecotaxTaxAmount, 'ecotax_tax_exc' => Tools::ps_round($this->product->ecotax, 2), 'ecotaxTax_rate' => $ecotax_rate, 'homeSize' => Image::getSize('home'), 'product_manufacturer' => new Manufacturer((int) $this->product->id_manufacturer, self::$cookie->id_lang), 'token' => Tools::getToken(false), 'productPriceWithoutEcoTax' => (double) $productPriceWithoutEcoTax, 'features' => $features, 'attachments' => $attachments, 'allow_oosp' => $this->product->isAvailableWhenOutOfStock((int) $this->product->out_of_stock), 'last_qties' => (int) Configuration::get('PS_LAST_QTIES'), 'group_reduction' => 1 - $group_reduction, 'col_img_dir' => _PS_COL_IMG_DIR_));
             self::$smarty->assign(array('HOOK_EXTRA_LEFT' => Module::hookExec('extraLeft'), 'HOOK_EXTRA_RIGHT' => Module::hookExec('extraRight'), 'HOOK_PRODUCT_OOS' => Hook::productOutOfStock($this->product), 'HOOK_PRODUCT_FOOTER' => Hook::productFooter($this->product, $category), 'HOOK_PRODUCT_ACTIONS' => Module::hookExec('productActions'), 'HOOK_PRODUCT_TAB' => Module::hookExec('productTab'), 'HOOK_PRODUCT_TAB_CONTENT' => Module::hookExec('productTabContent')));
             $images = $this->product->getImages((int) self::$cookie->id_lang);
             $productImages = array();
             foreach ($images as $k => $image) {
                 if ($image['cover']) {
                     self::$smarty->assign('mainImage', $images[0]);
                     $cover = $image;
                     $cover['id_image'] = Configuration::get('PS_LEGACY_IMAGES') ? $this->product->id . '-' . $image['id_image'] : $image['id_image'];
                     $cover['id_image_only'] = (int) $image['id_image'];
                 }
                 $productImages[(int) $image['id_image']] = $image;
             }
             if (!isset($cover)) {
                 $cover = array('id_image' => Language::getIsoById(self::$cookie->id_lang) . '-default', 'legend' => 'No picture', 'title' => 'No picture');
             }
             $size = Image::getSize('large');
             self::$smarty->assign(array('cover' => $cover, 'imgWidth' => (int) $size['width'], 'mediumSize' => Image::getSize('medium'), 'largeSize' => Image::getSize('large'), 'accessories' => $this->product->getAccessories((int) self::$cookie->id_lang)));
             if (count($productImages)) {
                 self::$smarty->assign('images', $productImages);
             }
             /* Attributes / Groups & colors */
             $colors = array();
             $attributesGroups = $this->product->getAttributesGroups((int) self::$cookie->id_lang);
             // @todo (RM) should only get groups and not all declination ?
             if (is_array($attributesGroups) and $attributesGroups) {
                 $groups = array();
                 $combinationImages = $this->product->getCombinationImages((int) self::$cookie->id_lang);
                 foreach ($attributesGroups as $k => $row) {
                     /* Color management */
                     if ((isset($row['attribute_color']) and $row['attribute_color'] or file_exists(_PS_COL_IMG_DIR_ . $row['id_attribute'] . '.jpg')) and $row['id_attribute_group'] == $this->product->id_color_default) {
                         $colors[$row['id_attribute']]['value'] = $row['attribute_color'];
                         $colors[$row['id_attribute']]['name'] = $row['attribute_name'];
                         if (!isset($colors[$row['id_attribute']]['attributes_quantity'])) {
                             $colors[$row['id_attribute']]['attributes_quantity'] = 0;
                         }
                         $colors[$row['id_attribute']]['attributes_quantity'] += (int) $row['quantity'];
                     }
                     if (!isset($groups[$row['id_attribute_group']])) {
                         $groups[$row['id_attribute_group']] = array('name' => $row['public_group_name'], 'is_color_group' => $row['is_color_group'], 'default' => -1);
                     }
                     $groups[$row['id_attribute_group']]['attributes'][$row['id_attribute']] = $row['attribute_name'];
                     if ($row['default_on'] && $groups[$row['id_attribute_group']]['default'] == -1) {
                         $groups[$row['id_attribute_group']]['default'] = (int) $row['id_attribute'];
                     }
                     if (!isset($groups[$row['id_attribute_group']]['attributes_quantity'][$row['id_attribute']])) {
                         $groups[$row['id_attribute_group']]['attributes_quantity'][$row['id_attribute']] = 0;
                     }
                     $groups[$row['id_attribute_group']]['attributes_quantity'][$row['id_attribute']] += (int) $row['quantity'];
                     $combinations[$row['id_product_attribute']]['attributes_values'][$row['id_attribute_group']] = $row['attribute_name'];
                     $combinations[$row['id_product_attribute']]['attributes'][] = (int) $row['id_attribute'];
                     $combinations[$row['id_product_attribute']]['price'] = (double) $row['price'];
                     $combinations[$row['id_product_attribute']]['ecotax'] = (double) $row['ecotax'];
                     $combinations[$row['id_product_attribute']]['weight'] = (double) $row['weight'];
                     $combinations[$row['id_product_attribute']]['quantity'] = (int) $row['quantity'];
                     $combinations[$row['id_product_attribute']]['reference'] = $row['reference'];
                     $combinations[$row['id_product_attribute']]['ean13'] = $row['ean13'];
                     $combinations[$row['id_product_attribute']]['unit_impact'] = $row['unit_price_impact'];
                     $combinations[$row['id_product_attribute']]['minimal_quantity'] = $row['minimal_quantity'];
                     $combinations[$row['id_product_attribute']]['id_image'] = isset($combinationImages[$row['id_product_attribute']][0]['id_image']) ? $combinationImages[$row['id_product_attribute']][0]['id_image'] : -1;
                 }
                 //wash attributes list (if some attributes are unavailables and if allowed to wash it)
                 if (!Product::isAvailableWhenOutOfStock($this->product->out_of_stock) && Configuration::get('PS_DISP_UNAVAILABLE_ATTR') == 0) {
                     foreach ($groups as &$group) {
                         foreach ($group['attributes_quantity'] as $key => &$quantity) {
                             if (!$quantity) {
                                 unset($group['attributes'][$key]);
                             }
                         }
                     }
                     foreach ($colors as $key => $color) {
                         if (!$color['attributes_quantity']) {
                             unset($colors[$key]);
                         }
                     }
                 }
                 foreach ($groups as &$group) {
                     natcasesort($group['attributes']);
                 }
                 foreach ($combinations as $id_product_attribute => $comb) {
                     $attributeList = '';
                     foreach ($comb['attributes'] as $id_attribute) {
                         $attributeList .= '\'' . (int) $id_attribute . '\',';
                     }
                     $attributeList = rtrim($attributeList, ',');
                     $combinations[$id_product_attribute]['list'] = $attributeList;
                 }
                 self::$smarty->assign(array('groups' => $groups, 'combinaisons' => $combinations, 'combinations' => $combinations, 'colors' => (sizeof($colors) and $this->product->id_color_default) ? $colors : false, 'combinationImages' => $combinationImages));
             }
             self::$smarty->assign(array('no_tax' => Tax::excludeTaxeOption() or !Tax::getProductTaxRate((int) $this->product->id, $cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}), 'customizationFields' => $this->product->customizable ? $this->product->getCustomizationFields((int) self::$cookie->id_lang) : false));
             // Pack management
             self::$smarty->assign('packItems', $this->product->cache_is_pack ? Pack::getItemTable($this->product->id, (int) self::$cookie->id_lang, true) : array());
             self::$smarty->assign('packs', Pack::getPacksTable($this->product->id, (int) self::$cookie->id_lang, true, 1));
         }
     }
     self::$smarty->assign(array('ENT_NOQUOTES' => ENT_NOQUOTES, 'outOfStockAllowed' => (int) Configuration::get('PS_ORDER_OUT_OF_STOCK'), 'errors' => $this->errors, 'categories' => Category::getHomeCategories((int) self::$cookie->id_lang), 'have_image' => isset($cover) ? (int) $cover['id_image'] : false, 'tax_enabled' => Configuration::get('PS_TAX'), 'display_qties' => (int) Configuration::get('PS_DISPLAY_QTIES'), 'display_ht' => !Tax::excludeTaxeOption(), 'ecotax' => !sizeof($this->errors) and $this->product->ecotax > 0 ? Tools::convertPrice((double) $this->product->ecotax) : 0, 'currencySign' => $currency->sign, 'currencyRate' => $currency->conversion_rate, 'currencyFormat' => $currency->format, 'currencyBlank' => $currency->blank, 'jqZoomEnabled' => Configuration::get('PS_DISPLAY_JQZOOM'), 'ipa_customization' => Tools::getIsset('ipa_customization') ? Tools::getValue('ipa_customization') : '', 'ipa_default' => Product::getDefaultAttribute($this->product->id)));
 }
Пример #11
0
 public static function getProductProperties($id_lang, $row)
 {
     if (!$row['id_product']) {
         return false;
     }
     $row['allow_oosp'] = Product::isAvailableWhenOutOfStock($row['out_of_stock']);
     if ((!isset($row['id_product_attribute']) or !$row['id_product_attribute']) and $ipa_default = Product::getDefaultAttribute($row['id_product'], !$row['allow_oosp'])) {
         $row['id_product_attribute'] = $ipa_default;
     }
     if (!isset($row['id_product_attribute'])) {
         $row['id_product_attribute'] = 0;
     }
     // Tax
     $usetax = true;
     $tax = floatval(Tax::getApplicableTax(intval($row['id_tax']), floatval($row['rate'])));
     if (Tax::excludeTaxeOption() or !$tax) {
         $usetax = false;
     }
     $cacheKey = $row['id_product'] . '-' . $row['id_product_attribute'] . '-' . $id_lang . '-' . intval($usetax);
     if (array_key_exists($cacheKey, self::$producPropertiesCache)) {
         return self::$producPropertiesCache[$cacheKey];
     }
     // Datas
     $link = new Link();
     $row['category'] = Category::getLinkRewrite($row['id_category_default'], intval($id_lang));
     $row['link'] = $link->getProductLink($row['id_product'], $row['link_rewrite'], $row['category'], $row['ean13']);
     $row['attribute_price'] = (isset($row['id_product_attribute']) and $row['id_product_attribute']) ? floatval(Product::getProductAttributePrice($row['id_product_attribute'])) : 0;
     $row['price_tax_exc'] = Product::getPriceStatic($row['id_product'], false, (isset($row['id_product_attribute']) and !empty($row['id_product_attribute'])) ? intval($row['id_product_attribute']) : NULL, 6);
     if (self::$_taxCalculationMethod == PS_TAX_EXC) {
         $row['price_tax_exc'] = Tools::ps_round($row['price_tax_exc'], 2);
         $row['price'] = Product::getPriceStatic($row['id_product'], true, (isset($row['id_product_attribute']) and !empty($row['id_product_attribute'])) ? intval($row['id_product_attribute']) : NULL, 6);
     } else {
         $row['price'] = Tools::ps_round(Product::getPriceStatic($row['id_product'], true, (isset($row['id_product_attribute']) and !empty($row['id_product_attribute'])) ? intval($row['id_product_attribute']) : NULL, 6), 2);
     }
     $row['reduction'] = self::getReductionValue($row['reduction_price'], $row['reduction_percent'], $row['reduction_from'], $row['reduction_to'], $row['price'], $usetax, floatval($row['rate']));
     $row['price_without_reduction'] = Product::getPriceStatic($row['id_product'], true, (isset($row['id_product_attribute']) and !empty($row['id_product_attribute'])) ? intval($row['id_product_attribute']) : NULL, 6, NULL, false, false);
     $row['quantity'] = Product::getQuantity($row['id_product']);
     $row['id_image'] = Product::defineProductImage($row);
     $row['features'] = Product::getFrontFeaturesStatic(intval($id_lang), $row['id_product']);
     $row['attachments'] = Product::getAttachmentsStatic(intval($id_lang), $row['id_product']);
     $row['pack'] = Pack::isPack($row['id_product']);
     $row['packItems'] = $row['pack'] ? Pack::getItemTable($row['id_product'], $id_lang) : array();
     $row['nopackprice'] = $row['pack'] ? Pack::noPackPrice($row['id_product']) : 0;
     self::$producPropertiesCache[$cacheKey] = $row;
     return self::$producPropertiesCache[$cacheKey];
 }
Пример #12
0
 public static function getProductProperties($id_lang, $row)
 {
     if (!$row['id_product']) {
         return false;
     }
     // Product::getDefaultAttribute is only called if id_product_attribute is missing from the SQL query at the origin of it: consider adding it in order to avoid unnecessary queries
     $row['allow_oosp'] = Product::isAvailableWhenOutOfStock($row['out_of_stock']);
     if ((!isset($row['id_product_attribute']) or !$row['id_product_attribute']) and (isset($row['cache_default_attribute']) and ($ipa_default = $row['cache_default_attribute']) !== NULL or $ipa_default = Product::getDefaultAttribute($row['id_product'], !$row['allow_oosp']))) {
         $row['id_product_attribute'] = $ipa_default;
     }
     if (!isset($row['id_product_attribute'])) {
         $row['id_product_attribute'] = 0;
     }
     // Tax
     $usetax = Tax::excludeTaxeOption();
     $cacheKey = $row['id_product'] . '-' . $row['id_product_attribute'] . '-' . $id_lang . '-' . (int) $usetax;
     if (array_key_exists($cacheKey, self::$producPropertiesCache)) {
         return self::$producPropertiesCache[$cacheKey];
     }
     // Datas
     $row['category'] = Category::getLinkRewrite((int) $row['id_category_default'], (int) $id_lang);
     if (!preg_match("/^1.3.*/", _PS_VERSION_)) {
         // Not available in Prestashop 1.3.x
         $row['reduction'] = Product::getPriceStatic((int) $row['id_product'], (bool) $usetax, (int) $row['id_product_attribute'], 6, NULL, true, true, 1, true, NULL, NULL, NULL, $specific_prices);
         $row['specific_prices'] = $specific_prices;
     }
     if ($row['id_product_attribute']) {
         $row['quantity_all_versions'] = $row['quantity'];
         $row['quantity'] = Product::getQuantity((int) $row['id_product'], $row['id_product_attribute'], isset($row['cache_is_pack']) ? $row['cache_is_pack'] : NULL);
     }
     $row['id_image'] = Product::defineProductImage($row, $id_lang);
     $row['features'] = Product::getFrontFeaturesStatic((int) $id_lang, $row['id_product']);
     // Pack management
     $row['pack'] = !isset($row['cache_is_pack']) ? Pack::isPack($row['id_product']) : (int) $row['cache_is_pack'];
     $row['packItems'] = $row['pack'] ? Pack::getItemTable($row['id_product'], $id_lang) : array();
     $row['nopackprice'] = $row['pack'] ? Pack::noPackPrice($row['id_product']) : 0;
     if ($row['pack'] and !Pack::isInStock($row['id_product'])) {
         $row['quantity'] = 0;
     }
     $sql_combination = '
   SELECT pa.id_product_attribute, pa.price, pa.quantity, pa.id_product
   FROM `' . _DB_PREFIX_ . 'product` p
   LEFT JOIN `' . _DB_PREFIX_ . 'product_attribute` pa ON (p.`id_product` = pa.`id_product`)
   WHERE p.`id_product` =' . $row['id_product'];
     $result_combination = ProductExtended::getDbInstance()->ExecuteS($sql_combination);
     $row['combinations'] = array();
     if ($result_combination) {
         foreach ($result_combination as $combination) {
             $combination['attributes'] = array();
             /* New combinations system Prestashop 1.5.x */
             if (!preg_match("/^1.(3|4).*/", _PS_VERSION_)) {
                 $combination['quantity'] = StockAvailable::getQuantityAvailableByProduct($row['id_product'], $combination['id_product_attribute']);
             }
             if (isset($combination['id_product_attribute'])) {
                 $sql_attribute = '
         SELECT pa.id_product_attribute, agl.id_attribute_group, al.name as name_value, agl.name as name_option
         FROM `' . _DB_PREFIX_ . '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_lang` al ON (al.`id_attribute` = a.`id_attribute` AND al.`id_lang` = ' . $id_lang . ')
         LEFT JOIN `' . _DB_PREFIX_ . 'attribute_group` ag ON (ag.`id_attribute_group` = a.`id_attribute_group`)
         LEFT JOIN `' . _DB_PREFIX_ . 'attribute_group_lang` agl ON (agl.`id_attribute_group` = ag.`id_attribute_group` AND agl.`id_lang` = ' . $id_lang . ')
         WHERE pa.`id_product_attribute` =' . $combination['id_product_attribute'];
                 $result_attribute = ProductExtended::getDbInstance()->ExecuteS($sql_attribute);
                 if ($result_attribute) {
                     foreach ($result_attribute as $attribute) {
                         array_push($combination['attributes'], $attribute);
                     }
                 }
                 array_push($row['combinations'], $combination);
             }
         }
     }
     $sql_image = '
   SELECT DISTINCT i.*, pl.link_rewrite
   FROM `' . _DB_PREFIX_ . 'product` p
   LEFT JOIN `' . _DB_PREFIX_ . 'image` i ON (p.`id_product` = i.`id_product`)
   LEFT JOIN `' . _DB_PREFIX_ . 'product_lang` pl ON (p.`id_product` = pl.`id_product`)
   WHERE p.`id_product` =' . $row['id_product'];
     $result_image = ProductExtended::getDbInstance()->ExecuteS($sql_image);
     $row['images'] = array();
     $lang = new Language($id_lang);
     $row['url_locale'] = $lang->iso_code;
     if ($result_image) {
         $link = preg_match("/^1.(3|4).*/", _PS_VERSION_) ? new Link() : Context::getContext()->link;
         foreach ($result_image as $image) {
             if (!preg_match("/^1.3.*/", _PS_VERSION_)) {
                 // Image URL gives relative version using 1.3.x-
                 $image['image_url'] = $link->getImageLink($image['link_rewrite'], $image['id_product'] . '-' . $image['id_image']);
             }
             array_push($row['images'], $image);
         }
     }
     self::$producPropertiesCache[$cacheKey] = $row;
     return self::$producPropertiesCache[$cacheKey];
 }
Пример #13
0
    public static function getProductProperties($id_lang, $row)
    {
        if (!$row['id_product']) {
            return false;
        }
        // Product::getDefaultAttribute is only called if id_product_attribute is missing from the SQL query at the origin of it: consider adding it in order to avoid unnecessary queries
        $row['allow_oosp'] = Product::isAvailableWhenOutOfStock($row['out_of_stock']);
        if ((!isset($row['id_product_attribute']) or !$row['id_product_attribute']) and (isset($row['cache_default_attribute']) and ($ipa_default = $row['cache_default_attribute']) !== NULL or $ipa_default = Product::getDefaultAttribute($row['id_product'], !$row['allow_oosp']))) {
            $row['id_product_attribute'] = $ipa_default;
        }
        if (!isset($row['id_product_attribute'])) {
            $row['id_product_attribute'] = 0;
        }
        // Tax
        $usetax = Tax::excludeTaxeOption();
        $cacheKey = $row['id_product'] . '-' . $row['id_product_attribute'] . '-' . $id_lang . '-' . (int) $usetax;
        if (array_key_exists($cacheKey, self::$producPropertiesCache)) {
            return self::$producPropertiesCache[$cacheKey];
        }
        // Datas mbj
        $link = new Link();
        $row['category'] = Category::getLinkRewrite((int) $row['id_category_default'], (int) $id_lang);
        $row['link'] = $link->getProductLink((int) $row['id_product'], $row['link_rewrite'], $row['category'], $row['ean13']);
        //usado link
        //init
        foreach (Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
		SELECT p.*
		FROM `' . _DB_PREFIX_ . 'product` p 
                    INNER JOIN ' . _DB_PREFIX_ . 'product_lang pl ON p.id_product = pl.id_product
		WHERE p.id_product = ' . (int) $ro1w['supplier_reference']) as $subrow) {
            $row_us['id_category_default'] = $subrow['id_category_default'];
            $row_us['link_rewrite'] = $subrow['link_rewrite'];
            $row_us['ean13'] = $subrow['ean13'];
        }
        $row['category_used'] = Category::getLinkRewrite((int) $row_us['id_category_default'], (int) $id_lang);
        $row['link_used'] = $link->getProductLink((int) $row['supplier_reference'], $row_us['link_rewrite'], $row['category_used'], $row_us['ean13']);
        $row['link_extr'] = 'id::' . $row['id_product'];
        //precio mall - distribuidor - lista - internet
        foreach (Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
                    SELECT pa.price
                    FROM `' . _DB_PREFIX_ . 'product_attribute` pa 
                        INNER JOIN ' . _DB_PREFIX_ . 'product_attribute_combination pac ON pa.id_product_attribute = pac.id_product_attribute
                    WHERE pac.id_attribute = 25 and  pa.id_product = ' . (int) $row['id_product']) as $subrow) {
            $row['price_distribuidor_p'] = round($subrow['price']);
        }
        foreach (Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
                    SELECT pa.price
                    FROM `' . _DB_PREFIX_ . 'product_attribute` pa 
                        INNER JOIN ' . _DB_PREFIX_ . 'product_attribute_combination pac ON pa.id_product_attribute = pac.id_product_attribute
                    WHERE pac.id_attribute = 24 and  pa.id_product = ' . (int) $row['id_product']) as $subrow) {
            $row['price_distribuidor'] = round($subrow['price']);
        }
        foreach (Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
		SELECT pa.price
		FROM `' . _DB_PREFIX_ . 'product_attribute` pa 
                    INNER JOIN ' . _DB_PREFIX_ . 'product_attribute_combination pac ON pa.id_product_attribute = pac.id_product_attribute
		WHERE pac.id_attribute = 23 and  pa.id_product = ' . (int) $row['id_product']) as $subrow) {
            $row['price_tienda'] = round($subrow['price']);
        }
        foreach (Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
		SELECT pa.price
		FROM `' . _DB_PREFIX_ . 'product_attribute` pa 
                    INNER JOIN ' . _DB_PREFIX_ . 'product_attribute_combination pac ON pa.id_product_attribute = pac.id_product_attribute
		WHERE pac.id_attribute = 22 and  pa.id_product = ' . (int) $row['id_product']) as $subrow) {
            $row['price_mall'] = round($subrow['price']);
        }
        foreach (Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
		SELECT pa.price
		FROM `' . _DB_PREFIX_ . 'product_attribute` pa 
                    INNER JOIN ' . _DB_PREFIX_ . 'product_attribute_combination pac ON pa.id_product_attribute = pac.id_product_attribute
		WHERE pac.id_attribute = 21 and  pa.id_product = ' . (int) $row['id_product']) as $subrow) {
            $row['price_internet'] = round($subrow['price']);
        }
        $row['attribute_price'] = (isset($row['id_product_attribute']) and $row['id_product_attribute']) ? (double) Product::getProductAttributePrice($row['id_product_attribute']) : 0;
        $row['price_tax_exc'] = Product::getPriceStatic((int) $row['id_product'], false, (isset($row['id_product_attribute']) and !empty($row['id_product_attribute'])) ? (int) $row['id_product_attribute'] : NULL, self::$_taxCalculationMethod == PS_TAX_EXC ? 2 : 6);
        if (self::$_taxCalculationMethod == PS_TAX_EXC) {
            $row['price_tax_exc'] = Tools::ps_round($row['price_tax_exc'], 2);
            $row['price'] = Product::getPriceStatic((int) $row['id_product'], true, (isset($row['id_product_attribute']) and !empty($row['id_product_attribute'])) ? (int) $row['id_product_attribute'] : NULL, 6);
            $row['price_without_reduction'] = Product::getPriceStatic((int) $row['id_product'], false, (isset($row['id_product_attribute']) and !empty($row['id_product_attribute'])) ? (int) $row['id_product_attribute'] : NULL, 2, NULL, false, false);
        } else {
            $row['price'] = Tools::ps_round(Product::getPriceStatic((int) $row['id_product'], true, (isset($row['id_product_attribute']) and !empty($row['id_product_attribute'])) ? (int) $row['id_product_attribute'] : NULL, 2), 2);
            $row['price_without_reduction'] = Product::getPriceStatic((int) $row['id_product'], true, (isset($row['id_product_attribute']) and !empty($row['id_product_attribute'])) ? (int) $row['id_product_attribute'] : NULL, 6, NULL, false, false);
        }
        $row['reduction'] = Product::getPriceStatic((int) $row['id_product'], (bool) $usetax, (int) $row['id_product_attribute'], 6, NULL, true, true, 1, true, NULL, NULL, NULL, $specific_prices);
        $row['specific_prices'] = $specific_prices;
        if ($row['id_product_attribute']) {
            $row['quantity_all_versions'] = $row['quantity'];
            $row['quantity'] = Product::getQuantity((int) $row['id_product'], $row['id_product_attribute'], isset($row['cache_is_pack']) ? $row['cache_is_pack'] : NULL);
        }
        $row['id_image'] = Product::defineProductImage($row, $id_lang);
        $row['features'] = Product::getFrontFeaturesStatic((int) $id_lang, $row['id_product']);
        $row['attachments'] = (!isset($row['cache_has_attachments']) or $row['cache_has_attachments']) ? Product::getAttachmentsStatic((int) $id_lang, $row['id_product']) : array();
        // Pack management
        $row['pack'] = !isset($row['cache_is_pack']) ? Pack::isPack($row['id_product']) : (int) $row['cache_is_pack'];
        $row['packItems'] = $row['pack'] ? Pack::getItemTable($row['id_product'], $id_lang) : array();
        $row['nopackprice'] = $row['pack'] ? Pack::noPackPrice($row['id_product']) : 0;
        if ($row['pack'] and !Pack::isInStock($row['id_product'])) {
            $row['quantity'] = 0;
        }
        self::$producPropertiesCache[$cacheKey] = $row;
        return self::$producPropertiesCache[$cacheKey];
    }
Пример #14
0
 public static function getDefaultAttribute($id_product, $minimum_quantity = 0)
 {
     if (isset(self::$_getDefaultAttributeCache[$id_product . '-' . $minimum_quantity])) {
         return self::$_getDefaultAttributeCache[$id_product . '-' . $minimum_quantity];
     }
     self::$_getDefaultAttributeCache[$id_product . '-' . $minimum_quantity] = Product::getDefaultAttribute($id_product, $minimum_quantity);
     return self::$_getDefaultAttributeCache[$id_product . '-' . $minimum_quantity];
 }
Пример #15
0
    public function searchProducts($query)
    {
        if (version_compare(_PS_VERSION_, '1.5', '<')) {
            $sql = '
				SELECT p.`id_product`, pl.`name`, p.`weight`
				FROM `' . _DB_PREFIX_ . 'category_product` cp
				LEFT JOIN `' . _DB_PREFIX_ . 'product` p ON (p.`id_product` = cp.`id_product`)
				LEFT JOIN `' . _DB_PREFIX_ . 'product_lang` pl ON (pl.`id_product` = p.`id_product` AND pl.`id_lang` = "' . (int) $this->context->language->id . '")
				WHERE pl.`name` LIKE \'%' . pSQL($query) . '%\'
					OR p.`ean13` LIKE \'%' . pSQL($query) . '%\'
					OR p.`upc` LIKE \'%' . pSQL($query) . '%\'
					OR p.`reference` LIKE \'%' . pSQL($query) . '%\'
					OR p.`supplier_reference` LIKE \'%' . pSQL($query) . '%\'
				GROUP BY `id_product`
				ORDER BY pl.`name` ASC
			';
        } else {
            $sql = new DbQuery();
            $sql->select('p.`id_product`, pl.`name`, p.`weight`');
            $sql->from('category_product', 'cp');
            $sql->leftJoin('product', 'p', 'p.`id_product` = cp.`id_product`');
            $sql->join(Shop::addSqlAssociation('product', 'p'));
            $sql->leftJoin('product_lang', 'pl', '
				p.`id_product` = pl.`id_product`
				AND pl.`id_lang` = ' . (int) $this->context->language->id . Shop::addSqlRestrictionOnLang('pl'));
            $where = 'pl.`name` LIKE \'%' . pSQL($query) . '%\'
			OR p.`ean13` LIKE \'%' . pSQL($query) . '%\'
			OR p.`upc` LIKE \'%' . pSQL($query) . '%\'
			OR p.`reference` LIKE \'%' . pSQL($query) . '%\'
			OR p.`supplier_reference` LIKE \'%' . pSQL($query) . '%\'
			OR  p.`id_product` IN (SELECT id_product FROM ' . _DB_PREFIX_ . 'product_supplier sp WHERE `product_supplier_reference` LIKE \'%' . pSQL($query) . '%\')';
            $sql->groupBy('`id_product`');
            $sql->orderBy('pl.`name` ASC');
            if (Combination::isFeatureActive()) {
                $sql->leftJoin('product_attribute', 'pa', 'pa.`id_product` = p.`id_product`');
                $sql->join(Shop::addSqlAssociation('product_attribute', 'pa', false));
                $where .= ' OR pa.`reference` LIKE \'%' . pSQL($query) . '%\'';
            }
            $sql->where($where);
        }
        $result = Db::getInstance()->executeS($sql);
        if (!$result) {
            return array('found' => false, 'notfound' => $this->l('No product has been found.'));
        }
        foreach ($result as &$product) {
            $product['id_product_attribute'] = Product::getDefaultAttribute($product['id_product']);
            $product['weight_numeric'] = $product['weight'];
            $product['weight'] = sprintf('%.3f', $product['weight']) . ' ' . _DPDPOLAND_DEFAULT_WEIGHT_UNIT_;
        }
        return array('products' => $result, 'found' => true);
    }
Пример #16
0
	/**
	* Price calculation / Get product price
	*
	* @param integer $id_shop Shop id
	* @param integer $id_product Product id
	* @param integer $id_product_attribute Product attribute id
	* @param integer $id_country Country id
	* @param integer $id_state State id
	* @param integer $id_currency Currency id
	* @param integer $id_group Group id
	* @param integer $quantity Quantity Required for Specific prices : quantity discount application
	* @param boolean $use_tax with (1) or without (0) tax
	* @param integer $decimals Number of decimals returned
	* @param boolean $only_reduc Returns only the reduction amount
	* @param boolean $use_reduc Set if the returned amount will include reduction
	* @param boolean $with_ecotax insert ecotax in price output.
	* @param variable_reference $specific_price_output
	* 	If a specific price applies regarding the previous parameters, this variable is filled with the corresponding SpecificPrice object
	* @return float Product price
	**/
	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)
	{
		static $address = null;
		static $context = null;

		if ($address === null)
			$address = new Address();
		
		if ($context == null)
			$context = Context::getContext()->cloneContext();

		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 = $id_product.'-'.$id_shop.'-'.$id_currency.'-'.$id_country.'-'.$id_state.'-'.$zipcode.'-'.$id_group.
			'-'.$quantity.'-'.$id_product_attribute.'-'.($use_tax?'1':'0').'-'.$decimals.'-'.($only_reduc?'1':'0').
			'-'.($use_reduc?'1':'0').'-'.$with_ecotax.'-'.$id_customer.'-'.(int)$use_group_reduction.'-'.(int)$id_cart.'-'.(int)$real_quantity;

		// 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;
		if (!isset(self::$_pricesLevel2[$cache_id_2]))
		{
			$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('product_attribute_shop.id_product_attribute, product_attribute_shop.`price` AS attribute_price, product_attribute_shop.default_on');
				$sql->leftJoin('product_attribute', 'pa', 'pa.`id_product` = p.`id_product`');
				$sql->leftJoin('product_attribute_shop', 'product_attribute_shop', '(product_attribute_shop.id_product_attribute = pa.id_product_attribute 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);

			foreach ($res as $row)
			{
				$array_tmp = array(
					'price' => $row['price'], 
					'ecotax' => $row['ecotax'],
					'attribute_price' => (isset($row['attribute_price']) ? $row['attribute_price'] : 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];

		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']))
			$price = Tools::convertPrice($price, $id_currency);

		// 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;
		}

		// 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);

		// 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 = !$use_tax ? $product_tax_calculator->removeTaxes($reduction_amount) : $reduction_amount;
			}
			else
				$specific_price_reduction = $price * $specific_price['reduction'];
		}

		if ($use_reduc)
			$price -= $specific_price_reduction;

		// Group reduction
		if ($use_group_reduction)
		{
			$reduction_from_category = GroupReduction::getValueForProduct($id_product, $id_group);
                        if($context->customer->id){
                            $id_group = array();
                            $customer_groups = Db::getInstance()->executeS("SELECT id_group FROM ps_customer_group WHERE id_customer={$context->customer->id}"); 
                            foreach ($customer_groups as $row_group)
                                $id_group[] = $row_group['id_group'];
                            
                        }else
                            $id_group = array($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;
		}
		else
			$group_reduction = 0;
		if ($only_reduc)
			return Tools::ps_round($group_reduction + $specific_price_reduction, $decimals);

		if ($use_reduc)
			$price -= $group_reduction;

		// 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)
			{
				// reinit the tax manager for ecotax handling
				$tax_manager = TaxManagerFactory::getManager(
					$address,
					(int)Configuration::get('PS_ECOTAX_TAX_RULES_GROUP_ID')
				);
				$ecotax_tax_calculator = $tax_manager->getTaxCalculator();
				$price += $ecotax_tax_calculator->addTaxes($ecotax);
			}
			else
				$price += $ecotax;
		}
		$price = Tools::ps_round($price, $decimals);
		if ($price < 0)
			$price = 0;

		self::$_prices[$cache_id] = $price;
		return self::$_prices[$cache_id];
	}
Пример #17
0
 public function preProcess()
 {
     parent::preProcess();
     $orderTotal = self::$cart->getOrderTotal(true, Cart::ONLY_PRODUCTS);
     $this->cartDiscounts = self::$cart->getDiscounts();
     foreach ($this->cartDiscounts as $k => $this->cartDiscount) {
         if ($error = self::$cart->checkDiscountValidity(new Discount((int) $this->cartDiscount['id_discount']), $this->cartDiscounts, $orderTotal, self::$cart->getProducts())) {
             self::$cart->deleteDiscount((int) $this->cartDiscount['id_discount']);
         }
     }
     $add = Tools::getIsset('add') ? 1 : 0;
     $delete = Tools::getIsset('delete') ? 1 : 0;
     if (Configuration::get('PS_TOKEN_ENABLE') == 1 && strcasecmp(Tools::getToken(false), strval(Tools::getValue('token'))) && self::$cookie->isLogged() === true) {
         $this->errors[] = Tools::displayError('Invalid token');
     }
     // Update the cart ONLY if $this->cookies are available, in order to avoid ghost carts created by bots
     if (($add or Tools::getIsset('update') or $delete) and isset(self::$cookie->date_add)) {
         //get the values
         $idProduct = (int) Tools::getValue('id_product', NULL);
         $idProductAttribute = (int) Tools::getValue('id_product_attribute', Tools::getValue('ipa'));
         $customizationId = (int) Tools::getValue('id_customization', 0);
         $qty = (int) abs(Tools::getValue('qty', 1));
         if ($qty == 0) {
             $this->errors[] = Tools::displayError('Null quantity');
         } elseif (!$idProduct) {
             $this->errors[] = Tools::displayError('Product not found');
         } else {
             $producToAdd = new Product((int) $idProduct, true, (int) self::$cookie->id_lang);
             if ((!$producToAdd->id or !$producToAdd->active) and !$delete) {
                 if (Tools::getValue('ajax') == 'true') {
                     die('{"hasError" : true, "errors" : ["' . Tools::displayError('Pproduct is no longer available.', false) . '"]}');
                 } else {
                     $this->errors[] = Tools::displayError('Pproduct is no longer available.', false);
                 }
             } else {
                 /* Check the quantity availability */
                 if ($idProductAttribute and is_numeric($idProductAttribute)) {
                     if (!$delete and !$producToAdd->isAvailableWhenOutOfStock($producToAdd->out_of_stock) and !Attribute::checkAttributeQty((int) $idProductAttribute, (int) $qty)) {
                         if (Tools::getValue('ajax') == 'true') {
                             die('{"hasError" : true, "errors" : ["' . Tools::displayError('There is not enough product in stock.', false) . '"]}');
                         } else {
                             $this->errors[] = Tools::displayError('There is not enough product in stock.');
                         }
                     }
                 } elseif ($producToAdd->hasAttributes() and !$delete) {
                     $idProductAttribute = Product::getDefaultAttribute((int) $producToAdd->id, (int) $producToAdd->out_of_stock == 2 ? !(int) Configuration::get('PS_ORDER_OUT_OF_STOCK') : !(int) $producToAdd->out_of_stock);
                     if (!$idProductAttribute) {
                         Tools::redirectAdmin($link->getProductLink($producToAdd));
                     } elseif (!$delete and !$producToAdd->isAvailableWhenOutOfStock($producToAdd->out_of_stock) and !Attribute::checkAttributeQty((int) $idProductAttribute, (int) $qty)) {
                         if (Tools::getValue('ajax') == 'true') {
                             die('{"hasError" : true, "errors" : ["' . Tools::displayError('There is not enough product in stock.', false) . '"]}');
                         } else {
                             $this->errors[] = Tools::displayError('There is not enough product in stock.');
                         }
                     }
                 } elseif (!$delete and !$producToAdd->checkQty((int) $qty)) {
                     if (Tools::getValue('ajax') == 'true') {
                         die('{"hasError" : true, "errors" : ["' . Tools::displayError('There is not enough product in stock.') . '"]}');
                     } else {
                         $this->errors[] = Tools::displayError('There is not enough product in stock.');
                     }
                 }
                 /* Check vouchers compatibility */
                 if ($add and ($producToAdd->specificPrice and (double) $producToAdd->specificPrice['reduction'] or $producToAdd->on_sale)) {
                     $discounts = self::$cart->getDiscounts();
                     foreach ($discounts as $discount) {
                         if (!$discount['cumulable_reduction']) {
                             $this->errors[] = Tools::displayError('Cannot add this product because current voucher does not allow additional discounts.');
                         }
                     }
                 }
                 if (!sizeof($this->errors)) {
                     if ($add and $qty >= 0) {
                         /* Product addition to the cart */
                         if (!isset(self::$cart->id) or !self::$cart->id) {
                             self::$cart->add();
                             if (self::$cart->id) {
                                 self::$cookie->id_cart = (int) self::$cart->id;
                             }
                         }
                         if ($add and !$producToAdd->hasAllRequiredCustomizableFields() and !$customizationId) {
                             $this->errors[] = Tools::displayError('Please fill in all required fields, then save the customization.');
                         }
                         if (!sizeof($this->errors)) {
                             $updateQuantity = self::$cart->updateQty((int) $qty, (int) $idProduct, (int) $idProductAttribute, $customizationId, Tools::getValue('op', 'up'));
                             if ($updateQuantity < 0) {
                                 /* if product has attribute, minimal quantity is set with minimal quantity of attribute*/
                                 if ((int) $idProductAttribute) {
                                     $minimal_quantity = Attribute::getAttributeMinimalQty((int) $idProductAttribute);
                                 } else {
                                     $minimal_quantity = $producToAdd->minimal_quantity;
                                 }
                                 if (Tools::getValue('ajax') == 'true') {
                                     die('{"hasError" : true, "errors" : ["' . Tools::displayError('You must add', false) . ' ' . $minimal_quantity . ' ' . Tools::displayError('Minimum quantity', false) . '"]}');
                                 } else {
                                     $this->errors[] = Tools::displayError('You must add') . ' ' . $minimal_quantity . ' ' . Tools::displayError('Minimum quantity') . ((isset($_SERVER['HTTP_REFERER']) and basename($_SERVER['HTTP_REFERER']) == 'order.php' or !Tools::isSubmit('ajax') and substr(basename($_SERVER['REQUEST_URI']), 0, strlen('cart.php')) == 'cart.php') ? '<script language="javascript">setTimeout("history.back()",5000);</script><br />- ' . Tools::displayError('You will be redirected to your cart in a few seconds.') : '');
                                 }
                             } elseif (!$updateQuantity) {
                                 if (Tools::getValue('ajax') == 'true') {
                                     die('{"hasError" : true, "errors" : ["' . Tools::displayError('You already have the maximum quantity available for this product.', false) . '"]}');
                                 } else {
                                     $this->errors[] = Tools::displayError('You already have the maximum quantity available for this product.') . ((isset($_SERVER['HTTP_REFERER']) and basename($_SERVER['HTTP_REFERER']) == 'order.php' or !Tools::isSubmit('ajax') and substr(basename($_SERVER['REQUEST_URI']), 0, strlen('cart.php')) == 'cart.php') ? '<script language="javascript">setTimeout("history.back()",5000);</script><br />- ' . Tools::displayError('You will be redirected to your cart in a few seconds.') : '');
                                 }
                             }
                         }
                     } elseif ($delete) {
                         if (self::$cart->deleteProduct((int) $idProduct, (int) $idProductAttribute, (int) $customizationId)) {
                             if (!Cart::getNbProducts((int) self::$cart->id)) {
                                 self::$cart->id_carrier = 0;
                                 self::$cart->gift = 0;
                                 self::$cart->gift_message = '';
                                 self::$cart->update();
                             }
                         }
                     }
                 }
                 $discounts = self::$cart->getDiscounts();
                 foreach ($discounts as $discount) {
                     $discountObj = new Discount((int) $discount['id_discount'], (int) self::$cookie->id_lang);
                     if ($error = self::$cart->checkDiscountValidity($discountObj, $discounts, self::$cart->getOrderTotal(true, Cart::ONLY_PRODUCTS), self::$cart->getProducts())) {
                         self::$cart->deleteDiscount((int) $discount['id_discount']);
                         self::$cart->update();
                         $errors[] = $error;
                     }
                 }
                 if (!sizeof($this->errors)) {
                     $queryString = Tools::safeOutput(Tools::getValue('query', NULL));
                     if ($queryString and !Configuration::get('PS_CART_REDIRECT')) {
                         Tools::redirect('search.php?search=' . $queryString);
                     }
                     if (isset($_SERVER['HTTP_REFERER'])) {
                         // Redirect to previous page
                         preg_match('!http(s?)://(.*)/(.*)!', $_SERVER['HTTP_REFERER'], $regs);
                         if (isset($regs[3]) and !Configuration::get('PS_CART_REDIRECT') and Tools::getValue('ajax') != 'true') {
                             Tools::redirect($regs[3]);
                         }
                     }
                 }
             }
             if (Tools::getValue('ajax') != 'true' and !sizeof($this->errors)) {
                 Tools::redirect('order.php?' . (isset($idProduct) ? 'ipa=' . (int) $idProduct : ''));
             }
         }
     }
 }
Пример #18
0
 public static function getProductProperties($id_lang, $row, Context $context = null)
 {
     if (!$row['id_product']) {
         return false;
     }
     if ($context == null) {
         $context = Context::getContext();
     }
     // Product::getDefaultAttribute is only called if id_product_attribute is missing from the SQL query at the origin of it:
     // consider adding it in order to avoid unnecessary queries
     $row['allow_oosp'] = Product::isAvailableWhenOutOfStock($row['out_of_stock']);
     if (Combination::isFeatureActive() && (!isset($row['id_product_attribute']) || !$row['id_product_attribute']) && (isset($row['cache_default_attribute']) && ($ipa_default = $row['cache_default_attribute']) !== null || ($ipa_default = Product::getDefaultAttribute($row['id_product'], !$row['allow_oosp'])))) {
         $row['id_product_attribute'] = $ipa_default;
     }
     if (!Combination::isFeatureActive() || !isset($row['id_product_attribute'])) {
         $row['id_product_attribute'] = 0;
     }
     // Tax
     $usetax = Tax::excludeTaxeOption();
     $cache_key = $row['id_product'] . '-' . $row['id_product_attribute'] . '-' . $id_lang . '-' . (int) $usetax;
     if (isset($row['id_product_pack'])) {
         $cache_key .= '-pack' . $row['id_product_pack'];
     }
     if (isset(self::$cacheProducProperties[$cache_key])) {
         return array_merge($row, self::$cacheProducProperties[$cache_key]);
     }
     // Datas
     $row['category'] = Category::getLinkRewrite((int) $row['id_category_default'], (int) $id_lang);
     $row['link'] = $context->link->getProductLink((int) $row['id_product'], $row['link_rewrite'], $row['category'], $row['ean13']);
     $row['attribute_price'] = 0;
     if (isset($row['id_product_attribute']) && $row['id_product_attribute']) {
         $row['attribute_price'] = (double) Product::getProductAttributePrice($row['id_product_attribute']);
     }
     $row['price_tax_exc'] = Product::getPriceStatic((int) $row['id_product'], false, isset($row['id_product_attribute']) && !empty($row['id_product_attribute']) ? (int) $row['id_product_attribute'] : null, self::$_taxCalculationMethod == PS_TAX_EXC ? 2 : 6);
     if (self::$_taxCalculationMethod == PS_TAX_EXC) {
         $row['price_tax_exc'] = Tools::ps_round($row['price_tax_exc'], 2);
         $row['price'] = Product::getPriceStatic((int) $row['id_product'], true, isset($row['id_product_attribute']) && !empty($row['id_product_attribute']) ? (int) $row['id_product_attribute'] : null, 6);
         $row['price_without_reduction'] = Product::getPriceStatic((int) $row['id_product'], false, isset($row['id_product_attribute']) && !empty($row['id_product_attribute']) ? (int) $row['id_product_attribute'] : null, 2, null, false, false);
     } else {
         $row['price'] = Tools::ps_round(Product::getPriceStatic((int) $row['id_product'], true, isset($row['id_product_attribute']) && !empty($row['id_product_attribute']) ? (int) $row['id_product_attribute'] : null, 2), 2);
         $row['price_without_reduction'] = Product::getPriceStatic((int) $row['id_product'], true, isset($row['id_product_attribute']) && !empty($row['id_product_attribute']) ? (int) $row['id_product_attribute'] : null, 6, null, false, false);
     }
     $row['reduction'] = Product::getPriceStatic((int) $row['id_product'], (bool) $usetax, (int) $row['id_product_attribute'], 6, null, true, true, 1, true, null, null, null, $specific_prices);
     $row['specific_prices'] = $specific_prices;
     $row['quantity'] = Product::getQuantity((int) $row['id_product'], 0, isset($row['cache_is_pack']) ? $row['cache_is_pack'] : null);
     $row['quantity_all_versions'] = $row['quantity'];
     if ($row['id_product_attribute']) {
         $row['quantity'] = Product::getQuantity((int) $row['id_product'], $row['id_product_attribute'], isset($row['cache_is_pack']) ? $row['cache_is_pack'] : null);
     }
     $row['id_image'] = Product::defineProductImage($row, $id_lang);
     $row['features'] = Product::getFrontFeaturesStatic((int) $id_lang, $row['id_product']);
     $row['attachments'] = array();
     if (!isset($row['cache_has_attachments']) || $row['cache_has_attachments']) {
         $row['attachments'] = Product::getAttachmentsStatic((int) $id_lang, $row['id_product']);
     }
     $row['virtual'] = !isset($row['is_virtual']) || $row['is_virtual'] ? 1 : 0;
     // Pack management
     $row['pack'] = !isset($row['cache_is_pack']) ? Pack::isPack($row['id_product']) : (int) $row['cache_is_pack'];
     $row['packItems'] = $row['pack'] ? Pack::getItemTable($row['id_product'], $id_lang) : array();
     $row['nopackprice'] = $row['pack'] ? Pack::noPackPrice($row['id_product']) : 0;
     if ($row['pack'] && !Pack::isInStock($row['id_product'])) {
         $row['quantity'] = 0;
     }
     $row['customization_required'] = false;
     if (isset($row['customizable']) && $row['customizable'] && Customization::isFeatureActive()) {
         if (count(Product::getRequiredCustomizableFieldsStatic((int) $row['id_product']))) {
             $row['customization_required'] = true;
         }
     }
     $row = Product::getTaxesInformations($row, $context);
     self::$cacheProducProperties[$cache_key] = $row;
     return self::$cacheProducProperties[$cache_key];
 }
Пример #19
0
 /**
  * Webservice getter : get virtual field default combination
  *
  * @return int
  */
 public function getWsDefaultCombination()
 {
     return Product::getDefaultAttribute($this->id);
 }
Пример #20
0
 if ($qty == 0) {
     $errors[] = Tools::displayError('null quantity');
 } elseif (!$idProduct) {
     $errors[] = Tools::displayError('product not found');
 } else {
     $producToAdd = new Product(intval($idProduct), false, intval($cookie->id_lang));
     if ((!$producToAdd->id or !$producToAdd->active) and !$delete) {
         $errors[] = Tools::displayError('product is no longer available');
     } else {
         /* Check the quantity availability */
         if ($idProductAttribute and is_numeric($idProductAttribute)) {
             if (!$delete and !$producToAdd->isAvailableWhenOutOfStock($producToAdd->out_of_stock) and !Attribute::checkAttributeQty(intval($idProductAttribute), intval($qty))) {
                 $errors[] = Tools::displayError('product is no longer available');
             }
         } elseif ($producToAdd->hasAttributes() and !$delete) {
             $idProductAttribute = Product::getDefaultAttribute(intval($producToAdd->id), intval($producToAdd->out_of_stock) == 2 ? !intval(Configuration::get('PS_ORDER_OUT_OF_STOCK')) : !intval($producToAdd->out_of_stock));
             if (!$idProductAttribute) {
                 Tools::redirectAdmin($link->getProductLink($producToAdd));
             } elseif (!$delete and !$producToAdd->isAvailableWhenOutOfStock($producToAdd->out_of_stock) and !Attribute::checkAttributeQty(intval($idProductAttribute), intval($qty))) {
                 $errors[] = Tools::displayError('product is no longer available');
             }
         } elseif (!$delete and !$producToAdd->checkQty(intval($qty))) {
             $errors[] = Tools::displayError('product is no longer available');
         }
         /* Check vouchers compatibility */
         if ($add and (intval($producToAdd->reduction_price) or intval($producToAdd->reduction_percent) or $producToAdd->on_sale)) {
             $discounts = $cart->getDiscounts();
             foreach ($discounts as $discount) {
                 if (!$discount['cumulable_reduction']) {
                     $errors[] = Tools::displayError('cannot add this product because current voucher doesn\'t allow additional discounts');
                 }
Пример #21
0
 public function initFormQuantities($obj)
 {
     if (!$this->default_form_language) {
         $this->getLanguages();
     }
     $data = $this->createTemplate($this->tpl_form);
     $data->assign('default_form_language', $this->default_form_language);
     if ($obj->id) {
         if ($this->product_exists_in_shop) {
             // Get all id_product_attribute
             $attributes = $obj->getAttributesResume($this->context->language->id);
             if (empty($attributes)) {
                 $attributes[] = array('id_product_attribute' => 0, 'attribute_designation' => '');
             }
             // Get available quantities
             $available_quantity = array();
             $product_designation = array();
             foreach ($attributes as $attribute) {
                 // Get available quantity for the current product attribute in the current shop
                 $available_quantity[$attribute['id_product_attribute']] = StockAvailable::getQuantityAvailableByProduct((int) $obj->id, $attribute['id_product_attribute']);
                 // Get all product designation
                 $product_designation[$attribute['id_product_attribute']] = rtrim($obj->name[$this->context->language->id] . ' - ' . $attribute['attribute_designation'], ' - ');
             }
             $show_quantities = true;
             $shop_context = Shop::getContext();
             $shop_group = new ShopGroup((int) Shop::getContextShopGroupID());
             // if we are in all shops context, it's not possible to manage quantities at this level
             if (Shop::isFeatureActive() && $shop_context == Shop::CONTEXT_ALL) {
                 $show_quantities = false;
             } elseif (Shop::isFeatureActive() && $shop_context == Shop::CONTEXT_GROUP) {
                 // if quantities are not shared between shops of the group, it's not possible to manage them at group level
                 if (!$shop_group->share_stock) {
                     $show_quantities = false;
                 }
             } else {
                 // if quantities are shared between shops of the group, it's not possible to manage them for a given shop
                 if ($shop_group->share_stock) {
                     $show_quantities = false;
                 }
             }
             $data->assign('ps_stock_management', Configuration::get('PS_STOCK_MANAGEMENT'));
             $data->assign('has_attribute', $obj->hasAttributes());
             // Check if product has combination, to display the available date only for the product or for each combination
             if (Combination::isFeatureActive()) {
                 $data->assign('countAttributes', (int) Db::getInstance()->getValue('SELECT COUNT(id_product) FROM ' . _DB_PREFIX_ . 'product_attribute WHERE id_product = ' . (int) $obj->id));
             } else {
                 $data->assign('countAttributes', false);
             }
             // if advanced stock management is active, checks associations
             $advanced_stock_management_warning = false;
             if (Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT') && $obj->advanced_stock_management) {
                 $p_attributes = Product::getProductAttributesIds($obj->id);
                 $warehouses = array();
                 if (!$p_attributes) {
                     $warehouses[] = Warehouse::getProductWarehouseList($obj->id, 0);
                 }
                 foreach ($p_attributes as $p_attribute) {
                     $ws = Warehouse::getProductWarehouseList($obj->id, $p_attribute['id_product_attribute']);
                     if ($ws) {
                         $warehouses[] = $ws;
                     }
                 }
                 $warehouses = Tools::arrayUnique($warehouses);
                 if (empty($warehouses)) {
                     $advanced_stock_management_warning = true;
                 }
             }
             if ($advanced_stock_management_warning) {
                 $this->displayWarning($this->l('If you wish to use the advanced stock management, you must:'));
                 $this->displayWarning('- ' . $this->l('associate your products with warehouses.'));
                 $this->displayWarning('- ' . $this->l('associate your warehouses with carriers.'));
                 $this->displayWarning('- ' . $this->l('associate your warehouses with the appropriate shops.'));
             }
             $pack_quantity = null;
             // if product is a pack
             if (Pack::isPack($obj->id)) {
                 $items = Pack::getItems((int) $obj->id, Configuration::get('PS_LANG_DEFAULT'));
                 // gets an array of quantities (quantity for the product / quantity in pack)
                 $pack_quantities = array();
                 foreach ($items as $item) {
                     if (!$item->isAvailableWhenOutOfStock((int) $item->out_of_stock)) {
                         $pack_id_product_attribute = Product::getDefaultAttribute($item->id, 1);
                         $pack_quantities[] = Product::getQuantity($item->id, $pack_id_product_attribute) / ($item->pack_quantity !== 0 ? $item->pack_quantity : 1);
                     }
                 }
                 // gets the minimum
                 if (count($pack_quantities)) {
                     $pack_quantity = $pack_quantities[0];
                     foreach ($pack_quantities as $value) {
                         if ($pack_quantity > $value) {
                             $pack_quantity = $value;
                         }
                     }
                 }
                 if (!Warehouse::getPackWarehouses((int) $obj->id)) {
                     $this->displayWarning($this->l('You must have a common warehouse between this pack and its product.'));
                 }
             }
             $data->assign(array('attributes' => $attributes, 'available_quantity' => $available_quantity, 'pack_quantity' => $pack_quantity, 'stock_management_active' => Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT'), 'product_designation' => $product_designation, 'product' => $obj, 'show_quantities' => $show_quantities, 'order_out_of_stock' => Configuration::get('PS_ORDER_OUT_OF_STOCK'), 'token_preferences' => Tools::getAdminTokenLite('AdminPPreferences'), 'token' => $this->token, 'languages' => $this->_languages, 'id_lang' => $this->context->language->id));
         } else {
             $this->displayWarning($this->l('You must save the product in this shop before managing quantities.'));
         }
     } else {
         $this->displayWarning($this->l('You must save this product before managing quantities.'));
     }
     $this->tpl_form_vars['custom_form'] = $data->fetch();
 }
 public function initContentVirtualProduct()
 {
     $ifqrqnfl = "id_product_download";
     $satpetgggdq = "product";
     $uvtmgqwfb = "product_download";
     $odpjsjcw = "product_download";
     ${"GLOBALS"}["dixhgmcc"] = "id_product_download";
     $epxbkxu = "currency";
     ${$satpetgggdq} = $this->object;
     ${$epxbkxu} = new Currency((int) Configuration::get("PS_CURRENCY_DEFAULT"));
     ${$uvtmgqwfb} = new ProductDownload();
     if (${$ifqrqnfl} = $product_download->getIdFromIdProduct($this->getFieldValue(${${"GLOBALS"}["vmqqtmkyw"]}, "id"))) {
         ${$odpjsjcw} = new ProductDownload(${${"GLOBALS"}["dixhgmcc"]});
     }
     $product->{"productDownload"} = ${${"GLOBALS"}["pctudmr"]};
     $product->cache_default_attribute = (int) Product::getDefaultAttribute($product->id);
     ${${"GLOBALS"}["nnybqqo"]} = realpath(_PS_DOWNLOAD_DIR_) . "/" . $product->productDownload->filename;
     self::$smarty->assign("product_downloaded", $product->productDownload->id && !empty($product->productDownload->display_filename));
     if (!file_exists(${${"GLOBALS"}["nnybqqo"]}) && !empty($product->productDownload->display_filename) && empty($product->cache_default_attribute)) {
         ${${"GLOBALS"}["ygidwjibrt"]} = sprintf(Tools::displayError("This file \"%s\" is missing"), $product->productDownload->display_filename);
     } else {
         ${${"GLOBALS"}["ygidwjibrt"]} = "";
     }
     self::$smarty->assign("download_product_file_missing", ${${"GLOBALS"}["ygidwjibrt"]});
     self::$smarty->assign("download_dir_writable", ProductDownload::checkWritableDir());
     self::$smarty->assign("up_filename", strval(Tools::getValue("virtual_product_filename")));
     self::$smarty->assign("product_type", (int) Tools::getValue("type_product", $product->getType()));
     $product->productDownload->nb_downloadable = $product->productDownload->id > 0 ? $product->productDownload->nb_downloadable : htmlentities(Tools::getValue("virtual_product_nb_downloable"), ENT_COMPAT, "UTF-8");
     $pbrwepgkw = "upload_max_filesize";
     $product->productDownload->date_expiration = $product->productDownload->id > 0 ? !empty($product->productDownload->date_expiration) && $product->productDownload->date_expiration != "0000-00-00 00:00:00" ? date("Y-m-d", strtotime($product->productDownload->date_expiration)) : "" : htmlentities(Tools::getValue("virtual_product_expiration_date"), ENT_COMPAT, "UTF-8");
     $product->productDownload->nb_days_accessible = $product->productDownload->id > 0 ? $product->productDownload->nb_days_accessible : htmlentities(Tools::getValue("virtual_product_nb_days"), ENT_COMPAT, "UTF-8");
     $product->productDownload->is_shareable = $product->productDownload->id > 0 && $product->productDownload->is_shareable;
     self::$smarty->assign("ad", dirname($_SERVER["PHP_SELF"]));
     self::$smarty->assign("product", ${${"GLOBALS"}["vmqqtmkyw"]});
     self::$smarty->assign("currency", ${${"GLOBALS"}["sxexnhlq"]});
     $ctepbh = "upload_max_filesize";
     self::$smarty->assign("link", $this->context->link);
     self::$smarty->assign("is_file", $product->productDownload->checkFile());
     ${"GLOBALS"}["hwvivbnezby"] = "upload_max_filesize";
     ${${"GLOBALS"}["biwrimpair"]} = Tools::getOctets(ini_get("upload_max_filesize"));
     ${$pbrwepgkw} = ${${"GLOBALS"}["hwvivbnezby"]} / 1024 / 1024;
     self::$smarty->assign("upload_max_filesize", ${$ctepbh});
 }
 public function processGenerate()
 {
     if (!is_array(Tools::getValue('options'))) {
         $this->errors[] = $this->trans('Please select at least one attribute.', array(), 'Admin.Catalog.Notification');
     } else {
         $tab = array_values(Tools::getValue('options'));
         if (count($tab) && Validate::isLoadedObject($this->product)) {
             AdminAttributeGeneratorController::setAttributesImpacts($this->product->id, $tab);
             $this->combinations = array_values(AdminAttributeGeneratorController::createCombinations($tab));
             $values = array_values(array_map(array($this, 'addAttribute'), $this->combinations));
             // @since 1.5.0
             if ($this->product->depends_on_stock == 0) {
                 $attributes = Product::getProductAttributesIds($this->product->id, true);
                 foreach ($attributes as $attribute) {
                     StockAvailable::removeProductFromStockAvailable($this->product->id, $attribute['id_product_attribute'], Context::getContext()->shop);
                 }
             }
             SpecificPriceRule::disableAnyApplication();
             $this->product->deleteProductAttributes();
             $this->product->generateMultipleCombinations($values, $this->combinations);
             // Reset cached default attribute for the product and get a new one
             Product::getDefaultAttribute($this->product->id, 0, true);
             Product::updateDefaultAttribute($this->product->id);
             // @since 1.5.0
             if ($this->product->depends_on_stock == 0) {
                 $attributes = Product::getProductAttributesIds($this->product->id, true);
                 $quantity = (int) Tools::getValue('quantity');
                 foreach ($attributes as $attribute) {
                     if (Shop::getContext() == Shop::CONTEXT_ALL) {
                         $shops_list = Shop::getShops();
                         if (is_array($shops_list)) {
                             foreach ($shops_list as $current_shop) {
                                 if (isset($current_shop['id_shop']) && (int) $current_shop['id_shop'] > 0) {
                                     StockAvailable::setQuantity($this->product->id, (int) $attribute['id_product_attribute'], $quantity, (int) $current_shop['id_shop']);
                                 }
                             }
                         }
                     } else {
                         StockAvailable::setQuantity($this->product->id, (int) $attribute['id_product_attribute'], $quantity);
                     }
                 }
             } else {
                 StockAvailable::synchronize($this->product->id);
             }
             SpecificPriceRule::enableAnyApplication();
             SpecificPriceRule::applyAllRules(array((int) $this->product->id));
             Tools::redirectAdmin($this->context->link->getAdminLink('AdminProducts') . '&id_product=' . (int) Tools::getValue('id_product') . '&updateproduct&key_tab=Combinations&conf=4');
         } else {
             $this->errors[] = $this->trans('Unable to initialize these parameters. A combination is missing or an object cannot be loaded.');
         }
     }
 }
Пример #24
0
 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, $service_date = null, $service_time_from = null, $service_time_to = null)
 {
     require_once dirname(__FILE__) . '/../../modules/aphrodinet/classes/AphCustomPrice.php';
     static $address = null;
     static $context = null;
     if ($address === null) {
         $address = new Address();
     }
     if ($context == null) {
         $context = Context::getContext()->cloneContext();
     }
     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);
     }
     if (!empty($id_cart)) {
         $res = Db::getInstance()->executeS('SELECT `delivery_date`, `delivery_time_from`, `delivery_time_to` ' . 'FROM ' . _DB_PREFIX_ . 'cart_product ' . 'WHERE `id_cart` = ' . (int) $id_cart . ' AND `id_product` = ' . (int) $id_product . ' AND `id_product_attribute` = ' . (int) $id_product_attribute . ' ' . 'LIMIT 1');
         if (!empty($res) && empty($service_date)) {
             $res = $res[0];
             if (!empty($res)) {
                 $service_date = $res['delivery_date'];
                 $service_time_from = $res['delivery_time_from'];
                 $service_time_to = $res['delivery_time_to'];
             }
         }
     }
     if (!empty($service_time_from) && strlen($service_time_from) == 5) {
         $service_time_from .= ':00';
     }
     if (!empty($service_time_to) && strlen($service_time_to) == 5) {
         $service_time_to .= ':00';
     }
     $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) $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 . (!empty($service_date) && $service_date != '0000-00-00' ? '-' . $service_date : '') . (!empty($service_time_to) && $service_time_to != '00:00:00' ? '-' . $service_time_from : '') . (!empty($service_time_to) && $service_time_to != '00:00:00' ? '-' . $service_time_to : '');
     // 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])) {
         if (isset($specific_price['price']) && $specific_price['price'] > 0) {
             $specific_price['price'] = self::$_prices[$cache_id];
         }
         return self::$_prices[$cache_id];
     }
     $cache_id_2 = $id_product . '-' . $id_shop . (!empty($service_date) && $service_date != '0000-00-00' ? '-' . $service_date : '') . (!empty($service_time_to) && $service_time_to != '00:00:00' ? '-' . $service_time_from : '') . (!empty($service_time_to) && $service_time_to != '00:00:00' ? '-' . $service_time_to : '');
     if (!isset(self::$_pricesLevel2[$cache_id_2])) {
         $base_price_wt = 0;
         $service_date_ts = strtotime($service_date);
         $service_date_week_day = date('w', $service_date_ts);
         if (!empty($service_date) && $service_date != '0000-00-00') {
             // cerco il prezzo del giorno
             $custom_prices = AphCustomPrice::getByDate($id_shop, $id_currency, $id_country, $id_group, $service_date, $id_customer, (int) $id_product, -1, NULL, 1);
             if (!empty($custom_prices)) {
                 $base_price_wt = $custom_prices[0]['price_wt'];
             }
         }
         if (!empty($service_date) && $service_date != '0000-00-00') {
             $offer_prices = AphCustomPrice::getByDate($id_shop, $id_currency, $id_country, $id_group, $service_date, $id_customer, (int) $id_product, -1, 0, 1);
         }
         if (!empty($service_date) && $service_date != '0000-00-00') {
             $offer_prices = AphCustomPrice::getByDate($id_shop, $id_currency, $id_country, $id_group, $service_date, $id_customer, (int) $id_product, $service_date_week_day, 0, 1);
         }
         if (!empty($service_date) && $service_date != '0000-00-00' && empty($offer_prices)) {
             $custom_prices = AphCustomPrice::getByDate($id_shop, $id_currency, $id_country, $id_group, $service_date, $id_customer, (int) $id_product, -1);
         }
         if (!empty($service_date) && $service_date != '0000-00-00' && empty($offer_prices)) {
             $custom_prices = AphCustomPrice::getByDate($id_shop, $id_currency, $id_country, $id_group, $service_date, $id_customer, (int) $id_product, $service_date_week_day);
         }
         if (!empty($service_date) && $service_date != '0000-00-00' && !empty($service_time_to) && $service_time_to != '00:00:00' && empty($custom_prices) && empty($offer_prices)) {
             $custom_prices = AphCustomPrice::getByDate($id_shop, $id_currency, $id_country, $id_group, $service_date, $id_customer, (int) $id_product, -1, $service_time_from);
         }
         if (!empty($service_date) && $service_date != '0000-00-00' && !empty($service_time_to) && $service_time_to != '00:00:00' && empty($custom_prices) && empty($offer_prices)) {
             $custom_prices = AphCustomPrice::getByDate($id_shop, $id_currency, $id_country, $id_group, $service_date, $id_customer, (int) $id_product, $service_date_week_day, $service_time_from);
         }
         if (!empty($service_date) && $service_date != '0000-00-00' && empty($custom_prices) && empty($offer_prices)) {
             $custom_prices = AphCustomPrice::getByDate(Configuration::get('PS_SHOP_DEFAULT'), $id_currency, $id_country, $id_group, $service_date, $id_customer, (int) $id_product, -1);
         }
         if (!empty($service_date) && $service_date != '0000-00-00' && empty($custom_prices) && empty($offer_prices)) {
             $custom_prices = AphCustomPrice::getByDate(Configuration::get('PS_SHOP_DEFAULT'), $id_currency, $id_country, $id_group, $service_date, $id_customer, (int) $id_product, $service_date_week_day);
         }
         if (!empty($service_date) && $service_date != '0000-00-00' && !empty($service_time_to) && $service_time_to != '00:00:00' && empty($custom_prices) && empty($offer_prices)) {
             $custom_prices = AphCustomPrice::getByDate(Configuration::get('PS_SHOP_DEFAULT'), $id_currency, $id_country, $id_group, $service_date, $id_customer, (int) $id_product, -1, $service_time_from);
         }
         if (!empty($service_date) && $service_date != '0000-00-00' && !empty($service_time_to) && $service_time_to != '00:00:00' && empty($custom_prices) && empty($offer_prices)) {
             $custom_prices = AphCustomPrice::getByDate(Configuration::get('PS_SHOP_DEFAULT'), $id_currency, $id_country, $id_group, $service_date, $id_customer, (int) $id_product, $service_date_week_day, $service_time_from);
         }
         if (!empty($offer_prices)) {
             $res = $offer_prices;
         } elseif (!empty($custom_prices)) {
             $res = $custom_prices;
         } else {
             $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');
                 $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) {
                 if ($row['price'] < 0) {
                     if ($row['reduction_type'] == 'amount') {
                         $row['price'] = 0;
                         //$base_price_wt - $row['reduction'];
                     } else {
                         $row['price'] = 0;
                         //$base_price_wt - (($row['reduction'] * $base_price_wt) / 100);
                     }
                 } else {
                     $row['price'] = 0;
                     //$row['price_wt'];
                 }
                 $array_tmp = array('price' => $row['price'], 'ecotax' => !empty($row['ecotax']), 'attribute_price' => isset($row['attribute_price']) ? $row['attribute_price'] : 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];
     if (!$specific_price || $specific_price['price'] < 0) {
         $price = (double) $result['price'];
     } else {
         $price = (double) $specific_price['price'];
     }
     if (!$specific_price || !($specific_price['price'] >= 0 && $specific_price['id_currency'])) {
         $price = Tools::convertPrice($price, $id_currency);
         if (isset($specific_price['price'])) {
             $specific_price['price'] = $price;
         }
     }
     if (is_array($result) && (!$specific_price || !$specific_price['id_product_attribute'] || $specific_price['price'] < 0)) {
         $attribute_price = Tools::convertPrice($result['attribute_price'] !== null ? (double) $result['attribute_price'] : 0, $id_currency);
         if ($id_product_attribute !== false) {
             $price += $attribute_price;
         }
     }
     $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();
     if ($use_tax) {
         $price = $product_tax_calculator->addTaxes($price);
     }
     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) {
             $tax_manager = TaxManagerFactory::getManager($address, (int) Configuration::get('PS_ECOTAX_TAX_RULES_GROUP_ID'));
             $ecotax_tax_calculator = $tax_manager->getTaxCalculator();
             $price += $ecotax_tax_calculator->addTaxes($ecotax);
         } else {
             $price += $ecotax;
         }
     }
     $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;
             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;
     }
     if ($use_group_reduction) {
         $reduction_from_category = GroupReduction::getValueForProduct($id_product, $id_group);
         if ($reduction_from_category !== false) {
             $group_reduction = $price * (double) $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];
 }
Пример #25
0
 protected function processChangeProductInCart()
 {
     $mode = Tools::getIsset('update') && $this->id_product ? 'update' : 'add';
     if (!$this->id_product) {
         $this->errors[] = Tools::displayError('Product not found', !Tools::getValue('ajax'));
     }
     $product = new Product($this->id_product, true, $this->context->language->id);
     if (!$product->id || !$product->active || !$product->checkAccess($this->context->cart->id_customer)) {
         $this->errors[] = Tools::displayError('This product is no longer available.', !Tools::getValue('ajax'));
         return;
     }
     $qty_factor = 1;
     $ext_qty_factor = 1;
     $ext_prop_quantities = null;
     $id_cart_product = 0;
     $qty_behavior = 0;
     $icp = (int) Tools::getValue('icp');
     $properties = $product->productProperties();
     if ($icp && $this->context->cart->id) {
         $cart_products = $this->context->cart->getProducts();
         if (count($cart_products)) {
             foreach ($cart_products as $cart_product) {
                 if ($icp == (int) $cart_product['id_cart_product']) {
                     $id_cart_product = $icp;
                     if ($mode == 'add') {
                         if (Tools::getValue('qty') != 'default') {
                             $qty_factor = (int) Tools::getValue('qty');
                         }
                         $_POST['qty'] = (double) $cart_product['cart_quantity_fractional'] > 0 ? (double) $cart_product['cart_quantity_fractional'] : ($product->qtyStep() > 0 ? $product->qtyStep() : 1);
                     } elseif ($mode == 'update') {
                         $qty_behavior = PP::qtyBehavior($product, $cart_product['cart_quantity']);
                     }
                     break;
                 }
             }
         }
     } else {
         if ($properties['pp_ext'] == 1 && in_array($properties['pp_ext_policy'], array(0, 2))) {
             $ext_prop_quantities = array();
             $ext_prop_qty_ratio = array();
             if ($properties['pp_ext_policy'] == 2) {
                 $prop = $product->productProp();
                 if ($this->id_product_attribute) {
                     $id_product_attribute = $this->id_product_attribute;
                 } else {
                     if ($product->hasAttributes()) {
                         $id_product_attribute = Product::getDefaultAttribute($product->id);
                     } else {
                         $id_product_attribute = 0;
                     }
                 }
             }
             $positions = count($properties['pp_ext_prop']);
             for ($position = 1; $position <= $positions; $position++) {
                 $pp_ext_prop = $properties['pp_ext_prop'][$position];
                 if ($properties['pp_ext_policy'] == 2) {
                     $q = PP::productProp($prop, $id_product_attribute, $position, 'quantity');
                     if ($q === false) {
                         $q = (double) $pp_ext_prop['default_quantity'];
                     }
                     if ($q <= 0) {
                         $q = 1;
                     }
                 } else {
                     $q = PP::resolveInputQty(Tools::getValue('pp_ext_prop_quantity_' . $position, 'default'), $properties['pp_qty_policy'], $pp_ext_prop['qty_step'], $pp_ext_prop['default_quantity'] > 0 ? $pp_ext_prop['default_quantity'] : 1);
                 }
                 $ext_prop_quantities[$position] = $q;
                 $ext_prop_qty_ratio[$position] = $properties['pp_ext_prop'][$position]['qty_ratio'];
                 if ($q <= 0) {
                     $this->errors[] = Tools::displayError('Quantity not specified.', !Tools::getValue('ajax'));
                 }
                 $min_qty = (double) $pp_ext_prop['minimum_quantity'];
                 if ($min_qty > 0 && $q < $min_qty) {
                     $this->errors[] = Tools::displayError(sprintf('Please specify at least %s for %s', (string) PP::formatQty($min_qty), (string) $pp_ext_prop['property']), !Tools::getValue('ajax'));
                 }
                 $max_qty = (double) $pp_ext_prop['maximum_quantity'];
                 if ($max_qty > 0 && $q > $max_qty) {
                     $this->errors[] = Tools::displayError(sprintf('Please specify no more than %s for %s', (string) PP::formatQty($max_qty), (string) $pp_ext_prop['property']), !Tools::getValue('ajax'));
                 }
             }
             if (!$this->errors) {
                 $ext_qty_factor = $properties['pp_ext_method'] == 1 ? 1 : 0;
                 $positions = count($ext_prop_quantities);
                 for ($position = 1; $position <= $positions; $position++) {
                     $value = $ext_prop_quantities[$position];
                     $qty_ratio = $ext_prop_qty_ratio[$position];
                     if ($properties['pp_ext_method'] == 1) {
                         $ext_qty_factor *= $qty_ratio > 0 ? $value / $qty_ratio : $value;
                     } elseif ($properties['pp_ext_method'] == 2) {
                         $ext_qty_factor += $qty_ratio > 0 ? $value / $qty_ratio : $value;
                     }
                 }
             }
         }
     }
     if (!$this->errors) {
         if ($this->id_product_attribute) {
             $default_quantity = $product->attributeDefaultQty($this->id_product_attribute);
             $this->qty = $qty_factor * $this->resolveInputQty($properties, $default_quantity);
             if ($this->qty == 0) {
                 $this->errors[] = Tools::displayError('Quantity not specified.', !Tools::getValue('ajax'));
             } else {
                 if (!Product::isAvailableWhenOutOfStock($product->out_of_stock) && !Attribute::checkAttributeQty($this->id_product_attribute, $ext_qty_factor * $this->qty)) {
                     $this->errors[] = Tools::displayError('There isn\'t enough product in stock.', !Tools::getValue('ajax'));
                 }
             }
         } else {
             if ($product->hasAttributes()) {
                 $min_quantity = $product->out_of_stock == 2 ? !Configuration::get('PS_ORDER_OUT_OF_STOCK') : !$product->out_of_stock;
                 $this->id_product_attribute = Product::getDefaultAttribute($product->id, $min_quantity);
                 if (!$this->id_product_attribute) {
                     Tools::redirectAdmin($this->context->link->getProductLink($product));
                 } else {
                     $default_quantity = $product->attributeDefaultQty($this->id_product_attribute);
                     $this->qty = $qty_factor * $this->resolveInputQty($properties, $default_quantity);
                     if ($this->qty == 0) {
                         $this->errors[] = Tools::displayError('Quantity not specified.', !Tools::getValue('ajax'));
                     } else {
                         if (!Product::isAvailableWhenOutOfStock($product->out_of_stock) && !Attribute::checkAttributeQty($this->id_product_attribute, $ext_qty_factor * $this->qty)) {
                             $this->errors[] = Tools::displayError('There isn\'t enough product in stock.', !Tools::getValue('ajax'));
                         }
                     }
                 }
             } else {
                 $default_quantity = $product->defaultQty();
                 $this->qty = $qty_factor * $this->resolveInputQty($properties, $default_quantity);
                 if ($this->qty == 0) {
                     $this->errors[] = Tools::displayError('Quantity not specified.', !Tools::getValue('ajax'));
                 } else {
                     if (!$product->checkQty($ext_qty_factor * $this->qty)) {
                         $this->errors[] = Tools::displayError('There isn\'t enough product in stock.', !Tools::getValue('ajax'));
                     }
                 }
             }
         }
     }
     if (!$this->errors && ($mode == 'add' || $mode == 'update' && $qty_behavior)) {
         if ($mode == 'add' && !$this->context->cart->id) {
             if (Context::getContext()->cookie->id_guest) {
                 $guest = new Guest(Context::getContext()->cookie->id_guest);
                 $this->context->cart->mobile_theme = $guest->mobile_theme;
             }
             $this->context->cart->add();
             if ($this->context->cart->id) {
                 $this->context->cookie->id_cart = (int) $this->context->cart->id;
             }
         }
         if (!$product->hasAllRequiredCustomizableFields() && !$this->customization_id) {
             $this->errors[] = Tools::displayError('Please fill in all of the required fields, and then save your customizations.', !Tools::getValue('ajax'));
         }
         if (!$this->errors) {
             $cart_rules = $this->context->cart->getCartRules();
             $update_quantity = $this->context->cart->updateQty($id_cart_product ? $mode == 'add' ? $qty_factor : $this->qty : ($ext_prop_quantities !== null ? $ext_qty_factor : $this->qty), $this->id_product, $this->id_product_attribute, $this->customization_id, $mode == 'update' ? 'update' : Tools::getValue('op', 'up'), $this->id_address_delivery, null, true, $id_cart_product, $ext_prop_quantities, $this->qty);
             if ($update_quantity < 0) {
                 $minimal_quantity = $this->id_product_attribute ? $product->attributeMinQty($this->id_product_attribute) : $product->minQty();
                 $this->errors[] = Tools::displayError(sprintf('You must add %s minimum quantity', $minimal_quantity), !Tools::getValue('ajax'));
             } elseif (!$update_quantity) {
                 $this->errors[] = Tools::displayError('You already have the maximum quantity available for this product.', !Tools::getValue('ajax'));
             } elseif ((int) Tools::getValue('allow_refresh')) {
                 $cart_rules2 = $this->context->cart->getCartRules();
                 if (count($cart_rules2) != count($cart_rules)) {
                     $this->ajax_refresh = true;
                 } else {
                     $rule_list = array();
                     foreach ($cart_rules2 as $rule) {
                         $rule_list[] = $rule['id_cart_rule'];
                     }
                     foreach ($cart_rules as $rule) {
                         if (!in_array($rule['id_cart_rule'], $rule_list)) {
                             $this->ajax_refresh = true;
                             break;
                         }
                     }
                 }
             }
         }
     }
     $removed = CartRule::autoRemoveFromCart();
     CartRule::autoAddToCart();
     if (count($removed) && (int) Tools::getValue('allow_refresh')) {
         $this->ajax_refresh = true;
     }
 }
 public function getPrice($id_shop = null, $id_product, $id_product_attribute = null, $id_country = null, $id_state = null, $county = null, $id_currency = null, $id_group = null, $quantity = null, $use_tax = null, $decimals = null, $only_reduc = null, $use_reduc = null, $with_ecotax = null, $specific_price_output = null, $divisor = null)
 {
     $id_shop = isset($id_shop) ? $id_shop : (int) Shop::getCurrentShop();
     // TO CHECK
     $id_product_attribute = isset($id_product_attribute) ? $id_product_attribute : Product::getDefaultAttribute($id_product);
     // FIXME
     $id_country = isset($id_country) ? $id_country : (int) Configuration::get('PS_COUNTRY_DEFAULT');
     $id_state = isset($id_state) ? $id_state : 0;
     $id_currency = isset($id_currency) ? $id_currency : Configuration::get('PS_CURRENCY_DEFAULT');
     $id_group = isset($id_group) ? $id_group : Configuration::get('_PS_DEFAULT_CUSTOMER_GROUP_');
     $quantity = isset($quantity) ? $quantity : 1;
     $use_tax = isset($use_tax) ? $use_tax : Configuration::get('PS_TAX');
     $decimals = isset($decimals) ? $decimals : 6;
     $only_reduc = isset($only_reduc) ? $only_reduc : false;
     $use_reduc = isset($use_reduc) ? $use_reduc : true;
     $use_ecotax = isset($use_ecotax) ? $use_ecotax : true;
     $specific_price_output = null;
     $county = isset($county) ? $county : 0;
     // UNUSED
     $divisor = null;
     $price = Product::priceCalculation($id_shop, $id_product, $id_product_attribute, $id_country, $id_state, $county, $id_currency, $id_group, $quantity, $use_tax, $decimals, $only_reduc, $use_reduc, $use_ecotax, $specific_price_output, $divisor);
     return Tools::ps_round($price, 2);
 }
Пример #27
0
 /**
  * Add an item to the pack
  *
  * @param int $id_product
  * @param int $id_item
  * @param int $qty
  * @param int     $id_attribute_item
  * @return bool true if everything was fine
  * @throws PrestaShopDatabaseException
  */
 public static function addItem($id_product, $id_item, $qty, $id_attribute_item = 0)
 {
     $id_attribute_item = (int) $id_attribute_item ? (int) $id_attribute_item : Product::getDefaultAttribute((int) $id_item);
     return Db::getInstance()->update('product', array('cache_is_pack' => 1), 'id_product = ' . (int) $id_product) && Db::getInstance()->insert('pack', array('id_product_pack' => (int) $id_product, 'id_product_item' => (int) $id_item, 'id_product_attribute_item' => (int) $id_attribute_item, 'quantity' => (int) $qty)) && Configuration::updateGlobalValue('PS_PACK_FEATURE_ACTIVE', '1');
 }
Пример #28
0
 public static function getProductProperties($id_lang, $row)
 {
     if (!$row['id_product']) {
         return false;
     }
     $link = new Link();
     // Tax
     $usetax = true;
     $tax = floatval(Tax::getApplicableTax(intval($row['id_tax']), floatval($row['rate'])));
     if (Tax::excludeTaxeOption() or !$tax) {
         $usetax = false;
     }
     // Datas
     $row['category'] = Category::getLinkRewrite($row['id_category_default'], intval($id_lang));
     $row['link'] = $link->getProductLink($row['id_product'], $row['link_rewrite'], $row['category'], $row['ean13']);
     $row['allow_oosp'] = Product::isAvailableWhenOutOfStock($row['out_of_stock']);
     if ((!isset($row['id_product_attribute']) or !$row['id_product_attribute']) and $ipa_default = Product::getDefaultAttribute($row['id_product'], !$row['allow_oosp'])) {
         $row['id_product_attribute'] = $ipa_default;
     }
     $row['attribute_price'] = isset($row['id_product_attribute']) and $row['id_product_attribute'] ? floatval(Product::getProductAttributePrice($row['id_product_attribute'])) : 0;
     $row['price_tax_exc'] = Product::getPriceStatic($row['id_product'], false, (isset($row['id_product_attribute']) and !empty($row['id_product_attribute'])) ? intval($row['id_product_attribute']) : NULL, 2);
     $row['price'] = Product::getPriceStatic($row['id_product'], true, (isset($row['id_product_attribute']) and !empty($row['id_product_attribute'])) ? intval($row['id_product_attribute']) : NULL, 2);
     $row['reduction'] = self::getReductionValue($row['reduction_price'], $row['reduction_percent'], $row['reduction_from'], $row['reduction_to'], $row['price'], $usetax, floatval($row['rate']));
     $row['price_without_reduction'] = Product::getPriceStatic($row['id_product'], true, (isset($row['id_product_attribute']) and !empty($row['id_product_attribute'])) ? intval($row['id_product_attribute']) : NULL, 2, NULL, false, false);
     $row['quantity'] = Product::getQuantity($row['id_product']);
     $row['id_image'] = Product::defineProductImage($row);
     $row['features'] = Product::getFrontFeaturesStatic(intval($id_lang), $row['id_product']);
     $row['attachments'] = Product::getAttachmentsStatic(intval($id_lang), $row['id_product']);
     $row['pack'] = Pack::isPack($row['id_product']);
     $row['packItems'] = $row['pack'] ? Pack::getItemTable($row['id_product'], $id_lang) : array();
     $row['nopackprice'] = $row['pack'] ? Pack::noPackPrice($row['id_product']) : 0;
     return $row;
 }