public function __construct($id = null, $enable_hook = true)
 {
     $this->class_name = get_class($this);
     if (!Object::$db) {
         Object::$db = Db::getInstance();
     }
     self::$is_cache_enabled = defined('OBJECT_CACHE_ENABLE') ? OBJECT_CACHE_ENABLE : false;
     if (isset($id) && Validate::isUnsignedId($id)) {
         $cache_id = $this->class_name . self::CACHE_PREFIX_MODEL . (int) $id;
         if (!Cache::isStored($cache_id)) {
             $sql = new DbQuery();
             $sql->from($this->def['table'], 'a');
             $sql->where('a.' . $this->def['primary'] . '=' . (int) $id);
             if ($object_datas = Object::$db->getRow($sql)) {
                 Cache::store($cache_id, $object_datas);
             }
         } else {
             $object_datas = Cache::retrieve($cache_id);
         }
         if ($object_datas) {
             $this->id = (int) $id;
             foreach ($object_datas as $key => $value) {
                 if (array_key_exists($key, $this)) {
                     $this->{$key} = $value;
                 }
             }
         }
         if ($enable_hook && method_exists($this, 'extraConstruct')) {
             $this->extraConstruct();
         }
     }
 }
    /**
     * Load ObjectModel
     * @param $id
     * @param $id_lang
     * @param $entity ObjectModel
     * @param $entity_defs
     * @param $id_shop
     * @param $should_cache_objects
     * @throws PrestaShopDatabaseException
     */
    public function load($id, $id_lang, $entity, $entity_defs, $id_shop, $should_cache_objects)
    {
        // Load object from database if object id is present
        $cache_id = 'objectmodel_' . $entity_defs['classname'] . '_' . (int) $id . '_' . (int) $id_shop . '_' . (int) $id_lang;
        if (!$should_cache_objects || !Cache::isStored($cache_id)) {
            $sql = new DbQuery();
            $sql->from($entity_defs['table'], 'a');
            $sql->where('a.`' . bqSQL($entity_defs['primary']) . '` = ' . (int) $id);
            // Get lang informations
            if ($id_lang && isset($entity_defs['multilang']) && $entity_defs['multilang']) {
                $sql->leftJoin($entity_defs['table'] . '_lang', 'b', 'a.`' . bqSQL($entity_defs['primary']) . '` = b.`' . bqSQL($entity_defs['primary']) . '` AND b.`id_lang` = ' . (int) $id_lang);
                if ($id_shop && !empty($entity_defs['multilang_shop'])) {
                    $sql->where('b.`id_shop` = ' . (int) $id_shop);
                }
            }
            // Get shop informations
            if (Shop::isTableAssociated($entity_defs['table'])) {
                $sql->leftJoin($entity_defs['table'] . '_shop', 'c', 'a.`' . bqSQL($entity_defs['primary']) . '` = c.`' . bqSQL($entity_defs['primary']) . '` AND c.`id_shop` = ' . (int) $id_shop);
            }
            if ($object_datas = Db::getInstance()->getRow($sql)) {
                if (!$id_lang && isset($entity_defs['multilang']) && $entity_defs['multilang']) {
                    $sql = 'SELECT *
							FROM `' . bqSQL(_DB_PREFIX_ . $entity_defs['table']) . '_lang`
							WHERE `' . bqSQL($entity_defs['primary']) . '` = ' . (int) $id . ($id_shop && $entity->isLangMultishop() ? ' AND `id_shop` = ' . (int) $id_shop : '');
                    if ($object_datas_lang = Db::getInstance()->executeS($sql)) {
                        foreach ($object_datas_lang as $row) {
                            foreach ($row as $key => $value) {
                                if ($key != $entity_defs['primary'] && array_key_exists($key, $entity)) {
                                    if (!isset($object_datas[$key]) || !is_array($object_datas[$key])) {
                                        $object_datas[$key] = array();
                                    }
                                    $object_datas[$key][$row['id_lang']] = $value;
                                }
                            }
                        }
                    }
                }
                $entity->id = (int) $id;
                foreach ($object_datas as $key => $value) {
                    if (array_key_exists($key, $entity)) {
                        $entity->{$key} = $value;
                    } else {
                        unset($object_datas[$key]);
                    }
                }
                if ($should_cache_objects) {
                    Cache::store($cache_id, $object_datas);
                }
            }
        } else {
            $object_datas = Cache::retrieve($cache_id);
            if ($object_datas) {
                $entity->id = (int) $id;
                foreach ($object_datas as $key => $value) {
                    $entity->{$key} = $value;
                }
            }
        }
    }
Exemple #3
0
 /**
  * @param int $id_tax
  * @return bool
  */
 public static function isTaxInUse($id_tax)
 {
     $cache_id = 'TaxRule::isTaxInUse_' . (int) $id_tax;
     if (!Cache::isStored($cache_id)) {
         $result = (int) Db::getInstance()->getValue('SELECT COUNT(*) FROM `' . _DB_PREFIX_ . 'tax_rule` WHERE `id_tax` = ' . (int) $id_tax);
         Cache::store($cache_id, $result);
         return $result;
     }
     return Cache::retrieve($cache_id);
 }
