public function run()
 {
     $this->init();
     $this->preProcess();
     global $cookie, $link;
     $id_product = Tools::getValue('id');
     $product = new Product($id_product, true, 1);
     $id_customer = (isset(self::$cookie->id_customer) and self::$cookie->id_customer) ? (int) self::$cookie->id_customer : 0;
     if ($id_customer) {
         $sql = "select id from ps_wishlist where id_customer = " . $id_customer . " and id_product = " . $product->id;
         $res = Db::getInstance()->ExecuteS($sql);
         if ($res) {
             self::$smarty->assign("in_wishlist", true);
         } else {
             self::$smarty->assign("in_wishlist", false);
         }
     } else {
         self::$smarty->assign("in_wishlist", false);
     }
     $idImage = $product->getCoverWs();
     if ($idImage) {
         $idImage = $productObj->id . '-' . $idImage;
     } else {
         $idImage = Language::getIsoById(1) . '-default';
     }
     $image_link = $link->getImageLink($productObj->link_rewrite, $idImage, 'thickbox');
     self::$smarty->assign('product', $product);
     self::$smarty->assign('imagelink', $image_link);
     self::$smarty->assign('productlink', $product->getLink());
     die(self::$smarty->display(_PS_THEME_DIR_ . 'quick-view.tpl'));
 }