Exemple #4
0
    /**
     * Get all available order statuses
     *
     * @param integer $id_lang Language id for status name
     * @return array Order statuses
     */
    public static function getOrderStates($id_lang)
    {
        $cache_id = 'OrderState::getOrderStates_' . (int) $id_lang;
        if (!Cache::isStored($cache_id)) {
            $result = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS('
			SELECT *
			FROM `' . _DB_PREFIX_ . 'order_state` os
			LEFT JOIN `' . _DB_PREFIX_ . 'order_state_lang` osl ON (os.`id_order_state` = osl.`id_order_state` AND osl.`id_lang` = ' . (int) $id_lang . ')
			WHERE deleted = 0
			ORDER BY `name` ASC');
            Cache::store($cache_id, $result);
        }
        return Cache::retrieve($cache_id);
    }
    /**
     * Get all available geographical zones
     *
     * @param bool $active
     * @return array Zones
     */
    public static function getZones($active = false)
    {
        $cache_id = 'Zone::getZones_' . (bool) $active;
        if (!Cache::isStored($cache_id)) {
            $result = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS('
				SELECT *
				FROM `' . _DB_PREFIX_ . 'zone`
				' . ($active ? 'WHERE active = 1' : '') . '
				ORDER BY `name` ASC
			');
            Cache::store($cache_id, $result);
        }
        return Cache::retrieve($cache_id);
    }
    /**
     * Return the tax calculator associated to this address
     *
     * @return TaxCalculator
     */
    public function getTaxCalculator()
    {
        static $tax_enabled = null;
        if (isset($this->tax_calculator)) {
            return $this->tax_calculator;
        }
        if ($tax_enabled === null) {
            $tax_enabled = $this->configurationManager->get('PS_TAX');
        }
        if (!$tax_enabled) {
            return new TaxCalculator(array());
        }
        $taxes = array();
        $postcode = 0;
        if (!empty($this->address->postcode)) {
            $postcode = $this->address->postcode;
        }
        $cache_id = (int) $this->address->id_country . '-' . (int) $this->address->id_state . '-' . $postcode . '-' . (int) $this->type;
        if (!Cache::isStored($cache_id)) {
            $rows = Db::getInstance()->executeS('
				SELECT tr.*
				FROM `' . _DB_PREFIX_ . 'tax_rule` tr
				JOIN `' . _DB_PREFIX_ . 'tax_rules_group` trg ON (tr.`id_tax_rules_group` = trg.`id_tax_rules_group`)
				WHERE trg.`active` = 1
				AND tr.`id_country` = ' . (int) $this->address->id_country . '
				AND tr.`id_tax_rules_group` = ' . (int) $this->type . '
				AND tr.`id_state` IN (0, ' . (int) $this->address->id_state . ')
				AND (\'' . pSQL($postcode) . '\' BETWEEN tr.`zipcode_from` AND tr.`zipcode_to`
					OR (tr.`zipcode_to` = 0 AND tr.`zipcode_from` IN(0, \'' . pSQL($postcode) . '\')))
				ORDER BY tr.`zipcode_from` DESC, tr.`zipcode_to` DESC, tr.`id_state` DESC, tr.`id_country` DESC');
            $behavior = 0;
            $first_row = true;
            foreach ($rows as $row) {
                $tax = new Tax((int) $row['id_tax']);
                $taxes[] = $tax;
                // the applied behavior correspond to the most specific rules
                if ($first_row) {
                    $behavior = $row['behavior'];
                    $first_row = false;
                }
                if ($row['behavior'] == 0) {
                    break;
                }
            }
            $result = new TaxCalculator($taxes, $behavior);
            Cache::store($cache_id, $result);
            return $result;
        }
        return Cache::retrieve($cache_id);
    }
Exemple #7
0
    /**
     * Get a state id with its name
     *
     * @param string $id_state Country ID
     * @return integer state id
     */
    public static function getIdByName($state)
    {
        if (empty($state)) {
            return false;
        }
        $cache_id = 'State::getNameById_' . pSQL($state);
        if (!Cache::isStored($cache_id)) {
            $result = (int) Db::getInstance()->getValue('
				SELECT `id_state`
				FROM `' . _DB_PREFIX_ . 'state`
				WHERE `name` LIKE \'' . pSQL($state) . '\'
			');
            Cache::store($cache_id, $result);
        }
        return Cache::retrieve($cache_id);
    }
 public function setLastVisitedCategory()
 {
     $cache_id = 'pspagebuilder::setLastVisitedCategory';
     $context = Context::getContext();
     if (!Cache::isStored($cache_id)) {
         if (method_exists($context->controller, 'getCategory') && ($category = $context->controller->getCategory())) {
             $context->cookie->last_visited_category = $category->id;
         } elseif (method_exists($context->controller, 'getProduct') && ($product = $context->controller->getProduct())) {
             if (!isset($context->cookie->last_visited_category) || !Product::idIsOnCategoryId($product->id, array(array('id_category' => $context->cookie->last_visited_category))) || !Category::inShopStatic($context->cookie->last_visited_category, $context->shop)) {
                 $context->cookie->last_visited_category = (int) $product->id_category_default;
             }
         }
         Cache::store($cache_id, $context->cookie->last_visited_category);
     }
     return Cache::retrieve($cache_id);
 }
Exemple #9
0
    /**
     * Return customer addresses
     * Override method with default Prestashop Method, To don't show the Receiver address to Custommer/ Sender
     * @param integer $id_lang Language ID
     * @param bool $ship2myid_flag flag to show the address
     * @return array Addresses
     */
    public function getAddresses($id_lang, $ship2myid_flag = true)
    {
        $share_order = (bool) Context::getContext()->shop->getGroup()->share_order;
        $cache_id = 'Customer::getAddresses' . (int) $this->id . '-' . (int) $id_lang . '-' . $share_order;
        if (!Cache::isStored($cache_id)) {
            $sql = 'SELECT DISTINCT a.*, cl.`name` AS country, s.name AS state, s.iso_code AS state_iso
					FROM `' . _DB_PREFIX_ . 'address` a
					LEFT JOIN `' . _DB_PREFIX_ . 'country` c ON (a.`id_country` = c.`id_country`)
					LEFT JOIN `' . _DB_PREFIX_ . 'country_lang` cl ON (c.`id_country` = cl.`id_country`)
					LEFT JOIN `' . _DB_PREFIX_ . 'state` s ON (s.`id_state` = a.`id_state`)
					' . ($share_order ? '' : Shop::addSqlAssociation('country', 'c')) . ' 
					WHERE `id_lang` = ' . (int) $id_lang . ' AND `id_customer` = ' . (int) $this->id . ' AND a.`deleted` = 0';
            //echo $ship2myid_flag.'hii';
            if ($ship2myid_flag) {
                $sql .= ' AND ( ( LOWER(alias ) NOT LIKE "ship2myid-%") AND (LOWER(alias) NOT LIKE "shiptomyid-%" ) ) ';
            }
            $result = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($sql);
            Cache::store($cache_id, $result);
        }
        return Cache::retrieve($cache_id);
    }
Exemple #10
0
 /**
  * Check employee informations saved into cookie and return employee validity
  *
  * @return bool employee validity
  */
 public function isLoggedBack()
 {
     if (!Cache::isStored('isLoggedBack' . $this->id)) {
         /* Employee is valid only if it can be load and if cookie password is the same as database one */
         $result = $this->id && Validate::isUnsignedId($this->id) && Employee::checkPassword($this->id, Context::getContext()->cookie->passwd) && (!isset(Context::getContext()->cookie->remote_addr) || Context::getContext()->cookie->remote_addr == ip2long(Tools::getRemoteAddr()) || !Configuration::get('PS_COOKIE_CHECKIP'));
         Cache::store('isLoggedBack' . $this->id, $result);
         return $result;
     }
     return Cache::retrieve('isLoggedBack' . $this->id);
 }
Exemple #11
0
    /**
     * Get a city id with its name
     *
     * @param string $id_state Country ID
     * @return int city id
     */
    public static function getIdByName($city)
    {
        if (empty($city)) {
            return false;
        }
        $cache_id = 'City::getIdByName_' . pSQL($city);
        if (!Cache::isStored($cache_id)) {
            $result = (int) Db::getInstance()->getValue('
				SELECT `id_city`
				FROM `' . _DB_PREFIX_ . 'city`
				WHERE `name` = \'' . pSQL($city) . '\'
			');
            Cache::store($cache_id, $result);
            return $result;
        }
        return Cache::retrieve($cache_id);
    }
Exemple #12
0
 /**
  * For a given {product, warehouse}, gets the carrier available
  *
  * @since 1.5.0
  *
  * @param Product $product             The id of the product, or an array with at least the package size and weight
  * @param int     $id_warehouse        Warehouse ID
  * @param int     $id_address_delivery Delivery Address ID
  * @param int     $id_shop             Shop ID
  * @param Cart    $cart                Cart object
  * @param array   &$error              contain an error message if an error occurs
  *
  * @return array Available Carriers
  * @throws PrestaShopDatabaseException
  */
 public static function getAvailableCarrierList(Product $product, $id_warehouse, $id_address_delivery = null, $id_shop = null, $cart = null, &$error = array())
 {
     static $ps_country_default = null;
     if ($ps_country_default === null) {
         $ps_country_default = Configuration::get('PS_COUNTRY_DEFAULT');
     }
     if (is_null($id_shop)) {
         $id_shop = Context::getContext()->shop->id;
     }
     if (is_null($cart)) {
         $cart = Context::getContext()->cart;
     }
     if (is_null($error) || !is_array($error)) {
         $error = array();
     }
     $id_address = (int) (!is_null($id_address_delivery) && $id_address_delivery != 0 ? $id_address_delivery : $cart->id_address_delivery);
     if ($id_address) {
         $id_zone = Address::getZoneById($id_address);
         // Check the country of the address is activated
         if (!Address::isCountryActiveById($id_address)) {
             return array();
         }
     } else {
         $country = new Country($ps_country_default);
         $id_zone = $country->id_zone;
     }
     // Does the product is linked with carriers?
     $cache_id = 'Carrier::getAvailableCarrierList_' . (int) $product->id . '-' . (int) $id_shop;
     if (!Cache::isStored($cache_id)) {
         $query = new DbQuery();
         $query->select('id_carrier');
         $query->from('product_carrier', 'pc');
         $query->innerJoin('carrier', 'c', 'c.id_reference = pc.id_carrier_reference AND c.deleted = 0 AND c.active = 1');
         $query->where('pc.id_product = ' . (int) $product->id);
         $query->where('pc.id_shop = ' . (int) $id_shop);
         $carriers_for_product = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($query);
         Cache::store($cache_id, $carriers_for_product);
     } else {
         $carriers_for_product = Cache::retrieve($cache_id);
     }
     $carrier_list = array();
     if (!empty($carriers_for_product)) {
         //the product is linked with carriers
         foreach ($carriers_for_product as $carrier) {
             //check if the linked carriers are available in current zone
             if (Carrier::checkCarrierZone($carrier['id_carrier'], $id_zone)) {
                 $carrier_list[$carrier['id_carrier']] = $carrier['id_carrier'];
             }
         }
         if (empty($carrier_list)) {
             return array();
         }
         //no linked carrier are available for this zone
     }
     // The product is not directly linked with a carrier
     // Get all the carriers linked to a warehouse
     if ($id_warehouse) {
         $warehouse = new Warehouse($id_warehouse);
         $warehouse_carrier_list = $warehouse->getCarriers();
     }
     $available_carrier_list = array();
     $cache_id = 'Carrier::getAvailableCarrierList_getCarriersForOrder_' . (int) $id_zone . '-' . (int) $cart->id;
     if (!Cache::isStored($cache_id)) {
         $customer = new Customer($cart->id_customer);
         $carrier_error = array();
         $carriers = Carrier::getCarriersForOrder($id_zone, $customer->getGroups(), $cart, $carrier_error);
         Cache::store($cache_id, array($carriers, $carrier_error));
     } else {
         list($carriers, $carrier_error) = Cache::retrieve($cache_id);
     }
     $error = array_merge($error, $carrier_error);
     foreach ($carriers as $carrier) {
         $available_carrier_list[$carrier['id_carrier']] = $carrier['id_carrier'];
     }
     if ($carrier_list) {
         $carrier_list = array_intersect($available_carrier_list, $carrier_list);
     } else {
         $carrier_list = $available_carrier_list;
     }
     if (isset($warehouse_carrier_list)) {
         $carrier_list = array_intersect($carrier_list, $warehouse_carrier_list);
     }
     $cart_quantity = 0;
     $cart_weight = 0;
     foreach ($cart->getProducts(false, false) as $cart_product) {
         if ($cart_product['id_product'] == $product->id) {
             $cart_quantity += $cart_product['cart_quantity'];
         }
         if (isset($cart_product['weight_attribute']) && $cart_product['weight_attribute'] > 0) {
             $cart_weight += $cart_product['weight_attribute'] * $cart_product['cart_quantity'];
         } else {
             $cart_weight += $cart_product['weight'] * $cart_product['cart_quantity'];
         }
     }
     if ($product->width > 0 || $product->height > 0 || $product->depth > 0 || $product->weight > 0 || $cart_weight > 0) {
         foreach ($carrier_list as $key => $id_carrier) {
             $carrier = new Carrier($id_carrier);
             // Get the sizes of the carrier and the product and sort them to check if the carrier can take the product.
             $carrier_sizes = array((int) $carrier->max_width, (int) $carrier->max_height, (int) $carrier->max_depth);
             $product_sizes = array((int) $product->width, (int) $product->height, (int) $product->depth);
             rsort($carrier_sizes, SORT_NUMERIC);
             rsort($product_sizes, SORT_NUMERIC);
             if ($carrier_sizes[0] > 0 && $carrier_sizes[0] < $product_sizes[0] || $carrier_sizes[1] > 0 && $carrier_sizes[1] < $product_sizes[1] || $carrier_sizes[2] > 0 && $carrier_sizes[2] < $product_sizes[2]) {
                 $error[$carrier->id] = Carrier::SHIPPING_SIZE_EXCEPTION;
                 unset($carrier_list[$key]);
             }
             if ($carrier->max_weight > 0 && ($carrier->max_weight < $product->weight * $cart_quantity || $carrier->max_weight < $cart_weight)) {
                 $error[$carrier->id] = Carrier::SHIPPING_WEIGHT_EXCEPTION;
                 unset($carrier_list[$key]);
             }
         }
     }
     return $carrier_list;
 }
Exemple #13
0
    /**
     * Update products cart address delivery with the address delivery of the cart
     */
    public function setNoMultishipping()
    {
        $emptyCache = false;
        if (Configuration::get('PS_ALLOW_MULTISHIPPING')) {
            // Upgrading quantities
            $sql = 'SELECT sum(`quantity`) as quantity, id_product, id_product_attribute, count(*) as count
					FROM `' . _DB_PREFIX_ . 'cart_product`
					WHERE `id_cart` = ' . (int) $this->id . '
						AND `id_shop` = ' . (int) $this->id_shop . '
					GROUP BY id_product, id_product_attribute
					HAVING count > 1';
            foreach (Db::getInstance()->executeS($sql) as $product) {
                $sql = 'UPDATE `' . _DB_PREFIX_ . 'cart_product`
					SET `quantity` = ' . $product['quantity'] . '
					WHERE  `id_cart` = ' . (int) $this->id . '
						AND `id_shop` = ' . (int) $this->id_shop . '
						AND id_product = ' . $product['id_product'] . '
						AND id_product_attribute = ' . $product['id_product_attribute'];
                if (Db::getInstance()->execute($sql)) {
                    $emptyCache = true;
                }
            }
            // Merging multiple lines
            $sql = 'DELETE cp1
				FROM `' . _DB_PREFIX_ . 'cart_product` cp1
					INNER JOIN `' . _DB_PREFIX_ . 'cart_product` cp2
					ON (
						(cp1.id_cart = cp2.id_cart)
						AND (cp1.id_product = cp2.id_product)
						AND (cp1.id_product_attribute = cp2.id_product_attribute)
						AND (cp1.id_address_delivery <> cp2.id_address_delivery)
						AND (cp1.date_add > cp2.date_add)
					)';
            Db::getInstance()->execute($sql);
        }
        // Update delivery address for each product line
        $sql = 'UPDATE `' . _DB_PREFIX_ . 'cart_product`
		SET `id_address_delivery` = (
			SELECT `id_address_delivery` FROM `' . _DB_PREFIX_ . 'cart`
			WHERE `id_cart` = ' . (int) $this->id . ' AND `id_shop` = ' . (int) $this->id_shop . '
		)
		WHERE `id_cart` = ' . (int) $this->id . '
		' . (Configuration::get('PS_ALLOW_MULTISHIPPING') ? ' AND `id_shop` = ' . (int) $this->id_shop : '');
        $cache_id = 'Cart::setNoMultishipping' . (int) $this->id . '-' . (int) $this->id_shop;
        if (!Cache::isStored($cache_id)) {
            if ($result = (bool) Db::getInstance()->execute($sql)) {
                $emptyCache = true;
            }
            Cache::store($cache_id, $result);
        }
        if (Customization::isFeatureActive()) {
            Db::getInstance()->execute('
			UPDATE `' . _DB_PREFIX_ . 'customization`
			SET `id_address_delivery` = (
				SELECT `id_address_delivery` FROM `' . _DB_PREFIX_ . 'cart`
				WHERE `id_cart` = ' . (int) $this->id . '
			)
			WHERE `id_cart` = ' . (int) $this->id);
        }
        if ($emptyCache) {
            $this->_products = null;
        }
    }
    public static function getDiscountsCustomer($id_customer, $id_cart_rule)
    {
        $cache_id = 'Order::getDiscountsCustomer_' . (int) $id_customer . '-' . (int) $id_cart_rule;
        if (!Cache::isStored($cache_id)) {
            $result = (int) Db::getInstance()->getValue('
			SELECT COUNT(*) FROM `' . _DB_PREFIX_ . 'orders` o
			LEFT JOIN ' . _DB_PREFIX_ . 'order_cart_rule ocr ON (ocr.id_order = o.id_order)
			WHERE o.id_customer = ' . (int) $id_customer . '
			AND ocr.id_cart_rule = ' . (int) $id_cart_rule);
            Cache::store($cache_id, $result);
        }
        return Cache::retrieve($cache_id);
    }
Exemple #15
0
    /**
     * Get category meta tags
     *
     * @since 1.5.0
     * @param int $id_category
     * @param int $id_lang
     * @param string $page_name
     * @return array
     */
    public static function getCategoryMetas($id_category, $id_lang, $page_name, $title = '')
    {
        if (!empty($title)) {
            $title = ' - ' . $title;
        }
        $page_number = (int) Tools::getValue('p');
        $sql = 'SELECT `name`, `meta_title`, `meta_description`, `meta_keywords`, `description`
				FROM `' . _DB_PREFIX_ . 'category_lang` cl
				WHERE cl.`id_lang` = ' . (int) $id_lang . '
					AND cl.`id_category` = ' . (int) $id_category . Shop::addSqlRestrictionOnLang('cl');
        $cache_id = 'Meta::getCategoryMetas' . (int) $id_category . '-' . (int) $id_lang;
        if (!Cache::isStored($cache_id)) {
            if ($row = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow($sql)) {
                if (empty($row['meta_description'])) {
                    $row['meta_description'] = strip_tags($row['description']);
                }
                // Paginate title
                if (!empty($row['meta_title'])) {
                    $row['meta_title'] = $title . $row['meta_title'] . (!empty($page_number) ? ' (' . $page_number . ')' : '') . ' - ' . Configuration::get('PS_SHOP_NAME') . ' %city_name';
                } else {
                    $row['meta_title'] = $row['name'] . (!empty($page_number) ? ' (' . $page_number . ')' : '') . ' - ' . Configuration::get('PS_SHOP_NAME') . ' %city_name';
                }
                if (!empty($title)) {
                    $row['meta_title'] = $title . (!empty($page_number) ? ' (' . $page_number . ')' : '') . ' - ' . Configuration::get('PS_SHOP_NAME') . ' %city_name';
                }
                $result = Meta::completeMetaTags($row, $row['name']);
            } else {
                $result = Meta::getHomeMetas($id_lang, $page_name);
            }
            Meta::getEgCeoWords('category', $id_category, $result);
            $result = Meta::replaceCity($result);
            //$row['meta_description'] = $result['description'];
            $row = Meta::replaceCity($row);
            Cache::store($cache_id, $result);
        }
        return Cache::retrieve($cache_id);
    }
Exemple #16
0
    public static function getPriceStatic($id_product, $usetax = true, $id_product_attribute = null, $decimals = 6, $divisor = null, $only_reduc = false, $usereduc = true, $quantity = 1, $force_associated_tax = false, $id_customer = null, $id_cart = null, $id_address = null, &$specific_price_output = null, $with_ecotax = true, $use_group_reduction = true, Context $context = null, $use_customer_price = true)
    {
        if (!$context) {
            $context = Context::getContext();
        }
        $cur_cart = $context->cart;
        if ($divisor !== null) {
            Tools::displayParameterAsDeprecated('divisor');
        }
        if (!Validate::isBool($usetax) || !Validate::isUnsignedId($id_product)) {
            die(Tools::displayError());
        }
        $id_group = null;
        if ($id_customer) {
            $id_group = Customer::getDefaultGroupId((int) $id_customer);
        }
        if (!$id_group) {
            $id_group = (int) Group::getCurrent()->id;
        }
        if (!is_object($cur_cart) || Validate::isUnsignedInt($id_cart) && $id_cart && $cur_cart->id != $id_cart) {
            /*
             * When a user (e.g., guest, customer, Google...) is on PrestaShop, he has already its cart as the global (see /init.php)
             * When a non-user calls directly this method (e.g., payment module...) is on PrestaShop, he does not have already it BUT knows the cart ID
             * When called from the back office, cart ID can be inexistant
             */
            if (!$id_cart && !isset($context->employee)) {
                die(Tools::displayError());
            }
            $cur_cart = new Cart($id_cart);
            if (!Validate::isLoadedObject($context->cart)) {
                $context->cart = $cur_cart;
            }
        }
        $qty = $quantity;
        if (is_array($quantity)) {
            $quantity = PP::resolveQty($qty[0], $qty[1]);
        }
        $cart_quantity = 0;
        if ((int) $id_cart) {
            $cache_id = 'Product::getPriceStatic_' . (int) $id_product . '-' . (int) $id_cart;
            if (!Cache::isStored($cache_id) || ($cart_quantity = Cache::retrieve($cache_id) != (double) $quantity)) {
                $sql = 'SELECT SUM(' . PP::sqlQty('quantity') . ')
				FROM `' . _DB_PREFIX_ . 'cart_product`
				WHERE `id_product` = ' . (int) $id_product . '
				AND `id_cart` = ' . (int) $id_cart;
                $cart_quantity = (double) Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue($sql);
                Cache::store($cache_id, $cart_quantity);
            }
            $cart_quantity = Cache::retrieve($cache_id);
        }
        $id_currency = (int) Validate::isLoadedObject($context->currency) ? $context->currency->id : Configuration::get('PS_CURRENCY_DEFAULT');
        $id_country = (int) $context->country->id;
        $id_state = 0;
        $zipcode = 0;
        if (!$id_address && Validate::isLoadedObject($cur_cart)) {
            $id_address = $cur_cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')};
        }
        if ($id_address) {
            $address_infos = Address::getCountryAndState($id_address);
            if ($address_infos['id_country']) {
                $id_country = (int) $address_infos['id_country'];
                $id_state = (int) $address_infos['id_state'];
                $zipcode = $address_infos['postcode'];
            }
        } elseif (isset($context->customer->geoloc_id_country)) {
            $id_country = (int) $context->customer->geoloc_id_country;
            $id_state = (int) $context->customer->id_state;
            $zipcode = $context->customer->postcode;
        }
        if (Tax::excludeTaxeOption()) {
            $usetax = false;
        }
        if ($usetax != false && !empty($address_infos['vat_number']) && $address_infos['id_country'] != Configuration::get('VATNUMBER_COUNTRY') && Configuration::get('VATNUMBER_MANAGEMENT')) {
            $usetax = false;
        }
        if (is_null($id_customer) && Validate::isLoadedObject($context->customer)) {
            $id_customer = $context->customer->id;
        }
        return Product::priceCalculation($context->shop->id, $id_product, $id_product_attribute, $id_country, $id_state, $zipcode, $id_currency, $id_group, $qty, $usetax, $decimals, $only_reduc, $usereduc, $with_ecotax, $specific_price_output, $use_group_reduction, $id_customer, $use_customer_price, $id_cart, $cart_quantity);
    }
Exemple #17
0
 /**
  * @param null $id_lang
  * @return Category
  */
 public static function getTopCategory($id_lang = null)
 {
     if (is_null($id_lang)) {
         $id_lang = (int) Context::getContext()->language->id;
     }
     $cache_id = 'Category::getTopCategory_' . (int) $id_lang;
     if (!Cache::isStored($cache_id)) {
         $id_category = (int) Db::getInstance()->getValue('
         SELECT `id_category`
         FROM `' . _DB_PREFIX_ . 'category`
         WHERE `id_parent` = 0');
         $category = new Category($id_category, $id_lang);
         Cache::store($cache_id, $category);
         return $category;
     }
     return Cache::retrieve($cache_id);
 }
Exemple #18
0
	/**
	 * For a given {product, warehouse}, gets the carrier available
	 *
	 * @since 1.5.0
	 * @param Product $product The id of the product, or an array with at least the package size and weight
	 * @return array
	 */
        public static function getAvailableCarrierList(Product $product, $id_warehouse, $id_address_delivery = null, $id_shop = null, $cart = null)
	{
		if (is_null($id_shop))
			$id_shop = Context::getContext()->shop->id;
		if (is_null($cart))
			$cart = Context::getContext()->cart;

		$id_address = (int)((!is_null($id_address_delivery) && $id_address_delivery != 0) ? $id_address_delivery :  $cart->id_address_delivery);
		if ($id_address)
		{
			$address = new Address($id_address);
			$id_zone = Address::getZoneById($address->id);

			// Check the country of the address is activated
			if (!Address::isCountryActiveById($address->id))
				return array();
		}
		else
		{
			// changed for Presto-Changeo carrier modules --->
			$cookie = Context::getContext()->cookie;
			$cookie_country = $cookie->id_country ? $cookie->id_country : $cookie->pc_dest_country;
			$country = new Country((isset($cookie_country) && strlen($cookie_country) ? $cookie_country : Configuration::get('PS_COUNTRY_DEFAULT')));
			// <--- changed for Presto-Changeo carrier modules
			$id_zone = $country->id_zone;
		}

		// Does the product is linked with carriers?
		$query = new DbQuery();
		$query->select('id_carrier');
		$query->from('product_carrier', 'pc');
		$query->innerJoin('carrier', 'c', 'c.id_reference = pc.id_carrier_reference AND c.deleted = 0');
		$query->where('pc.id_product = '.(int)$product->id);
		$query->where('pc.id_shop = '.(int)$id_shop);

		$cache_id = 'Carrier::getAvailableCarrierList_'.(int)$product->id.'-'.(int)$id_shop;
		if (!Cache::isStored($cache_id))
		{
			$carriers_for_product = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($query);
			Cache::store($cache_id, $carriers_for_product);
		}
		$carriers_for_product = Cache::retrieve($cache_id);
		$carrier_list = array();
		if (!empty($carriers_for_product))
		{
			//the product is linked with carriers
			foreach ($carriers_for_product as $carrier) //check if the linked carriers are available in current zone
				if (Carrier::checkCarrierZone($carrier['id_carrier'], $id_zone))
					$carrier_list[] = $carrier['id_carrier'];
			if (empty($carrier_list))
				return array();//no linked carrier are available for this zone
		}

		// The product is not dirrectly linked with a carrier
		// Get all the carriers linked to a warehouse
		if ($id_warehouse)
		{
			$warehouse = new Warehouse($id_warehouse);
			$warehouse_carrier_list = $warehouse->getCarriers();
		}

		$available_carrier_list = array();
		$customer = new Customer($cart->id_customer);
		$carriers = Carrier::getCarriersForOrder($id_zone, $customer->getGroups(), $cart);

		foreach ($carriers as $carrier)
			$available_carrier_list[] = $carrier['id_carrier'];

		if ($carrier_list)
			$carrier_list = array_intersect($available_carrier_list, $carrier_list);
		else
			$carrier_list = $available_carrier_list;

		if (isset($warehouse_carrier_list))
			$carrier_list = array_intersect($carrier_list, $warehouse_carrier_list);

		if ($product->width > 0 || $product->height > 0 || $product->depth > 0 || $product->weight > 0)
		{
			foreach ($carrier_list as $key => $id_carrier)
			{
				$carrier = new Carrier($id_carrier);
				if (($carrier->max_width > 0 && $carrier->max_width < $product->width)
					|| ($carrier->max_height > 0 && $carrier->max_height < $product->height)
					|| ($carrier->max_depth > 0 && $carrier->max_depth < $product->depth)
					|| ($carrier->max_weight > 0 && $carrier->max_weight < $product->weight))
					unset($carrier_list[$key]);
			}
		}
		return $carrier_list;
	}
Exemple #19
0
    public static function getIdTaxRulesGroupByIdCarrier($id_carrier, Context $context = null)
    {
        if (!$context) {
            $context = Context::getContext();
        }
        $key = 'carrier_id_tax_rules_group_' . (int) $id_carrier . '_' . (int) $context->shop->id;
        if (!Cache::isStored($key)) {
            Cache::store($key, Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue('
				SELECT `id_tax_rules_group`
				FROM `' . _DB_PREFIX_ . 'carrier_tax_rules_group_shop`
				WHERE `id_carrier` = ' . (int) $id_carrier . ' AND id_shop=' . (int) Context::getContext()->shop->id));
        }
        return Cache::retrieve($key);
    }
Exemple #20
0
 public static function getNestedCategories($images, $root_category = null, $id_lang = false, $active = true, $groups = null, $use_shop_restriction = true, $sql_filter = '', $sql_sort = '', $sql_limit = '')
 {
     $protocol = !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443 ? 'https://' : 'http://';
     $url = Tools::htmlentitiesutf8($protocol . $_SERVER['HTTP_HOST'] . __PS_BASE_URI__);
     $themeName = Context::getContext()->shop->getTheme();
     $image_path = 'themes/' . $themeName . '/img/icontab/';
     if (isset($root_category) && !Validate::isInt($root_category)) {
         die(Tools::displayError());
     }
     if (!Validate::isBool($active)) {
         die(Tools::displayError());
     }
     if (isset($groups) && Group::isFeatureActive() && !is_array($groups)) {
         $groups = (array) $groups;
     }
     $cache_id = 'Category::getNestedCategories_' . md5((int) $root_category . (int) $id_lang . (int) $active . (int) $active . (isset($groups) && Group::isFeatureActive() ? implode('', $groups) : ''));
     if (!Cache::isStored($cache_id)) {
         $result = Db::getInstance()->executeS('
             SELECT c.*, cl.*
             FROM `' . _DB_PREFIX_ . 'category` c
             ' . ($use_shop_restriction ? Shop::addSqlAssociation('category', 'c') : '') . '
             LEFT JOIN `' . _DB_PREFIX_ . 'category_lang` cl ON c.`id_category` = cl.`id_category`' . Shop::addSqlRestrictionOnLang('cl') . '
             ' . (isset($groups) && Group::isFeatureActive() ? 'LEFT JOIN `' . _DB_PREFIX_ . 'category_group` cg ON c.`id_category` = cg.`id_category`' : '') . '
             ' . (isset($root_category) ? 'RIGHT JOIN `' . _DB_PREFIX_ . 'category` c2 ON c2.`id_category` = ' . (int) $root_category . ' AND c.`nleft` >= c2.`nleft` AND c.`nright` <= c2.`nright`' : '') . '
             WHERE 1 ' . $sql_filter . ' ' . ($id_lang ? 'AND `id_lang` = ' . (int) $id_lang : '') . '
             ' . ($active ? ' AND c.`active` = 1' : '') . '
             ' . (isset($groups) && Group::isFeatureActive() ? ' AND cg.`id_group` IN (' . implode(',', $groups) . ')' : '') . '
             ' . (!$id_lang || isset($groups) && Group::isFeatureActive() ? ' GROUP BY c.`id_category`' : '') . '
             ' . ($sql_sort != '' ? $sql_sort : ' ORDER BY c.`level_depth` ASC') . '
             ' . ($sql_sort == '' && $use_shop_restriction ? ', category_shop.`position` ASC' : '') . '
             ' . ($sql_limit != '' ? $sql_limit : ''));
         $categories = array();
         $buff = array();
         if (!isset($root_category)) {
             $root_category = 1;
         }
         foreach ($result as $row) {
             //add image to a category
             if (array_key_exists($row['id_category'], $images)) {
                 # validate module
                 $row['image'] = $url . $image_path . $images[$row['id_category']];
             }
             $row['id_image'] = $row['id_category'] && file_exists(_PS_CAT_IMG_DIR_ . (int) $row['id_category'] . '.jpg') ? (int) $row['id_category'] : false;
             $current =& $buff[$row['id_category']];
             $current = $row;
             if ($row['id_category'] == $root_category) {
                 # validate module
                 $categories[$row['id_category']] =& $current;
             } else {
                 # validate module
                 $buff[$row['id_parent']]['children'][$row['id_category']] =& $current;
             }
         }
         Cache::store($cache_id, $categories);
     }
     return Cache::retrieve($cache_id);
 }
Exemple #21
0
 /**
  * Amounts of payments
  * @since 1.5.0.2
  * @return float Total paid
  */
 public function getTotalPaid()
 {
     $cache_id = 'order_invoice_paid_' . (int) $this->id;
     if (!Cache::isStored($cache_id)) {
         $amount = 0;
         $payments = OrderPayment::getByInvoiceId($this->id);
         foreach ($payments as $payment) {
             /** @var OrderPayment $payment */
             $amount += $payment->amount;
         }
         Cache::store($cache_id, $amount);
         return $amount;
     }
     return Cache::retrieve($cache_id);
 }
Exemple #22
0
    public function getProducts($refresh = false, $id_product = false, $id_country = null)
    {
        if (!$this->id) {
            return array();
        }
        // Product cache must be strictly compared to NULL, or else an empty cart will add dozens of queries
        if ($this->_products !== null && !$refresh) {
            // Return product row with specified ID if it exists
            if (is_int($id_product)) {
                foreach ($this->_products as $product) {
                    if ($product['id_product'] == $id_product) {
                        return array($product);
                    }
                }
                return array();
            }
            return $this->_products;
        }
        // Build query
        $sql = new DbQuery();
        // Build SELECT
        $sql->select('cp.`id_product_attribute`, cp.`id_product`, cp.`quantity` AS cart_quantity, cp.id_shop, pl.`name`, p.`is_virtual`,
						pl.`description_short`, pl.`available_now`, pl.`available_later`, product_shop.`id_category_default`, p.`id_supplier`,
						p.`id_manufacturer`, product_shop.`on_sale`, product_shop.`ecotax`, product_shop.`additional_shipping_cost`,
						product_shop.`available_for_order`, product_shop.`price`, product_shop.`active`, product_shop.`unity`, product_shop.`unit_price_ratio`, 
						stock.`quantity` AS quantity_available, p.`width`, p.`height`, p.`depth`, stock.`out_of_stock`, p.`weight`,
						p.`date_add`, p.`date_upd`, IFNULL(stock.quantity, 0) as quantity, pl.`link_rewrite`, cl.`link_rewrite` AS category,
						CONCAT(LPAD(cp.`id_product`, 10, 0), LPAD(IFNULL(cp.`id_product_attribute`, 0), 10, 0), IFNULL(cp.`id_address_delivery`, 0)) AS unique_id, cp.id_address_delivery,
						product_shop.`wholesale_price`, product_shop.advanced_stock_management, ps.product_supplier_reference supplier_reference');
        // Build FROM
        $sql->from('cart_product', 'cp');
        // Build JOIN
        $sql->leftJoin('product', 'p', 'p.`id_product` = cp.`id_product`');
        $sql->innerJoin('product_shop', 'product_shop', '(product_shop.`id_shop` = cp.`id_shop` AND product_shop.`id_product` = p.`id_product`)');
        $sql->leftJoin('product_lang', 'pl', '
			p.`id_product` = pl.`id_product`
			AND pl.`id_lang` = ' . (int) $this->id_lang . Shop::addSqlRestrictionOnLang('pl', 'cp.id_shop'));
        $sql->leftJoin('category_lang', 'cl', '
			product_shop.`id_category_default` = cl.`id_category`
			AND cl.`id_lang` = ' . (int) $this->id_lang . Shop::addSqlRestrictionOnLang('cl', 'cp.id_shop'));
        $sql->leftJoin('product_supplier', 'ps', 'ps.`id_product` = cp.`id_product` AND ps.`id_product_attribute` = cp.`id_product_attribute` AND ps.`id_supplier` = p.`id_supplier`');
        // @todo test if everything is ok, then refactorise call of this method
        $sql->join(Product::sqlStock('cp', 'cp'));
        // Build WHERE clauses
        $sql->where('cp.`id_cart` = ' . (int) $this->id);
        if ($id_product) {
            $sql->where('cp.`id_product` = ' . (int) $id_product);
        }
        $sql->where('p.`id_product` IS NOT NULL');
        // Build GROUP BY
        $sql->groupBy('unique_id');
        // Build ORDER BY
        $sql->orderBy('p.`id_product`, cp.`id_product_attribute`, cp.`date_add` ASC');
        if (Customization::isFeatureActive()) {
            $sql->select('cu.`id_customization`, cu.`quantity` AS customization_quantity');
            $sql->leftJoin('customization', 'cu', 'p.`id_product` = cu.`id_product` AND cp.`id_product_attribute` = cu.`id_product_attribute` AND cu.`id_cart` = ' . (int) $this->id);
        } else {
            $sql->select('NULL AS customization_quantity, NULL AS id_customization');
        }
        if (Combination::isFeatureActive()) {
            $sql->select('
				product_attribute_shop.`price` AS price_attribute, product_attribute_shop.`ecotax` AS ecotax_attr,
				IF (IFNULL(pa.`reference`, \'\') = \'\', p.`reference`, pa.`reference`) AS reference,
				(p.`weight`+ pa.`weight`) weight_attribute,
				IF (IFNULL(pa.`ean13`, \'\') = \'\', p.`ean13`, pa.`ean13`) AS ean13,
				IF (IFNULL(pa.`upc`, \'\') = \'\', p.`upc`, pa.`upc`) AS upc,
				pai.`id_image` as pai_id_image, il.`legend` as pai_legend,
				IFNULL(product_attribute_shop.`minimal_quantity`, product_shop.`minimal_quantity`) as minimal_quantity
			');
            $sql->leftJoin('product_attribute', 'pa', 'pa.`id_product_attribute` = cp.`id_product_attribute`');
            $sql->leftJoin('product_attribute_shop', 'product_attribute_shop', '(product_attribute_shop.`id_shop` = cp.`id_shop` AND product_attribute_shop.`id_product_attribute` = pa.`id_product_attribute`)');
            $sql->leftJoin('product_attribute_image', 'pai', 'pai.`id_product_attribute` = pa.`id_product_attribute`');
            $sql->leftJoin('image_lang', 'il', 'il.`id_image` = pai.`id_image` AND il.`id_lang` = ' . (int) $this->id_lang);
        } else {
            $sql->select('p.`reference` AS reference, p.`ean13`,
				p.`upc` AS upc, product_shop.`minimal_quantity` AS minimal_quantity');
        }
        $result = Db::getInstance()->executeS($sql);
        // Reset the cache before the following return, or else an empty cart will add dozens of queries
        $products_ids = array();
        $pa_ids = array();
        if ($result) {
            foreach ($result as $row) {
                $products_ids[] = $row['id_product'];
                $pa_ids[] = $row['id_product_attribute'];
            }
        }
        // Thus you can avoid one query per product, because there will be only one query for all the products of the cart
        Product::cacheProductsFeatures($products_ids);
        Cart::cacheSomeAttributesLists($pa_ids, $this->id_lang);
        $this->_products = array();
        if (empty($result)) {
            return array();
        }
        $cart_shop_context = Context::getContext()->cloneContext();
        foreach ($result as &$row) {
            //                        $quantityDiscount = SpecificPrice::getQuantityDiscount((int)$row['id_product'], $row['id_shop'],
            //			(int)$cart->id_currency, (int)$this->vat_address->id_country,
            //			(int)$this->customer->id_default_group, (int)$row['cart_quantity'], false, null, null, $null, true, true, $this->context);
            //
            //                        echo '<pre>';
            //                        print_r($quantityDiscount);
            //                        echo '</pre>';
            if (isset($row['ecotax_attr']) && $row['ecotax_attr'] > 0) {
                $row['ecotax'] = (double) $row['ecotax_attr'];
            }
            $row['stock_quantity'] = (int) $row['quantity'];
            // for compatibility with 1.2 themes
            $row['quantity'] = (int) $row['cart_quantity'];
            if (isset($row['id_product_attribute']) && (int) $row['id_product_attribute'] && isset($row['weight_attribute'])) {
                $row['weight'] = (double) $row['weight_attribute'];
            }
            if (Configuration::get('PS_TAX_ADDRESS_TYPE') == 'id_address_invoice') {
                $address_id = (int) $this->id_address_invoice;
            } else {
                $address_id = (int) $row['id_address_delivery'];
            }
            if (!Address::addressExists($address_id)) {
                $address_id = null;
            }
            if ($cart_shop_context->shop->id != $row['id_shop']) {
                $cart_shop_context->shop = new Shop((int) $row['id_shop']);
            }
            if ($this->_taxCalculationMethod == PS_TAX_EXC) {
                $row['price'] = Product::getPriceStatic((int) $row['id_product'], false, isset($row['id_product_attribute']) ? (int) $row['id_product_attribute'] : null, 2, null, false, true, (int) $row['cart_quantity'], false, (int) $this->id_customer ? (int) $this->id_customer : null, (int) $this->id, (int) $address_id ? (int) $address_id : null, $specific_price_output, true, true, $cart_shop_context);
                // Here taxes are computed only once the quantity has been applied to the product price
                $row['price_wt'] = Product::getPriceStatic((int) $row['id_product'], true, isset($row['id_product_attribute']) ? (int) $row['id_product_attribute'] : null, 2, null, false, true, (int) $row['cart_quantity'], false, (int) $this->id_customer ? (int) $this->id_customer : null, (int) $this->id, (int) $address_id ? (int) $address_id : null, $null, true, true, $cart_shop_context);
                $tax_rate = Tax::getProductTaxRate((int) $row['id_product'], (int) $address_id);
                $row['total_wt'] = Tools::ps_round($row['price'] * (double) $row['cart_quantity'] * (1 + (double) $tax_rate / 100), 2);
                $row['total'] = $row['price'] * (int) $row['cart_quantity'];
            } else {
                $row['price'] = Product::getPriceStatic((int) $row['id_product'], false, (int) $row['id_product_attribute'], 2, null, false, true, $row['cart_quantity'], false, (int) $this->id_customer ? (int) $this->id_customer : null, (int) $this->id, (int) $address_id ? (int) $address_id : null, $specific_price_output, true, true, $cart_shop_context);
                $row['price_wt'] = Product::getPriceStatic((int) $row['id_product'], true, (int) $row['id_product_attribute'], 2, null, false, true, $row['cart_quantity'], false, (int) $this->id_customer ? (int) $this->id_customer : null, (int) $this->id, (int) $address_id ? (int) $address_id : null, $null, true, true, $cart_shop_context);
                // In case when you use QuantityDiscount, getPriceStatic() can be return more of 2 decimals
                $row['price_wt'] = Tools::ps_round($row['price_wt'], 2);
                $row['total_wt'] = $row['price_wt'] * (int) $row['cart_quantity'];
                $row['total'] = Tools::ps_round($row['price'] * (int) $row['cart_quantity'], 2);
                $row['description_short'] = Tools::nl2br($row['description_short']);
            }
            if (!isset($row['pai_id_image']) || $row['pai_id_image'] == 0) {
                $cache_id = 'Cart::getProducts_' . '-pai_id_image-' . (int) $row['id_product'] . '-' . (int) $this->id_lang . '-' . (int) $row['id_shop'];
                if (!Cache::isStored($cache_id)) {
                    $row2 = Db::getInstance()->getRow('
						SELECT image_shop.`id_image` id_image, il.`legend`
						FROM `' . _DB_PREFIX_ . 'image` i
						JOIN `' . _DB_PREFIX_ . 'image_shop` image_shop ON (i.id_image = image_shop.id_image AND image_shop.cover=1 AND image_shop.id_shop=' . (int) $row['id_shop'] . ')
						LEFT JOIN `' . _DB_PREFIX_ . 'image_lang` il ON (image_shop.`id_image` = il.`id_image` AND il.`id_lang` = ' . (int) $this->id_lang . ')
						WHERE i.`id_product` = ' . (int) $row['id_product'] . ' AND image_shop.`cover` = 1');
                    Cache::store($cache_id, $row2);
                }
                $row2 = Cache::retrieve($cache_id);
                if (!$row2) {
                    $row2 = array('id_image' => false, 'legend' => false);
                } else {
                    $row = array_merge($row, $row2);
                }
            } else {
                $row['id_image'] = $row['pai_id_image'];
                $row['legend'] = $row['pai_legend'];
            }
            $row['reduction_applies'] = $specific_price_output && (double) $specific_price_output['reduction'];
            $row['quantity_discount_applies'] = $specific_price_output && $row['cart_quantity'] >= (int) $specific_price_output['from_quantity'];
            $row['id_image'] = Product::defineProductImage($row, $this->id_lang);
            $row['allow_oosp'] = Product::isAvailableWhenOutOfStock($row['out_of_stock']);
            $row['features'] = Product::getFeaturesStatic((int) $row['id_product']);
            if (array_key_exists($row['id_product_attribute'] . '-' . $this->id_lang, self::$_attributesLists)) {
                $row = array_merge($row, self::$_attributesLists[$row['id_product_attribute'] . '-' . $this->id_lang]);
            }
            if (Context::getContext()->language->id != 1) {
                $row['name'] = Tools::rus2translit($row['name']);
            }
            $row = Product::getTaxesInformations($row, $cart_shop_context);
            $this->_products[] = $row;
        }
        return $this->_products;
    }
Exemple #23
0
 public function getPackageShippingCost($id_carrier = null, $use_tax = true, Country $default_country = null, $product_list = null, $id_zone = null)
 {
     if (!Configuration::get('LEGAL_SHIPTAXMETH')) {
         return parent::getPackageShippingCost($id_carrier, $use_tax, $default_country, $product_list, $id_zone);
     }
     if ($this->isVirtualCart()) {
         return 0;
     }
     if (!$default_country) {
         $default_country = Context::getContext()->country;
     }
     if (!is_null($product_list)) {
         foreach ($product_list as $key => $value) {
             if ($value['is_virtual'] == 1) {
                 unset($product_list[$key]);
             }
         }
     }
     $complete_product_list = $this->getProducts();
     if (is_null($product_list)) {
         $products = $complete_product_list;
     } else {
         $products = $product_list;
     }
     if (Configuration::get('PS_TAX_ADDRESS_TYPE') == 'id_address_invoice') {
         $address_id = (int) $this->id_address_invoice;
     } elseif (count($product_list)) {
         $prod = current($product_list);
         $address_id = (int) $prod['id_address_delivery'];
     } else {
         $address_id = null;
     }
     if (!Address::addressExists($address_id)) {
         $address_id = null;
     }
     $cache_id = 'getPackageShippingCost_' . (int) $this->id . '_' . (int) $address_id . '_' . (int) $id_carrier . '_' . (int) $use_tax . '_' . (int) $default_country->id;
     if ($products) {
         foreach ($products as $product) {
             $cache_id .= '_' . (int) $product['id_product'] . '_' . (int) $product['id_product_attribute'];
         }
     }
     if (Cache::isStored($cache_id)) {
         return Cache::retrieve($cache_id);
     }
     // Order total in default currency without fees
     $order_total = $this->getOrderTotal(true, Cart::ONLY_PHYSICAL_PRODUCTS_WITHOUT_SHIPPING, $product_list);
     // Start with shipping cost at 0
     $shipping_cost = 0;
     // If no product added, return 0
     if (!count($products)) {
         Cache::store($cache_id, $shipping_cost);
         return $shipping_cost;
     }
     if (!isset($id_zone)) {
         // Get id zone
         if (!$this->isMultiAddressDelivery() && isset($this->id_address_delivery) && $this->id_address_delivery && Customer::customerHasAddress($this->id_customer, $this->id_address_delivery)) {
             $id_zone = Address::getZoneById((int) $this->id_address_delivery);
         } else {
             if (!Validate::isLoadedObject($default_country)) {
                 $default_country = new Country(Configuration::get('PS_COUNTRY_DEFAULT'), Configuration::get('PS_LANG_DEFAULT'));
             }
             $id_zone = (int) $default_country->id_zone;
         }
     }
     if ($id_carrier && !$this->isCarrierInRange((int) $id_carrier, (int) $id_zone)) {
         $id_carrier = '';
     }
     if (empty($id_carrier) && $this->isCarrierInRange((int) Configuration::get('PS_CARRIER_DEFAULT'), (int) $id_zone)) {
         $id_carrier = (int) Configuration::get('PS_CARRIER_DEFAULT');
     }
     $total_package_without_shipping_tax_inc = $this->getOrderTotal(true, Cart::BOTH_WITHOUT_SHIPPING, $product_list);
     if (empty($id_carrier)) {
         if ((int) $this->id_customer) {
             $customer = new Customer((int) $this->id_customer);
             $result = Carrier::getCarriers((int) Configuration::get('PS_LANG_DEFAULT'), true, false, (int) $id_zone, $customer->getGroups());
             unset($customer);
         } else {
             $result = Carrier::getCarriers((int) Configuration::get('PS_LANG_DEFAULT'), true, false, (int) $id_zone);
         }
         foreach ($result as $k => $row) {
             if ($row['id_carrier'] == Configuration::get('PS_CARRIER_DEFAULT')) {
                 continue;
             }
             if (!isset(self::$_carriers[$row['id_carrier']])) {
                 self::$_carriers[$row['id_carrier']] = new Carrier((int) $row['id_carrier']);
             }
             $carrier = self::$_carriers[$row['id_carrier']];
             // Get only carriers that are compliant with shipping method
             if ($carrier->getShippingMethod() == Carrier::SHIPPING_METHOD_WEIGHT && $carrier->getMaxDeliveryPriceByWeight((int) $id_zone) === false || $carrier->getShippingMethod() == Carrier::SHIPPING_METHOD_PRICE && $carrier->getMaxDeliveryPriceByPrice((int) $id_zone) === false) {
                 unset($result[$k]);
                 continue;
             }
             // If out-of-range behavior carrier is set on "Desactivate carrier"
             if ($row['range_behavior']) {
                 $check_delivery_price_by_weight = Carrier::checkDeliveryPriceByWeight($row['id_carrier'], $this->getTotalWeight(), (int) $id_zone);
                 $total_order = $total_package_without_shipping_tax_inc;
                 $check_delivery_price_by_price = Carrier::checkDeliveryPriceByPrice($row['id_carrier'], $total_order, (int) $id_zone, (int) $this->id_currency);
                 // Get only carriers that have a range compatible with cart
                 if ($carrier->getShippingMethod() == Carrier::SHIPPING_METHOD_WEIGHT && !$check_delivery_price_by_weight || $carrier->getShippingMethod() == Carrier::SHIPPING_METHOD_PRICE && !$check_delivery_price_by_price) {
                     unset($result[$k]);
                     continue;
                 }
             }
             if ($carrier->getShippingMethod() == Carrier::SHIPPING_METHOD_WEIGHT) {
                 $shipping = $carrier->getDeliveryPriceByWeight($this->getTotalWeight($product_list), (int) $id_zone);
             } else {
                 $shipping = $carrier->getDeliveryPriceByPrice($order_total, (int) $id_zone, (int) $this->id_currency);
             }
             if (!isset($min_shipping_price)) {
                 $min_shipping_price = $shipping;
             }
             if ($shipping <= $min_shipping_price) {
                 $id_carrier = (int) $row['id_carrier'];
                 $min_shipping_price = $shipping;
             }
         }
     }
     if (empty($id_carrier)) {
         $id_carrier = Configuration::get('PS_CARRIER_DEFAULT');
     }
     if (!isset(self::$_carriers[$id_carrier])) {
         self::$_carriers[$id_carrier] = new Carrier((int) $id_carrier, Configuration::get('PS_LANG_DEFAULT'));
     }
     $carrier = self::$_carriers[$id_carrier];
     // No valid Carrier or $id_carrier <= 0 ?
     if (!Validate::isLoadedObject($carrier)) {
         Cache::store($cache_id, 0);
         return 0;
     }
     if (!$carrier->active) {
         Cache::store($cache_id, $shipping_cost);
         return $shipping_cost;
     }
     // Free fees if free carrier
     if ($carrier->is_free == 1) {
         Cache::store($cache_id, 0);
         return 0;
     }
     // Select carrier tax
     if ($use_tax && !Tax::excludeTaxeOption()) {
         $address = Address::initialize((int) $address_id);
         $carrier_tax = $carrier->getTaxesRate($address);
     }
     $configuration = Configuration::getMultiple(array('PS_SHIPPING_FREE_PRICE', 'PS_SHIPPING_HANDLING', 'PS_SHIPPING_METHOD', 'PS_SHIPPING_FREE_WEIGHT'));
     // Free fees
     $free_fees_price = 0;
     if (isset($configuration['PS_SHIPPING_FREE_PRICE'])) {
         $free_fees_price = Tools::convertPrice((double) $configuration['PS_SHIPPING_FREE_PRICE'], Currency::getCurrencyInstance((int) $this->id_currency));
     }
     $orderTotalwithDiscounts = $this->getOrderTotal(true, Cart::BOTH_WITHOUT_SHIPPING, null, null, false);
     if ($orderTotalwithDiscounts >= (double) $free_fees_price && (double) $free_fees_price > 0) {
         Cache::store($cache_id, $shipping_cost);
         return $shipping_cost;
     }
     if (isset($configuration['PS_SHIPPING_FREE_WEIGHT']) && $this->getTotalWeight() >= (double) $configuration['PS_SHIPPING_FREE_WEIGHT'] && (double) $configuration['PS_SHIPPING_FREE_WEIGHT'] > 0) {
         Cache::store($cache_id, $shipping_cost);
         return $shipping_cost;
     }
     // Get shipping cost using correct method
     if ($carrier->range_behavior) {
         if (!isset($id_zone)) {
             // Get id zone
             if (isset($this->id_address_delivery) && $this->id_address_delivery && Customer::customerHasAddress($this->id_customer, $this->id_address_delivery)) {
                 $id_zone = Address::getZoneById((int) $this->id_address_delivery);
             } else {
                 $id_zone = (int) $default_country->id_zone;
             }
         }
         if ($carrier->getShippingMethod() == Carrier::SHIPPING_METHOD_WEIGHT && !Carrier::checkDeliveryPriceByWeight($carrier->id, $this->getTotalWeight(), (int) $id_zone) || $carrier->getShippingMethod() == Carrier::SHIPPING_METHOD_PRICE && !Carrier::checkDeliveryPriceByPrice($carrier->id, $total_package_without_shipping_tax_inc, $id_zone, (int) $this->id_currency)) {
             $shipping_cost += 0;
         } else {
             if ($carrier->getShippingMethod() == Carrier::SHIPPING_METHOD_WEIGHT) {
                 $shipping_cost += $carrier->getDeliveryPriceByWeight($this->getTotalWeight($product_list), $id_zone);
             } else {
                 // by price
                 $shipping_cost += $carrier->getDeliveryPriceByPrice($order_total, $id_zone, (int) $this->id_currency);
             }
         }
     } else {
         if ($carrier->getShippingMethod() == Carrier::SHIPPING_METHOD_WEIGHT) {
             $shipping_cost += $carrier->getDeliveryPriceByWeight($this->getTotalWeight($product_list), $id_zone);
         } else {
             $shipping_cost += $carrier->getDeliveryPriceByPrice($order_total, $id_zone, (int) $this->id_currency);
         }
     }
     // Adding handling charges
     if (isset($configuration['PS_SHIPPING_HANDLING']) && $carrier->shipping_handling) {
         $shipping_cost += (double) $configuration['PS_SHIPPING_HANDLING'];
     }
     // Additional Shipping Cost per product
     foreach ($products as $product) {
         if (!$product['is_virtual']) {
             $shipping_cost += $product['additional_shipping_cost'] * $product['cart_quantity'];
         }
     }
     $shipping_cost = Tools::convertPrice($shipping_cost, Currency::getCurrencyInstance((int) $this->id_currency));
     //get external shipping cost from module
     if ($carrier->shipping_external) {
         $module_name = $carrier->external_module_name;
         $module = Module::getInstanceByName($module_name);
         if (Validate::isLoadedObject($module)) {
             if (array_key_exists('id_carrier', $module)) {
                 $module->id_carrier = $carrier->id;
             }
             if ($carrier->need_range) {
                 if (method_exists($module, 'getPackageShippingCost')) {
                     $shipping_cost = $module->getPackageShippingCost($this, $shipping_cost, $products);
                 } else {
                     $shipping_cost = $module->getOrderShippingCost($this, $shipping_cost);
                 }
             } else {
                 $shipping_cost = $module->getOrderShippingCostExternal($this);
             }
             // Check if carrier is available
             if ($shipping_cost === false) {
                 Cache::store($cache_id, false);
                 return false;
             }
         } else {
             Cache::store($cache_id, false);
             return false;
         }
     }
     $shipping_cost = (double) Tools::ps_round((double) $shipping_cost, 2);
     Cache::store($cache_id, $shipping_cost);
     return $shipping_cost;
 }
Exemple #24
0
    protected function _getFormatDB($id_country)
    {
        if (!Cache::isStored('AddressFormat::_getFormatDB' . $id_country)) {
            $format = Db::getInstance()->getValue('
			SELECT format
			FROM `' . _DB_PREFIX_ . $this->def['table'] . '`
			WHERE `id_country` = ' . (int) $id_country);
            Cache::store('AddressFormat::_getFormatDB' . $id_country, trim($format));
        }
        return Cache::retrieve('AddressFormat::_getFormatDB' . $id_country);
    }
Exemple #25
0
    public function setUrl()
    {
        $cache_id = 'Shop::setUrl_' . (int) $this->id;
        if (!Cache::isStored($cache_id)) {
            $row = Db::getInstance()->getRow('
			SELECT su.physical_uri, su.virtual_uri, su.domain, su.domain_ssl, t.id_theme, t.name, t.directory
			FROM ' . _DB_PREFIX_ . 'shop s
			LEFT JOIN ' . _DB_PREFIX_ . 'shop_url su ON (s.id_shop = su.id_shop)
			LEFT JOIN ' . _DB_PREFIX_ . 'theme t ON (t.id_theme = s.id_theme)
			WHERE s.id_shop = ' . (int) $this->id . '
			AND s.active = 1 AND s.deleted = 0 AND su.main = 1');
            Cache::store($cache_id, $row);
        }
        $row = Cache::retrieve($cache_id);
        if (!$row) {
            return false;
        }
        $this->theme_id = $row['id_theme'];
        $this->theme_name = $row['name'];
        $this->theme_directory = $row['directory'];
        $this->physical_uri = $row['physical_uri'];
        $this->virtual_uri = $row['virtual_uri'];
        $this->domain = $row['domain'];
        $this->domain_ssl = $row['domain_ssl'];
        return true;
    }
Exemple #26
0
    /**
     * The reduction value is POSITIVE
     *
     * @param bool $use_tax
     * @param Context $context
     * @param boolean $use_cache Allow using cache to avoid multiple free gift using multishipping
     * @return float|int|string
     */
    public function getContextualValue($use_tax, Context $context = null, $filter = null, $package = null, $use_cache = true)
    {
        if (!CartRule::isFeatureActive()) {
            return 0;
        }
        if (!$context) {
            $context = Context::getContext();
        }
        if (!$filter) {
            $filter = CartRule::FILTER_ACTION_ALL;
        }
        $all_products = $context->cart->getProducts();
        $package_products = is_null($package) ? $all_products : $package['products'];
        $reduction_value = 0;
        $cache_id = 'getContextualValue_' . (int) $this->id . '_' . (int) $use_tax . '_' . (int) $context->cart->id . '_' . (int) $filter;
        foreach ($package_products as $product) {
            $cache_id .= '_' . (int) $product['id_product'] . '_' . (int) $product['id_product_attribute'];
        }
        if (Cache::isStored($cache_id)) {
            return Cache::retrieve($cache_id);
        }
        // Free shipping on selected carriers
        if ($this->free_shipping && in_array($filter, array(CartRule::FILTER_ACTION_ALL, CartRule::FILTER_ACTION_ALL_NOCAP, CartRule::FILTER_ACTION_SHIPPING))) {
            if (!$this->carrier_restriction) {
                $reduction_value += $context->cart->getOrderTotal($use_tax, Cart::ONLY_SHIPPING, is_null($package) ? null : $package['products'], is_null($package) ? null : $package['id_carrier']);
            } else {
                $data = Db::getInstance()->executeS('
					SELECT crc.id_cart_rule, c.id_carrier
					FROM ' . _DB_PREFIX_ . 'cart_rule_carrier crc
					INNER JOIN ' . _DB_PREFIX_ . 'carrier c ON (c.id_reference = crc.id_carrier AND c.deleted = 0)					
					WHERE crc.id_cart_rule = ' . (int) $this->id . '
					AND c.id_carrier = ' . (int) $context->cart->id_carrier);
                if ($data) {
                    foreach ($data as $cart_rule) {
                        $reduction_value += $context->cart->getCarrierCost((int) $cart_rule['id_carrier'], $use_tax, $context->country);
                    }
                }
            }
        }
        if (in_array($filter, array(CartRule::FILTER_ACTION_ALL, CartRule::FILTER_ACTION_ALL_NOCAP, CartRule::FILTER_ACTION_REDUCTION))) {
            // Discount (%) on the whole order
            if ($this->reduction_percent && $this->reduction_product == 0) {
                // Do not give a reduction on free products!
                $order_total = $context->cart->getOrderTotal($use_tax, Cart::ONLY_PRODUCTS, $package_products);
                foreach ($context->cart->getCartRules(CartRule::FILTER_ACTION_GIFT) as $cart_rule) {
                    $order_total -= Tools::ps_round($cart_rule['obj']->getContextualValue($use_tax, $context, CartRule::FILTER_ACTION_GIFT, $package), 2);
                }
                $reduction_value += $order_total * $this->reduction_percent / 100;
            }
            // Discount (%) on a specific product
            if ($this->reduction_percent && $this->reduction_product > 0) {
                foreach ($package_products as $product) {
                    if ($product['id_product'] == $this->reduction_product) {
                        $reduction_value += ($use_tax ? $product['total_wt'] : $product['total']) * $this->reduction_percent / 100;
                    }
                }
            }
            // Discount (%) on the cheapest product
            if ($this->reduction_percent && $this->reduction_product == -1) {
                $minPrice = false;
                $cheapest_product = null;
                foreach ($all_products as $product) {
                    $price = $use_tax ? $product['price_wt'] : $product['price'];
                    if ($price > 0 && ($minPrice === false || $minPrice > $price)) {
                        $minPrice = $price;
                        $cheapest_product = $product['id_product'] . '-' . $product['id_product_attribute'];
                    }
                }
                // Check if the cheapest product is in the package
                $in_package = false;
                foreach ($package_products as $product) {
                    if ($product['id_product'] . '-' . $product['id_product_attribute'] == $cheapest_product || $product['id_product'] . '-0' == $cheapest_product) {
                        $in_package = true;
                    }
                }
                if ($in_package) {
                    $reduction_value += $minPrice * $this->reduction_percent / 100;
                }
            }
            // Discount (%) on the selection of products
            if ($this->reduction_percent && $this->reduction_product == -2) {
                $selected_products_reduction = 0;
                $selected_products = $this->checkProductRestrictions($context, true);
                if (is_array($selected_products)) {
                    foreach ($package_products as $product) {
                        if (in_array($product['id_product'] . '-' . $product['id_product_attribute'], $selected_products) || in_array($product['id_product'] . '-0', $selected_products)) {
                            $price = $use_tax ? $product['price_wt'] : $product['price'];
                            $selected_products_reduction += $price * $product['cart_quantity'];
                        }
                    }
                }
                $reduction_value += $selected_products_reduction * $this->reduction_percent / 100;
            }
            // Discount (¤)
            if ($this->reduction_amount) {
                $prorata = 1;
                if (!is_null($package) && count($all_products)) {
                    $total_products = $context->cart->getOrderTotal($use_tax, Cart::ONLY_PRODUCTS);
                    if ($total_products) {
                        $prorata = $context->cart->getOrderTotal($use_tax, Cart::ONLY_PRODUCTS, $package['products']) / $total_products;
                    }
                }
                $reduction_amount = $this->reduction_amount;
                // If we need to convert the voucher value to the cart currency
                if ($this->reduction_currency != $context->currency->id) {
                    $voucherCurrency = new Currency($this->reduction_currency);
                    // First we convert the voucher value to the default currency
                    if ($reduction_amount == 0 || $voucherCurrency->conversion_rate == 0) {
                        $reduction_amount = 0;
                    } else {
                        $reduction_amount /= $voucherCurrency->conversion_rate;
                    }
                    // Then we convert the voucher value in the default currency into the cart currency
                    $reduction_amount *= $context->currency->conversion_rate;
                    $reduction_amount = Tools::ps_round($reduction_amount);
                }
                // If it has the same tax application that you need, then it's the right value, whatever the product!
                if ($this->reduction_tax == $use_tax) {
                    // The reduction cannot exceed the products total, except when we do not want it to be limited (for the partial use calculation)
                    if ($filter != CartRule::FILTER_ACTION_ALL_NOCAP) {
                        $cart_amount = $context->cart->getOrderTotal($use_tax, Cart::ONLY_PRODUCTS);
                        $reduction_amount = min($reduction_amount, $cart_amount);
                    }
                    $reduction_value += $prorata * $reduction_amount;
                } else {
                    if ($this->reduction_product > 0) {
                        foreach ($context->cart->getProducts() as $product) {
                            if ($product['id_product'] == $this->reduction_product) {
                                $product_price_ti = $product['price_wt'];
                                $product_price_te = $product['price'];
                                $product_vat_amount = $product_price_ti - $product_price_te;
                                if ($product_vat_amount == 0 || $product_price_te == 0) {
                                    $product_vat_rate = 0;
                                } else {
                                    $product_vat_rate = $product_vat_amount / $product_price_te;
                                }
                                if ($this->reduction_tax && !$use_tax) {
                                    $reduction_value += $prorata * $reduction_amount / (1 + $product_vat_rate);
                                } elseif (!$this->reduction_tax && $use_tax) {
                                    $reduction_value += $prorata * $reduction_amount * (1 + $product_vat_rate);
                                }
                            }
                        }
                    } elseif ($this->reduction_product == 0) {
                        $cart_amount_ti = $context->cart->getOrderTotal(true, Cart::ONLY_PRODUCTS);
                        $cart_amount_te = $context->cart->getOrderTotal(false, Cart::ONLY_PRODUCTS);
                        // The reduction cannot exceed the products total, except when we do not want it to be limited (for the partial use calculation)
                        if ($filter != CartRule::FILTER_ACTION_ALL_NOCAP) {
                            $reduction_amount = min($reduction_amount, $this->reduction_tax ? $cart_amount_ti : $cart_amount_te);
                        }
                        $cart_vat_amount = $cart_amount_ti - $cart_amount_te;
                        if ($cart_vat_amount == 0 || $cart_amount_te == 0) {
                            $cart_average_vat_rate = 0;
                        } else {
                            $cart_average_vat_rate = Tools::ps_round($cart_vat_amount / $cart_amount_te, 3);
                        }
                        if ($this->reduction_tax && !$use_tax) {
                            $reduction_value += $prorata * $reduction_amount / (1 + $cart_average_vat_rate);
                        } elseif (!$this->reduction_tax && $use_tax) {
                            $reduction_value += $prorata * $reduction_amount * (1 + $cart_average_vat_rate);
                        }
                    }
                    /*
                     * Reduction on the cheapest or on the selection is not really meaningful and has been disabled in the backend
                     * Please keep this code, so it won't be considered as a bug
                     * elseif ($this->reduction_product == -1)
                     * elseif ($this->reduction_product == -2)
                     */
                }
            }
        }
        // Free gift
        if ((int) $this->gift_product && in_array($filter, array(CartRule::FILTER_ACTION_ALL, CartRule::FILTER_ACTION_ALL_NOCAP, CartRule::FILTER_ACTION_GIFT))) {
            $id_address = is_null($package) ? 0 : $package['id_address'];
            foreach ($package_products as $product) {
                if ($product['id_product'] == $this->gift_product && ($product['id_product_attribute'] == $this->gift_product_attribute || !(int) $this->gift_product_attribute)) {
                    // The free gift coupon must be applied to one product only (needed for multi-shipping which manage multiple product lists)
                    if (!isset(CartRule::$only_one_gift[$this->id . '-' . $this->gift_product]) || CartRule::$only_one_gift[$this->id . '-' . $this->gift_product] == $id_address || CartRule::$only_one_gift[$this->id . '-' . $this->gift_product] == 0 || $id_address == 0 || !$use_cache) {
                        $reduction_value += $use_tax ? $product['price_wt'] : $product['price'];
                        if ($use_cache && (!isset(CartRule::$only_one_gift[$this->id . '-' . $this->gift_product]) || CartRule::$only_one_gift[$this->id . '-' . $this->gift_product] == 0)) {
                            CartRule::$only_one_gift[$this->id . '-' . $this->gift_product] = $id_address;
                        }
                        break;
                    }
                }
            }
        }
        Cache::store($cache_id, $reduction_value);
        return $reduction_value;
    }
    public function customGetNestedCategories($shop_id, $root_category = null, $id_lang = false, $active = false, $groups = null, $use_shop_restriction = true, $sql_filter = '', $sql_sort = '', $sql_limit = '')
    {
        if (isset($root_category) && !Validate::isInt($root_category)) {
            die(Tools::displayError());
        }
        if (!Validate::isBool($active)) {
            die(Tools::displayError());
        }
        if (isset($groups) && Group::isFeatureActive() && !is_array($groups)) {
            $groups = (array) $groups;
        }
        $cache_id = 'Category::getNestedCategories_' . md5((int) $shop_id . (int) $root_category . (int) $id_lang . (int) $active . (int) $active . (isset($groups) && Group::isFeatureActive() ? implode('', $groups) : ''));
        if (!Cache::isStored($cache_id)) {
            $result = Db::getInstance()->executeS('
							SELECT c.*, cl.*
				FROM `' . _DB_PREFIX_ . 'category` c
				INNER JOIN `' . _DB_PREFIX_ . 'category_shop` category_shop ON (category_shop.`id_category` = c.`id_category` AND category_shop.`id_shop` = "' . (int) $shop_id . '")
				LEFT JOIN `' . _DB_PREFIX_ . 'category_lang` cl ON (c.`id_category` = cl.`id_category` AND cl.`id_shop` = "' . (int) $shop_id . '")
				WHERE 1 ' . $sql_filter . ' ' . ($id_lang ? 'AND cl.`id_lang` = ' . (int) $id_lang : '') . '
				' . ($active ? ' AND (c.`active` = 1 OR c.`is_root_category` = 1)' : '') . '
				' . (isset($groups) && Group::isFeatureActive() ? ' AND cg.`id_group` IN (' . implode(',', $groups) . ')' : '') . '
				' . (!$id_lang || isset($groups) && Group::isFeatureActive() ? ' GROUP BY c.`id_category`' : '') . '
				' . ($sql_sort != '' ? $sql_sort : ' ORDER BY c.`level_depth` ASC') . '
				' . ($sql_sort == '' && $use_shop_restriction ? ', category_shop.`position` ASC' : '') . '
				' . ($sql_limit != '' ? $sql_limit : ''));
            $categories = array();
            $buff = array();
            foreach ($result as $row) {
                $current =& $buff[$row['id_category']];
                $current = $row;
                if ($row['id_parent'] == 0) {
                    $categories[$row['id_category']] =& $current;
                } else {
                    $buff[$row['id_parent']]['children'][$row['id_category']] =& $current;
                }
            }
            Cache::store($cache_id, $categories);
        }
        return Cache::retrieve($cache_id);
    }
 public static function getLanguagePackListContent($iso, $tar)
 {
     $key = 'Language::getLanguagePackListContent_' . $iso;
     if (!Cache::isStored($key)) {
         if (!$tar instanceof Archive_Tar) {
             return false;
         }
         $result = $tar->listContent();
         Cache::store($key, $result);
         return $result;
     }
     return Cache::retrieve($key);
 }
Exemple #29
0
 public static function getPlugin($name, $base = null)
 {
     $cache_id = 'psm.plugin:' . $name . '!' . $base;
     if (!Cache::isStored($cache_id)) {
         if ($base == null && !Module::isEnabled($name)) {
             Cache::store($cache_id, false);
         } else {
             $classname = Tools::toCamelCase($name, true) . 'Plugin';
             $basedir = $base == null ? $name : $base . '/plugins/' . Tools::strtolower($name);
             $file = _PS_MODULE_DIR_ . $basedir . '/' . $classname . '.php';
             $file = self::normalizePath($file);
             if (is_file($file)) {
                 require_once $file;
                 Cache::store($cache_id, new $classname());
             } else {
                 Cache::store($cache_id, false);
             }
         }
     }
     return Cache::retrieve($cache_id);
 }
 public function validateOrder($id_cart, $id_order_state, $amountPaid, $paymentMethod = 'Unknown', $message = NULL, $extraVars = array(), $currency_special = NULL, $dont_touch_amount = false, $secure_key = false, Shop $shop = null)
 {
     @session_start();
     @set_time_limit(120);
     $_SESSION['id_cart_validating'] = (int) $id_cart;
     if (Module::isInstalled('agileprepaidcredit')) {
         require_once _PS_ROOT_DIR_ . "/modules/agileprepaidcredit/agileprepaidcredit.php";
         AgilePrepaidCredit::set_token_payment_processing_marker($id_cart, true);
     }
     if (!Module::isInstalled('agilemultipleseller')) {
         $ret = parent::validateOrder($id_cart, $id_order_state, $amountPaid, $paymentMethod, $message, $extraVars, $currency_special, $dont_touch_amount, $secure_key);
         if (Module::isInstalled('agileprepaidcredit')) {
             AgilePrepaidCredit::adjustOrderForTokens($this->currentOrder);
             if ($this->name == 'agilepaypalparallel' || ($this->name = 'agilepaypaladaptive')) {
                 AgilePrepaidCredit::checkOrderInvoicePayment($this->currentOrder);
             }
         }
         return $ret;
     }
     require_once _PS_ROOT_DIR_ . "/modules/agilemultipleseller/agilemultipleseller.php";
     $paymode = (int) Configuration::get('AGILE_MS_PAYMENT_MODE');
     $sellers = AgileMultipleSeller::getSellersByCart($id_cart);
     if (count($sellers) <= 1) {
         $id_cart_patent = AgileMultipleSeller::get_subcart_parentid($id_cart);
         $ordervalided = parent::validateOrder($id_cart, $id_order_state, $amountPaid, $paymentMethod, $message, $extraVars, $currency_special, $dont_touch_amount, $secure_key);
         $this->updateSellerCommissionRecordType($paymode, $message);
         if ($ordervalided and $id_cart_patent > 0) {
             AgileMultipleSeller::remove_subcart_items_from_maincart($id_cart, $this->currentOrder);
         }
         if (Module::isInstalled('agileprepaidcredit')) {
             AgilePrepaidCredit::adjustOrderForTokens($this->currentOrder);
             if ($this->name == 'agilepaypalparallel' || ($this->name = 'agilepaypaladaptive')) {
                 AgilePrepaidCredit::checkOrderInvoicePayment($this->currentOrder);
             }
         }
         return $ordervalided;
     }
     $cartinfos = AgileMultipleSeller::split_shopping_cart($id_cart, $sellers);
     if (empty($cartinfos)) {
         $ret = parent::validateOrder($id_cart, $id_order_state, $amountPaid, $paymentMethod, $message, $extraVars, $currency_special, $dont_touch_amount, $secure_key);
         $this->updateSellerCommissionRecordType($paymode, $message);
         if (Module::isInstalled('agileprepaidcredit')) {
             AgilePrepaidCredit::adjustOrderForTokens($this->currentOrder);
             if ($this->name == 'agilepaypalparallel' || ($this->name = 'agilepaypaladaptive')) {
                 AgilePrepaidCredit::checkOrderInvoicePayment($this->currentOrder);
             }
         }
         return $ret;
     }
     $ret = true;
     foreach ($cartinfos as $cartinfo) {
         $_SESSION['id_cart_validating'] = (int) $cartinfo['id_cart'];
         $this->context->cart = new Cart(intval($cartinfo['id_cart']));
         $this->context->cart->getPackageList(true);
         $filter = CartRule::FILTER_ACTION_ALL;
         $cache_key = 'Cart::getCartRules' . $cartinfo['id_cart'] . '-' . $filter;
         if (Cache::isStored($cache_key)) {
             Cache::clean($cache_key);
         }
         if (Module::isInstalled('agileprepaidcredit')) {
             AgilePrepaidCredit::set_token_payment_processing_marker($cartinfo['id_cart'], true);
         }
         $ret = $ret and parent::validateOrder($cartinfo['id_cart'], $id_order_state, $cartinfo['amountPaid'], $paymentMethod, $message, $extraVars, $currency_special, $dont_touch_amount, $secure_key);
         $this->updateSellerCommissionRecordType($paymode, $message);
         if ($this->name == 'agilepaypalparallel') {
             $this->updateTxnDetailCartID($message, $this->currentOrder, $cartinfo['id_cart']);
         }
         if (Module::isInstalled('agileprepaidcredit')) {
             AgilePrepaidCredit::adjustOrderForTokens($this->currentOrder);
             if ($this->name == 'agilepaypalparallel' || ($this->name = 'agilepaypaladaptive')) {
                 AgilePrepaidCredit::adjustOrderPaymentAmount($this->currentOrder, $this->name);
                 AgilePrepaidCredit::checkOrderInvoicePayment($this->currentOrder);
             }
         }
     }
     return $ret;
 }