Example #2
0
function sendCartMails()
{
    global $link;
    $sql = "SELECT c.id_cart, cc.email, cc.`firstname`, cc.id_customer\n\tFROM `ps_cart` c\n\tINNER JOIN ps_customer cc ON cc.`id_customer` = c.`id_customer`\n\tINNER JOIN `ps_cart_product` cp ON cp.`id_cart` = c.id_cart\n\tLEFT JOIN ps_orders o ON o.`id_cart` = c.id_cart\n\tWHERE o.id_cart IS NULL\n\tAND datediff(curdate(), c.`date_upd`) = 3\n\tAND cc.newsletter = 0\n\tGROUP BY cc.`id_customer`";
    /*$sql = "SELECT c.id_cart, cc.email, cc.`firstname`, cc.id_customer
    	FROM `ps_cart` c
    	INNER JOIN ps_customer cc ON cc.`id_customer` = c.`id_customer`
    	INNER JOIN `ps_cart_product` cp ON cp.`id_cart` = c.id_cart
    	LEFT JOIN ps_orders o ON o.`id_cart` = c.id_cart
    	WHERE cc.id_customer = 1
    	GROUP BY cc.`id_customer`";*/
    $res = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS($sql);
    $count = 0;
    foreach ($res as $row) {
        $count++;
        $id_cart = Cart::lastNoneOrderedCart($row['id_customer']);
        $cart = new Cart($id_cart);
        $id_product = $cart->getLastProduct();
        $id_product = $id_product['id_product'];
        $product = new Product($id_product, true, 1);
        $idImage = $product->getCoverWs();
        if ($idImage) {
            $idImage = $product->id . '-' . $idImage;
        } else {
            $idImage = Language::getIsoById(1) . '-default';
        }
        $templateVars = array();
        $templateVars['{firstname}'] = $row['firstname'];
        $templateVars['{product_url}'] = $product->getLink();
        $templateVars['{product_name}'] = $product->name;
        $templateVars['{image_link}'] = $link->getImageLink($product->link_rewrite, $idImage, 'list');
        $mailTo = $row['email'];
        echo "" . $count . " : " . $mailTo . "\n";
        $subject = $row['firstname'] . ", you left your shopping bag with us";
        @Mail::Send(1, 'abandoned', $subject, $templateVars, $mailTo, $row['firstname'], '*****@*****.**', 'Indusdiva.com', NULL, NULL, _PS_MAIL_DIR_, false);
        usleep(200000);
    }
}
Example #3
0
function sendWishlistMails()
{
    global $link;
    $sql = "SELECT w.id_product, cc.email, cc.`firstname`, cc.id_customer\n\tFROM `ps_wishlist` w\n\tINNER JOIN ps_customer cc ON cc.`id_customer` = w.`id_customer`\n\tINNER JOIN ps_product p ON p.id_product = w.id_product\n\tLEFT JOIN ps_orders o ON o.`id_customer` = cc.`id_customer`\n\tWHERE o.id_customer IS NULL\n\tAND p.`quantity` > 0\n\tAND p.active = 1\n\tAND cc.newsletter = 0\n\tOR cc.id_customer = 1\n\tGROUP BY cc.`id_customer`";
    /*$sql = "SELECT w.id_product, cc.email, cc.`firstname`, cc.id_customer
    	FROM `ps_wishlist` w
    	INNER JOIN ps_customer cc ON cc.`id_customer` = w.`id_customer`
    	INNER JOIN ps_product p ON p.id_product = w.id_product
    	LEFT JOIN ps_orders o ON o.`id_customer` = cc.`id_customer`
    	WHERE cc.id_customer in (1)
    	AND p.`quantity` > 0
    	AND p.active = 1
    	GROUP BY cc.`id_customer`";*/
    $res = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS($sql);
    $count = 0;
    foreach ($res as $row) {
        $count++;
        $id_product = $row['id_product'];
        $product = new Product($id_product, true, 1);
        $idImage = $product->getCoverWs();
        if ($idImage) {
            $idImage = $product->id . '-' . $idImage;
        } else {
            $idImage = Language::getIsoById(1) . '-default';
        }
        $templateVars = array();
        $templateVars['{firstname}'] = $row['firstname'];
        $templateVars['{product_url}'] = $product->getLink();
        $templateVars['{product_name}'] = $product->name;
        $templateVars['{image_link}'] = $link->getImageLink($product->link_rewrite, $idImage, 'list');
        $mailTo = $row['email'];
        echo "" . $count . " : " . $mailTo . "\n";
        $subject = $row['firstname'] . ", Let your Wishlist Come True";
        @Mail::Send(1, 'wishlistreminder', $subject, $templateVars, $mailTo, $row['firstname'], '*****@*****.**', 'Indusdiva.com', NULL, NULL, _PS_MAIL_DIR_, true);
        usleep(200000);
    }
}
 protected function manageEntityDeclinatedImages($directory, $normal_image_sizes)
 {
     $normal_image_size_names = array();
     foreach ($normal_image_sizes as $normal_image_size) {
         $normal_image_size_names[] = $normal_image_size['name'];
     }
     // If id is detected
     $object_id = $this->wsObject->urlSegment[2];
     if (!Validate::isUnsignedId($object_id)) {
         throw new WebserviceException('The image id is invalid. Please set a valid id or the "default" value', array(60, 400));
     }
     // For the product case
     if ($this->imageType == 'products') {
         // Get available image ids
         $available_image_ids = array();
         // New Behavior
         $languages = Language::getLanguages();
         foreach ($languages as $language) {
             foreach (Image::getImages($language['id_lang'], $object_id) as $image) {
                 $available_image_ids[] = $image['id_image'];
             }
         }
         // If an image id is specified
         if ($this->wsObject->urlSegment[3] != '') {
             if ($this->wsObject->urlSegment[3] == 'bin') {
                 $currentProduct = new Product($object_id);
                 $this->wsObject->urlSegment[3] = $currentProduct->getCoverWs();
             }
             if (!Validate::isUnsignedId($object_id) || !in_array($this->wsObject->urlSegment[3], $available_image_ids)) {
                 throw new WebserviceException('This image id does not exist', array(57, 400));
             } else {
                 // Check for new image system
                 $image_id = $this->wsObject->urlSegment[3];
                 $path = implode('/', str_split((string) $image_id));
                 $image_size = $this->wsObject->urlSegment[4];
                 if (file_exists($directory . $path . '/' . $image_id . (strlen($this->wsObject->urlSegment[4]) > 0 ? '-' . $this->wsObject->urlSegment[4] : '') . '.jpg')) {
                     $filename = $directory . $path . '/' . $image_id . (strlen($this->wsObject->urlSegment[4]) > 0 ? '-' . $this->wsObject->urlSegment[4] : '') . '.jpg';
                     $orig_filename = $directory . $path . '/' . $image_id . '.jpg';
                 } else {
                     $orig_filename = $directory . $object_id . '-' . $image_id . '.jpg';
                     $filename = $directory . $object_id . '-' . $image_id . '-' . $image_size . '.jpg';
                 }
             }
         } else {
             if ($this->wsObject->method == 'GET' || $this->wsObject->method == 'HEAD') {
                 if ($available_image_ids) {
                     $this->output .= $this->objOutput->getObjectRender()->renderNodeHeader('image', array(), array('id' => $object_id));
                     foreach ($available_image_ids as $available_image_id) {
                         $this->output .= $this->objOutput->getObjectRender()->renderNodeHeader('declination', array(), array('id' => $available_image_id, 'xlink_resource' => $this->wsObject->wsUrl . 'images/' . $this->imageType . '/' . $object_id . '/' . $available_image_id), false);
                     }
                     $this->output .= $this->objOutput->getObjectRender()->renderNodeFooter('image', array());
                 } else {
                     $this->objOutput->setStatus(404);
                     $this->wsObject->setOutputEnabled(false);
                 }
             }
         }
     } else {
         $orig_filename = $directory . $object_id . '.jpg';
         $image_size = $this->wsObject->urlSegment[3];
         $filename = $directory . $object_id . '-' . $image_size . '.jpg';
     }
     // in case of declinated images list of a product is get
     if ($this->output != '') {
         return true;
     } elseif (isset($image_size) && $image_size != '') {
         // Check the given size
         if ($this->imageType == 'products' && $image_size == 'bin') {
             $filename = $directory . $object_id . '-' . $image_id . '.jpg';
         } elseif (!in_array($image_size, $normal_image_size_names)) {
             $exception = new WebserviceException('This image size does not exist', array(58, 400));
             throw $exception->setDidYouMean($image_size, $normal_image_size_names);
         }
         if (!file_exists($filename)) {
             throw new WebserviceException('This image does not exist on disk', array(59, 500));
         }
         // Display the resized specific image
         $this->imgToDisplay = $filename;
         return true;
     } elseif (isset($orig_filename)) {
         $orig_filename_exists = file_exists($orig_filename);
         return $this->manageDeclinatedImagesCRUD($orig_filename_exists, $orig_filename, $normal_image_sizes, $directory);
     } else {
         return $this->manageDeclinatedImagesCRUD(false, '', $normal_image_sizes, $directory);
     }
 }
 public function process()
 {
     global $cart, $currency;
     parent::process();
     if (!($id_product = (int) Tools::getValue('id_product')) or !Validate::isUnsignedId($id_product)) {
         $this->errors[] = Tools::displayError('Product not found');
     } else {
         if (!Validate::isLoadedObject($this->product) or !$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);
             }
             /* rewrited url set */
             $rewrited_url = self::$link->getProductLink($this->product->id, $this->product->link_rewrite);
             /* Product pictures management */
             require_once 'images.inc.php';
             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));
             if ((int) Tools::getValue('pp') == 1) {
                 echo 'here1';
             }
             $productPriceWithTax = Product::getPriceStatic($id_product, true, NULL, 6);
             if (Product::$_taxCalculationMethod == PS_TAX_INC) {
                 $productPriceWithTax = Tools::ps_round($productPriceWithTax, 2);
             }
             if ((int) Tools::getValue('pp') == 1) {
                 $time2 = time();
                 echo 'time2: ' . $time2;
             }
             $productPriceWithoutEcoTax = (double) ($productPriceWithTax - $this->product->ecotax);
             $configs = Configuration::getMultiple(array('PS_ORDER_OUT_OF_STOCK', 'PS_LAST_QTIES'));
             /* Features / Values */
             $features = $this->product->getFrontFeatures((int) self::$cookie->id_lang);
             $attachments = $this->product->getAttachments((int) self::$cookie->id_lang);
             /* 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();');
             $lang = Configuration::get('PS_LANG_DEFAULT');
             if (Pack::isPack((int) $this->product->id, (int) $lang) and !Pack::isInStock((int) $this->product->id, (int) $lang)) {
                 $this->product->quantity = 0;
             }
             $group_reduction = (100 - Group::getReduction((int) self::$cookie->id_customer)) / 100;
             $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'));
             if ((int) Tools::getValue('pp') == 1) {
                 $time3 = time();
                 echo 'time3: ' . $time3;
             }
             // Tax
             $tax = (double) Tax::getProductTaxRate((int) $this->product->id, $cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
             self::$smarty->assign('tax_rate', $tax);
             $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);
             }
             $manufacturer = new Manufacturer((int) $this->product->id_manufacturer, 1);
             $sizechart = new Sizechart((int) $this->product->id_sizechart, 1);
             //see if the product is already in the wishlist
             if ($id_customer) {
                 $sql = "select id from ps_wishlist where id_customer = " . $id_customer . " and id_product = " . $this->product->id;
                 $res = Db::getInstance()->ExecuteS($sql);
                 if ($res) {
                     self::$smarty->assign("in_wishlist", true);
                 } else {
                     self::$smarty->assign("in_wishlist", false);
                 }
             } else {
                 self::$smarty->assign("in_wishlist", false);
             }
             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' => $manufacturer, '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) $configs['PS_LAST_QTIES'], 'group_reduction' => $group_reduction, 'col_img_dir' => _PS_COL_IMG_DIR_, 'sizechart' => $sizechart->sizechart, 'sizechart_data' => $sizechart->sizechart_data));
             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')));
             if ((int) Tools::getValue('pp') == 1) {
                 $time4 = time();
                 echo 'time4: ' . $time4;
             }
             $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 (sizeof($productImages)) {
                 self::$smarty->assign('images', $productImages);
             }
             if ((int) Tools::getValue('pp') == 1) {
                 $time5 = time();
                 echo 'time5: ' . $time5;
             }
             /* Attributes / Groups & colors */
             $colors = array();
             //see if the product has shades
             if ($this->product->id_group && $this->product->id_group > 0) {
                 global $link;
                 $related_productIds = $this->product->getRelatedProducts();
                 $related_products = array();
                 foreach ($related_productIds as &$productId) {
                     $relProduct = new Product((int) $productId['id_product'], true, self::$cookie->id_lang);
                     $idImage = $relProduct->getCoverWs();
                     if ($idImage) {
                         $idImage = $relProduct->id . '-' . $idImage;
                     } else {
                         $idImage = Language::getIsoById(1) . '-default';
                     }
                     $relProduct->image_link = $link->getImageLink($relProduct->link_rewrite, $idImage, 'small');
                     $relProduct->link = $relProduct->getLink();
                     $related_products[] = $relProduct;
                 }
                 self::$smarty->assign('relatedProducts', $related_products);
             }
             if ((int) Tools::getValue('pp') == 1) {
                 $time6 = time();
                 echo 'time6: ' . $time6;
             }
             $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']]['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;
                 }
                 if ((int) Tools::getValue('pp') == 1) {
                     $time7 = time();
                     echo 'time7: ' . $time7;
                 }
                 //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]);
                         }
                     }
                 }
                 if ((int) Tools::getValue('pp') == 1) {
                     $time71 = time();
                     echo 'time71: ' . $time71;
                 }
                 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));
             }
             if ((int) Tools::getValue('pp') == 1) {
                 $time72 = time();
                 echo 'time72: ' . $time72;
             }
             //$newProducts = Product::getNewProducts((int)(self::$cookie->id_lang), 0, 10, false, 'date_add', 'desc');
             /*$categoryProducts = $this->getRandomCatProducts();
               self::$smarty->assign('cat_products', $categoryProducts);*/
             //$brandProducts = $this->getRandomBrandProducts();
             //self::$smarty->assign('brand_products', $brandProducts);
             if ((int) Tools::getValue('pp') == 1) {
                 $time73 = time();
                 echo ' time73: ' . $time73;
             }
             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->getCustomizationFields((int) self::$cookie->id_lang)));
             if ((int) Tools::getValue('pp') == 1) {
                 $time74 = time();
                 echo 'time74: ' . $time74;
             }
             // 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));
             if ((int) Tools::getValue('pp') == 1) {
                 print_r('pack done');
             }
         }
     }
     if ((int) Tools::getValue('pp') == 1) {
         $time8 = time();
         echo 'time8: ' . $time8;
     }
     if ($this->is_saree || $this->is_lehenga) {
         if ($this->is_lehenga) {
             self::$smarty->assign('is_lehenga', $this->is_lehenga);
         }
         self::$smarty->assign('as_shown', (bool) $this->product->as_shown);
         /*if($blouse_measurements = $this->getCustomerMeasurements(self::$cookie->id_customer, 1))
               self::$smarty->assign('measurement_info', $blouse_measurements);
           if($skirt_measurements = $this->getCustomerMeasurements(self::$cookie->id_customer, 2))
               self::$smarty->assign('skirt_measurement_info', $skirt_measurements);*/
         if ((int) Tools::getValue('pp') == 1) {
             $time81 = time();
             echo 'time81: ' . $time81;
         }
         if ($this->is_saree) {
             //count of all styles mapped to this product
             $res = Db::getInstance()->getRow("select count(s.id_style) as style_count from ps_styles s inner join ps_product_style ps on ps.id_style = s.id_style and ps.id_product = {$id_product} and s.style_type = 1");
             $style_count = (int) $res['style_count'];
             if ($style_count === 0) {
                 // show the default style for sarees
                 $style = array('id_style' => 1, 'style_image_small' => '1-small.png', 'style_name' => 'Round');
             } else {
                 $res = Db::getInstance()->getRow("select s.id_style, s.style_name, s.style_image_small  from ps_styles s inner join ps_product_style ps on ps.id_style = s.id_style and ps.id_product = {$id_product} and s.style_type = 1 and ps.is_default = 1");
                 if (!empty($res)) {
                     //show the default style for this product
                     $style = array('id_style' => $res['id_style'], 'style_image_small' => $res['style_image_small'], 'style_name' => $res['style_name']);
                 }
             }
             if ((int) Tools::getValue('pp') == 1) {
                 $time82 = time();
                 echo 'time82: ' . $time82;
             }
             self::$smarty->assign('blouse_style_count', $style_count);
             self::$smarty->assign('blouse_style', $style);
         }
     } else {
         if ($this->is_skd || $this->is_skd_rts) {
             self::$smarty->assign('is_anarkali', $this->is_anarkali);
             if ($this->is_anarkali) {
                 if ($kurta_measurements = $this->getCustomerMeasurements(self::$cookie->id_customer, 5)) {
                     self::$smarty->assign('kurta_measurement_info', $kurta_measurements);
                 }
             } else {
                 if ($kurta_measurements = $this->getCustomerMeasurements(self::$cookie->id_customer, 3)) {
                     self::$smarty->assign('kurta_measurement_info', $kurta_measurements);
                 }
             }
             if ($salwar_measurements = $this->getCustomerMeasurements(self::$cookie->id_customer, 4)) {
                 self::$smarty->assign('salwar_measurement_info', $salwar_measurements);
             }
             //get default styles for this product (RTS)
             if ($this->is_skd_rts) {
                 $res = Db::getInstance()->ExecuteS("select count(s.id_style) as style_count, s.style_type, ps.id_product from ps_styles s inner join ps_product_style ps on ps.id_style = s.id_style and ps.id_product = {$id_product} group by ps.id_product,s.style_type");
                 foreach ($res as $s) {
                     $style_count = (int) $s['style_count'];
                     if ((int) $s['style_type'] === 4) {
                         self::$smarty->assign('kurta_style_count', $style_count);
                     } else {
                         if ((int) $s['style_type'] === 5) {
                             self::$smarty->assign('salwar_style_count', $style_count);
                         }
                     }
                 }
                 $res = Db::getInstance()->ExecuteS("select s.id_style, s.style_type, s.style_image_small, s.style_name from ps_styles s inner join ps_product_style ps on ps.id_style = s.id_style and ps.id_product = {$id_product} and ps.is_default = 1");
                 foreach ($res as $s) {
                     $style = array('id_style' => $s['id_style'], 'style_image_small' => $s['style_image_small'], 'style_name' => $s['style_name']);
                     if ((int) $s['style_type'] === 4) {
                         self::$smarty->assign('kurta_style', $style);
                     } else {
                         if ((int) $s['style_type'] === 5) {
                             self::$smarty->assign('salwar_style', $style);
                         }
                     }
                 }
             }
         }
     }
     self::$smarty->assign('is_bottoms', $this->is_bottoms);
     self::$smarty->assign('is_abaya', $this->is_abaya);
     self::$smarty->assign('is_wristwear', $this->is_wristwear);
     self::$smarty->assign('is_pakistani_rts', $this->is_pakistani_rts);
     if ((int) Tools::getValue('pp') == 1) {
         $time85 = time();
         echo 'time85: ' . $time85;
     }
     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' => Product::getCover((int) Tools::getValue('id_product')), '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')));
     if ((int) Tools::getValue('pp') == 1) {
         $time9 = time();
         echo 'time9: ' . $time9;
     }
     //add this to product stats
     //Tools::captureActivity(PSTAT_VIEWS,$id_product);
     if ((int) Tools::getValue('pp') == 1) {
         $time1 = time();
         echo 'process end: ' . $time1;
     }
 }
Example #6
0
     $category = 'Choli';
 } elseif (in_array(CAT_GIFTCARD, $catIds)) {
     $category = 'GiftCard';
 } elseif (in_array(CAT_JEWELRY, $catIds)) {
     $category = 'Jewelry';
 } elseif (in_array(CAT_KIDS, $catIds)) {
     $category = 'Kids';
 } elseif (in_array(CAT_ABAYA, $catIds)) {
     $category = 'Abaya';
 } elseif (in_array(CAT_MEN, $catIds)) {
     $category = 'Men';
 } elseif (in_array(CAT_HANDBAG, $catIds)) {
     $category = 'Handbag';
 }
 $doc->product_link = $productObj->getLink();
 $idImage = $productObj->getCoverWs();
 if ($idImage) {
     $idImage = $productObj->id . '-' . $idImage;
 } else {
     $idImage = Language::getIsoById(1) . '-default';
 }
 $thickbox_image = $link->getImageLink($productObj->link_rewrite, $idImage, 'thickbox');
 $large_image = $link->getImageLink($productObj->link_rewrite, $idImage, 'large');
 $id_manufacturer = $productObj->id_manufacturer;
 $manufacturer = '';
 if (!empty($id_manufacturer)) {
     $manufacturer = Manufacturer::getNameById($id_manufacturer);
 }
 $productRec = array($id_product, $productObj->reference, $productObj->supplier_reference, $productObj->name, $productObj->getLink(), $productObj->getPriceWithoutReduct(), round($productObj->getPrice()), round($mrp_in_rs), round($offer_price_in_rs), strip_tags($productObj->description), '0', $availability, $manufacturer, $category, $categories, $color, $fabric, (int) $productObj->active === 1 ? 'ACTIVE' : 'INACTIVE', $quantity, $productObj->shipping_sla, $productObj->is_customizable, $large_image, $thickbox_image, date('Y-m-d', strtotime($productObj->date_add)));
 $images = $productObj->getImages(1);
 foreach ($images as $image) {
    private function manageEntityDeclinatedImages($directory, $normal_image_sizes)
    {
        $normal_image_size_names = array();
        foreach ($normal_image_sizes as $normal_image_size) {
            $normal_image_size_names[] = $normal_image_size['name'];
        }
        // If id is detected
        $object_id = $this->wsObject->urlSegment[2];
        if (!Validate::isUnsignedId($object_id)) {
            throw new WebserviceException('The image id is invalid. Please set a valid id or the "default" value', array(60, 400));
        }
        // For the product case
        if ($this->imageType == 'products') {
            // Get available image ids
            $available_image_ids = array();
            $images = Db::getInstance()->ExecuteS('
				SELECT `id_image`, `id_product`
				FROM `' . _DB_PREFIX_ . 'image`
				WHERE id_product = ' . (int) $object_id . '
				ORDER BY `position` ASC');
            if ($images) {
                foreach ($images as $image) {
                    $available_image_ids[] = $image['id_image'];
                }
            }
            // Old Behavior
            $nodes = scandir($directory);
            foreach ($nodes as $node) {
                // avoid too much preg_match...
                if ($node != '.' && $node != '..' && $node != '.svn') {
                    preg_match('/^' . intval($object_id) . '-(\\d+)\\.jpg*$/Ui', $node, $matches);
                    if (isset($matches[1])) {
                        $available_image_ids[] = $matches[1];
                    }
                }
            }
            $available_image_ids = array_unique($available_image_ids);
            // If an image id is specified
            if ($this->wsObject->urlSegment[3] != '') {
                if ($this->wsObject->urlSegment[3] == 'bin') {
                    $currentProduct = new Product($object_id);
                    $this->wsObject->urlSegment[3] = $currentProduct->getCoverWs();
                }
                if (!Validate::isUnsignedId($object_id) || !in_array($this->wsObject->urlSegment[3], $available_image_ids)) {
                    throw new WebserviceException('This image id does not exist', array(57, 400));
                } else {
                    // Check for new image system
                    $image_id = $this->wsObject->urlSegment[3];
                    $path = implode('/', str_split((string) $image_id));
                    $image_size = $this->wsObject->urlSegment[4];
                    if (file_exists($directory . $path . '/' . $image_id . (strlen($this->wsObject->urlSegment[4]) > 0 ? '-' . $this->wsObject->urlSegment[4] : '') . '.jpg')) {
                        $filename = $directory . $path . '/' . $image_id . (strlen($this->wsObject->urlSegment[4]) > 0 ? '-' . $this->wsObject->urlSegment[4] : '') . '.jpg';
                        $orig_filename = $directory . $path . '/' . $image_id . '.jpg';
                    } else {
                        $orig_filename = $directory . $object_id . '-' . $image_id . '.jpg';
                        $filename = $directory . $object_id . '-' . $image_id . '-' . $image_size . '.jpg';
                    }
                }
            } elseif ($this->wsObject->method == 'GET' || $this->wsObject->method == 'HEAD') {
                if ($available_image_ids) {
                    $this->output .= $this->objOutput->getObjectRender()->renderNodeHeader('image', array(), array('id' => $object_id));
                    foreach ($available_image_ids as $available_image_id) {
                        $this->output .= $this->objOutput->getObjectRender()->renderNodeHeader('declination', array(), array('id' => $available_image_id, 'xlink_resource' => $this->wsObject->wsUrl . 'images/' . $this->imageType . '/' . $object_id . '/' . $available_image_id), false);
                    }
                    $this->output .= $this->objOutput->getObjectRender()->renderNodeFooter('image', array());
                } else {
                    $this->objOutput->setStatus(404);
                    $this->wsObject->setOutputEnabled(false);
                }
            }
        } else {
            $orig_filename = $directory . $object_id . '.jpg';
            $image_size = $this->wsObject->urlSegment[3];
            $filename = $directory . $object_id . '-' . $image_size . '.jpg';
        }
        // in case of declinated images list of a product is get
        if ($this->output != '') {
            return true;
        } elseif (isset($image_size) && $image_size != '') {
            // Check the given size
            if ($this->imageType == 'products' && $image_size == 'bin') {
                $filename = $directory . $object_id . '-' . $image_id . '.jpg';
            } elseif (!in_array($image_size, $normal_image_size_names)) {
                $exception = new WebserviceException('This image size does not exist', array(58, 400));
                throw $exception->setDidYouMean($image_size, $normal_image_size_names);
            }
            if (!file_exists($filename)) {
                throw new WebserviceException('This image does not exist on disk', array(59, 500));
            }
            // Display the resized specific image
            $this->imgToDisplay = $filename;
            return true;
        } elseif (isset($orig_filename)) {
            $orig_filename_exists = file_exists($orig_filename);
            return $this->manageDeclinatedImagesCRUD($orig_filename_exists, $orig_filename, $normal_image_sizes, $directory);
        } else {
            return $this->manageDeclinatedImagesCRUD(false, '', $normal_image_sizes, $directory);
        }
    }
Example #8
0
 /**
  * Returns the absolute product image url of the primary image.
  *
  * @param Product|ProductCore $product the product model.
  * @param Link|LinkCore $link optional link instance to use instead of the one in current context.
  * @return string the url or empty string if could not be generated.
  */
 public function getProductImageUrl($product, $link = null)
 {
     if (is_null($link)) {
         $link = Context::getContext()->link;
     }
     $image_id = $product->getCoverWs();
     if ((int) $image_id > 0) {
         $image_type = $this->chooseOptimalImageType();
         if (!empty($image_type)) {
             return $link->getImageLink($product->link_rewrite, $product->id . '-' . $image_id, $image_type);
         }
     }
     return '';
 }
Example #9
0
function addProducts($client, $ids = array())
{
    //update currency
    // update_currency();
    $default_tz = date_default_timezone_get();
    date_default_timezone_set('UTC');
    $category = new Category(1, 1);
    $sql = "select p.id_product, DATEDIFF(NOW(), p.`date_add`) as 'age'\n            from ps_product p\n            where p.price > 0 and p.active = 1";
    $productScores = array();
    $products = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS($sql);
    foreach ($products as $product) {
        $productScores[$product['id_product']] = array('age' => $product['age'], 'week_sold' => 0, 'month_sales' => 0, 'year_sales' => 0);
    }
    $sql = "select p.`id_product`, sum(od.product_quantity) as 'quantity'\n            from `ps_product` p\n            inner join `ps_order_detail` od on od.product_id = p.id_product\n            inner join ps_orders o on o.id_order = od.id_order\n            where p.price > 0 \n            and p.active = 1\n            and o.date_add > now() - INTERVAL 7 DAY\n            group by p.id_product";
    $week_quantities = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS($sql);
    foreach ($week_quantities as $week_quantity) {
        $productScores[$week_quantity['id_product']]['week_sold'] = $week_quantity['quantity'];
    }
    $sql = "select p.`id_product`, round(sum(od.product_quantity * od.product_price * 55 / o.`conversion_rate`)) as 'month_revenue'\n            from `ps_product` p\n            inner join `ps_order_detail` od on od.product_id = p.id_product\n            inner join ps_orders o on o.id_order = od.id_order\n            where p.price > 0 and p.active = 1\n            and o.date_add > now() - INTERVAL 30 DAY\n            group by p.id_product";
    $month_sales = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS($sql);
    foreach ($month_sales as $month_sale) {
        $productScores[$month_sale['id_product']]['month_sales'] = $month_sale['month_revenue'];
    }
    $sql = "select p.`id_product`, round(sum(od.product_quantity * od.product_price * 55 / o.`conversion_rate`)) as 'year_revenue'\n            from `ps_product` p\n            inner join `ps_order_detail` od on od.product_id = p.id_product\n            inner join ps_orders o on o.id_order = od.id_order\n            where p.price > 0 and p.active = 1\n            and o.date_add > now() - INTERVAL 365 DAY\n            group by p.id_product";
    $year_sales = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS($sql);
    foreach ($year_sales as $year_sale) {
        $productScores[$year_sale['id_product']]['year_sales'] = $year_sale['year_revenue'];
    }
    foreach ($products as $product) {
        $productScores[$product['id_product']]['score'] = getWeekSalesScore($productScores[$product['id_product']]['week_sold']) + getAgeScore($productScores[$product['id_product']]['age']) + getMonthScore($productScores[$product['id_product']]['month_sales']) + getYearScore($productScores[$product['id_product']]['year_sales']);
    }
    $docs = array();
    $link = new Link();
    $count = 0;
    $update = $client->createUpdate();
    foreach ($products as $product) {
        if (!empty($ids) && !in_array((int) $product['id_product'], $ids)) {
            continue;
        }
        $productObj = new Product((int) $product['id_product'], true, 1);
        print_r('\\n' . 'reindexing ' . $product['id_product']);
        if (!$productObj->active) {
            deleteProduct($productObj->id, $client);
            continue;
        }
        $doc = $update->createDocument();
        $doc->id_product = $productObj->id;
        $doc->reference = $productObj->reference;
        $doc->name = $productObj->name;
        $doc->description = preg_replace('@[\\x00-\\x08\\x0B\\x0C\\x0E-\\x1F]@', ' ', $productObj->description);
        $doc->description_short = preg_replace('@[\\x00-\\x08\\x0B\\x0C\\x0E-\\x1F]@', ' ', $productObj->description_short);
        $doc->brand_id = $productObj->id_manufacturer;
        $doc->brand_name = $productObj->manufacturer_name;
        $doc->style_tips = $productObj->description_short;
        $doc->alphaNameSort = $productObj->name;
        $dbresult = $productObj->getWsCategories();
        $catIds = array();
        foreach ($dbresult as $catIdRow) {
            $catIds[] = $catIdRow['id'];
        }
        $category_names = array();
        foreach ($catIds as $catID) {
            $category = new Category((int) $catID);
            $category_names[] = $category->getName(1);
        }
        $doc->cat_name = $category_names;
        $doc->cat_id = $catIds;
        $doc->tags = $productObj->getTags(1);
        $doc->shipping_sla = $productObj->shipping_sla ? $productObj->shipping_sla : 0;
        $doc->weight = $productObj->weight ? $productObj->weight : 0.5;
        if (isset($productObj->work_type)) {
            $doc->work_type = preg_replace('@[\\x00-\\x08\\x0B\\x0C\\x0E-\\x1F]@', ' ', $productObj->work_type ? $productObj->work_type : '');
        }
        if (isset($productObj->garment_type)) {
            $doc->garment_type = preg_replace('@[\\x00-\\x08\\x0B\\x0C\\x0E-\\x1F]@', ' ', $productObj->garment_type ? $productObj->garment_type : '');
        }
        if (isset($productObj->blouse_length)) {
            $doc->blouse_length = $productObj->blouse_length ? $productObj->blouse_length : '';
        }
        $doc->height = $productObj->height;
        $doc->width = $productObj->width;
        $atributeQty = Attribute::getAttributeQty($productObj->id);
        if ($productObj->quantity > 0 || $atributeQty > 0) {
            $doc->inStock = true;
        } else {
            $doc->inStock = false;
        }
        $doc->isPlusSize = $productObj->is_plussize ? true : false;
        $doc->isRTS = $productObj->is_rts ? true : false;
        $doc->quantity = $productObj->quantity ? $productObj->quantity : ($atributeQty ? $atributeQty : 0);
        //Indian Price
        $doc->offer_price_in = Product::getPriceStatic($productObj->id, true, NULL, 6, NULL, false, true, 1, false, NULL, NULL, IND_ADDRESS_ID);
        $doc->offer_price_in_rs = Tools::convertPrice($doc->offer_price_in, 4);
        $doc->mrp_in = Product::getPriceStatic($productObj->id, true, NULL, 6, NULL, false, false, 1, false, NULL, NULL, IND_ADDRESS_ID);
        if ($doc->mrp_in > $doc->offer_price_in) {
            $doc->discount_in = Tools::ps_round(($doc->mrp_in - $doc->offer_price_in) / $doc->mrp_in * 100);
        }
        //Worldwide Price
        $doc->offer_price = $productObj->getPrice();
        $doc->offer_price_rs = Tools::convertPrice($doc->offer_price, 4);
        $doc->mrp = $productObj->getPriceWithoutReduct();
        if ($doc->mrp > $doc->offer_price) {
            $doc->discount = Tools::ps_round(($doc->mrp - $doc->offer_price) / $doc->mrp * 100);
        }
        $date = DateTime::createFromFormat('Y-m-d H:i:s', $productObj->date_add);
        $doc->date_add = $date->format("Y-m-d\\TG:i:s\\Z");
        $doc->product_link = $productObj->getLink();
        $idImage = $productObj->getCoverWs();
        if ($idImage) {
            $idImage = $productObj->id . '-' . $idImage;
        } else {
            $idImage = Language::getIsoById(1) . '-default';
        }
        $doc->image_link_list = $link->getImageLink($productObj->link_rewrite, $idImage, 'list');
        $doc->image_link_medium = $link->getImageLink($productObj->link_rewrite, $idImage, 'medium');
        $doc->image_link_large = $link->getImageLink($productObj->link_rewrite, $idImage, 'large');
        $images = $productObj->getImages(1);
        $productImages = array();
        foreach ($images as $k => $image) {
            $productImages[] = $link->getImageLink($productObj->link_rewrite, $image['id_image'], 'large');
        }
        $doc->image_links = $productImages;
        $doc->sales = $productScores[$product['id_product']]['score'];
        $productObj->fabric = trim($productObj->fabric);
        $productObj->fabric = preg_replace('/\\s+/', '-', $productObj->fabric);
        $doc->fabric = strtolower($productObj->fabric);
        $doc->is_customizable = $productObj->is_customizable;
        if (isset($productObj->generic_color) && !empty($productObj->generic_color)) {
            $colors = explode(',', $productObj->generic_color);
            $indexed_colors = array();
            foreach ($colors as $color) {
                $indexed_colors[] = strtolower(preg_replace('/\\s+/', '-', trim($color)));
            }
            $doc->color = $indexed_colors;
        }
        if (isset($productObj->stone) && !empty($productObj->stone)) {
            $stones = explode(',', $productObj->stone);
            $indexed_stones = array();
            foreach ($stones as $stone) {
                $indexed_stones[] = strtolower(preg_replace('/\\s+/', '-', trim($stone)));
            }
            $doc->stone = $indexed_stones;
        }
        if (isset($productObj->plating) && !empty($productObj->plating)) {
            $platings = explode(',', $productObj->plating);
            $indexed_platings = array();
            foreach ($platings as $plating) {
                $indexed_platings[] = strtolower(preg_replace('/\\s+/', '-', trim($plating)));
            }
            $doc->plating = $indexed_platings;
        }
        if (isset($productObj->material) && !empty($productObj->material)) {
            $materials = explode(',', $productObj->material);
            $indexed_materials = array();
            foreach ($materials as $material) {
                $indexed_materials[] = strtolower(preg_replace('/\\s+/', '-', trim($material)));
            }
            $doc->material = $indexed_materials;
        }
        if (isset($productObj->look) && !empty($productObj->look)) {
            $looks = explode(',', $productObj->look);
            $indexed_looks = array();
            foreach ($looks as $look) {
                $indexed_looks[] = strtolower(preg_replace('/\\s+/', '-', trim($look)));
            }
            $doc->look = $indexed_looks;
        }
        if (isset($productObj->handbag_occasion) && !empty($productObj->handbag_occasion)) {
            $handbag_occasions = explode(',', $productObj->handbag_occasion);
            $indexed_handbag_occasions = array();
            foreach ($handbag_occasions as $handbag_occasion) {
                $indexed_handbag_occasions[] = strtolower(preg_replace('/\\s+/', '-', trim($handbag_occasion)));
            }
            $doc->handbag_occasion = $indexed_handbag_occasions;
        }
        if (isset($productObj->handbag_style) && !empty($productObj->handbag_style)) {
            $handbag_styles = explode(',', $productObj->handbag_style);
            $indexed_handbag_styles = array();
            foreach ($handbag_styles as $handbag_style) {
                $indexed_handbag_styles[] = strtolower(preg_replace('/\\s+/', '-', trim($handbag_style)));
            }
            $doc->handbag_style = $indexed_handbag_styles;
        }
        if (isset($productObj->handbag_material) && !empty($productObj->handbag_material)) {
            $handbag_materials = explode(',', $productObj->handbag_material);
            $indexed_handbag_materials = array();
            foreach ($handbag_materials as $handbag_material) {
                $indexed_handbag_materials[] = strtolower(preg_replace('/\\s+/', '-', trim($handbag_material)));
            }
            $doc->handbag_material = $indexed_handbag_materials;
        }
        $combinaisons = $productObj->getAttributeCombinaisons(1);
        $indexed_sizes = array();
        foreach ($combinaisons as $k => $combinaison) {
            if ($combinaison['group_name'] == 'size' || $combinaison['group_name'] == 'Size') {
                $indexed_sizes[] = $combinaison['attribute_name'];
            }
        }
        $doc->size = $indexed_sizes;
        $doc->cashback_percentage = $productObj->cashback_percentage;
        $docs[] = $doc;
        if (++$count == 300) {
            $update->addDocuments($docs);
            $result = $client->update($update);
            echo 'Update query executed' . PHP_EOL;
            echo 'Query status: ' . $result->getStatus() . PHP_EOL;
            echo 'Query time: ' . $result->getQueryTime() . PHP_EOL;
            $count = 0;
            $docs = array();
            $update = $client->createUpdate();
        }
    }
    $update->addDocuments($docs);
    date_default_timezone_set($default_tz);
    $result = $client->update($update);
    $sql = "update ps_product set indexed = 1 where indexed = 0";
    Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS($sql);
}
</head>
<body style="font-size:0.9em">
<table style="font-size:0.9em;border-collapse:collapse; border:1px solid #CCC;">
<tr>
	<th> Image</th>
	<th> Exclusive </th>	
	<th></th>	
</tr>
<?php 
foreach ($products as $product) {
    $id_product = $product['id_product'];
    $found = 0;
    $sproduct = SolrSearch::getProductsForIDs(array($product['id_product']), $found);
    if (empty($sproduct)) {
        $sproduct = new Product($id_product, true, 1);
        $idImage = $sproduct->getCoverWs();
        if ($idImage) {
            $idImage = $sproduct->id . '-' . $idImage;
        } else {
            $idImage = Language::getIsoById(1) . '-default';
        }
        $list_image = $link->getImageLink($sproduct->link_rewrite, $idImage, "medium");
    } else {
        $list_image = $sproduct[0]['image_link_medium'];
    }
    if (!empty($product['is_exclusive'])) {
        echo "<tr style='background-color:#383; color:#FFF; height:205px' id='trow_{$id_product}'>";
    } else {
        echo "<tr id='trow_{$id_product}' style='height:205px'>";
    }
    echo "<td style='text-align:center'><a target='__new' href='http://www.indusdiva.com/{$id_product}-product.html'><img src='" . $list_image . "'/></a></td>";
Example #11
0
 /**
  * @param Solarium_Query_Update $update
  * @param Link $link
  * @param Product $productObj
  * @return Solarium_Document_ReadWrite
  */
 private static function getProductDoc($update, $link, $productObj)
 {
     $doc = $update->createDocument();
     $doc->id_product = $productObj->id;
     $doc->reference = $productObj->reference;
     $doc->name = $productObj->name;
     //$doc->description = $productObj->description;
     $doc->description = preg_replace('@[\\x00-\\x08\\x0B\\x0C\\x0E-\\x1F]@', ' ', $productObj->description);
     $doc->description_short = preg_replace('@[\\x00-\\x08\\x0B\\x0C\\x0E-\\x1F]@', ' ', $productObj->description_short);
     $doc->brand_id = $productObj->id_manufacturer;
     $doc->brand_name = $productObj->manufacturer_name;
     $doc->style_tips = preg_replace('@[\\x00-\\x08\\x0B\\x0C\\x0E-\\x1F]@', ' ', $productObj->description_short);
     $doc->alphaNameSort = $productObj->name;
     $dbresult = $productObj->getWsCategories();
     $catIds = array();
     foreach ($dbresult as $catIdRow) {
         $catIds[] = $catIdRow['id'];
     }
     $category_names = array();
     foreach ($catIds as $catID) {
         $category = new Category((int) $catID);
         $category_names[] = $category->getName(1);
     }
     $doc->cat_name = $category_names;
     $doc->cat_id = $catIds;
     $doc->tags = $productObj->getTags(1);
     $doc->shipping_sla = $productObj->shipping_sla;
     $doc->weight = $productObj->weight ? $productObj->weight : 0.5;
     $doc->cashback_percentage = $productObj->cashback_percentage;
     if (isset($productObj->work_type)) {
         $doc->work_type = preg_replace('@[\\x00-\\x08\\x0B\\x0C\\x0E-\\x1F]@', ' ', $productObj->work_type ? $productObj->work_type : '');
     }
     if (isset($productObj->garment_type)) {
         $doc->garment_type = preg_replace('@[\\x00-\\x08\\x0B\\x0C\\x0E-\\x1F]@', ' ', $productObj->garment_type ? $productObj->garment_type : '');
     }
     if (isset($productObj->blouse_length)) {
         $doc->blouse_length = $productObj->blouse_length ? $productObj->blouse_length : '';
     }
     $doc->height = $productObj->height;
     $doc->width = $productObj->width;
     $atributeQty = Attribute::getAttributeQty($productObj->id);
     if ($productObj->quantity > 0 || $atributeQty > 0) {
         $doc->inStock = true;
     } else {
         $doc->inStock = false;
     }
     $doc->isPlusSize = $productObj->is_plussize ? true : false;
     $doc->isRTS = $productObj->is_rts ? true : false;
     $doc->quantity = $productObj->quantity ? $productObj->quantity : ($atributeQty ? $atributeQty : 0);
     $date = DateTime::createFromFormat('Y-m-d H:i:s', $productObj->date_add);
     $doc->date_add = $date->format("Y-m-d\\TG:i:s\\Z");
     $productObj->fabric = trim($productObj->fabric);
     $productObj->fabric = preg_replace('/\\s+/', '-', $productObj->fabric);
     $doc->fabric = strtolower($productObj->fabric);
     $doc->is_customizable = $productObj->is_customizable;
     if (isset($productObj->generic_color) && !empty($productObj->generic_color)) {
         $colors = explode(',', $productObj->generic_color);
         $indexed_colors = array();
         foreach ($colors as $color) {
             $indexed_colors[] = strtolower(preg_replace('/\\s+/', '-', trim($color)));
         }
         $doc->color = $indexed_colors;
     }
     if (isset($productObj->stone) && !empty($productObj->stone)) {
         $stones = explode(',', $productObj->stone);
         $indexed_stones = array();
         foreach ($stones as $stone) {
             $indexed_stones[] = strtolower(preg_replace('/\\s+/', '-', trim($stone)));
         }
         $doc->stone = $indexed_stones;
     }
     if (isset($productObj->plating) && !empty($productObj->plating)) {
         $platings = explode(',', $productObj->plating);
         $indexed_platings = array();
         foreach ($platings as $plating) {
             $indexed_platings[] = strtolower(preg_replace('/\\s+/', '-', trim($plating)));
         }
         $doc->plating = $indexed_platings;
     }
     if (isset($productObj->material) && !empty($productObj->material)) {
         $materials = explode(',', $productObj->material);
         $indexed_materials = array();
         foreach ($materials as $material) {
             $indexed_materials[] = strtolower(preg_replace('/\\s+/', '-', trim($material)));
         }
         $doc->material = $indexed_materials;
     }
     if (isset($productObj->look) && !empty($productObj->look)) {
         $looks = explode(',', $productObj->look);
         $indexed_looks = array();
         foreach ($looks as $look) {
             $indexed_looks[] = strtolower(preg_replace('/\\s+/', '-', trim($look)));
         }
         $doc->look = $indexed_looks;
     }
     if (isset($productObj->handbag_occasion) && !empty($productObj->handbag_occasion)) {
         $handbag_occasions = explode(',', $productObj->handbag_occasion);
         $indexed_handbag_occasions = array();
         foreach ($handbag_occasions as $handbag_occasion) {
             $indexed_handbag_occasions[] = strtolower(preg_replace('/\\s+/', '-', trim($handbag_occasion)));
         }
         $doc->handbag_occasion = $indexed_handbag_occasions;
     }
     if (isset($productObj->handbag_style) && !empty($productObj->handbag_style)) {
         $handbag_styles = explode(',', $productObj->handbag_style);
         $indexed_handbag_styles = array();
         foreach ($handbag_styles as $handbag_style) {
             $indexed_handbag_styles[] = strtolower(preg_replace('/\\s+/', '-', trim($handbag_style)));
         }
         $doc->handbag_style = $indexed_handbag_styles;
     }
     if (isset($productObj->handbag_material) && !empty($productObj->handbag_material)) {
         $handbag_materials = explode(',', $productObj->handbag_material);
         $indexed_handbag_materials = array();
         foreach ($handbag_materials as $handbag_material) {
             $indexed_handbag_materials[] = strtolower(preg_replace('/\\s+/', '-', trim($handbag_material)));
         }
         $doc->handbag_material = $indexed_handbag_materials;
     }
     $combinaisons = $productObj->getAttributeCombinaisons(1);
     $indexed_sizes = array();
     foreach ($combinaisons as $k => $combinaison) {
         if ($combinaison['group_name'] == 'size' || $combinaison['group_name'] == 'Size') {
             $indexed_sizes[] = $combinaison['attribute_name'];
         }
     }
     $doc->size = $indexed_sizes;
     //Indian Price
     $doc->offer_price_in = Product::getPriceStatic($productObj->id, true, NULL, 6, NULL, false, true, 1, false, NULL, NULL, IND_ADDRESS_ID);
     $doc->offer_price_in_rs = Tools::convertPrice($doc->offer_price_in, 4);
     $doc->mrp_in = Product::getPriceStatic($productObj->id, true, NULL, 6, NULL, false, false, 1, false, NULL, NULL, IND_ADDRESS_ID);
     if ($doc->mrp_in > $doc->offer_price_in) {
         $doc->discount_in = Tools::ps_round(($doc->mrp_in - $doc->offer_price_in) / $doc->mrp_in * 100);
     }
     //Worldwide Price
     $doc->offer_price = $productObj->getPrice();
     $doc->offer_price_rs = Tools::convertPrice($doc->offer_price, 4);
     $doc->mrp = $productObj->getPriceWithoutReduct();
     if ($doc->mrp > $doc->offer_price) {
         $doc->discount = Tools::ps_round(($doc->mrp - $doc->offer_price) / $doc->mrp * 100);
     }
     $doc->product_link = $productObj->getLink();
     $idImage = $productObj->getCoverWs();
     if ($idImage) {
         $idImage = $productObj->id . '-' . $idImage;
     } else {
         $idImage = Language::getIsoById(1) . '-default';
     }
     $doc->image_link_list = $link->getImageLink($productObj->link_rewrite, $idImage, 'list');
     $doc->image_link_medium = $link->getImageLink($productObj->link_rewrite, $idImage, 'medium');
     $doc->image_link_large = $link->getImageLink($productObj->link_rewrite, $idImage, 'large');
     $images = $productObj->getImages(1);
     $productImages = array();
     foreach ($images as $k => $image) {
         $productImages[] = $link->getImageLink($productObj->link_rewrite, $image['id_image'], 'large');
     }
     $doc->image_links = $productImages;
     return $doc;
 }
    /**
     * Validate an order in database
     * Function called from a payment module
     *
     * @param integer $id_cart Value
     * @param integer $id_order_state Value
     * @param float $amountPaid Amount really paid by customer (in the default currency)
     * @param string $paymentMethod Payment method (eg. 'Credit card')
     * @param string $message Message to attach to order
     */
    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)
    {
        global $cart, $link, $cookie;
        $id_payment_state = _PS_PS_NOT_PAID_;
        $cart = new Cart((int) $id_cart);
        // Does order already exists ?
        if (Validate::isLoadedObject($cart) and $cart->OrderExists() == false) {
            if ($secure_key !== false and $secure_key != $cart->secure_key) {
                die(Tools::displayError());
            }
            // Copying data from cart
            $order = new Order();
            $order->id_carrier = (int) $cart->id_carrier;
            $order->id_customer = (int) $cart->id_customer;
            $order->id_address_invoice = (int) $cart->id_address_invoice;
            $order->id_address_delivery = (int) $cart->id_address_delivery;
            $vat_address = new Address((int) $order->id_address_delivery);
            $order->id_currency = $currency_special ? (int) $currency_special : (int) $cart->id_currency;
            $order->id_lang = (int) $cart->id_lang;
            $order->id_cart = (int) $cart->id;
            $customer = new Customer((int) $order->id_customer);
            $order->secure_key = $secure_key ? pSQL($secure_key) : pSQL($customer->secure_key);
            $order->payment = $paymentMethod;
            if (isset($this->name)) {
                $order->module = $this->name;
            }
            $order->recyclable = $cart->recyclable;
            $order->gift = (int) $cart->gift;
            $order->gift_message = $cart->gift_message;
            $currency = new Currency($order->id_currency);
            $order->conversion_rate = $currency->conversion_rate;
            $amountPaid = !$dont_touch_amount ? Tools::ps_round((double) $amountPaid, 2) : $amountPaid;
            $order->total_paid_real = $amountPaid;
            $order->total_products = (double) $cart->getOrderTotal(false, Cart::ONLY_PRODUCTS);
            $order->total_products_wt = (double) $cart->getOrderTotal(true, Cart::ONLY_PRODUCTS);
            $order->total_customization = $cart->getCartCustomizationCost();
            $order->total_donation = round($cookie->donation_amount);
            unset($cookie->donation_amount);
            if (strpos($order->payment, 'COD') === false) {
                $order->total_discounts = (double) abs($cart->getOrderTotal(true, Cart::ONLY_DISCOUNTS, true));
                $order->total_paid = (double) Tools::ps_round((double) $cart->getOrderTotal(true, Cart::BOTH, true));
            } else {
                $order->total_discounts = (double) abs($cart->getOrderTotal(true, Cart::ONLY_DISCOUNTS, false));
                $order->total_paid = (double) Tools::ps_round((double) $cart->getOrderTotal(true, Cart::BOTH, false));
                $order->total_cod = COD_CHARGE;
            }
            $order->total_shipping = (double) $cart->getOrderShippingCost();
            $order->carrier_tax_rate = (double) Tax::getCarrierTaxRate($cart->id_carrier, (int) $cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
            $order->total_wrapping = (double) abs($cart->getOrderTotal(true, Cart::ONLY_WRAPPING));
            $order->invoice_date = '0000-00-00 00:00:00';
            $order->delivery_date = '0000-00-00 00:00:00';
            $shippingdate = $cart->getExpectedShippingDate();
            $order->expected_shipping_date = pSQL($shippingdate->format('Y-m-d H:i:s'));
            $order->actual_expected_shipping_date = pSQL($shippingdate->format('Y-m-d H:i:s'));
            // Amount paid by customer is not the right one -> Status = payment error
            // We don't use the following condition to avoid the float precision issues : http://www.php.net/manual/en/language.types.float.php
            // if ($order->total_paid != $order->total_paid_real)
            // We use number_format in order to compare two string
            if (number_format(round($order->total_paid)) != number_format(round($order->total_paid_real))) {
                $id_order_state = _PS_OS_ERROR_;
                $id_payment_state = _PS_PS_NOT_PAID_;
            } else {
                if (strpos($order->payment, 'COD') === false) {
                    $id_payment_state = _PS_PS_PAID_;
                }
            }
            //update payment status
            // Creating order
            if ($cart->OrderExists() == false) {
                $cart_value = $cart->getOrderTotal();
                if ($cart_value >= 1000) {
                    //if(!$cart->containsProduct(FREE_GIFT_ID, NULL, NULL))
                    //$cart->updateQty(1, FREE_GIFT_ID, NULL, false, 'up', TRUE);
                }
                $result = $order->add();
            } else {
                $errorMessage = Tools::displayError('An order has already been placed using this cart.');
                Logger::addLog($errorMessage, 4, '0000001', 'Cart', intval($order->id_cart));
                die($errorMessage);
            }
            // Next !
            if ($result and isset($order->id)) {
                if (!$secure_key) {
                    $message .= $this->l('Warning : the secure key is empty, check your payment account before validation');
                }
                // Optional message to attach to this order
                if (isset($message) and !empty($message)) {
                    $msg = new Message();
                    $message = strip_tags($message, '<br>');
                    if (Validate::isCleanHtml($message)) {
                        $msg->message = $message;
                        $msg->id_order = intval($order->id);
                        $msg->private = 1;
                        $msg->add();
                    }
                }
                // Insert products from cart into order_detail table
                $products = $cart->getProducts();
                $productsList = '';
                $db = Db::getInstance();
                $query = 'INSERT INTO `' . _DB_PREFIX_ . 'order_detail`
					(`id_order`, `product_id`, `product_attribute_id`, `product_name`, `product_quantity`, `product_quantity_in_stock`, `product_price`, `reduction_percent`, `reduction_amount`, `group_reduction`, `product_quantity_discount`, `product_ean13`, `product_upc`, `product_reference`, `product_supplier_reference`, `product_weight`, `tax_name`, `tax_rate`, `ecotax`, `ecotax_tax_rate`, `discount_quantity_applied`, `download_deadline`, `download_hash`, `customization`)
				VALUES ';
                $customizedDatas = Product::getAllCustomizedDatas((int) $order->id_cart);
                Product::addCustomizationPrice($products, $customizedDatas);
                $outOfStock = false;
                foreach ($products as $key => $product) {
                    $productQuantity = (int) Product::getQuantity((int) $product['id_product'], $product['id_product_attribute'] ? (int) $product['id_product_attribute'] : NULL);
                    $quantityInStock = $productQuantity - (int) $product['cart_quantity'] < 0 ? $productQuantity : (int) $product['cart_quantity'];
                    if ($id_order_state != _PS_OS_CANCELED_ and $id_order_state != _PS_OS_ERROR_) {
                        if (Product::updateQuantity($product, (int) $order->id)) {
                            $product['stock_quantity'] -= $product['cart_quantity'];
                        }
                        if ($product['stock_quantity'] < 0 && Configuration::get('PS_STOCK_MANAGEMENT')) {
                            $outOfStock = true;
                        }
                        if ($product['stock_quantity'] < 1) {
                            SolrSearch::updateProduct((int) $product['id_product']);
                        }
                        Product::updateDefaultAttribute($product['id_product']);
                    }
                    $price = Product::getPriceStatic((int) $product['id_product'], false, $product['id_product_attribute'] ? (int) $product['id_product_attribute'] : NULL, 6, NULL, false, true, $product['cart_quantity'], false, (int) $order->id_customer, (int) $order->id_cart, (int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
                    $price_wt = Product::getPriceStatic((int) $product['id_product'], true, $product['id_product_attribute'] ? (int) $product['id_product_attribute'] : NULL, 2, NULL, false, true, $product['cart_quantity'], false, (int) $order->id_customer, (int) $order->id_cart, (int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
                    // Add some informations for virtual products
                    $deadline = '0000-00-00 00:00:00';
                    $download_hash = NULL;
                    if ($id_product_download = ProductDownload::getIdFromIdProduct((int) $product['id_product'])) {
                        $productDownload = new ProductDownload((int) $id_product_download);
                        $deadline = $productDownload->getDeadLine();
                        $download_hash = $productDownload->getHash();
                    }
                    // Exclude VAT
                    if (Tax::excludeTaxeOption()) {
                        $product['tax'] = 0;
                        $product['rate'] = 0;
                        $tax_rate = 0;
                    } else {
                        $tax_rate = Tax::getProductTaxRate((int) $product['id_product'], $cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
                    }
                    $ecotaxTaxRate = 0;
                    if (!empty($product['ecotax'])) {
                        $ecotaxTaxRate = Tax::getProductEcotaxRate($order->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
                    }
                    $quantityDiscount = SpecificPrice::getQuantityDiscount((int) $product['id_product'], Shop::getCurrentShop(), (int) $cart->id_currency, (int) $vat_address->id_country, (int) $customer->id_default_group, (int) $product['cart_quantity']);
                    $unitPrice = Product::getPriceStatic((int) $product['id_product'], true, $product['id_product_attribute'] ? intval($product['id_product_attribute']) : NULL, 2, NULL, false, true, 1, false, (int) $order->id_customer, NULL, (int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
                    $quantityDiscountValue = $quantityDiscount ? (Product::getTaxCalculationMethod((int) $order->id_customer) == PS_TAX_EXC ? Tools::ps_round($unitPrice, 2) : $unitPrice) - $quantityDiscount['price'] * (1 + $tax_rate / 100) : 0.0;
                    $specificPrice = 0;
                    $query .= '(' . (int) $order->id . ',
						' . (int) $product['id_product'] . ',
						' . (isset($product['id_product_attribute']) ? (int) $product['id_product_attribute'] : 'NULL') . ',
						\'' . pSQL($product['name'] . ((isset($product['attributes']) and $product['attributes'] != NULL) ? ' - ' . $product['attributes'] : '')) . '\',
						' . (int) $product['cart_quantity'] . ',
						' . $quantityInStock . ',
						' . (double) Product::getPriceStatic((int) $product['id_product'], false, $product['id_product_attribute'] ? (int) $product['id_product_attribute'] : NULL, Product::getTaxCalculationMethod((int) $order->id_customer) == PS_TAX_EXC ? 2 : 6, NULL, false, false, $product['cart_quantity'], false, (int) $order->id_customer, (int) $order->id_cart, (int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE')}, $specificPrice, FALSE) . ',
						' . (double) (($specificPrice and $specificPrice['reduction_type'] == 'percentage') ? $specificPrice['reduction'] * 100 : 0.0) . ',
						' . (double) (($specificPrice and $specificPrice['reduction_type'] == 'amount') ? !$specificPrice['id_currency'] ? Tools::convertPrice($specificPrice['reduction'], $order->id_currency) : $specificPrice['reduction'] : 0.0) . ',
						' . (double) Group::getReduction((int) $order->id_customer) . ',
						' . $quantityDiscountValue . ',
						' . (empty($product['ean13']) ? 'NULL' : '\'' . pSQL($product['ean13']) . '\'') . ',
						' . (empty($product['upc']) ? 'NULL' : '\'' . pSQL($product['upc']) . '\'') . ',
						' . (empty($product['reference']) ? 'NULL' : '\'' . pSQL($product['reference']) . '\'') . ',
						' . (empty($product['supplier_reference']) ? 'NULL' : '\'' . pSQL($product['supplier_reference']) . '\'') . ',
						' . (double) ($product['id_product_attribute'] ? $product['weight_attribute'] : $product['weight']) . ',
						\'' . (empty($tax_rate) ? '' : pSQL($product['tax'])) . '\',
						' . (double) $tax_rate . ',
						' . (double) Tools::convertPrice(floatval($product['ecotax']), intval($order->id_currency)) . ',
						' . (double) $ecotaxTaxRate . ',
						' . (($specificPrice and $specificPrice['from_quantity'] > 1) ? 1 : 0) . ',
						\'' . pSQL($deadline) . '\',
						\'' . pSQL($download_hash) . '\', ' . $cart->getProductCustomizationCost($product['id_product']) . '),';
                    $customizationQuantity = 0;
                    if (isset($customizedDatas[$product['id_product']][$product['id_product_attribute']])) {
                        $customizationText = '';
                        foreach ($customizedDatas[$product['id_product']][$product['id_product_attribute']] as $customization) {
                            if (isset($customization['datas'][_CUSTOMIZE_TEXTFIELD_])) {
                                foreach ($customization['datas'][_CUSTOMIZE_TEXTFIELD_] as $text) {
                                    if ($text['index'] == 8) {
                                        $customizationText .= 'Saree with unstitched blouse and fall/pico work.' . '<br />';
                                    } else {
                                        if ($text['index'] == 1) {
                                            $customizationText .= 'Pre-stitched saree with unstitched blouse and fall/pico work.' . '<br />';
                                        } else {
                                            if ($text['index'] == 2) {
                                                $customizationText .= 'Stitched to measure blouse.' . '<br />';
                                            } else {
                                                if ($text['index'] == 3) {
                                                    $customizationText .= 'Stitched to measure in-skirt.' . '<br />';
                                                } else {
                                                    if ($text['index'] == 4) {
                                                        $customizationText .= 'Stitched to measure kurta.' . '<br />';
                                                    } else {
                                                        if ($text['index'] == 5) {
                                                            $customizationText .= 'Stitched to measure salwar.' . '<br />';
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            if (isset($customization['datas'][_CUSTOMIZE_FILE_])) {
                                $customizationText .= sizeof($customization['datas'][_CUSTOMIZE_FILE_]) . ' ' . Tools::displayError('image(s)') . '<br />';
                            }
                            $customizationText .= '---<br />';
                        }
                        $customizationText = rtrim($customizationText, '---<br />');
                        $customizationQuantity = (int) $product['customizationQuantityTotal'];
                        $productsList .= '<tr style="background-color: ' . ($key % 2 ? '#DDE2E6' : '#EBECEE') . ';">
							<td style="padding: 0.6em 0.4em;">' . $product['reference'] . '</td>
							<td style="padding: 0.6em 0.4em;"><strong>' . $product['name'] . (isset($product['attributes_small']) ? ' ' . $product['attributes_small'] : '') . ' - ' . $this->l('Customized') . (!empty($customizationText) ? ' - ' . $customizationText : '') . '</strong></td>
							<td style="padding: 0.6em 0.4em; text-align: right;">' . Tools::displayPrice(round(Product::getTaxCalculationMethod() == PS_TAX_EXC ? $price : $price_wt), $currency, false) . '</td>
							<td style="padding: 0.6em 0.4em; text-align: center;">' . $customizationQuantity . '</td>
							<td style="padding: 0.6em 0.4em; text-align: right;">' . Tools::displayPrice($customizationQuantity * round(Product::getTaxCalculationMethod() == PS_TAX_EXC ? $price : $price_wt), $currency, false) . '</td>
						</tr>';
                    }
                    if (!$customizationQuantity or (int) $product['cart_quantity'] > $customizationQuantity) {
                        $productsList .= '<tr style="background-color: ' . ($key % 2 ? '#DDE2E6' : '#EBECEE') . ';">
							<td style="padding: 0.6em 0.4em;">' . $product['reference'] . '</td>
							<td style="padding: 0.6em 0.4em;"><strong>' . $product['name'] . (isset($product['attributes_small']) ? ' ' . $product['attributes_small'] : '') . '</strong></td>
							<td style="padding: 0.6em 0.4em; text-align: right;">' . Tools::displayPrice(round(Product::getTaxCalculationMethod() == PS_TAX_EXC ? $price : $price_wt), $currency, false) . '</td>
							<td style="padding: 0.6em 0.4em; text-align: center;">' . ((int) $product['cart_quantity'] - $customizationQuantity) . '</td>
							<td style="padding: 0.6em 0.4em; text-align: right;">' . Tools::displayPrice(((int) $product['cart_quantity'] - $customizationQuantity) * round(Product::getTaxCalculationMethod() == PS_TAX_EXC ? $price : $price_wt), $currency, false) . '</td>
						</tr>';
                    }
                    //if giftcard, create voucher and send the mails now.
                    $categories = Product::getProductCategories($product['id_product']);
                    if (in_array(CAT_GIFTCARD, $categories)) {
                        $friendsName = '';
                        $friendsEmail = '';
                        $giftMessage = '';
                        foreach ($customizedDatas[$product['id_product']][$product['id_product_attribute']] as $customization) {
                            if (isset($customization['datas'][_CUSTOMIZE_TEXTFIELD_])) {
                                foreach ($customization['datas'][_CUSTOMIZE_TEXTFIELD_] as $text) {
                                    if ($text['index'] == 21) {
                                        $friendsName = $text['value'];
                                    } else {
                                        if ($text['index'] == 22) {
                                            $friendsEmail = $text['value'];
                                        } else {
                                            if ($text['index'] == 23) {
                                                $giftMessage = $text['value'];
                                            } else {
                                                if ($text['index'] == 25) {
                                                    $couponCode = $text['value'];
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        //$couponCode = "GC" . Tools::rand_string(8);
                        // create discount
                        $languages = Language::getLanguages($order);
                        $voucher = new Discount();
                        $voucher->id_discount_type = 2;
                        foreach ($languages as $language) {
                            $voucher->description[$language['id_lang']] = $product['name'];
                        }
                        $voucher->value = (double) $unitPrice;
                        $voucher->name = $couponCode;
                        $voucher->id_currency = 2;
                        //USD
                        $voucher->quantity = 1;
                        $voucher->quantity_per_user = 1;
                        $voucher->cumulable = 1;
                        $voucher->cumulable_reduction = 1;
                        $voucher->minimal = 0;
                        $voucher->active = 1;
                        $voucher->cart_display = 0;
                        $now = time();
                        $voucher->date_from = date('Y-m-d H:i:s', $now);
                        $voucher->date_to = date('Y-m-d H:i:s', $now + 3600 * 24 * 365);
                        /* 365 days */
                        $voucher->add();
                        $productObj = new Product($product['id_product'], true, 1);
                        $idImage = $productObj->getCoverWs();
                        if ($idImage) {
                            $idImage = $productObj->id . '-' . $idImage;
                        } else {
                            $idImage = Language::getIsoById(1) . '-default';
                        }
                        $params = array();
                        $params['{voucher_code}'] = $voucher->name;
                        $params['{freinds_name}'] = $friendsName;
                        $params['{gift_message}'] = $giftMessage;
                        $params['{product_name}'] = $product['name'];
                        $params['{voucher_value}'] = $voucher->value;
                        $params['{image_url}'] = _PS_BASE_URL_ . _PS_IMG_ . 'banners/' . $productObj->location;
                        $params['{sender_name}'] = $customer->firstname . ' ' . $customer->lastname;
                        $subject = $friendsName . ', You Have Received A $' . $voucher->value . ' IndusDiva Gift Card';
                        @Mail::Send(1, 'gift_card', $subject, $params, $friendsEmail, $friendsName, '*****@*****.**', 'Indusdiva.com', NULL, NULL, _PS_MAIL_DIR_, true);
                        @Mail::Send(1, 'gift_card', $subject, $params, $customer->email, $customer->firstname . ' ' . $customer->lastname, '*****@*****.**', 'Indusdiva.com', NULL, NULL, _PS_MAIL_DIR_, true);
                    }
                }
                // end foreach ($products)
                $query = rtrim($query, ',');
                $result = $db->Execute($query);
                // Insert discounts from cart into order_discount table
                $discounts = $cart->getDiscounts();
                $discountsList = '';
                $total_discount_value = 0;
                $shrunk = false;
                foreach ($discounts as $discount) {
                    $objDiscount = new Discount((int) $discount['id_discount'], $order->id_lang);
                    $value = $objDiscount->getValue(sizeof($discounts), $cart->getOrderTotal(true, Cart::ONLY_PRODUCTS), $order->total_shipping, $cart->id);
                    if ($objDiscount->id_discount_type == 2 || $objDiscount->id_discount_type == 4 and in_array($objDiscount->behavior_not_exhausted, array(1, 2))) {
                        $shrunk = true;
                    }
                    if ($shrunk and $total_discount_value + $value > $order->total_products + $order->total_shipping + $order->total_wrapping) {
                        $amount_to_add = $order->total_products + $order->total_shipping + $order->total_wrapping - $total_discount_value;
                        if ($objDiscount->id_discount_type == 2 || $objDiscount->id_discount_type == 4 and $objDiscount->behavior_not_exhausted == 2) {
                            $voucher = new Discount();
                            foreach ($objDiscount as $key => $discountValue) {
                                $voucher->{$key} = $discountValue;
                            }
                            $voucher->name = 'VSRK' . (int) $order->id_customer . 'O' . (int) $order->id;
                            $voucher->value = (double) $value - $amount_to_add;
                            $voucher->add();
                            $params['{voucher_amount}'] = Tools::displayPrice($voucher->value, $currency, false);
                            $params['{voucher_num}'] = $voucher->name;
                            @Mail::Send((int) $order->id_lang, 'voucher', Mail::l('New voucher regarding your order #') . $order->id, $params, $customer->email, $customer->firstname . ' ' . $customer->lastname);
                        }
                    } else {
                        $amount_to_add = $value;
                    }
                    $order->addDiscount($objDiscount->id, $objDiscount->name, $amount_to_add);
                    $total_discount_value += $amount_to_add;
                    if ($id_order_state != _PS_OS_ERROR_ and $id_order_state != _PS_OS_CANCELED_) {
                        $objDiscount->quantity = $objDiscount->quantity - 1;
                    }
                    $objDiscount->update();
                    $discountsList .= '<tr style="background-color:#EBECEE;">
							<td colspan="4" style="padding: 0.6em 0.4em; text-align: right;">' . $this->l('Voucher code:') . ' ' . $objDiscount->name . '</td>
							<td style="padding: 0.6em 0.4em; text-align: right;">' . ($value != 0.0 ? '-' : '') . Tools::displayPrice($value, $currency, false) . '</td>
					</tr>';
                }
                // Specify order id for message
                $oldMessage = Message::getMessageByCartId((int) $cart->id);
                if ($oldMessage) {
                    $message = new Message((int) $oldMessage['id_message']);
                    $message->id_order = (int) $order->id;
                    $message->update();
                }
                // Hook new order
                $orderStatus = new OrderState((int) $id_order_state, (int) $order->id_lang);
                if (Validate::isLoadedObject($orderStatus)) {
                    Hook::newOrder($cart, $order, $customer, $currency, $orderStatus);
                    foreach ($cart->getProducts() as $product) {
                        if ($orderStatus->logable) {
                            ProductSale::addProductSale((int) $product['id_product'], (int) $product['cart_quantity']);
                        }
                    }
                }
                if (isset($outOfStock) and $outOfStock) {
                    $history = new OrderHistory();
                    $history->id_order = (int) $order->id;
                    $history->changeIdOrderState(_PS_OS_OUTOFSTOCK_, (int) $order->id);
                    $history->addWithemail();
                }
                // Set order state in order history ONLY even if the "out of stock" status has not been yet reached
                // So you migth have two order states
                $new_history = new OrderHistory();
                $new_history->id_order = (int) $order->id;
                $new_history->changeIdOrderState((int) $id_order_state, (int) $order->id);
                $new_history->addWithemail(true, $extraVars);
                //Payment status
                $paymentHistory = new OrderPaymentHistory();
                $paymentHistory->id_order = (int) $order->id;
                $paymentHistory->changeIdOrderPaymentState($id_payment_state, (int) $order->id);
                $paymentHistory->addState();
                // Order is reloaded because the status just changed
                $order = new Order($order->id);
                //Update tracking code for quantium
                if ($order->id_carrier == QUANTIUM) {
                    if (strpos($order->payment, 'COD') === false) {
                        $order->shipping_number = 'VBN' . $order->id;
                    } else {
                        $order->shipping_number = 'VBC' . $order->id;
                    }
                    $order->update();
                } else {
                    if ($order->id_carrier == SABEXPRESS) {
                        $db = Db::getInstance();
                        $db->Execute('LOCK TABLES vb_awb_pool WRITE');
                        $res = $db->getRow("select min(id) as 'id', awb from vb_awb_pool where id_carrier = " . SABEXPRESS . " and assigned = 0");
                        $awb = $res['awb'];
                        $id = $res['id'];
                        $db->Execute("update vb_awb_pool set assigned = 1 where id = " . $id);
                        $db->Execute('UNLOCK TABLES');
                        $order->shipping_number = $awb;
                        $order->update();
                    } else {
                        if ($order->id_carrier == AFL) {
                            $db = Db::getInstance();
                            $db->Execute('LOCK TABLES vb_awb_pool WRITE');
                            $res = $db->getRow("select min(id) as 'id' , awb from vb_awb_pool where id_carrier = " . AFL . " and assigned = 0");
                            $awb = $res['awb'];
                            $id = $res['id'];
                            $db->Execute("update vb_awb_pool set assigned = 1 where id = " . $id);
                            $db->Execute('UNLOCK TABLES');
                            $order->shipping_number = $awb;
                            $order->update();
                        }
                    }
                }
                // Send an e-mail to customer
                if ($id_order_state != _PS_OS_ERROR_ and $id_order_state != _PS_OS_CANCELED_ and $customer->id and $id_order_state != _PS_OS_OP_PAYEMENT_FAILED) {
                    //deduct reward points
                    $points_redeemed = $cart->getPoints();
                    if ($points_redeemed) {
                        VBRewards::removeRewardPoints($order->id_customer, EVENT_POINTS_REDEEMED, 0, $cart->getPoints(), 'Coins redeemed - Order no ' . $order->id, $order->id, $order->date_add);
                    }
                    /*
                    if(strpos($order->payment, 'COD') === false && $order->total_paid_real > 0)
                    {
                        VBRewards::addRewardPoints($order->id_customer, ONLINE_ORDER, 0, 100, 'Online payment bonus - Order no ' . $order->id, $order->id, $order->date_add);
                    }
                    */
                    $invoice = new Address((int) $order->id_address_invoice);
                    $delivery = new Address((int) $order->id_address_delivery);
                    $carrier = new Carrier((int) $order->id_carrier, $order->id_lang);
                    $delivery_state = $delivery->id_state ? new State((int) $delivery->id_state) : false;
                    $invoice_state = $invoice->id_state ? new State((int) $invoice->id_state) : false;
                    $shippingdate = new DateTime($order->expected_shipping_date);
                    $data = array('{firstname}' => $customer->firstname, '{shipping_date}' => $shippingdate->format("F j, Y"), '{lastname}' => $customer->lastname, '{email}' => $customer->email, '{delivery_block_txt}' => $this->_getFormatedAddress($delivery, "\n"), '{invoice_block_txt}' => $this->_getFormatedAddress($invoice, "\n"), '{delivery_block_html}' => $this->_getFormatedAddress($delivery, "<br />", array('firstname' => '<span style="color:#DB3484; font-weight:bold;">%s</span>', 'lastname' => '<span style="color:#DB3484; font-weight:bold;">%s</span>')), '{invoice_block_html}' => $this->_getFormatedAddress($invoice, "<br />", array('firstname' => '<span style="color:#DB3484; font-weight:bold;">%s</span>', 'lastname' => '<span style="color:#DB3484; font-weight:bold;">%s</span>')), '{delivery_company}' => $delivery->company, '{delivery_firstname}' => $delivery->firstname, '{delivery_lastname}' => $delivery->lastname, '{delivery_address1}' => $delivery->address1, '{delivery_address2}' => $delivery->address2, '{delivery_city}' => $delivery->city, '{delivery_postal_code}' => $delivery->postcode, '{delivery_country}' => $delivery->country, '{delivery_state}' => $delivery->id_state ? $delivery_state->name : '', '{delivery_phone}' => $delivery->phone ? $delivery->phone : $delivery->phone_mobile, '{delivery_other}' => $delivery->other, '{invoice_company}' => $invoice->company, '{invoice_vat_number}' => $invoice->vat_number, '{invoice_firstname}' => $invoice->firstname, '{invoice_lastname}' => $invoice->lastname, '{invoice_address2}' => $invoice->address2, '{invoice_address1}' => $invoice->address1, '{invoice_city}' => $invoice->city, '{invoice_postal_code}' => $invoice->postcode, '{invoice_country}' => $invoice->country, '{invoice_state}' => $invoice->id_state ? $invoice_state->name : '', '{invoice_phone}' => $invoice->phone ? $invoice->phone : $invoice->phone_mobile, '{invoice_other}' => $invoice->other, '{order_name}' => sprintf("#%06d", (int) $order->id), '{date}' => date("F j, Y, g:i a"), '{carrier}' => $carrier->name, '{payment}' => Tools::substr($order->payment, 0, 32), '{products}' => $productsList, '{discounts}' => $discountsList, '{total_paid}' => Tools::displayPrice($order->total_paid, $currency, false), '{total_products}' => Tools::displayPrice($order->total_paid - $order->total_shipping - $order->total_cod - $order->total_wrapping + $order->total_discounts, $currency, false), '{total_discounts}' => Tools::displayPrice($order->total_discounts, $currency, false), '{total_shipping}' => Tools::displayPrice($order->total_shipping, $currency, false), '{total_cod}' => Tools::displayPrice($order->total_cod, $currency, false), '{total_wrapping}' => Tools::displayPrice($order->total_wrapping, $currency, false));
                    if (is_array($extraVars)) {
                        $data = array_merge($data, $extraVars);
                    }
                    // Join PDF invoice
                    if ((int) Configuration::get('PS_INVOICE') and Validate::isLoadedObject($orderStatus) and $orderStatus->invoice and $order->invoice_number) {
                        $fileAttachment['content'] = PDF::invoice($order, 'S');
                        $fileAttachment['name'] = $fileAttachment['name'] = 'IndusDiva Order #' . sprintf('%06d', (int) $order->id) . '.pdf';
                        $fileAttachment['mime'] = 'application/pdf';
                    } else {
                        $fileAttachment = NULL;
                    }
                    if (Validate::isEmail($customer->email)) {
                        if ($id_order_state == _PS_OS_BANKWIRE_) {
                            Mail::Send((int) $order->id_lang, 'order_conf_bankwire', Mail::l('Your order #' . $order->id . ' with IndusDiva.com is confirmed'), $data, $customer->email, $customer->firstname . ' ' . $customer->lastname, NULL, NULL, $fileAttachment);
                        } else {
                            $data['payment'] = 'Online Payment';
                            Mail::Send((int) $order->id_lang, 'order_conf', Mail::l('Your order #' . $order->id . ' with IndusDiva.com is confirmed'), $data, $customer->email, $customer->firstname . ' ' . $customer->lastname, NULL, NULL, $fileAttachment);
                        }
                    }
                    //Send SMS
                    //$smsText = 'Dear customer, your order #'.$order->id.' at IndusDiva.com is confirmed and will be delivered to you within 3-5 business days. www.indusdiva.com';
                    //Tools::sendSMS($delivery->phone_mobile, $smsText);
                }
                $this->currentOrder = (int) $order->id;
                return true;
            } else {
                $errorMessage = Tools::displayError('Order creation failed');
                Logger::addLog($errorMessage, 4, '0000002', 'Cart', intval($order->id_cart));
                die($errorMessage);
            }
        } else {
            $errorMessage = Tools::displayError('Cart can\'t be loaded or an order has already been placed using this cart');
            Logger::addLog($errorMessage, 4, '0000001', 'Cart', intval($cart->id));
            die($errorMessage);
        }
    }