protected function generateProductsData()
    {
        $delimiter = ';';
        $titles = array();
        $id_lang = $this->use_lang;
        $new_path = new Sampledatainstall();
        $f = fopen($new_path->sendPath() . 'output/products.vsc', 'w');
        foreach ($this->product_fields as $field => $array) {
            $titles[] = $array['label'];
        }
        fputcsv($f, $titles, $delimiter, '"');
        $products = Product::getProducts($id_lang, 0, 0, 'id_product', 'ASC', false, true);
        foreach ($products as $product) {
            $line = array();
            $p = new Product($product['id_product'], true, $id_lang, 1);
            foreach ($this->product_fields as $field => $array) {
                $line[$field] = property_exists('Product', $field) && !is_array($p->{$field}) && !Tools::isEmpty($p->{$field}) ? $p->{$field} : '';
            }
            $cats = $p->getProductCategoriesFull($p->id, 1);
            $cat_array = array();
            foreach ($cats as $cat) {
                $cat_array[] = $cat['id_category'];
            }
            $line['categories'] = implode(',', $cat_array);
            $line['price_tex'] = $p->getPrice(false);
            $line['price_tin'] = $p->getPrice(true);
            $line['upc'] = $p->upc ? $p->upc : '';
            $line['features'] = '';
            $features = $p->getFrontFeatures($id_lang);
            $position = 1;
            $devider = '';
            foreach ($features as $feature) {
                $sql = 'SELECT `id_feature`
						FROM ' . _DB_PREFIX_ . 'feature_lang
						WHERE `name` = "' . pSql($feature['name']) . '"';
                $sql1 = 'SELECT `id_feature_value`
						FROM ' . _DB_PREFIX_ . 'feature_value_lang
						WHERE `value` = "' . pSql($feature['value']) . '"';
                $id_feature = Db::getInstance()->getValue($sql);
                $id_feature_value = Db::getInstance()->getValue($sql1);
                $line['features'] .= $devider . $id_feature . ':' . $id_feature_value . ':' . $position;
                $devider = ',';
                $position++;
            }
            $specificPrice = SpecificPrice::getSpecificPrice($p->id, 1, 0, 0, 0, 0);
            $line['reduction_price'] = '';
            $line['reduction_percent'] = '';
            $line['reduction_from'] = '';
            $line['reduction_to'] = '';
            if ($specificPrice) {
                if ($specificPrice['reduction_type'] == 'amount') {
                    $line['reduction_price'] = $specificPrice['reduction'];
                } elseif ($specificPrice['reduction_type'] == 'percent') {
                    $line['reduction_percent'] = $specificPrice['reduction'];
                }
                if ($line['reduction_price'] !== '' || $line['reduction_percent'] !== '') {
                    $line['reduction_from'] = $specificPrice['from'];
                    $line['reduction_to'] = $specificPrice['to'];
                }
            }
            $tags = $p->getTags($id_lang);
            $line['tags'] = $tags;
            $link = new Link();
            $imagelinks = array();
            $images = $p->getImages($id_lang);
            foreach ($images as $image) {
                $imagelink = Tools::getShopProtocol() . $link->getImageLink($p->link_rewrite, $p->id . '-' . $image['id_image']);
                $this->copyConverFileName($imagelink);
                $imagelinks[] = $imagelink;
            }
            $line['image'] = implode(',', $imagelinks);
            $line['delete_existing_images'] = 0;
            $line['shop'] = 1;
            $warehouses = Warehouse::getWarehousesByProductId($p->id);
            $line['warehouse'] = '';
            if (!empty($warehouses)) {
                $line['warehouse'] = implode(',', array_map("{$this->getWarehouses}", $warehouses));
            }
            $values = array();
            $accesories = $p->getAccessories($id_lang);
            if (isset($accesories) && $accesories && count($accesories)) {
                foreach ($accesories as $accesorie) {
                    $values[] = $accesorie['id_product'];
                }
            }
            $line['accessories'] = $values ? implode(',', $values) : '';
            $values = array();
            $carriers = $p->getCarriers();
            if (isset($carriers) && $carriers && count($carriers)) {
                foreach ($carriers as $carrier) {
                    $values[] = $carrier['id_carrier'];
                }
            }
            $line['carriers'] = $values ? implode(',', $values) : '';
            $values = array();
            $customization_fields_ids = $p->getCustomizationFieldIds();
            if (class_exists('CustomizationField') && isset($customization_fields_ids) && $customization_fields_ids && count($customization_fields_ids)) {
                foreach ($customization_fields_ids as $customization_field_id) {
                    $cf = new CustomizationField($customization_field_id['id_customization_field'], $this->use_lang);
                    $values[] = $cf->id . ':' . $cf->type . ':' . $cf->required . ':' . $cf->name;
                }
            }
            $line['customization_fields_ids'] = $values ? implode(',', $values) : '';
            $values = array();
            $attachments = $p->getAttachments($this->use_lang);
            if (isset($attachments) && $attachments && count($attachments)) {
                foreach ($attachments as $attachment) {
                    $values[] = $attachment['id_attachment'];
                }
            }
            $line['attachments'] = $values ? implode(',', $values) : '';
            if (!property_exists('Product', 'base_price')) {
                // for versions < 1.6.0.13
                $line['base_price'] = !is_array($p->base_price) && !Tools::isEmpty($p->base_price) ? $p->base_price : '';
            }
            if (!$line[$field]) {
                $line[$field] = '';
            }
            fputcsv($f, $line, $delimiter, '"');
        }
        fclose($f);
    }
 protected static function generateImageLink($product, $ps_product, $id_lang, $iso_code)
 {
     $link = new Link();
     $cover = Image::getCover($ps_product->id);
     $product->{"image_link_small_{$iso_code}"} = $link->getImageLink($ps_product->link_rewrite[$id_lang], $cover["id_image"], ImageType::getFormatedName("small"));
     $product->{"image_link_large_{$iso_code}"} = $link->getImageLink($ps_product->link_rewrite[$id_lang], $cover["id_image"], ImageType::getFormatedName("large"));
     return $product;
 }
 protected function formatProduct($id_product, $id_lang)
 {
     $link = new Link();
     $product = new Product($id_product, true, $id_lang);
     $category = new Category($product->id_category_default, $id_lang);
     $product->objectID = $product->id;
     $product->category = $category->name;
     $product->url = $link->getProductLink($product->id);
     /* Cover */
     $cover = Image::getCover($product->id);
     $product->image_link_small = $link->getImageLink($product->link_rewrite, $cover['id_image'], ImageType::getFormatedName('small'));
     $product->image_link_large = $link->getImageLink($product->link_rewrite, $cover['id_image'], ImageType::getFormatedName('large'));
     return $product;
 }
    public function sendCampaign()
    {
        // get abandoned cart :
        $sql = "SELECT * FROM (\n\t\tSELECT\n\t\tCONCAT(LEFT(c.`firstname`, 1), '. ', c.`lastname`) `customer`, a.id_cart total, ca.name carrier, c.id_customer, a.id_cart, a.date_upd,a.date_add,\n\t\t\t\tIF (IFNULL(o.id_order, 'Non ordered') = 'Non ordered', IF(TIME_TO_SEC(TIMEDIFF('" . date('Y-m-d H:i:s') . "', a.`date_add`)) > 86400, 'Abandoned cart', 'Non ordered'), o.id_order) id_order, IF(o.id_order, 1, 0) badge_success, IF(o.id_order, 0, 1) badge_danger, IF(co.id_guest, 1, 0) id_guest\n\t\tFROM `" . _DB_PREFIX_ . "cart` a  \n\t\t\t\tJOIN `" . _DB_PREFIX_ . "customer` c ON (c.id_customer = a.id_customer)\n\t\t\t\tLEFT JOIN `" . _DB_PREFIX_ . "currency` cu ON (cu.id_currency = a.id_currency)\n\t\t\t\tLEFT JOIN `" . _DB_PREFIX_ . "carrier` ca ON (ca.id_carrier = a.id_carrier)\n\t\t\t\tLEFT JOIN `" . _DB_PREFIX_ . "orders` o ON (o.id_cart = a.id_cart)\n\t\t\t\tLEFT JOIN `" . _DB_PREFIX_ . "connections` co ON (a.id_guest = co.id_guest AND TIME_TO_SEC(TIMEDIFF('" . date('Y-m-d H:i:s') . "', co.`date_add`)) < 1800)\n\t\t) AS toto WHERE id_order='Abandoned cart'";
        $currency = Context::getContext()->currency->sign;
        $defaultLanguage = new Language((int) Configuration::get('PS_LANG_DEFAULT'));
        $abandoned_carts = Db::getInstance()->ExecuteS($sql);
        // get all available campaigns
        $sqlCampaigns = 'SELECT * FROM `' . _DB_PREFIX_ . 'campaign` WHERE active=1';
        $allCampaigns = Db::getInstance()->ExecuteS($sqlCampaigns);
        // loop on all abandoned carts
        foreach ($abandoned_carts as $abncart) {
            // loop on all available campaigns
            foreach ($allCampaigns as $camp) {
                $cartIsOnCampaign = $this->checkIfCartIsOnCampaign($abncart['date_add'], $camp['execution_time_day'], $camp['execution_time_hour']);
                if ($cartIsOnCampaign) {
                    $id_lang = (int) Configuration::get('PS_LANG_DEFAULT');
                    $customer = new Customer($abncart['id_customer']);
                    $cR = new CartRule($camp['id_voucher'], $id_lang);
                    $cart = new Cart($abncart['id_cart']);
                    $products = $cart->getProducts();
                    $campM = new Campaign($camp['id_campaign']);
                    if (!empty($products)) {
                        $cart_content = $campM->getCartContentHeader();
                    } else {
                        $cart_content = '';
                    }
                    foreach ($products as $prod) {
                        $p = new Product($prod['id_product'], true, $id_lang);
                        $price_no_tax = Product::getPriceStatic($p->id, false, null, 2, null, false, true, 1, false, null, $abncart['id_cart'], null, $null, true, true, null, false, false);
                        $total_no_tax = $prod['cart_quantity'] * $price_no_tax;
                        $images = Image::getImages((int) $id_lang, (int) $p->id);
                        $link = new Link();
                        $cart_content .= '<tr >
										<td align="center" ><img src="' . $link->getImageLink($p->link_rewrite, $images[0]['id_image']) . '" width="80"/></td>
										<td align="center" ><a href="' . $link->getProductLink($p) . '"/>' . $p->name . '</a></td>
										<td align="center" >' . Tools::displayprice($price_no_tax) . '</td>
										<td align="center" >' . $prod['cart_quantity'] . '</td>
										<td align="center" >' . Tools::displayprice($total_no_tax) . '</td>
									</tr>';
                    }
                    $tpl_vars = array('{firstname}' => $customer->firstname, '{lastname}' => $customer->lastname, '{coupon_name}' => $cR->name, '{coupon_code}' => $cR->code, '{cart_content}' => $cart_content, '{coupon_value}' => $camp['voucher_amount_type'] == 'percent' ? $cR->reduction_percent . '%' : $currency . $cR->reduction_amount, '{coupon_valid_to}' => date('d/m/Y', strtotime($cR->date_to)), '{campaign_name}' => $camp['name']);
                    $path = _PS_ROOT_DIR_ . '/modules/superabandonedcart/mails/';
                    // send email to customer :
                    Mail::Send($id_lang, $campM->getFileName(), $camp['name'], $tpl_vars, $customer->email, null, null, null, null, null, $path, false, Context::getContext()->shop->id);
                    // Email to admin :
                    Mail::Send($id_lang, $campM->getFileName(), Mail::l(sprintf('Email sent to %s %s for campaign %s', $customer->lastname, $customer->firstname, $camp['name'])), $tpl_vars, Configuration::get('PS_SHOP_EMAIL'), null, null, null, null, null, $path, false, Context::getContext()->shop->id);
                    //	echo 'ID ' . $abncart['id_cart'];
                }
            }
        }
    }
Ejemplo n.º 5
0
 protected function getArticles(Order $order, $cart = false)
 {
     $this->to_refund = 0;
     $this->to_refund_tax = 0;
     if ($cart) {
         $products = $cart->getProducts();
     } else {
         $products = $order->getProducts();
         foreach ($products as $key => &$order_item) {
             $order_item['product_quantity'] -= $order_item['product_quantity_refunded'];
             $this->to_refund += $order_item['product_quantity_refunded'] * $order_item['unit_price_tax_incl'];
             $this->to_refund_tax += $order_item['product_quantity_refunded'] * $order_item['unit_price_tax_excl'];
             if ((int) $order_item['product_quantity'] <= 0) {
                 unset($products[$key]);
             }
         }
     }
     $articles = array();
     $link = new Link();
     foreach ($products as $order_item) {
         if ($cart) {
             $productId = $order_item['id_product'];
             $Product = new Product($productId);
             $discounts = $order_item['reduction_applies'];
             $quantity = $order_item['cart_quantity'];
             $price = $order_item['price_wt'];
             $description_short = strip_tags($order_item['description_short']);
             $image_url = str_replace('http://', '', $link->getImageLink('product', $order_item['id_image']));
             $name = $order_item['name'];
             $sku = $order_item['id_product_attribute'];
             $product_url = $link->getProductLink($productId);
         } else {
             $productId = $order_item['product_id'];
             $Product = new Product($productId);
             $discounts = $order_item['reduction_amount_tax_incl'];
             $quantity = $order_item['product_quantity'];
             $price = $order_item['unit_price_tax_incl'];
             $description_short = strip_tags($order_item['description_short']);
             $image_url = str_replace('http://', '', $link->getImageLink('product', $order_item['image']->id));
             $name = $order_item['product_name'];
             $sku = $order_item['product_attribute_id'];
             $product_url = $link->getProductLink($productId);
         }
         $articles[] = array("id" => $productId, "sku" => $sku, "name" => $name, "description" => substr($description_short, 0, 255), "url" => $product_url, "image_url" => 'http://' . $image_url, "quantity" => intval($quantity), "price" => static::formatDecimals($price), "tax_rate" => static::formatDecimals($Product->getTaxesRate()), "discount" => static::formatDecimals($discounts));
     }
     return $articles;
 }
Ejemplo n.º 6
0
    public function sendCampaign()
    {
        // get abandoned cart :
        $sql = "SELECT * FROM (\n\t\tSELECT\n\t\tCONCAT(LEFT(c.`firstname`, 1), '. ', c.`lastname`) `customer`, a.id_cart total, ca.name carrier, c.id_customer, a.id_cart, a.date_upd,a.date_add,\n\t\t\t\tIF (IFNULL(o.id_order, 'Non ordered') = 'Non ordered', IF(TIME_TO_SEC(TIMEDIFF('" . date('Y-m-d H:i:s') . "', a.`date_add`)) > 86000, 'Abandoned cart', 'Non ordered'), o.id_order) id_order, IF(o.id_order, 1, 0) badge_success, IF(o.id_order, 0, 1) badge_danger, IF(co.id_guest, 1, 0) id_guest\n\t\tFROM `" . _DB_PREFIX_ . "cart` a  \n\t\t\t\tJOIN `" . _DB_PREFIX_ . "customer` c ON (c.id_customer = a.id_customer)\n\t\t\t\tLEFT JOIN `" . _DB_PREFIX_ . "currency` cu ON (cu.id_currency = a.id_currency)\n\t\t\t\tLEFT JOIN `" . _DB_PREFIX_ . "carrier` ca ON (ca.id_carrier = a.id_carrier)\n\t\t\t\tLEFT JOIN `" . _DB_PREFIX_ . "orders` o ON (o.id_cart = a.id_cart)\n\t\t\t\tLEFT JOIN `" . _DB_PREFIX_ . "connections` co ON (a.id_guest = co.id_guest AND TIME_TO_SEC(TIMEDIFF('" . date('Y-m-d H:i:s') . "', co.`date_add`)) < 1800)\n\t\t\t\tWHERE a.date_add > (NOW() - INTERVAL 60 DAY) ORDER BY a.id_cart DESC \n\t\t) AS toto WHERE id_order='Abandoned cart'";
        $currency = Context::getContext()->currency->sign;
        $defaultLanguage = new Language((int) Configuration::get('PS_LANG_DEFAULT'));
        $abandoned_carts = Db::getInstance()->ExecuteS($sql);
        // get all available campaigns
        $sqlCampaigns = 'SELECT * FROM `' . _DB_PREFIX_ . 'campaign` WHERE active=1';
        $allCampaigns = Db::getInstance()->ExecuteS($sqlCampaigns);
        if (!$allCampaigns || empty($allCampaigns)) {
            die('NO CAMPAIGN');
        }
        // loop on all abandoned carts
        foreach ($abandoned_carts as $abncart) {
            if (Cart::getNbProducts((int) $abncart['id_cart']) > 0) {
                $emailsSent = 0;
                // loop on all available campaigns
                foreach ($allCampaigns as $camp) {
                    if (DEBUG_SAC) {
                        echo 'IdCustomer : ' . $abncart['id_customer'] . ' - IdCart : ' . $abncart['id_cart'] . '<br/>';
                    }
                    $cartIsOnCampaign = $this->checkIfCartIsOnCampaign($abncart['date_add'], $camp['execution_time_day'], $camp['execution_time_hour']);
                    if ($cartIsOnCampaign) {
                        if (DEBUG_SAC) {
                            echo 'Cart on campaign</br>';
                        }
                        $id_lang = (int) Configuration::get('PS_LANG_DEFAULT');
                        $customer = new Customer($abncart['id_customer']);
                        $cart = new Cart($abncart['id_cart']);
                        $products = $cart->getProducts();
                        $tpl_vars = array('{firstname}' => $customer->firstname, '{lastname}' => $customer->lastname, '{campaign_name}' => $camp['name'], '{track_url}' => $this->getBaseURL() . '?id_cart=' . (int) $abncart['id_cart'] . '&id_customer=' . (int) $abncart['id_customer'], '{track_request}' => '?id_cart=' . (int) $abncart['id_cart'] . '&id_customer=' . (int) $abncart['id_customer']);
                        $campM = new Campaign($camp['id_campaign']);
                        if ($campM->voucher_amount && $campM->voucher_day && $campM->voucher_amount_type) {
                            $campM->clean_old_reduction($campM->voucher_prefix);
                            $customerVoucher = $campM->registerDiscount($customer->id, $campM->voucher_amount, $campM->voucher_day, $campM->voucher_amount_type, $campM->voucher_prefix);
                            $tpl_vars['{coupon_name}'] = $customerVoucher->name;
                            $tpl_vars['{coupon_code}'] = $customerVoucher->code;
                            $tpl_vars['{coupon_value}'] = $camp['voucher_amount_type'] == 'percent' ? $customerVoucher->reduction_percent . '%' : Tools::displayprice($customerVoucher->reduction_amount);
                            $tpl_vars['{coupon_valid_to}'] = date('d/m/Y', strtotime($customerVoucher->date_to));
                        }
                        if (!empty($products)) {
                            $cart_content = $campM->getCartContentHeader();
                        } else {
                            $cart_content = '';
                        }
                        foreach ($products as $prod) {
                            $p = new Product($prod['id_product'], true, $id_lang);
                            $price_no_tax = Product::getPriceStatic($p->id, false, null, 2, null, false, true, 1, false, null, $abncart['id_cart'], null, $null, true, true, null, false, false);
                            $total_no_tax = $prod['cart_quantity'] * $price_no_tax;
                            $images = Image::getImages((int) $id_lang, (int) $p->id);
                            $link = new Link();
                            $cart_content .= '<tr>
											<td align="center" ><img src="' . Tools::getShopProtocol() . $link->getImageLink($p->link_rewrite, $images[0]['id_image']) . '" width="80"/></td>
											<td align="center" ><a href="' . $link->getProductLink($p) . '?id_cart=' . (int) $abncart['id_cart'] . '&id_customer=' . (int) $abncart['id_customer'] . '"/>' . $p->name . '</a></td>
											<td align="center" >' . Tools::displayprice($price_no_tax) . '</td>
											<td align="center" >' . $prod['cart_quantity'] . '</td>
											<td align="center" >' . Tools::displayprice($total_no_tax) . '</td>
										</tr>';
                        }
                        $cart_content .= '</table>';
                        $tpl_vars['{cart_content}'] = $cart_content;
                        $path = _PS_ROOT_DIR_ . '/modules/superabandonedcart/mails/';
                        // send email to customer :
                        $mailUser = Mail::Send($id_lang, $campM->getFileName(), $camp['name'], $tpl_vars, $customer->email, null, null, null, null, null, $path, false, Context::getContext()->shop->id);
                        // if mail user is successfully sent :
                        if ($mailUser) {
                            $history = new CampaignHistory();
                            $history->id_campaign = (int) $camp['id_campaign'];
                            $history->id_customer = $abncart['id_customer'];
                            $history->id_cart = $abncart['id_cart'];
                            $history->id_cart_rule = isset($customerVoucher->id) ? $customerVoucher->id : 0;
                            $history->click = 0;
                            $history->converted = 0;
                            $history->date_update = date('Y-m-d H:i:s', time());
                            $history->save();
                            // Email to admin :
                            Mail::Send($id_lang, $campM->getFileName(), Mail::l(sprintf('Email sent to %s %s for campaign %s', $customer->lastname, $customer->firstname, $camp['name'])), $tpl_vars, Configuration::get('PS_SHOP_EMAIL'), null, null, null, null, null, $path, false, Context::getContext()->shop->id);
                            ++$emailsSent;
                        } else {
                            PrestaShopLogger::addLog('Error when sending user email (tpl:' . $campM->getFileName() . ',customer:' . $customer->email . ', campagne : ' . $camp['name'], 3);
                        }
                    }
                }
                // log emailing results :
                if ($emailsSent > 0) {
                    PrestaShopLogger::addLog($emailsSent . ' emails sent for ' . $camp['name'] . ' campaign', 1);
                }
            }
        }
    }
Ejemplo n.º 7
0
 public static function getUrlsProduct($product_id)
 {
     $product_exist = Db::getInstance()->getRow('SELECT * FROM ' . _DB_PREFIX_ . 'product WHERE id_product =' . (int) $product_id);
     if ($product_exist) {
         $o_product = new Product($product_id, false, (int) Configuration::get('PS_LANG_DEFAULT'));
         $protocol_link = Configuration::get('PS_SSL_ENABLED') || Tools::usingSecureMode() ? 'https://' : 'http://';
         $use_ssl = Configuration::get('PS_SSL_ENABLED') || Tools::usingSecureMode() ? true : false;
         $protocol_content = $use_ssl ? 'https://' : 'http://';
         $link = new Link($protocol_link, $protocol_content);
         $id_cover_image = Image::getCover($product_id);
         $image_path = $link->getImageLink($o_product->link_rewrite[(int) Configuration::get('PS_LANG_DEFAULT')], $id_cover_image['id_image']);
         $url_product = $link->getProductLink($product_id);
         return array('url_product' => $url_product, 'url_image_product' => $image_path);
     }
 }
Ejemplo n.º 8
0
 public function hookProductOneImg($listPro)
 {
     $protocol_link = Configuration::get('PS_SSL_ENABLED') || Tools::usingSecureMode() ? 'https://' : 'http://';
     $useSSL = isset($this->ssl) && $this->ssl && Configuration::get('PS_SSL_ENABLED') || Tools::usingSecureMode() ? true : false;
     $protocol_content = $useSSL ? 'https://' : 'http://';
     $link = new Link($protocol_link, $protocol_content);
     $id_lang = Context::getContext()->language->id;
     $where = ' WHERE i.`id_product` IN (' . $listPro . ') AND (ish.`cover`=0 OR ish.`cover` IS NULL) AND ish.`id_shop` = ' . Context::getContext()->shop->id;
     $order = ' ORDER BY i.`id_product`,`position`';
     $limit = ' LIMIT 0,1';
     //get product info
     $listImg = $this->getAllImages($id_lang, $where, $order, $limit);
     $savedImg = array();
     $obj = array();
     $this->smarty->assign(array('homeSize' => Image::getSize(ImageType::getFormatedName('home')), 'mediumSize' => Image::getSize(ImageType::getFormatedName('medium')), 'smallSize' => Image::getSize(ImageType::getFormatedName('small'))));
     foreach ($listImg as $product) {
         if (!in_array($product['id_product'], $savedImg)) {
             $obj[] = array('id' => $product['id_product'], 'content' => $link->getImageLink($product['link_rewrite'], $product['id_image'], 'home' . '_default'));
         }
         $savedImg[] = $product['id_product'];
     }
     return $obj;
 }
Ejemplo n.º 9
0
    public function generateXmlFlow()
    {
        global $cart, $cookie;
        $cookie->id_lang = (int) Configuration::get('PS_LANG_DEFAULT');
        // url rewriting case
        $cart = new Cart();
        $link = new Link();
        $defaultCurrencyIsoCode = strtoupper(Db::getInstance()->getValue('SELECT c.iso_code FROM ' . _DB_PREFIX_ . 'currency c WHERE c.id_currency = ' . (int) Configuration::get('PS_CURRENCY_DEFAULT')));
        $defaultIdLang = (int) Configuration::get('PS_LANG_DEFAULT');
        $sqlLangs = Db::getInstance()->ExecuteS('SELECT l.id_lang, l.iso_code FROM ' . _DB_PREFIX_ . 'lang l');
        foreach ($sqlLangs as $sqlLang) {
            $langs[$sqlLang['id_lang']] = $sqlLang['iso_code'];
        }
        $xmlString = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<products>
</products>
XML;
        $products = new SimpleXMLExtended($xmlString);
        $infos = $products->addChild('infos');
        $infos->addCData('url', $this->_getShopURL());
        $infos->addCData('logo', $this->_getShopURL());
        $languages = Db::getInstance()->ExecuteS('
		SELECT l.iso_code
		FROM ' . _DB_PREFIX_ . 'lang l
		WHERE l.active = 1');
        foreach ($languages as $language) {
            $infos->addChild('lang', $language['iso_code']);
        }
        $limit_sql = '';
        $limit_start = (int) Tools::getValue('limit_start');
        $limit_end = (int) Tools::getValue('limit_end');
        if ($limit_start > 0) {
            if ($limit_end < $limit_start) {
                $limit_end = $limit_start + 10;
            }
            $limit_sql = ' LIMIT ' . (int) $limit_start . ',' . (int) $limit_end;
        }
        $sqlProducts = Db::getInstance()->ExecuteS('
		SELECT p.id_product, p.reference, p.weight, m.name manufacturer, s.name supplier, p.on_sale, p.id_manufacturer, pd.id_product_download
		FROM ' . _DB_PREFIX_ . 'product p
		LEFT JOIN ' . _DB_PREFIX_ . 'manufacturer m ON (m.id_manufacturer = p.id_manufacturer)
		LEFT JOIN ' . _DB_PREFIX_ . 'supplier s ON (s.id_supplier = p.id_supplier)
		LEFT JOIN ' . _DB_PREFIX_ . 'product_download pd ON (pd.id_product = p.id_product)
		WHERE p.active = 1' . $limit_sql);
        foreach ($sqlProducts as $sqlProduct) {
            $id_product = $sqlProduct['id_product'];
            $product = $products->addChild('product');
            $product->addChild('sku', (int) $sqlProduct['id_product']);
            $product->addCData('manufacturer', $sqlProduct['manufacturer']);
            if (file_exists(dirname(__FILE__) . '/../../img/m/' . (int) $sqlProduct['id_manufacturer'] . 'jpg')) {
                $product->addCData('manufacturer-logo', $_SERVER['HTTP_HOST'] . __PS_BASE_URI__ . 'img/m/' . (int) $sqlProduct['id_manufacturer'] . 'jpg');
            }
            $product->addChild('weight', (double) $sqlProduct['weight']);
            $product->addChild('weight_unit', strtolower(Configuration::get('PS_WEIGHT_UNIT')));
            $product->addCData('supplier', $sqlProduct['supplier']);
            $name = $product->addChild('name');
            $languageVariant = $name->addChild('language-variant');
            $texts = Db::getInstance()->ExecuteS('
			SELECT pl.name, pl.description_short, pl.link_rewrite, l.iso_code, l.id_lang
			FROM ' . _DB_PREFIX_ . 'product_lang pl
			LEFT JOIN ' . _DB_PREFIX_ . 'lang l ON (l.id_lang = pl.id_lang)
			WHERE pl.id_product = ' . (int) $sqlProduct['id_product']);
            foreach ($texts as $text) {
                $variant = $languageVariant->addChild('variant');
                $variant->addChild('locale', $text['iso_code']);
                $variant->addCData('value', $text['name']);
                if ($text['id_lang'] == $defaultIdLang) {
                    $productName = $text['name'];
                    $productLinkRewrite = $text['link_rewrite'];
                }
            }
            $product->addCData('page-url', $link->getProductLink((int) $sqlProduct['id_product'], $productLinkRewrite));
            $shortDescription = $product->addChild('short-description');
            $languageVariant = $shortDescription->addChild('language-variant');
            foreach ($texts as $text) {
                $variant = $languageVariant->addChild('variant');
                $variant->addChild('locale', $text['iso_code']);
                $variant->addCData('value', Tools::htmlentitiesDecodeUTF8(strip_tags($text['description_short'])));
            }
            $accessories = Db::getInstance()->ExecuteS('
			SELECT a.id_product_2
			FROM ' . _DB_PREFIX_ . 'accessory a
			WHERE a.id_product_1 = ' . (int) $sqlProduct['id_product']);
            foreach ($accessories as $accessory) {
                $product->addChild('accessory-sku', (int) $accessory['id_product_2']);
            }
            $price = $product->addChild('price');
            $price->addChild('currency', $defaultCurrencyIsoCode);
            $price->addChild('retail-price-with-tax', Product::getPriceStatic((int) $sqlProduct['id_product'], true, NULL, 6, NULL, false, false));
            $price->addChild('retail-price-without-tax', Product::getPriceStatic((int) $sqlProduct['id_product'], false, NULL, 6, NULL, false, false));
            $price->addChild('final-retail-price-with-tax', Product::getPriceStatic((int) $sqlProduct['id_product'], true));
            if (version_compare(_PS_VERSION_, '1.4') < 0) {
                $price->addChild('final-retail-price-without-tax', Product::getPriceStatic(intval($sqlProduct['id_product']), false));
                $price->addChild('reduction_percent', floatval($sqlProduct['reduction_percent']));
                $price->addChild('reduction_price', floatval($sqlProduct['reduction_price']));
            } else {
                $price->addChild('final-retail-price-without-tax', Product::getPriceStatic((int) $sqlProduct['id_product'], false, NULL, 6, NULL, false, true, 1, false, NULL, NULL, NULL, $specificPrice));
                $price->addChild('reduction_percent', ($specificPrice and $specificPrice['reduction_type'] == 'percentage') ? $specificPrice['reduction'] * 100 : 0.0);
                $price->addChild('reduction_price', ($specificPrice and $specificPrice['reduction_type'] == 'amount') ? (double) $specificPrice['reduction'] : 0.0);
            }
            $price->addChild('display-on-sale', (int) $sqlProduct['on_sale']);
            $product->addChild('downloadable', $sqlProduct['id_product_download'] >= 1 ? 1 : 0);
            $pack = Db::getInstance()->ExecuteS('
			SELECT p.id_product, pp.quantity
			FROM ' . _DB_PREFIX_ . 'pack pp
			LEFT JOIN ' . _DB_PREFIX_ . 'product p ON (p.id_product = pp.id_product_item)
			WHERE pp.id_product_pack = ' . (int) $sqlProduct['id_product']);
            if (sizeof($pack)) {
                $pack = $product->addChild('pack');
                foreach ($pack as $p) {
                    $packItem = $pack->addChild('pack-item');
                    $packItem->addChild('quantity', (int) $p['quantity']);
                    $packItem->addChild('sku', (int) $p['id_product']);
                }
            }
            $images = Db::getInstance()->ExecuteS('
			SELECT i.id_image, il.legend, l.iso_code
			FROM ' . _DB_PREFIX_ . 'image i
			LEFT JOIN ' . _DB_PREFIX_ . 'image_lang il ON (il.id_image = i.id_image)
			LEFT JOIN ' . _DB_PREFIX_ . 'lang l ON (l.id_lang = il.id_lang)
			WHERE i.id_product = ' . (int) $sqlProduct['id_product']);
            $imagesLegends = array();
            foreach ($images as $image) {
                $imagesLegends[(int) $image['id_image']][$image['iso_code']]['legend'] = $image['legend'];
                $imagesLegends[(int) $image['id_image']][$image['iso_code']]['iso_code'] = $image['iso_code'];
            }
            $imagesAlreadyDone = array();
            foreach ($images as $imageSQL) {
                if (isset($imagesAlreadyDone[$imageSQL['id_image']])) {
                    continue;
                }
                $imagesAlreadyDone[(int) $imageSQL['id_image']] = 1;
                $image = $product->addChild('image');
                $image->addAttribute('id', $imageSQL['id_image']);
                $image->addCData('image-url', $link->getImageLink($productLinkRewrite, (int) $sqlProduct['id_product'] . '-' . (int) $imageSQL['id_image'], 'large'));
                if (isset($imagesLegends[$imageSQL['id_image']]) and sizeof($imagesLegends[$imageSQL['id_image']])) {
                    $imageCaption = $image->addChild('image-caption');
                    $languageVariant = $imageCaption->addChild('language-variant');
                    foreach ($imagesLegends[(int) $imageSQL['id_image']] as $legend) {
                        $variant = $languageVariant->addChild('variant');
                        $variant->addChild('locale', $legend['iso_code']);
                        $variant->addCData('value', $legend['legend']);
                    }
                }
            }
            if (version_compare(_PS_VERSION_, '1.4') < 0) {
                $quantityDiscounts = Db::getInstance()->ExecuteS('
				SELECT dq.quantity, dq.value, dq.id_discount_type
				FROM ' . _DB_PREFIX_ . 'discount_quantity dq
				WHERE dq.id_product = ' . intval($sqlProduct['id_product']));
                foreach ($quantityDiscounts as $quantityDiscount) {
                    $discount = $product->addChild('discount');
                    $discount->addChild('discount-quantity', intval($quantityDiscount['quantity']));
                    $discount->addChild('discount-value', floatval($quantityDiscount['value']));
                    $discount->addChild('discount-type', $quantityDiscount['id_discount_type'] == 1 ? $defaultCurrencyIsoCode : '%');
                }
            } else {
                $quantityDiscounts = SpecificPrice::getQuantityDiscounts((int) $sqlProduct['id_product'], (int) Shop::getCurrentShop(), 0, 0, 0);
                foreach ($quantityDiscounts as $quantityDiscount) {
                    $discount = $product->addChild('discount');
                    $discount->addChild('discount-quantity', (int) $quantityDiscount['from_quantity']);
                    $discount->addChild('discount-value', ((double) $quantityDiscount['price'] and $quantityDiscount['reduction_type'] == 'amount') ? (double) $quantityDiscount['price'] : $quantityDiscount['reduction'] * 100);
                    $discount->addChild('discount-type', $quantityDiscount['reduction_type'] == 'amount' ? $defaultCurrencyIsoCode : '%');
                }
            }
            $categories = Db::getInstance()->ExecuteS('
			SELECT cl.name, l.iso_code
			FROM ' . _DB_PREFIX_ . 'category_product cp
			LEFT JOIN ' . _DB_PREFIX_ . 'category_lang cl ON (cl.id_category = cp.id_category)
			LEFT JOIN ' . _DB_PREFIX_ . 'lang l ON (l.id_lang = cl.id_lang)
			WHERE cp.id_product = ' . (int) $sqlProduct['id_product']);
            if (sizeof($categories)) {
                $category = $product->addChild('category');
                $languageVariant = $category->addChild('language-variant');
                foreach ($categories as $category) {
                    $variant = $languageVariant->addChild('variant');
                    $variant->addChild('locale', $category['iso_code']);
                    $variant->addCData('value', $category['name']);
                }
            }
            $tags = Db::getInstance()->ExecuteS('
			SELECT pt.id_product, pt.id_tag, l.iso_code, t.name
			FROM ' . _DB_PREFIX_ . 'product_tag pt
			LEFT JOIN ' . _DB_PREFIX_ . 'tag t ON (t.id_tag = pt.id_tag)
			LEFT JOIN ' . _DB_PREFIX_ . 'lang l ON (l.id_lang = t.id_lang)
			WHERE pt.id_product = ' . (int) $sqlProduct['id_product']);
            if (!empty($tags) && sizeof($tags) > 0) {
                $tagsTexts = array();
                $tagsIso = array();
                foreach ($tags as $tag) {
                    if (!in_array($tag['iso_code'], $tagsIso)) {
                        $tagsIso[] = $tag['iso_code'];
                    }
                    $tagsTexts[$tag['iso_code']][] = $tag['name'];
                }
                $tags_item = $product->addChild('tags');
                foreach ($tagsIso as $iso) {
                    $languageVariant = $tags_item->addChild('language-variant');
                    $languageVariant->addChild('locale', $iso);
                    $languageVariant->addCData('value', implode(',', $tagsTexts[$iso]));
                }
            }
            $groupAttributes = Db::getInstance()->ExecuteS('
			SELECT DISTINCT agl.id_attribute_group, agl.name, l.iso_code, a.id_attribute, al.name as attribute_name, al.id_lang, pa.id_product_attribute
			FROM ' . _DB_PREFIX_ . 'attribute_group_lang agl
			LEFT JOIN ' . _DB_PREFIX_ . 'attribute a ON (a.id_attribute_group = agl.id_attribute_group)
			LEFT JOIN ' . _DB_PREFIX_ . 'attribute_lang al ON (al.id_attribute = a.id_attribute)
			LEFT JOIN ' . _DB_PREFIX_ . 'lang l ON (l.id_lang = al.id_lang)
			LEFT JOIN ' . _DB_PREFIX_ . 'product_attribute_combination pac ON (pac.id_attribute = a.id_attribute)
			LEFT JOIN ' . _DB_PREFIX_ . 'product_attribute pa ON (pa.id_product_attribute = pac.id_product_attribute)
			WHERE pa.id_product = ' . (int) $sqlProduct['id_product'] . '
			GROUP BY a.id_attribute, l.iso_code');
            $groups = array();
            foreach ($groupAttributes as $groupAttribute) {
                $id_group_attribute = $groupAttribute['id_attribute_group'];
                $id_attribute = $groupAttribute['id_attribute'];
                $id_product_attribute = $groupAttribute['id_product_attribute'];
                $groups[$id_group_attribute]['name'][$groupAttribute['iso_code']] = $groupAttribute['name'];
                $groups[$id_group_attribute]['attributes'][$groupAttribute['id_attribute']][$groupAttribute['iso_code']] = $groupAttribute['attribute_name'];
            }
            if (!empty($groups)) {
                foreach ($groups as $id_group => $group) {
                    $xml_group = $product->addChild('attribute-group');
                    $xml_group->addAttribute('id', $id_group);
                    if (!empty($group['name'])) {
                        $nameGroup = $xml_group->addChild('name');
                        $languageVariant = $nameGroup->addChild('language-variant');
                        foreach ($group['name'] as $iso2 => $name_group) {
                            $variant = $languageVariant->addChild('variant');
                            $variant->addChild('locale', $iso2);
                            $variant->addCData('value', $name_group);
                        }
                    }
                    if (!empty($group['attributes'])) {
                        foreach ($group['attributes'] as $id_attribute => $attribute) {
                            $xml_attribute = $xml_group->addChild('attribute');
                            $xml_attribute->addAttribute('id', $id_attribute);
                            $languageVariant = $xml_attribute->addChild('language-variant');
                            foreach ($attribute as $iso2 => $name_attribute) {
                                $variant = $languageVariant->addChild('variant');
                                $variant->addChild('locale', $iso2);
                                $variant->addCData('value', $name_attribute);
                            }
                        }
                    }
                }
            }
            $groupAttributes = Db::getInstance()->ExecuteS('
			SELECT agl.id_attribute_group, agl.name, l.iso_code, a.id_attribute, al.name attribute_name, al.id_lang, pa.id_product_attribute
			FROM ' . _DB_PREFIX_ . 'attribute_group_lang agl
			LEFT JOIN ' . _DB_PREFIX_ . 'lang l ON (l.id_lang = agl.id_lang)
			LEFT JOIN ' . _DB_PREFIX_ . 'attribute a ON (a.id_attribute_group = agl.id_attribute_group)
			LEFT JOIN ' . _DB_PREFIX_ . 'attribute_lang al ON (al.id_attribute = a.id_attribute)
			LEFT JOIN ' . _DB_PREFIX_ . 'product_attribute_combination pac ON (pac.id_attribute = a.id_attribute)
			LEFT JOIN ' . _DB_PREFIX_ . 'product_attribute pa ON (pa.id_product_attribute = pac.id_product_attribute)
			WHERE pa.id_product = ' . (int) $sqlProduct['id_product']);
            $combinaison = array();
            foreach ($groupAttributes as $groupAttribute) {
                $id_group_attribute = $groupAttribute['id_attribute_group'];
                $id_attribute = $groupAttribute['id_attribute'];
                $id_product_attribute = $groupAttribute['id_product_attribute'];
                $combinaison[$id_product_attribute][$id_group_attribute] = $id_attribute;
            }
            $productAttributes = Db::getInstance()->ExecuteS('
			SELECT pa.id_product_attribute, pa.weight, pa.quantity, pi.id_image
			FROM ' . _DB_PREFIX_ . 'product_attribute pa
			LEFT JOIN ' . _DB_PREFIX_ . 'product_attribute_image pi ON (pa.id_product_attribute = pi.id_product_attribute)
			WHERE pa.id_product = ' . (int) $sqlProduct['id_product']);
            if (!empty($productAttributes)) {
                foreach ($productAttributes as $productAttribute) {
                    $id_product_attribute = (int) $productAttribute['id_product_attribute'];
                    $attributeCombination = $product->addChild('attribute-combination');
                    $attributeCombination->addAttribute('id', $id_product_attribute);
                    $attributeCombination->addChild('weight', (double) ($sqlProduct['weight'] + $productAttribute['weight']));
                    $attributeCombination->addChild('final-retail-price-with-tax', Product::getPriceStatic((int) $sqlProduct['id_product'], true, $id_product_attribute));
                    $attributeCombination->addChild('final-retail-price-without-tax', Product::getPriceStatic((int) $sqlProduct['id_product'], false, $id_product_attribute));
                    $attributeCombination->addChild('quantity', $productAttribute['quantity']);
                    if (isset($productAttribute['id_image']) && !empty($productAttribute['id_image'])) {
                        $image = $attributeCombination->addChild('image');
                        $image->addAttribute('ref-id', $productAttribute['id_image']);
                    }
                    if (isset($combinaison[$id_product_attribute]) && !empty($combinaison[$id_product_attribute])) {
                        foreach ($combinaison[$id_product_attribute] as $id_group_attribute => $id_attribute) {
                            $attribute = $attributeCombination->addChild('attribute');
                            $attribute->addAttribute('group-ref-id', $id_group_attribute);
                            $attribute->addAttribute('ref-id', $id_attribute);
                        }
                    }
                }
            }
        }
        echo $products->asXML();
    }
Ejemplo n.º 10
0
 private function _addSitemapNodeImage($xml, $product)
 {
     foreach ($product['images'] as $img) {
         $link = new Link();
         $image = $xml->addChild('image', null, 'http://www.google.com/schemas/sitemap-image/1.1');
         $image->addChild('loc', $link->getImageLink($product['link_rewrite'], (int) $product['id_product'] . '-' . (int) $img['id_image']), 'http://www.google.com/schemas/sitemap-image/1.1');
         $legend_image = preg_replace('/(&+)/i', '&amp;', $img['legend_image']);
         $image->addChild('caption', $legend_image, 'http://www.google.com/schemas/sitemap-image/1.1');
         $image->addChild('title', $legend_image, 'http://www.google.com/schemas/sitemap-image/1.1');
     }
 }
 public function hookProductOneImg($listPro)
 {
     $link = new Link();
     $id_lang = Context::getContext()->language->id;
     $where = " WHERE i.`id_product` IN (" . $listPro . ") AND ish.`cover`=0";
     $order = " ORDER BY i.`id_product`,`position`";
     $limit = " LIMIT 0,1";
     //get product info
     $listImg = $this->getAllImages($id_lang, $where, $order, $limit);
     $savedImg = array();
     $obj = array();
     $this->smarty->assign(array('homeSize' => Image::getSize(ImageType::getFormatedName('home')), 'mediumSize' => Image::getSize(ImageType::getFormatedName('medium')), 'smallSize' => Image::getSize(ImageType::getFormatedName('small'))));
     foreach ($listImg as $product) {
         if (!in_array($product["id_product"], $savedImg)) {
             $obj[] = array("id" => $product["id_product"], "content" => $link->getImageLink($product['link_rewrite'], $product["id_image"], 'home' . '_default'));
         }
         $savedImg[] = $product["id_product"];
     }
     return $obj;
 }
Ejemplo n.º 12
0
 public function generateFlux()
 {
     if (Tools::getValue('token') == '' || Tools::getValue('token') != Configuration::get('SHOPPING_FLUX_TOKEN')) {
         die('Invalid Token');
     }
     $titles = array(0 => 'id_produit', 1 => 'nom_produit', 2 => 'url_produit', 3 => 'url_image', 4 => 'description', 5 => 'description_courte', 6 => 'prix', 7 => 'prix_barre', 8 => 'frais_de_port', 9 => 'delaiLiv', 10 => 'marque', 11 => 'rayon', 12 => 'stock', 13 => 'qte_stock', 14 => 'EAN', 15 => 'poids', 16 => 'ecotaxe', 17 => 'TVA', 18 => 'Reference constructeur', 19 => 'Reference fournisseur');
     echo implode("|", $titles) . "\r\n";
     //For Shipping
     $configuration = Configuration::getMultiple(array('PS_TAX_ADDRESS_TYPE', 'PS_CARRIER_DEFAULT', 'PS_COUNTRY_DEFAULT', 'PS_LANG_DEFAULT', 'PS_SHIPPING_FREE_PRICE', 'PS_SHIPPING_HANDLING', 'PS_SHIPPING_METHOD', 'PS_SHIPPING_FREE_WEIGHT'));
     $products = Product::getSimpleProducts($configuration['PS_LANG_DEFAULT']);
     $defaultCountry = new Country($configuration['PS_COUNTRY_DEFAULT'], Configuration::get('PS_LANG_DEFAULT'));
     $id_zone = (int) $defaultCountry->id_zone;
     $carrier = new Carrier((int) $configuration['PS_CARRIER_DEFAULT']);
     $carrierTax = Tax::getCarrierTaxRate((int) $carrier->id, (int) $this->{$configuration['PS_TAX_ADDRESS_TYPE']});
     foreach ($products as $key => $produit) {
         $product = new Product((int) $produit['id_product'], true, $configuration['PS_LANG_DEFAULT']);
         //For links
         $link = new Link();
         //For images
         $cover = $product->getCover($product->id);
         $ids = $product->id . '-' . $cover['id_image'];
         //For shipping
         if ($product->getPrice(true, NULL, 2, NULL, false, true, 1) >= (double) $configuration['PS_SHIPPING_FREE_PRICE'] and (double) $configuration['PS_SHIPPING_FREE_PRICE'] > 0) {
             $shipping = 0;
         } elseif (isset($configuration['PS_SHIPPING_FREE_WEIGHT']) and $product->weight >= (double) $configuration['PS_SHIPPING_FREE_WEIGHT'] and (double) $configuration['PS_SHIPPING_FREE_WEIGHT'] > 0) {
             $shipping = 0;
         } else {
             if (isset($configuration['PS_SHIPPING_HANDLING']) and $carrier->shipping_handling) {
                 $shipping = (double) $configuration['PS_SHIPPING_HANDLING'];
             }
             if ($carrier->getShippingMethod() == Carrier::SHIPPING_METHOD_WEIGHT) {
                 $shipping += $carrier->getDeliveryPriceByWeight($product->weight, $id_zone);
             } else {
                 $shipping += $carrier->getDeliveryPriceByPrice($product->getPrice(true, NULL, 2, NULL, false, true, 1), $id_zone);
             }
             $shipping *= 1 + $carrierTax / 100;
             $shipping = (double) Tools::ps_round((double) $shipping, 2);
         }
         $data = array();
         $data[0] = $product->id;
         $data[1] = $product->name;
         $data[2] = $link->getProductLink($product);
         $data[3] = $link->getImageLink($product->link_rewrite, $ids, 'large');
         $data[4] = $product->description;
         $data[5] = $product->description_short;
         $data[6] = $product->getPrice(true, NULL, 2, NULL, false, true, 1);
         $data[7] = $product->getPrice(true, NULL, 2, NULL, false, false, 1);
         $data[8] = $shipping;
         $data[9] = $carrier->delay[2];
         $data[10] = $product->manufacturer_name;
         $data[11] = $product->category;
         $data[12] = $product->quantity > 0 ? 'oui' : 'non';
         $data[13] = $product->quantity;
         $data[14] = $product->ean13;
         $data[15] = $product->weight;
         $data[16] = $product->ecotax;
         $data[17] = $product->tax_rate;
         $data[18] = $product->reference;
         $data[19] = $product->supplier_reference;
         foreach ($data as $key => $value) {
             $data[$key] = $this->clean($value);
         }
         echo implode("|", $data) . "\r\n";
     }
 }
 function createProductObject($prestaProduct, $variant, $categories, $extradata)
 {
     $id = $prestaProduct['id_product'];
     $product = new CEProduct();
     $active = filter_var($prestaProduct['active'], FILTER_VALIDATE_BOOLEAN);
     $product->setDeactivate(!$active);
     $product->setName($prestaProduct['name']);
     $product->setDescription(strip_tags($prestaProduct['description']));
     $product->setBrand($prestaProduct['manufacturer_name']);
     if (isset($extradata[$id])) {
         $this->setSpecs($product, $extradata[$id], false);
     }
     if (isset($prestaProduct['rate'])) {
         $product->setVatRate($prestaProduct['rate']);
     } else {
         $taxObject = new Tax($prestaProduct['id_tax_rules_group'], 1);
         $product->setVatRate($taxObject->rate);
     }
     //product data
     $id_image = $prestaProduct['id_image'];
     $price = $prestaProduct['price'] * (1.0 + $product->getVatRate() / 100.0);
     $ed = $product->getExtraData();
     $minQty = new CEProductExtraDataItem();
     $minQty->setKey('MinimalOrderQuantity');
     $minQty->setIsPublic(false);
     if (!$variant) {
         $merchantProductNo = $id;
         $product->setStock($prestaProduct['quantity']);
         $product->setEan($this->extractGtin($prestaProduct));
         $minQty->setValue($prestaProduct['minimal_quantity']);
     } else {
         $merchantProductNo = $id . "-" . $variant['id_product_attribute'];
         $product->setGroupNo($id);
         $product->setStock($variant['quantity']);
         $product->setEan($this->extractGtin($variant));
         $minQty->setValue($variant['minimal_quantity']);
         //add variant specific image
         if (isset($variant['id_image']) && $variant['id_image']) {
             $id_image = $variant['id_image'];
         }
         //add variant price change to default price. Using product_attribute_shop.price
         if ($variant['price'] != 0) {
             $price = ($prestaProduct['price'] + $variant['price']) * (1.0 + $product->getVatRate() / 100.0);
         }
         //loop all variant attribute_info
         if (isset($variant['all_attribute_info']) && is_array($variant['all_attribute_info'])) {
             $this->setSpecs($product, $variant['all_attribute_info'], true);
         }
     }
     $ed[] = $minQty;
     $product->setExtraData($ed);
     $product->setMerchantProductNo($merchantProductNo);
     $product->setPrice($price);
     $product->setListPrice($price);
     if (isset($prestaProduct['id_category'])) {
         $product->setCategoryTrail($categories[$prestaProduct['id_category']]);
     } else {
         $category_path = $this->getProductCategories($id);
         $product->setCategoryTrail($category_path);
     }
     $product->setShippingCost($prestaProduct['additional_shipping_cost']);
     $link = new Link();
     $product->setUrl($link->getProductLink($id));
     $base_path = _PS_BASE_URL_ . __PS_BASE_URI__;
     $base_path = preg_replace('#^https?://#', '', $base_path);
     $imagePath = $id_image == "" ? $base_path . 'img/p/en-default-home_default.jpg' : $link->getImageLink($prestaProduct['link_rewrite'], $id_image, '');
     $product->setImageUrl((Configuration::get("PS_SSL_ENABLED") ? 'https://' : 'http://') . $imagePath);
     return $product;
 }
Ejemplo n.º 14
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;
 }
Ejemplo n.º 15
0
 public function generate($to_file = true)
 {
     $link = new Link();
     include_once 'YMarket.class.php';
     //Язык по умолчанию
     $id_lang = intval(Configuration::get('PS_LANG_DEFAULT'));
     //Валюта по умолчанию
     $curr_def = new Currency(intval(Configuration::get('PS_CURRENCY_DEFAULT')));
     //создаем новый магазин
     $market = new YMarket($this->_settings['y_sn'], $this->_settings['y_fn'], 'http://' . Tools::getHttpHost(false, true), $this->_settings['y_ldc']);
     //Валюты
     if ($this->_settings['y_cu']) {
         $currencies = Currency::getCurrencies();
         foreach ($currencies as $currency) {
             $market->add(new yCurrency($currency['iso_code'], floatval($currency['conversion_rate'])));
         }
         unset($currencies);
     } else {
         $market->add(new yCurrency($curr_def->iso_code, floatval($curr_def->conversion_rate)));
     }
     //Категории
     $categories = Category::getCategories($id_lang, false, false);
     foreach ($categories as $category) {
         $catdesc = $category['meta_title'] ? $category['meta_title'] : $category['name'];
         $market->add(new yCategory($category['id_category'], $catdesc, $category['id_parent']));
     }
     unset($categories);
     //Продукты
     $products = self::getProducts($id_lang);
     while ($product = Db::getInstance()->nextRow($products)) {
         $tmp = new yOffer($product['id_product'], $product['name'], Product::getPriceStatic($product['id_product'], $usetax = true, NULL, $decimals = 2, $divisor = NULL, $only_reduc = false, $usereduc = true, $quantity = 1, $forceAssociatedTax = true));
         $tmp->id = $product['id_product'];
         $tmp->type = '';
         $tmp->sales_notes = $this->_settings['y_sl'];
         $tmp->url = $link->getProductLink((int) $product['id_product'], $product['link_rewrite']);
         //Картинка
         if ($cover = self::getCover($product['id_product'])) {
             $tmp->picture = $link->getImageLink($product['link_rewrite'], $cover);
         }
         $tmp->currencyId = $curr_def->iso_code;
         $tmp->categoryId = $product['id_category_default'];
         //$tmp->vendorCode = $product['reference'];
         $tmp->description = $product['description'];
         if ($this->_settings['y_dl']) {
             $tmp->delivery = 'true';
         } else {
             $tmp->delivery = 'false';
         }
         switch ($this->_settings['y_av']) {
             case 1:
                 $tmp->available = $product['quantity'] == 0 ? 'false' : 'true';
                 break;
             case 3:
                 $tmp->available = 'false';
                 break;
             default:
                 $tmp->available = 'true';
         }
         //$tmp->barcode = $product['ean13'];
         if (ProductDownload::getIdFromIdProduct($product['id_product'])) {
             $tmp->downloadable = 'true';
         }
         if (!($this->_settings['y_av'] == 2 and $product['quantity'] == 0)) {
             $market->add($tmp);
         }
     }
     if ($to_file) {
         $fp = fopen(dirname(__FILE__) . '/../../upload/yml.xml' . ($this->_settings['y_gz'] ? '.gz' : ''), 'w');
         fwrite($fp, $market->generate(false, $this->_settings['y_gz']));
         fclose($fp);
     } else {
         $market->generate(true, $this->_settings['y_gz']);
     }
 }
Ejemplo n.º 16
0
 private function _syncProducts($productsList)
 {
     $fees = 0;
     $count = 0;
     $count_success = 0;
     $count_error = 0;
     $tab_error = array();
     $date = date('Y-m-d H:i:s');
     $ebay = new eBayRequest();
     $categoryDefaultCache = array();
     // Get errors back
     if (file_exists(dirname(__FILE__) . '/log/syncError.php')) {
         global $tab_error;
         include dirname(__FILE__) . '/log/syncError.php';
     }
     // Up the time limit
     @set_time_limit(3600);
     // Run the products list
     foreach ($productsList as $p) {
         // Product instanciation
         $product = new Product((int) $p['id_product'], true, $this->id_lang);
         if (!$this->isVersionOneDotFive()) {
             $productQuantity = new Product((int) $p['id_product']);
             $quantityProduct = $productQuantity->quantity;
         } else {
             $quantityProduct = $product->quantity;
         }
         //Fix for payment modules validating orders out of context, $link will not  generate fatal error.
         if (is_object($this->context->link)) {
             $link = $this->context->link;
         } else {
             $link = new Link();
         }
         if (Validate::isLoadedObject($product) && $product->id_category_default > 0) {
             // Load default category matched in cache
             if (!isset($categoryDefaultCache[$product->id_category_default])) {
                 $categoryDefaultCache[$product->id_category_default] = Db::getInstance()->getRow('SELECT ec.`id_category_ref`, ec.`is_multi_sku`, ecc.`percent` FROM `' . _DB_PREFIX_ . 'ebay_category` ec LEFT JOIN `' . _DB_PREFIX_ . 'ebay_category_configuration` ecc ON (ecc.`id_ebay_category` = ec.`id_ebay_category`) WHERE ecc.`id_category` = ' . (int) $product->id_category_default);
             }
             if ($categoryDefaultCache[$product->id_category_default]['is_multi_sku'] != 1) {
                 $categoryDefaultCache[$product->id_category_default]['is_multi_sku'] = $this->findIfCategoryParentIsMultiSku($categoryDefaultCache[$product->id_category_default]['id_category_ref']);
             }
             // Load Pictures
             $pictures = array();
             $picturesMedium = array();
             $picturesLarge = array();
             $prefix = substr(_PS_VERSION_, 0, 3) == '1.3' ? Tools::getShopDomain(true) . '/' : '';
             $images = $product->getImages($this->id_lang);
             foreach ($images as $image) {
                 $pictures[] = str_replace('https://', 'http://', $prefix . $link->getImageLink('ebay', $product->id . '-' . $image['id_image'], 'large' . ($this->isVersionOneDotFive('>=', '1.5.1') ? '_default' : '')));
                 $picturesMedium[] = str_replace('https://', 'http://', $prefix . $link->getImageLink('ebay', $product->id . '-' . $image['id_image'], 'medium' . ($this->isVersionOneDotFive('>=', '1.5.1') ? '_default' : '')));
                 $picturesLarge[] = str_replace('https://', 'http://', $prefix . $link->getImageLink('ebay', $product->id . '-' . $image['id_image'], 'large' . ($this->isVersionOneDotFive('>=', '1.5.1') ? '_default' : '')));
             }
             // Load Variations
             $variations = array();
             $variationsList = array();
             $combinations = $this->isVersionOneDotFive() ? $product->getAttributeCombinations($this->context->cookie->id_lang) : $product->getAttributeCombinaisons($this->context->cookie->id_lang);
             if (isset($combinations)) {
                 foreach ($combinations as $c) {
                     $variationsList[$c['group_name']][$c['attribute_name']] = 1;
                     $variations[$c['id_product'] . '-' . $c['id_product_attribute']]['id_attribute'] = $c['id_product_attribute'];
                     $variations[$c['id_product'] . '-' . $c['id_product_attribute']]['reference'] = $c['reference'];
                     $variations[$c['id_product'] . '-' . $c['id_product_attribute']]['quantity'] = $c['quantity'];
                     $variations[$c['id_product'] . '-' . $c['id_product_attribute']]['variations'][] = array('name' => $c['group_name'], 'value' => $c['attribute_name']);
                     $variations[$c['id_product'] . '-' . $c['id_product_attribute']]['price_static'] = Product::getPriceStatic((int) $c['id_product'], true, (int) $c['id_product_attribute']);
                     $price = $variations[$c['id_product'] . '-' . $c['id_product_attribute']]['price_static'];
                     $price_original = $price;
                     if (preg_match("#[-]{0,1}[0-9]{1,2}%\$#is", $categoryDefaultCache[$product->id_category_default]['percent'])) {
                         if ($categoryDefaultCache[$product->id_category_default]['percent'] > 0) {
                             $price *= 1 + $categoryDefaultCache[$product->id_category_default]['percent'] / 100;
                         } else {
                             if ($categoryDefaultCache[$product->id_category_default]['percent'] < 0) {
                                 $price *= 1 - $categoryDefaultCache[$product->id_category_default]['percent'] / -100;
                             }
                         }
                     } else {
                         $price += $categoryDefaultCache[$product->id_category_default]['percent'];
                     }
                     $variations[$c['id_product'] . '-' . $c['id_product_attribute']]['price'] = round($price, 2);
                     if ($categoryDefaultCache[$product->id_category_default]['percent'] < 0) {
                         $variations[$c['id_product'] . '-' . $c['id_product_attribute']]['price_original'] = round($price_original, 2);
                         $variations[$c['id_product'] . '-' . $c['id_product_attribute']]['price_percent'] = round($categoryDefaultCache[$product->id_category_default]['percent']);
                     }
                 }
             }
             // Load Variations Pictures
             $combinationsImages = $product->getCombinationImages(2);
             if (isset($combinationsImages) && !empty($combinationsImages) && count($combinationsImages) > 0) {
                 foreach ($combinationsImages as $ci) {
                     foreach ($ci as $i) {
                         $variations[$product->id . '-' . $i['id_product_attribute']]['pictures'][] = $prefix . $link->getImageLink('ebay', $product->id . '-' . $i['id_image'], 'large' . ($this->isVersionOneDotFive('>=', '1.5.1') ? '_default' : ''));
                     }
                 }
             }
             // Load basic price
             $price = Product::getPriceStatic((int) $product->id, true);
             $price_original = $price;
             if (preg_match("#[-]{0,1}[0-9]{1,2}%\$#is", $categoryDefaultCache[$product->id_category_default]['percent'])) {
                 if ($categoryDefaultCache[$product->id_category_default]['percent'] > 0) {
                     $price *= 1 + $categoryDefaultCache[$product->id_category_default]['percent'] / 100;
                 } else {
                     if ($categoryDefaultCache[$product->id_category_default]['percent'] < 0) {
                         $price *= 1 - $categoryDefaultCache[$product->id_category_default]['percent'] / -100;
                     }
                 }
             } else {
                 $price += $categoryDefaultCache[$product->id_category_default]['percent'];
             }
             $price = round($price, 2);
             // Loading Shipping Method
             if (!isset($this->_shippingMethod[Configuration::get('EBAY_SHIPPING_CARRIER_ID')]['shippingService'])) {
                 $this->_shippingMethod = $this->eBayCountry->loadShippingMethod();
             }
             // Generate array and try insert in database
             $datas = array('id_product' => $product->id, 'reference' => $product->reference, 'name' => str_replace('&', '&amp;', $product->name), 'brand' => $product->manufacturer_name, 'description' => $product->description, 'description_short' => $product->description_short, 'price' => $price, 'quantity' => $quantityProduct, 'categoryId' => $categoryDefaultCache[$product->id_category_default]['id_category_ref'], 'variationsList' => $variationsList, 'variations' => $variations, 'pictures' => $pictures, 'picturesMedium' => $picturesMedium, 'picturesLarge' => $picturesLarge);
             //Add Item Conditions for eBay
             switch ($product->condition) {
                 case 'new':
                     $datas['condition'] = Configuration::get('EBAY_CONDITION_NEW');
                     break;
                 case 'used':
                     $datas['condition'] = Configuration::get('EBAY_CONDITION_USED');
                     break;
                 case 'refurbished':
                     $datas['condition'] = Configuration::get('EBAY_CONDITION_REFURBISHED');
                     break;
                 default:
                     $datas['condition'] = Configuration::get('EBAY_CONDITION_NEW');
                     break;
             }
             //Add shipping details
             $datas['shipping'] = $this->getShippingDetailsForProduct($product);
             // Fix hook update product
             if (isset($this->context->employee) && $this->context->employee->id > 0 && Tools::getValue('submitProductAttribute') && Tools::getValue('id_product_attribute') && Tools::getValue('attribute_mvt_quantity') && Tools::getValue('id_mvt_reason')) {
                 if (substr(_PS_VERSION_, 0, 3) == '1.3') {
                     $id_product_attribute_fix = (int) $_POST['id_product_attribute'];
                     $quantity_fix = (int) $_POST['attribute_quantity'];
                     if ($id_product_attribute_fix > 0 && $quantity_fix > 0 && isset($datas['variations'][$product->id . '-' . $id_product_attribute_fix]['quantity'])) {
                         $datas['variations'][$product->id . '-' . $id_product_attribute_fix]['quantity'] = (int) $quantity_fix;
                     }
                 } else {
                     $action = Db::getInstance()->getValue('SELECT `sign` FROM `' . _DB_PREFIX_ . 'stock_mvt_reason` WHERE `id_stock_mvt_reason` = ' . (int) $_POST['id_mvt_reason']);
                     $id_product_attribute_fix = (int) $_POST['id_product_attribute'];
                     $quantity_fix = (int) $_POST['attribute_mvt_quantity'];
                     if ($id_product_attribute_fix > 0 && $quantity_fix > 0 && isset($datas['variations'][$product->id . '-' . $id_product_attribute_fix]['quantity'])) {
                         if ($action > 0) {
                             $datas['variations'][$product->id . '-' . $id_product_attribute_fix]['quantity'] += (int) $quantity_fix;
                         }
                         if ($action < 0) {
                             $datas['variations'][$product->id . '-' . $id_product_attribute_fix]['quantity'] -= (int) $quantity_fix;
                         }
                     }
                 }
             }
             // Price Update
             if (isset($p['noPriceUpdate'])) {
                 $datas['noPriceUpdate'] = $p['noPriceUpdate'];
             }
             $categoryDefaultCache[$product->id_category_default]['percent'] = preg_replace("#%\$#is", "", $categoryDefaultCache[$product->id_category_default]['percent']);
             // Save percent and price discount
             if ($categoryDefaultCache[$product->id_category_default]['percent'] < 0) {
                 $datas['price_original'] = round($price_original, 2);
                 $datas['price_percent'] = round($categoryDefaultCache[$product->id_category_default]['percent']);
             }
             // Load eBay Description
             $features = $product->getFrontFeatures((int) $this->id_lang);
             $featuresHtml = '';
             if (isset($features)) {
                 foreach ($features as $f) {
                     $featuresHtml .= '<b>' . $f['name'] . '</b> : ' . $f['value'] . '<br/>';
                 }
             }
             $datas['description'] = str_replace(array('{DESCRIPTION_SHORT}', '{DESCRIPTION}', '{FEATURES}', '{EBAY_IDENTIFIER}', '{EBAY_SHOP}', '{SLOGAN}', '{PRODUCT_NAME}'), array($datas['description_short'], $datas['description'], $featuresHtml, Configuration::get('EBAY_IDENTIFIER'), Configuration::get('EBAY_SHOP'), '', $product->name), Configuration::get('EBAY_PRODUCT_TEMPLATE'));
             // Export on eBay
             if (count($datas['variations']) > 0) {
                 // Variations Case
                 if ($categoryDefaultCache[$product->id_category_default]['is_multi_sku'] == 1) {
                     // Load eBay Description
                     $datas['description'] = str_replace(array('{MAIN_IMAGE}', '{MEDIUM_IMAGE_1}', '{MEDIUM_IMAGE_2}', '{MEDIUM_IMAGE_3}', '{PRODUCT_PRICE}', '{PRODUCT_PRICE_DISCOUNT}'), array(isset($datas['picturesLarge'][0]) ? '<img src="' . $datas['picturesLarge'][0] . '" class="bodyMainImageProductPrestashop" />' : '', isset($datas['picturesMedium'][1]) ? '<img src="' . $datas['picturesMedium'][1] . '" class="bodyFirstMediumImageProductPrestashop" />' : '', isset($datas['picturesMedium'][2]) ? '<img src="' . $datas['picturesMedium'][2] . '" class="bodyMediumImageProductPrestashop" />' : '', isset($datas['picturesMedium'][3]) ? '<img src="' . $datas['picturesMedium'][3] . '" class="bodyMediumImageProductPrestashop" />' : '', '', ''), $datas['description']);
                     // Multi Sku case
                     // Check if product exists on eBay
                     $itemID = Db::getInstance()->getValue('SELECT `id_product_ref` FROM `' . _DB_PREFIX_ . 'ebay_product` WHERE `id_product` = ' . (int) $product->id);
                     if ($itemID) {
                         // Update
                         $datas['itemID'] = $itemID;
                         if ($ebay->reviseFixedPriceItemMultiSku($datas)) {
                             Db::getInstance()->autoExecute(_DB_PREFIX_ . 'ebay_product', array('date_upd' => pSQL($date)), 'UPDATE', '`id_product_ref` = ' . (int) $itemID);
                         }
                         // if product not on eBay we add it
                         if ($ebay->errorCode == 291) {
                             // We delete from DB and Add it on eBay
                             Db::getInstance()->execute('DELETE FROM `' . _DB_PREFIX_ . 'ebay_product` WHERE `id_product_ref` = \'' . pSQL($datas['itemID']) . '\'');
                             $ebay->addFixedPriceItemMultiSku($datas);
                             if ($ebay->itemID > 0) {
                                 Db::getInstance()->autoExecute(_DB_PREFIX_ . 'ebay_product', array('id_country' => 8, 'id_product' => (int) $product->id, 'id_attribute' => 0, 'id_product_ref' => pSQL($ebay->itemID), 'date_add' => pSQL($date), 'date_upd' => pSQL($date)), 'INSERT');
                             }
                         }
                     } else {
                         // Add
                         $ebay->addFixedPriceItemMultiSku($datas);
                         if ($ebay->itemID > 0) {
                             Db::getInstance()->autoExecute(_DB_PREFIX_ . 'ebay_product', array('id_country' => 8, 'id_product' => (int) $product->id, 'id_attribute' => 0, 'id_product_ref' => pSQL($ebay->itemID), 'date_add' => pSQL($date), 'date_upd' => pSQL($date)), 'INSERT');
                         }
                     }
                 } else {
                     // No Multi Sku case
                     foreach ($datas['variations'] as $v) {
                         $datasTmp = $datas;
                         if (isset($v['pictures']) && count($v['pictures']) > 0) {
                             $datasTmp['pictures'] = $v['pictures'];
                         }
                         if (isset($v['picturesMedium']) && count($v['picturesMedium']) > 0) {
                             $datasTmp['picturesMedium'] = $v['picturesMedium'];
                         }
                         if (isset($v['picturesLarge']) && count($v['picturesLarge']) > 0) {
                             $datasTmp['picturesLarge'] = $v['picturesLarge'];
                         }
                         foreach ($v['variations'] as $vLabel) {
                             $datasTmp['name'] .= ' ' . $vLabel['value'];
                             $datasTmp['attributes'][$vLabel['name']] = $vLabel['value'];
                         }
                         $datasTmp['price'] = $v['price'];
                         if (isset($v['price_original'])) {
                             $datasTmp['price_original'] = $v['price_original'];
                             $datasTmp['price_percent'] = $v['price_percent'];
                         }
                         $datasTmp['quantity'] = $v['quantity'];
                         $datasTmp['id_attribute'] = $v['id_attribute'];
                         unset($datasTmp['variations']);
                         unset($datasTmp['variationsList']);
                         // Load eBay Description
                         $datasTmp['description'] = str_replace(array('{MAIN_IMAGE}', '{MEDIUM_IMAGE_1}', '{MEDIUM_IMAGE_2}', '{MEDIUM_IMAGE_3}', '{PRODUCT_PRICE}', '{PRODUCT_PRICE_DISCOUNT}'), array(isset($datasTmp['picturesLarge'][0]) ? '<img src="' . $datasTmp['picturesLarge'][0] . '" class="bodyMainImageProductPrestashop" />' : '', isset($datasTmp['picturesMedium'][1]) ? '<img src="' . $datasTmp['picturesMedium'][1] . '" class="bodyFirstMediumImageProductPrestashop" />' : '', isset($datasTmp['picturesMedium'][2]) ? '<img src="' . $datasTmp['picturesMedium'][2] . '" class="bodyMediumImageProductPrestashop" />' : '', isset($datasTmp['picturesMedium'][3]) ? '<img src="' . $datasTmp['picturesMedium'][3] . '" class="bodyMediumImageProductPrestashop" />' : '', Tools::displayPrice($datasTmp['price']), isset($datasTmp['price_original']) ? 'au lieu de <del>' . Tools::displayPrice($datasTmp['price_original']) . '</del> (remise de ' . round($datasTmp['price_percent']) . ')' : ''), $datas['description']);
                         $datasTmp['id_product'] = (int) $product->id . '-' . (int) $datasTmp['id_attribute'];
                         // Check if product exists on eBay
                         $itemID = Db::getInstance()->getValue('SELECT `id_product_ref` FROM `' . _DB_PREFIX_ . 'ebay_product` WHERE `id_product` = ' . (int) $product->id . ' AND `id_attribute` = ' . (int) $datasTmp['id_attribute']);
                         if ($itemID) {
                             // Get Item ID
                             $datasTmp['itemID'] = $itemID;
                             // Delete or Update
                             if ($datasTmp['quantity'] < 1) {
                                 // Delete
                                 if ($ebay->endFixedPriceItem($datasTmp)) {
                                     Db::getInstance()->execute('DELETE FROM `' . _DB_PREFIX_ . 'ebay_product` WHERE `id_product_ref` = \'' . pSQL($datasTmp['itemID']) . '\'');
                                 }
                             } else {
                                 // Update
                                 if ($ebay->reviseFixedPriceItem($datasTmp)) {
                                     Db::getInstance()->autoExecute(_DB_PREFIX_ . 'ebay_product', array('date_upd' => pSQL($date)), 'UPDATE', '`id_product_ref` = ' . (int) $itemID);
                                 }
                                 // if product not on eBay we add it
                                 if ($ebay->errorCode == 291) {
                                     // We delete from DB and Add it on eBay
                                     Db::getInstance()->execute('DELETE FROM `' . _DB_PREFIX_ . 'ebay_product` WHERE `id_product_ref` = \'' . pSQL($datasTmp['itemID']) . '\'');
                                     $ebay->addFixedPriceItem($datasTmp);
                                     if ($ebay->itemID > 0) {
                                         Db::getInstance()->autoExecute(_DB_PREFIX_ . 'ebay_product', array('id_country' => 8, 'id_product' => (int) $product->id, 'id_attribute' => (int) $datasTmp['id_attribute'], 'id_product_ref' => pSQL($ebay->itemID), 'date_add' => pSQL($date), 'date_upd' => pSQL($date)), 'INSERT');
                                     }
                                 }
                             }
                         } else {
                             // Add
                             $ebay->addFixedPriceItem($datasTmp);
                             if ($ebay->itemID > 0) {
                                 Db::getInstance()->autoExecute(_DB_PREFIX_ . 'ebay_product', array('id_country' => 8, 'id_product' => (int) $product->id, 'id_attribute' => (int) $datasTmp['id_attribute'], 'id_product_ref' => pSQL($ebay->itemID), 'date_add' => pSQL($date), 'date_upd' => pSQL($date)), 'INSERT');
                             }
                         }
                     }
                 }
             } else {
                 // No variations case
                 // Load eBay Description
                 $datas['description'] = str_replace(array('{MAIN_IMAGE}', '{MEDIUM_IMAGE_1}', '{MEDIUM_IMAGE_2}', '{MEDIUM_IMAGE_3}', '{PRODUCT_PRICE}', '{PRODUCT_PRICE_DISCOUNT}'), array(isset($datas['picturesLarge'][0]) ? '<img src="' . $datas['picturesLarge'][0] . '" class="bodyMainImageProductPrestashop" />' : '', isset($datas['picturesMedium'][1]) ? '<img src="' . $datas['picturesMedium'][1] . '" class="bodyFirstMediumImageProductPrestashop" />' : '', isset($datas['picturesMedium'][2]) ? '<img src="' . $datas['picturesMedium'][2] . '" class="bodyMediumImageProductPrestashop" />' : '', isset($datas['picturesMedium'][3]) ? '<img src="' . $datas['picturesMedium'][3] . '" class="bodyMediumImageProductPrestashop" />' : '', Tools::displayPrice($datas['price']), isset($datas['price_original']) ? 'au lieu de <del>' . Tools::displayPrice($datas['price_original']) . '</del> (remise de ' . round($datas['price_percent']) . ')' : ''), $datas['description']);
                 // Check if product exists on eBay
                 $itemID = Db::getInstance()->getValue('SELECT `id_product_ref` FROM `' . _DB_PREFIX_ . 'ebay_product` WHERE `id_product` = ' . (int) $product->id);
                 if ($itemID) {
                     // Get Item ID
                     $datas['itemID'] = $itemID;
                     // Delete or Update
                     if ($datas['quantity'] < 1) {
                         // Delete
                         if ($ebay->endFixedPriceItem($datas)) {
                             Db::getInstance()->execute('DELETE FROM `' . _DB_PREFIX_ . 'ebay_product` WHERE `id_product_ref` = \'' . pSQL($datas['itemID']) . '\'');
                         }
                     } else {
                         // Update
                         if ($ebay->reviseFixedPriceItem($datas)) {
                             Db::getInstance()->autoExecute(_DB_PREFIX_ . 'ebay_product', array('date_upd' => pSQL($date)), 'UPDATE', '`id_product_ref` = ' . (int) $itemID);
                         }
                         // if product not on eBay we add it
                         if ($ebay->errorCode == 291) {
                             // We delete from DB and Add it on eBay
                             Db::getInstance()->execute('DELETE FROM `' . _DB_PREFIX_ . 'ebay_product` WHERE `id_product_ref` = \'' . pSQL($datas['itemID']) . '\'');
                             $ebay->addFixedPriceItem($datas);
                             if ($ebay->itemID > 0) {
                                 Db::getInstance()->autoExecute(_DB_PREFIX_ . 'ebay_product', array('id_country' => 8, 'id_product' => (int) $product->id, 'id_attribute' => 0, 'id_product_ref' => pSQL($ebay->itemID), 'date_add' => pSQL($date), 'date_upd' => pSQL($date)), 'INSERT');
                             }
                         }
                     }
                 } else {
                     // Add
                     $ebay->addFixedPriceItem($datas);
                     if ($ebay->itemID > 0) {
                         Db::getInstance()->autoExecute(_DB_PREFIX_ . 'ebay_product', array('id_country' => 8, 'id_product' => (int) $product->id, 'id_attribute' => 0, 'id_product_ref' => pSQL($ebay->itemID), 'date_add' => pSQL($date), 'date_upd' => pSQL($date)), 'INSERT');
                     }
                 }
             }
             // Check error
             if (!empty($ebay->error)) {
                 $tab_error[md5($ebay->error)]['msg'] = $ebay->error;
                 if (!isset($tab_error[md5($ebay->error)]['products'])) {
                     $tab_error[md5($ebay->error)]['products'] = array();
                 }
                 if (count($tab_error[md5($ebay->error)]['products']) < 10) {
                     $tab_error[md5($ebay->error)]['products'][] = $datas['name'];
                 }
                 if (count($tab_error[md5($ebay->error)]['products']) == 10) {
                     $tab_error[md5($ebay->error)]['products'][] = '...';
                 }
                 $count_error++;
             } else {
                 $count_success++;
             }
             $count++;
         }
     }
     if ($count_error > 0) {
         file_put_contents(dirname(__FILE__) . '/log/syncError.php', '<?php $tab_error = ' . var_export($tab_error, true) . '; ' . ($ebay->itemConditionError ? '$itemConditionError = true; ' : '$itemConditionError = false;') . ' ?>');
     }
 }
Ejemplo n.º 17
0
 private function _getCSVFileText()
 {
     $link = new Link();
     $schema = '';
     $schema .= $this->quoting . $this->_idealocsv->l('id', 'idealo') . $this->quoting . $this->fieldseparator . $this->quoting . $this->_idealocsv->l('brand', 'idealo') . $this->quoting . $this->fieldseparator . $this->quoting . $this->_idealocsv->l('title', 'idealo') . $this->quoting . $this->fieldseparator . $this->quoting . $this->_idealocsv->l('Category', 'idealo') . $this->quoting . $this->fieldseparator . $this->quoting . $this->_idealocsv->l('Short Description', 'idealo') . $this->quoting . $this->fieldseparator . $this->quoting . $this->_idealocsv->l('description', 'idealo') . $this->quoting . $this->fieldseparator . $this->quoting . $this->_idealocsv->l('image_link', 'idealo') . $this->quoting . $this->fieldseparator . $this->quoting . $this->_idealocsv->l('link', 'idealo') . $this->quoting . $this->fieldseparator . $this->quoting . $this->_idealocsv->l('price', 'idealo') . $this->quoting . $this->fieldseparator . $this->quoting . $this->_idealocsv->l('ean', 'idealo') . $this->quoting . $this->fieldseparator . $this->quoting . $this->_idealocsv->l('availability', 'idealo') . $this->quoting . $this->fieldseparator;
     foreach ($this->shipping as $ship) {
         if ($ship['active'] == '1') {
             foreach ($this->payment as $pay) {
                 if ($pay['active'] == '1') {
                     $schema .= $this->quoting . strtoupper($pay['db']) . '_' . $ship['country'] . $this->quoting . $this->fieldseparator;
                 }
             }
         }
     }
     foreach ($this->shipping as $ship) {
         if ($ship['active'] == '1') {
             $schema .= $this->quoting . $this->_idealocsv->l('shipping', 'idealo') . '_' . $ship['country'] . $this->quoting . $this->fieldseparator;
         }
     }
     $schema .= $this->quoting . $this->_idealocsv->l('shipping_weight', 'idealo') . $this->quoting . $this->fieldseparator . $this->quoting . $this->_idealocsv->l('baseprice', 'idealo') . $this->quoting . $this->fieldseparator . $this->quoting . $this->_idealocsv->l('EAN', 'idealo') . $this->quoting . $this->fieldseparator . $this->quoting . $this->_idealocsv->l('condition', 'idealo') . $this->quoting . $this->fieldseparator . $this->quoting . 'portocomment' . $this->quoting . $this->fieldseparator;
     if ($this->minOrderPrice != '') {
         $schema .= $this->quoting . $this->_idealocsv->l('Small order value surcharge', 'idealo') . $this->quoting . $this->fieldseparator;
     }
     $schema .= $this->quoting . 'Attributes' . $this->quoting . $this->fieldseparator;
     $schema .= "\n";
     setlocale(LC_ALL, 'de_DE');
     $date = date("d.m.y H:i:s");
     $schema .= $this->quoting . sprintf($this->_idealocsv->l('Last file created on %s o\'clock', 'idealo'), $date) . $this->quoting . $this->fieldseparator;
     $schema .= "\n";
     $schema .= sprintf($this->_idealocsv->l('idealo - CSV export-modul V %s for PrestaShop from %s', 'idealo'), IDEALO_MODULE_VERSION, IDEALO_MODULE_DATE);
     $schema .= "\n";
     $article = $this->getArticleNumbers();
     foreach ($article as $a) {
         $product = new Product($a['id_product'], false, $this->id_lang);
         $productlink = $product->getLink();
         if ($this->campaign == '1') {
             $productlink .= CAMPAIGN;
         }
         $cat = $product->getProductCategoriesFull($a['id_product'], $this->id_lang);
         $brand = $this->getBrand($product->id_manufacturer);
         $cat_text = $this->getCatText($cat);
         if ($this->checkFilter($cat_text, $brand, $a['id_product']) === true) {
             $images = $product->getCover($a['id_product']);
             $imagelink = $link->getImageLink($product->link_rewrite[1], $product->id . '-' . $images['id_image'], '');
             $price = number_format($product->getprice(), 2, '.', '');
             $attributeCombinations = $product->getAttributeCombinaisons($this->id_lang);
             if (!empty($attributeCombinations)) {
                 $attributeCombinations = $this->sortAttributeCombinations($attributeCombinations);
                 $taxRate = $this->getTaxRate($product->id_tax_rules_group);
                 $i = 1;
                 foreach ($attributeCombinations as $combination) {
                     if ($combination[0]['quantity'] > 0) {
                         $image = '';
                         $image_id = $this->getImegeLinkOfAtrribute($combination[0]['id_product_attribute']);
                         if ($image_id == 0) {
                             $image = $imagelink;
                         } else {
                             $image = new Image($image_id);
                             $image = _PS_BASE_URL_ . _THEME_PROD_DIR_ . $image->getExistingImgPath() . '.jpg';
                         }
                         $articleId = $a['id_product'] . '_' . $i;
                         $combinationString = $this->getCombinationString($combination);
                         $title = $product->name . ' ' . str_replace(';', ',', $combinationString);
                         $combinationPrice = $price + number_format($combination[0]['price'] * (1 + $taxRate / 100), 2, '.', '');
                         $weight = $product->weight + $combination[0]['weight'];
                         $combinationEan = $combination[0]['ean13'];
                         $schema .= $this->getProductLine($product, $articleId, $brand, $title, $cat_text, $image, $productlink, $combinationPrice, $weight, $combinationString, ${$combinationEan});
                     }
                     $i++;
                     if ($i >= 100) {
                         break;
                     }
                 }
             } else {
                 $schema .= $this->getProductLine($product, $a['id_product'], $brand, $product->name, $cat_text, $imagelink, $productlink, $price, $product->weight);
             }
         }
     }
     return $schema;
 }
Ejemplo n.º 18
0
include dirname(__FILE__) . '/../../../init.php';
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
$now = date("Y-m-d");
$period = Configuration::get('PS_COLLECT_REVIEW_PERIOD_DAY');
$minus = date('Y-m-d', strtotime($now . ' - ' . $period . ' day'));
if ($orders = CollectReview::getAllOrderByDay($minus)) {
    $link = new Link();
    foreach ($orders as $value) {
        $order = new Order($value);
        $customer = new Customer($order->id_customer);
        $emailTo = $customer->email;
        $products_order = $order->getProducts();
        $products = array();
        foreach ($products_order as $item) {
            $cover = Product::getCover($item['product_id']);
            array_push($products, array('name' => $item['product_name'], 'price' => Tools::displayPrice($item['price']), 'quantity' => StockAvailable::getQuantityAvailableByProduct($item['product_id']), 'link' => $link->getProductLink($item['product_id']) . '#reviews', 'image' => $link->getImageLink($item['image']->id, $cover['id_image'], 'large_default')));
        }
        $template = 'collectReview';
        $subject = 'Оставьте отзыв';
        $product_list_html = CollectReview::getEmailTemplateContent('collectReview.tpl', Mail::TYPE_HTML, $products);
        $templateVars = array('{products}' => $product_list_html);
        $admin_mails = Configuration::get('PS_SHOP_EMAIL');
        $te = Mail::Send(1, $template, $subject, $templateVars, $emailTo);
    }
    $r = CollectReview::deactivate($orders);
    echo 'Письма отправлены';
} else {
    echo 'Не кому отправлять письма';
}
Ejemplo n.º 19
0
    public function process()
    {
        parent::process();
        $address = new Address((int) self::$cart->id_address_delivery);
        $country = new Country((int) $address->id_country);
        $current_offer = Db::getInstance()->getValue('
		SELECT c.rateoffer_id
		FROM ' . _DB_PREFIX_ . 'currency c
		WHERE c.iso_code = \'' . pSQL($this->context->cookie->interpay_currency_code) . '\' AND deleted = 0');
        $id_rate = 0;
        if ($current_offer) {
            $id_rate = $current_offer;
        }
        $customer = new Customer((int) self::$cart->id_customer);
        $address_shipping = new Address((int) self::$cart->id_address_delivery);
        $state = new State((int) $address->id_state);
        $link = new Link();
        $products = '';
        $i = 1;
        $cart_currency = new Currency((int) self::$cart->id_currency);
        foreach (self::$cart->getProducts() as $val) {
            $products .= 'itemDescription' . $i . '=' . urlencode($val['name']) . '&';
            // .': '.$val['description_short']
            $products .= 'itemQuantity' . $i . '=' . (int) $val['quantity'] . '&';
            $products .= 'itemUnitPrice' . $i . '=' . (double) number_format($val['price'] / $cart_currency->conversion_rate, 2, '.', '') . '&';
            $products .= 'itemImageURL' . $i . '=' . urlencode('https://' . $link->getImageLink($val['id_product'], $val['id_image'])) . '&';
            $products .= 'itemSkuN' . $i . '=' . '' . '&';
            $products .= 'itemProductId' . $i . '=' . (int) $val['id_product'] . '&';
            $products .= 'itemWeight' . $i . '=' . (double) $val['weight'] . '&';
            $products .= 'itemLength' . $i . '=' . (double) $val['depth'] . '&';
            $products .= 'itemWidth' . $i . '=' . (double) $val['width'] . '&';
            $products .= 'itemHeight' . $i . '=' . (double) $val['height'] . '&';
            $products .= 'itemStatus' . $i . '=' . '' . '&';
            $products .= 'itemCountryOfOrigin' . $i . '=' . '' . '&';
            $products .= 'itemURL' . $i . '=' . '' . '&';
            $i++;
        }
        $discounts = _PS_VERSION_ >= 1.5 ? self::$cart->getCartRules() : self::$cart->getDiscounts();
        foreach ($discounts as $val) {
            $products .= 'itemDescription' . $i . '=' . urlencode($val['name'] . ': ' . $val['description']) . '&';
            $products .= 'itemQuantity' . $i . '=' . (int) $val['quantity'] . '&';
            $products .= 'itemUnitPrice' . $i . '=' . (double) $val['value_real'] . '&';
            $products .= 'itemImageURL' . $i . '=' . '' . '&';
            $products .= 'itemSkuN' . $i . '=' . '' . '&';
            $products .= 'itemProductId' . $i . '=' . 'discount_' . (int) $val['id_cart_rule'] . '&';
            $products .= 'itemWeight' . $i . '=' . '' . '&';
            $products .= 'itemLength' . $i . '=' . '' . '&';
            $products .= 'itemWidth' . $i . '=' . '' . '&';
            $products .= 'itemHeight' . $i . '=' . '' . '&';
            $products .= 'itemStatus' . $i . '=' . '' . '&';
            $products .= 'itemCountryOfOrigin' . $i . '=' . '' . '&';
            $products .= 'itemURL' . $i . '=' . '' . '&';
            $i++;
        }
        self::$cart->id_carrier = (int) Configuration::get('GOINTERPAY_SHIPPING_CARRIER');
        self::$cart->update();
        $carrierPrice = (double) self::$cart->getOrderTotal(true, Cart::ONLY_SHIPPING);
        if ($carrierPrice === false) {
            self::$smarty->assign('error', true);
            return false;
        }
        $account = 'store' . '=' . (int) Configuration::get('GOINTERPAY_STORE') . '&';
        $account .= 'secret' . '=' . urlencode(Configuration::get('GOINTERPAY_SECRET')) . '&';
        $data = 'misc1' . '=' . (int) self::$cart->id . '&';
        $data .= 'misc2' . '=' . (double) $carrierPrice . '&';
        $data .= 'domesticShippingCharge' . '=' . (double) $carrierPrice . '&';
        $data .= 'interpayRateOfferId' . '=' . urlencode($id_rate) . '&';
        $data .= 'customerName' . '=' . urlencode($customer->firstname . ' ' . $customer->lastname) . '&';
        $data .= 'customerCompany' . '=' . urlencode($address->company) . '&';
        $data .= 'customerEmail' . '=' . urlencode($customer->email) . '&';
        $data .= 'customerPhone' . '=' . urlencode($address->phone) . '&';
        $data .= 'CustomerAltPhone' . '=' . urlencode($address->phone_mobile) . '&';
        $data .= 'customerAddress1' . '=' . urlencode($address->address1) . '&';
        $data .= 'customerAddress2' . '=' . urlencode($address->address2) . '&';
        $data .= 'customerCity' . '=' . urlencode($address->city) . '&';
        $data .= 'customerState' . '=' . ($address->id_state ? urlencode($state->name) : '') . '&';
        $data .= 'customerZip' . '=' . urlencode($address->postcode);
        $address_country = new Country((int) $address->id_country);
        if (Validate::isLoadedObject($address_country)) {
            $address_country_iso = $address_country->iso_code;
        }
        $post = $account . $products . $data;
        include_once _PS_MODULE_DIR_ . 'gointerpay/Rest.php';
        $uuid = Rest::getUUID($post);
        if ($uuid) {
            self::$smarty->assign(array('pathInterpaySsl' => _GOINTERPAY_MAIN_URL_ . (isset($address_country_iso) ? '?country=' . $address_country->iso_code : '') . '#Destination', 'store' => (int) Configuration::get('GOINTERPAY_STORE'), 'tempCartUUID' => Tools::safeOutput($uuid), 'country' => urlencode($country->iso_code), 'modulePath' => './'));
        } else {
            self::$smarty->assign('error', 'An error has occured, please try again later.');
        }
    }
Ejemplo n.º 20
0
 /**
  * @param \Payin7\Models\QuoteModel $quote
  * @param null $cart
  * @param bool $full_data
  * @return \Payin7\Models\QuoteModel
  */
 public function prepareCartQuote(\Payin7\Models\QuoteModel $quote = null, $full_data = false, $cart = null)
 {
     /** @var \Payin7\Models\QuoteModel $quote */
     $quote = $quote ? $quote : $this->getModelInstance('quote');
     $cart = $cart ? $cart : $this->context->cart;
     if (!$cart) {
         return null;
     }
     /** @noinspection PhpUndefinedMethodInspection */
     $products = $cart->getProducts();
     /** @noinspection PhpUndefinedClassInspection */
     $carrier = new Carrier($cart->id_carrier);
     /** @noinspection PhpUndefinedClassInspection */
     $cust = new Customer($cart->id_customer);
     /** @noinspection PhpUndefinedMethodInspection */
     $shipping_cost = $this->_is14 ? $cart->getOrderShippingCost() : $cart->getTotalShippingCost(null, true, null);
     // order
     $quote->setQuoteId($cart->id);
     /** @noinspection PhpUndefinedFieldInspection */
     $quote->setCurrencyCode($this->context->currency->iso_code);
     /** @noinspection PhpUndefinedFieldInspection */
     $quote->setShippingMethodCode('carrier_' . (property_exists($carrier, 'id_reference') ? $carrier->id_reference : $carrier->id));
     /** @noinspection PhpUndefinedFieldInspection */
     $quote->setShippingMethodTitle($carrier->name);
     $quote->setCreatedAt($cart->date_add);
     $quote->setUpdatedAt($cart->date_upd);
     $quote->setShippingAmount($this->roundPrice($shipping_cost));
     /** @noinspection PhpUndefinedMethodInspection */
     $quote->setGrandTotal($this->roundPrice($cart->getOrderTotal()));
     $quote->setOrderedItems($products ? count($products) : null);
     /** @noinspection PhpUndefinedFieldInspection */
     $quote->setCustomerIsGuest((bool) $cust->is_guest);
     // billing address
     /** @noinspection PhpUndefinedClassInspection */
     $address = new Address($this->context->cart->id_address_invoice);
     /** @noinspection PhpUndefinedClassInspection */
     /** @noinspection PhpUndefinedFieldInspection */
     $user_state = new State($address->id_state);
     /** @noinspection PhpUndefinedClassInspection */
     /** @noinspection PhpUndefinedFieldInspection */
     $user_country = new Country($address->id_country);
     $billing_addr = $quote->getBillingAddress();
     $billing_addr->setCustomerAddressId($this->context->cart->id_address_invoice);
     /** @noinspection PhpUndefinedFieldInspection */
     $billing_addr->setFirstname($address->firstname);
     /** @noinspection PhpUndefinedFieldInspection */
     $billing_addr->setLastname($address->lastname);
     /** @noinspection PhpUndefinedFieldInspection */
     $billing_addr->setCompany($address->company);
     /** @noinspection PhpUndefinedFieldInspection */
     $billing_addr->setStreet1($address->address1);
     /** @noinspection PhpUndefinedFieldInspection */
     $billing_addr->setStreet2($address->address2);
     /** @noinspection PhpUndefinedFieldInspection */
     $billing_addr->setCity($address->city);
     /** @noinspection PhpUndefinedFieldInspection */
     $billing_addr->setCountry($user_country->iso_code);
     /** @noinspection PhpUndefinedFieldInspection */
     $billing_addr->setCountryState($user_state->name);
     /** @noinspection PhpUndefinedFieldInspection */
     $billing_addr->setPostcode($address->postcode);
     /** @noinspection PhpUndefinedFieldInspection */
     $billing_addr->setTelephone1($address->phone);
     /** @noinspection PhpUndefinedFieldInspection */
     $billing_addr->setTelephone2($address->phone_mobile);
     /** @noinspection PhpUndefinedFieldInspection */
     $billing_addr->setTaxVATNumber($address->vat_number);
     if (!$full_data) {
         return $quote;
     }
     // shipping address
     /** @noinspection PhpUndefinedClassInspection */
     $address = new Address($this->context->cart->id_address_delivery);
     /** @noinspection PhpUndefinedClassInspection */
     /** @noinspection PhpUndefinedFieldInspection */
     $user_state = new State($address->id_state);
     /** @noinspection PhpUndefinedClassInspection */
     /** @noinspection PhpUndefinedFieldInspection */
     $user_country = new Country($address->id_country);
     $shipping_addr = $quote->getShippingAddress();
     $shipping_addr->setCustomerAddressId($this->context->cart->id_address_delivery);
     /** @noinspection PhpUndefinedFieldInspection */
     $shipping_addr->setFirstname($address->firstname);
     /** @noinspection PhpUndefinedFieldInspection */
     $shipping_addr->setLastname($address->lastname);
     /** @noinspection PhpUndefinedFieldInspection */
     $shipping_addr->setCompany($address->company);
     /** @noinspection PhpUndefinedFieldInspection */
     $shipping_addr->setStreet1($address->address1);
     /** @noinspection PhpUndefinedFieldInspection */
     $shipping_addr->setStreet2($address->address2);
     /** @noinspection PhpUndefinedFieldInspection */
     $shipping_addr->setCity($address->city);
     /** @noinspection PhpUndefinedFieldInspection */
     $shipping_addr->setCountry($user_country->iso_code);
     /** @noinspection PhpUndefinedFieldInspection */
     $shipping_addr->setCountryState($user_state->name);
     /** @noinspection PhpUndefinedFieldInspection */
     $shipping_addr->setPostcode($address->postcode);
     /** @noinspection PhpUndefinedFieldInspection */
     $shipping_addr->setTelephone1($address->phone);
     /** @noinspection PhpUndefinedFieldInspection */
     $shipping_addr->setTelephone2($address->phone_mobile);
     /** @noinspection PhpUndefinedFieldInspection */
     $shipping_addr->setTaxVATNumber($address->vat_number);
     // products
     if ($products) {
         foreach ($products as $product) {
             /** @noinspection PhpUndefinedClassInspection */
             $link = new Link();
             /** @noinspection PhpUndefinedMethodInspection */
             $url = $link->getProductLink($product);
             /** @noinspection PhpUndefinedClassInspection */
             /** @noinspection PhpUndefinedMethodInspection */
             $image = Image::getCover($product['id_product']);
             /** @noinspection PhpUndefinedMethodInspection */
             $imagePath = $image ? $link->getImageLink($product['link_rewrite'], $image['id_image'], 'home_default') : null;
             $imagePath = $imagePath ? 'http://' . $imagePath : $imagePath;
             /** @var \Payin7\Models\OrderItemModel $pm */
             $pm = $this->getModelInstance('order_item');
             $pm->setId($product['id_product']);
             $pm->setProductId($product['id_product']);
             $pm->setName($product['name']);
             $pm->setProductUrl($url);
             $pm->setImageUrl($imagePath);
             $pm->setShortDescription(isset($product['description_short']) ? $product['description_short'] : null);
             $pm->setFullDescription(isset($product['attributes']) ? $product['attributes'] : null);
             $pm->setIsVirtual(isset($product['is_virtual']) ? $product['is_virtual'] : null);
             $pm->setQtyOrdered($product['cart_quantity']);
             $pm->setPriceInclTax($this->roundPrice($product['price_wt']));
             $pm->setPrice($this->roundPrice($product['price']));
             $pm->setTaxAmount($product['price_wt'] - $product['price']);
             $pm->setPriceBeforeDiscount($this->roundPrice(isset($product['price_without_reduction']) ? $product['price_without_reduction'] : null));
             $pm->setDiscountAmount($this->roundPrice(isset($product['price_with_reduction_without_tax']) ? $product['price_with_reduction_without_tax'] : null));
             $pm->setDiscountAmountWithTax($this->roundPrice(isset($product['price_with_reduction']) ? $product['price_with_reduction'] : null));
             $pm->setShippingAmountWithTax($this->roundPrice(isset($product['additional_shipping_cost']) ? $product['additional_shipping_cost'] : null));
             $pm->setShippingAmount($this->roundPrice($pm->getShippingAmountWithTax()));
             $pm->setRowTotal($this->roundPrice($product['price']));
             $pm->setRowTotalInclTax($this->roundPrice($product['price_wt']));
             $pm->setTaxRate(isset($product['rate']) ? $product['rate'] : null);
             $quote->addItem($pm);
             unset($product);
         }
     }
     // customer
     /** @noinspection PhpUndefinedClassInspection */
     $cust = new Customer($cart->id_customer);
     /** @noinspection PhpUndefinedClassInspection */
     $custlang = new Language($cart->id_lang);
     /** @noinspection PhpUndefinedFieldInspection */
     $gender = $cust->id_gender == 1 ? \Payin7\Models\CustomerModel::GENDER_MALE : ($cust->id_gender == 2 ? \Payin7\Models\CustomerModel::GENDER_FEMALE : null);
     /** @var \Payin7\Models\CustomerModel $customer */
     $customer = $this->getModelInstance('customer');
     $customer->setCustomerId($cart->id_customer);
     $customer->setGender($gender);
     /** @noinspection PhpUndefinedFieldInspection */
     $customer->setPreferredLanguageCode($custlang->iso_code);
     /** @noinspection PhpUndefinedFieldInspection */
     $customer->setCreatedAt($cust->date_add);
     /** @noinspection PhpUndefinedFieldInspection */
     $customer->setUpdatedAt($cust->date_upd);
     /** @noinspection PhpUndefinedFieldInspection */
     $customer->setDob($cust->birthday);
     /** @noinspection PhpUndefinedFieldInspection */
     $customer->setEmail($cust->email);
     /** @noinspection PhpUndefinedFieldInspection */
     $customer->setFirstName($cust->firstname);
     /** @noinspection PhpUndefinedFieldInspection */
     $customer->setLastName($cust->lastname);
     // missing on 1.4
     if (property_exists($cust, 'company')) {
         /** @noinspection PhpUndefinedFieldInspection */
         $customer->setCompany($cust->company);
     }
     $quote->setCustomer($customer);
     return $quote;
 }
Ejemplo n.º 21
0
    private function _postProcess()
    {
        $link = new Link();
        $defaultLanguage = Configuration::get('PS_LANG_DEFAULT');
        $ruBackup = $_SERVER['REQUEST_URI'];
        $snBackup = $_SERVER['SCRIPT_NAME'];
        $getBackup = $_GET;
        $xml = new SimpleXMLElement('<urlset
			xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
			xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
			xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9
			http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">
		</urlset>');
        $sitemap = $xml->addChild('url');
        $sitemap->addChild('loc', 'http://' . htmlspecialchars($_SERVER['HTTP_HOST'], ENT_COMPAT, 'UTF-8') . __PS_BASE_URI__);
        $sitemap->addChild('priority', '1.00');
        $sitemap->addChild('lastmod', date("Y-m-d"));
        $sitemap->addChild('changefreq', 'daily');
        $cmss = Db::getInstance()->ExecuteS('
		SELECT DISTINCT b.id_cms, cl.link_rewrite, cl.id_lang
		FROM ' . _DB_PREFIX_ . 'block_cms b
		LEFT JOIN ' . _DB_PREFIX_ . 'cms_lang cl ON (b.id_cms = cl.id_cms)
		LEFT JOIN ' . _DB_PREFIX_ . 'lang l ON (cl.id_lang = l.id_lang)
		WHERE l.`active` = 1
		ORDER BY cl.id_cms, cl.id_lang ASC');
        foreach ($cmss as $cms) {
            $sitemap = $xml->addChild('url');
            $tmpLink = $link->getCMSLink($cms['id_cms'], $cms['link_rewrite']);
            $_GET = array('id_cms' => $cms['id_cms']);
            if ($cms['id_lang'] != $defaultLanguage) {
                $_SERVER['REQUEST_URI'] = substr($tmpLink, strpos($tmpLink, __PS_BASE_URI__));
                $_SERVER['SCRIPT_NAME'] = substr($_SERVER['REQUEST_URI'], 0, strpos($_SERVER['REQUEST_URI'], '?'));
                $link = new Link();
                $tmpLink = $link->getLanguageLink(intval($cms['id_lang']));
                $tmpLink = 'http://' . htmlspecialchars($_SERVER['HTTP_HOST'], ENT_COMPAT, 'UTF-8') . $tmpLink;
            }
            $sitemap->addChild('loc', htmlspecialchars($tmpLink));
            $sitemap->addChild('priority', '0.8');
            $sitemap->addChild('changefreq', 'monthly');
        }
        $categories = Db::getInstance()->ExecuteS('
		SELECT c.id_category, c.level_depth, link_rewrite, DATE_FORMAT(IF(date_upd,date_upd,date_add), \'%Y-%m-%d\') AS date_upd, cl.id_lang
		FROM ' . _DB_PREFIX_ . 'category c
		LEFT JOIN ' . _DB_PREFIX_ . 'category_lang cl ON c.id_category = cl.id_category
		LEFT JOIN ' . _DB_PREFIX_ . 'lang l ON cl.id_lang = l.id_lang
		WHERE l.`active` = 1 AND c.`active` = 1 AND c.id_category != 1
		ORDER BY cl.id_category, cl.id_lang ASC');
        foreach ($categories as $category) {
            if (($priority = 0.9 - $category['level_depth'] / 10) < 0.1) {
                $priority = 0.1;
            }
            $sitemap = $xml->addChild('url');
            $tmpLink = $link->getCategoryLink($category['id_category'], $category['link_rewrite']);
            $_GET = array('id_category' => $category['id_category']);
            if ($category['id_lang'] != $defaultLanguage) {
                $_SERVER['REQUEST_URI'] = substr($tmpLink, strpos($tmpLink, __PS_BASE_URI__));
                $_SERVER['SCRIPT_NAME'] = substr($_SERVER['REQUEST_URI'], 0, strpos($_SERVER['REQUEST_URI'], '?'));
                $link = new Link();
                $tmpLink = $link->getLanguageLink(intval($category['id_lang']));
                $tmpLink = 'http://' . htmlspecialchars($_SERVER['HTTP_HOST'], ENT_COMPAT, 'UTF-8') . $tmpLink;
            }
            $sitemap->addChild('loc', htmlspecialchars($tmpLink));
            $sitemap->addChild('priority', $priority);
            $sitemap->addChild('lastmod', substr($category['date_upd'], 0, 10));
            $sitemap->addChild('changefreq', 'weekly');
        }
        $products = Db::getInstance()->ExecuteS('
		SELECT p.id_product, pl.link_rewrite, DATE_FORMAT(IF(date_upd,date_upd,date_add), \'%Y-%m-%d\') AS date_upd, pl.id_lang, cl.`link_rewrite` AS category, ean13, (
			SELECT MIN(level_depth)
			FROM ' . _DB_PREFIX_ . 'product p2
			LEFT JOIN ' . _DB_PREFIX_ . 'category_product cp2 ON p2.id_product = cp2.id_product
			LEFT JOIN ' . _DB_PREFIX_ . 'category c2 ON cp2.id_category = c2.id_category
			WHERE p2.id_product = p.id_product AND p2.`active` = 1 AND c2.`active` = 1) AS level_depth
		FROM ' . _DB_PREFIX_ . 'product p
		LEFT JOIN ' . _DB_PREFIX_ . 'product_lang pl ON p.id_product = pl.id_product
		LEFT JOIN `' . _DB_PREFIX_ . 'category_lang` cl ON (p.`id_category_default` = cl.`id_category` AND pl.`id_lang` = cl.`id_lang`)
		LEFT JOIN ' . _DB_PREFIX_ . 'lang l ON pl.id_lang = l.id_lang
		WHERE l.`active` = 1 AND p.`active` = 1
		ORDER BY pl.id_product, pl.id_lang ASC');
        foreach ($products as $product) {
            if (($priority = 0.7 - $product['level_depth'] / 10) < 0.1) {
                $priority = 0.1;
            }
            $sitemap = $xml->addChild('url');
            $tmpLink = $link->getProductLink($product['id_product'], $product['link_rewrite'], $product['category'], $product['ean13']);
            $_GET = array('id_product' => $product['id_product']);
            if ($product['id_lang'] != $defaultLanguage) {
                $_SERVER['REQUEST_URI'] = substr($tmpLink, strpos($tmpLink, __PS_BASE_URI__));
                $_SERVER['SCRIPT_NAME'] = substr($_SERVER['REQUEST_URI'], 0, strpos($_SERVER['REQUEST_URI'], '?'));
                $link = new Link();
                $tmpLink = $link->getLanguageLink(intval($product['id_lang']));
                $tmpLink = 'http://' . htmlspecialchars($_SERVER['HTTP_HOST'], ENT_COMPAT, 'UTF-8') . $tmpLink;
            }
            $sitemap->addChild('loc', htmlspecialchars($tmpLink));
            $sitemap->addChild('priority', $priority);
            $sitemap->addChild('lastmod', substr($product['date_upd'], 0, 10));
            $sitemap->addChild('changefreq', 'weekly');
        }
        $images = Db::getInstance()->ExecuteS('
		SELECT *
		FROM ' . _DB_PREFIX_ . 'product p
		LEFT JOIN ' . _DB_PREFIX_ . 'image i ON p.id_product = i.id_product
		LEFT JOIN ' . _DB_PREFIX_ . 'image_lang il ON i.id_image = il.id_image AND il.id_lang = ' . intval($defaultLanguage) . '
		WHERE p.`active` = 1
		ORDER BY p.id_product');
        foreach ($images as $image) {
            $sitemap = $xml->addChild('url');
            $tmpLink = 'http://' . htmlspecialchars($_SERVER['HTTP_HOST'], ENT_COMPAT, 'UTF-8') . $link->getImageLink(Tools::link_rewrite($image['legend']), $image['id_product'] . '-' . $image['id_image']);
            $sitemap->addChild('loc', htmlspecialchars($tmpLink));
            $sitemap->addChild('priority', 0.4);
            $sitemap->addChild('lastmod', substr($image['date_upd'], 0, 10));
            $sitemap->addChild('changefreq', 'monthly');
        }
        $xmlString = $xml->asXML();
        $fp = fopen(GSITEMAP_FILE, 'w');
        fwrite($fp, $xmlString, Tools::strlen($xmlString));
        fclose($fp);
        $res = file_exists(GSITEMAP_FILE);
        $this->_html .= '<h3 class="' . ($res ? 'conf confirm' : 'alert error') . '" style="margin-bottom: 20px">';
        $this->_html .= $res ? $this->l('Sitemap file successfully generated') : $this->l('Error while creating sitemap file');
        $this->_html .= '</h3>';
        $_SERVER['REQUEST_URI'] = $ruBackup;
        $_SERVER['SCRIPT_NAME'] = $snBackup;
        $_GET = $getBackup;
    }
 public function postProcess()
 {
     if (Tools::isSubmit('submitExport')) {
         $delimiter = Tools::getValue('export_delimiter');
         $id_lang = Tools::getValue('export_language');
         $id_shop = (int) $this->context->shop->id;
         set_time_limit(0);
         $fileName = 'products_' . date("Y_m_d_H_i_s") . '.csv';
         header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
         header('Content-Description: File Transfer');
         header("Content-type: text/csv");
         header("Content-Disposition: attachment; filename={$fileName}");
         header("Expires: 0");
         header("Pragma: public");
         $f = fopen('php://output', 'w');
         foreach ($this->available_fields as $field => $array) {
             $titles[] = $array['label'];
         }
         fputcsv($f, $titles, $delimiter, '"');
         $export_active = Tools::getValue('export_active') == 0 ? false : true;
         $export_category = Tools::getValue('export_category') == 99999 ? false : Tools::getValue('export_category');
         $products = Product::getProducts($id_lang, 0, 0, 'id_product', 'ASC', $export_category, $export_active);
         foreach ($products as $product) {
             $line = array();
             $p = new Product($product['id_product'], true, $id_lang, $id_shop);
             $p->loadStockData();
             foreach ($this->available_fields as $field => $array) {
                 if (isset($p->{$field}) && !is_array($p->{$field})) {
                     $line[$field] = $p->{$field} ? $p->{$field} : ' ';
                 } else {
                     switch ($field) {
                         case 'categories':
                             $cats = $p->getProductCategoriesFull($p->id, $id_lang);
                             $cat_array = array();
                             foreach ($cats as $cat) {
                                 $cat_array[] = $cat['name'];
                             }
                             $line['categories'] = implode(",", $cat_array);
                             break;
                         case 'price_tex':
                             $line['price_tex'] = $p->getPrice(false);
                             $line['price_tin'] = $p->getPrice(true);
                             break;
                         case 'upc':
                             $line['upc'] = $p->upc ? $p->upc : ' ';
                             break;
                         case 'features':
                             $line['features'] = '';
                             $features = $p->getFrontFeatures($id_lang);
                             $position = 1;
                             foreach ($features as $feature) {
                                 $line['features'] .= $feature['name'] . ':' . $feature['value'] . ':' . $position;
                                 $position++;
                             }
                             break;
                         case 'reduction_price':
                             $specificPrice = SpecificPrice::getSpecificPrice($p->id, $id_shop, 0, 0, 0, 0);
                             $line['reduction_price'] = '';
                             $line['reduction_percent'] = '';
                             $line['reduction_from'] = '';
                             $line['reduction_to'] = '';
                             if ($specificPrice['reduction_type'] == "amount") {
                                 $line['reduction_price'] = $specificPrice['reduction'];
                             } elseif ($specificPrice['reduction_type'] == "percent") {
                                 $line['reduction_percent'] = $specificPrice['reduction'];
                             }
                             if ($line['reduction_price'] !== '' || $line['reduction_percent'] !== '') {
                                 $line['reduction_from'] = date_format(date_create($specificPrice['from']), "Y-m-d");
                                 $line['reduction_to'] = date_format(date_create($specificPrice['to']), "Y-m-d");
                             }
                             break;
                         case 'tags':
                             $tags = $p->getTags($id_lang);
                             $line['tags'] = $tags;
                             break;
                         case 'image':
                             $link = new Link();
                             $imagelinks = array();
                             $images = $p->getImages($id_lang);
                             foreach ($images as $image) {
                                 $imagelinks[] = Tools::getShopProtocol() . $link->getImageLink($p->link_rewrite, $p->id . '-' . $image['id_image']);
                             }
                             $line['image'] = implode(",", $imagelinks);
                             break;
                         case 'delete_existing_images':
                             $line['delete_existing_images'] = 0;
                             break;
                         case 'shop':
                             $line['shop'] = $id_shop;
                             break;
                         case 'warehouse':
                             $warehouses = Warehouse::getWarehousesByProductId($p->id);
                             $line['warehouse'] = '';
                             if (!empty($warehouses)) {
                                 $line['warehouse'] = implode(',', array_map("{$this->getWarehouses}", $warehouses));
                             }
                             break;
                         case 'date_added':
                             $date = new DateTime($p->date_add);
                             $line['date_add'] = $date->format("Y-m-d");
                             break;
                     }
                 }
             }
             if (!$line[$field]) {
                 $line[$field] = '';
             }
             fputcsv($f, $line, $delimiter, '"');
         }
         fclose($f);
         die;
     }
 }
Ejemplo n.º 23
0
 private function _addSitemapNodeImage($xml, $product)
 {
     $link = new Link();
     $image = $xml->addChild('image', null, 'http://www.google.com/schemas/sitemap-image/1.1');
     $image->addChild('loc', $link->getImageLink($product['link_rewrite'], (int) $product['id_product'] . '-' . (int) $product['id_image']), 'http://www.google.com/schemas/sitemap-image/1.1');
     $image->addChild('caption', $product['legend_image'], 'http://www.google.com/schemas/sitemap-image/1.1');
     $image->addChild('title', $product['legend_image'], 'http://www.google.com/schemas/sitemap-image/1.1');
 }
Ejemplo n.º 24
0
 public static function indexation($id_product = false, $update = false)
 {
     $id_lang = Cmsearch::getLangId();
     $convermax = new ConvermaxAPI();
     if (!$id_product) {
         if (!$convermax->batchStart()) {
             return false;
         }
     }
     $start = 0;
     while ($products = Cmsearch::getProductsToIndex($id_lang, $start, 200, $id_product)) {
         $start = $start + 200;
         if (count($products) == 0) {
             break;
         }
         $products_array = array();
         $products_count = count($products);
         for ($i = 0; $i < $products_count; $i++) {
             if ($products[$i]['features']) {
                 foreach ($products[$i]['features'] as $feature) {
                     $f_name = 'f_' . $convermax->sanitize($feature['name']);
                     $products[$i][$f_name][] = $feature['value'];
                 }
                 unset($products[$i]['features']);
             }
             foreach ($products[$i] as $key => $val) {
                 if (is_array($val)) {
                     foreach ($val as $k => $v) {
                         if (is_array($v)) {
                             unset($products[$i][$key]);
                         }
                     }
                 }
             }
             $img_id = Product::getCover($products[$i]['id_product']);
             $link = new Link();
             $img_link = $link->getImageLink($products[$i]['link_rewrite'], $img_id['id_image'], ImageType::getFormatedName('small'));
             $products[$i]['img_link'] = str_replace(Tools::getHttpHost(), '', $img_link);
             $products[$i]['link'] = str_replace(Tools::getHttpHost(true), '', $products[$i]['link']);
             $cat_full = Product::getProductCategoriesFull($products[$i]['id_product']);
             $category_full = array();
             $home_category = Configuration::get('PS_HOME_CATEGORY');
             foreach ($cat_full as $cat) {
                 $category = new Category($cat['id_category']);
                 $categories = $category->getParentsCategories();
                 $c_full = array();
                 foreach ($categories as $cats) {
                     if ($cats['id_category'] != $home_category) {
                         $c_full[] = $cats['name'];
                     }
                 }
                 if (!empty($c_full)) {
                     $category_full[] = implode('>', array_reverse($c_full));
                 }
             }
             $products[$i]['category_full'] = $category_full;
             $attributes = Product::getAttributesInformationsByProduct($products[$i]['id_product']);
             if (!empty($attributes)) {
                 foreach ($attributes as $attribute) {
                     $a_name = 'a_' . $convermax->sanitize($attribute['group']);
                     $products[$i][$a_name][] = $attribute['attribute'];
                 }
             }
             if (!in_array($products[$i]['id_product'], $products_array)) {
                 $products_array[] = (int) $products[$i]['id_product'];
             }
         }
         if ($update) {
             if (!$convermax->update($products)) {
                 return false;
             }
         } elseif ($id_product) {
             if (!$convermax->add($products)) {
                 return false;
             }
         } elseif (!$convermax->batchAdd($products)) {
             return false;
         }
         if ($id_product) {
             break;
         }
     }
     if (!$id_product) {
         if (!$convermax->batchEnd()) {
             return false;
         }
     }
     return true;
 }
 protected function getFormattedProducts($cartId)
 {
     $formattedProducts = array();
     $link = new Link();
     $cart = new CartCore($cartId);
     $products = $cart->getProducts();
     $currencyId = (int) Configuration::get('PS_CURRENCY_DEFAULT');
     foreach ($products as $product) {
         $formattedProducts[] = array('name' => $product['name'], 'description' => strip_tags($product['description_short']), 'thumbnail' => 'http://' . $link->getImageLink($product['link_rewrite'], $product['id_image'], 'home_default'), 'quantity' => $product['quantity'], 'price' => Tools::displayPrice($product['price_wt'], $currencyId));
     }
     return $formattedProducts;
 }
Ejemplo n.º 26
0
 protected function getImageObj($divaProduct, $sku)
 {
     $id_product = $sku["id_product"];
     $id_sku = $sku["id_sku"];
     $is_parent = $sku["is_parent"];
     $has_children = empty($sku["attribute"]) ? false : true;
     $size = empty($sku["attribute"]) ? "One Size" : $sku["attribute"]["attribute_name"];
     global $protocol_content;
     $protocol_content = (isset($useSSL) and $useSSL and Configuration::get('PS_SSL_ENABLED')) ? 'https://' : 'http://';
     $link = new Link();
     $imageDataArray = array();
     $imageData = new MarketplaceWebService_XML_Data_Image();
     $imageData->setSKU($id_sku);
     $imageData->setImageType('Main');
     $idImage = $divaProduct->getCoverWs();
     if ($idImage) {
         $idImage = $divaProduct->id . '-' . $idImage;
     } else {
         $idImage = Language::getIsoById(1) . '-default';
     }
     $mainImage = $link->getImageLink($divaProduct->link_rewrite, $idImage, 'thickbox');
     $imageData->setImageLocation($mainImage);
     array_push($imageDataArray, $imageData);
     $c = 1;
     $images = $divaProduct->getImages(1);
     foreach ($images as $image) {
         $oImage = $link->getImageLink($divaProduct->link_rewrite, $image['id_image'], 'thickbox');
         if ($mainImage !== $oImage) {
             $imageData = new MarketplaceWebService_XML_Data_Image();
             $imageData->setSKU($id_sku);
             $imageData->setImageType('PT' . $c++);
             $imageData->setImageLocation($oImage);
             array_push($imageDataArray, $imageData);
         }
     }
     return $imageDataArray;
 }
 /**
  * @param \Product $product
  *
  * @return string
  * @throws \Exception
  * @author Panagiotis Vagenas <*****@*****.**>
  * @since 150213
  */
 protected function getProductImageLink(\Product &$product)
 {
     $link = new \Link();
     $imageLink = null;
     if ($this->Options->getValue('map_image') == 1) {
         $images = $product->getImages($this->defaultLang);
         if (!empty($images)) {
             shuffle($images);
             $imageLink = $link->getImageLink($product->link_rewrite, end($images)['id_image']);
         }
     } else {
         $coverImage = \Image::getCover($product->id);
         if ($coverImage && !empty($coverImage) && isset($coverImage['id_image'])) {
             $imageLink = $link->getImageLink($product->link_rewrite, $coverImage['id_image']);
         }
     }
     return empty($imageLink) ? '' : urldecode($this->addHttp($imageLink));
 }
Ejemplo n.º 28
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);
}
Ejemplo n.º 29
0
 /**
  * @param Product $product to get the product properties
  * @param array $combination to get particular properties from a declination
  * @param int $lang id lang to take all text in good language
  * @param Link $link to set the link of the product and its images.
  * @param Carrier $carrier not used now, but usable for next version, needed for calculate the shipping cost,
  * 		  But for now it's not sure enough.
  * @return array with good value for the XML.
  */
 private function preparedValues(Product $product, $combination, $lang, Link $link, Carrier $carrier)
 {
     $arr_return = array();
     $str_features = array();
     $model = array();
     $version = str_replace('.', '', _PS_VERSION_);
     // To build description and model tags.
     if (isset($combination['attributes'])) {
         foreach ($combination['attributes'] as $attribut) {
             $str_features[] = $attribut['group_name'] . ' : ' . $attribut['name'];
             $model[] = $attribut['name'];
         }
     }
     if (isset($combination['weight']) && (int) $combination['weight'] !== 0) {
         $str_features[] = 'weight : ' . $combination['weight'];
     } elseif ($product->weight !== 0) {
         $str_features[] = 'weight : ' . $product->weight;
     }
     $features = $product->getFrontFeatures($lang);
     foreach ($features as $feature) {
         $str_features[] = $feature['name'] . ' : ' . $feature['value'];
     }
     // Category tag
     $category = new Category((int) $product->id_category_default, $lang);
     $category_path = (isset($category->id) and $category->id) ? Tools::getFullPath((int) $category->id, $product->name[$lang]) : Tools::getFullPath((int) $product->id_category_default, $product->name[$lang]);
     $category_path = Configuration::get('PS_NAVIGATION_PIPE') != false && Configuration::get('PS_NAVIGATION_PIPE') !== '>' ? str_replace(Configuration::get('PS_NAVIGATION_PIPE'), '>', $category_path) : $category_path;
     // image tag
     $id_image = isset($combination['id_image']) ? $combination['id_image'] : 0;
     if ($id_image === 0 || $id_image < 0) {
         $image = $product->getCover((int) $product->id);
         $id_image = $image['id_image'];
     }
     $quantity = Product::getQuantity($product->id, isset($combination['id_combination']) ? $combination['id_combination'] : NULL);
     $condition = '';
     if (strlen((string) $version) < 2) {
         $version = (string) $version . '0';
     }
     if ((int) substr($version, 0, 2) >= 14) {
         $condition = $product->condition === 'new' ? 0 : 1;
     }
     $price = $product->getPrice(true, isset($combination['id_combination']) ? $combination['id_combination'] : NULL, 2);
     $upc_ean = strlen((string) $product->ean13) == 13 ? $product->ean13 : '';
     $arr_return['product_url'] = $link->getProductLink((int) $product->id, $product->link_rewrite[$lang], $product->ean13, $lang);
     $arr_return['designation'] = Tools::htmlentitiesUTF8($product->name[$lang] . ' ' . Manufacturer::getNameById($product->id_manufacturer) . ' ' . implode(' ', $model));
     $arr_return['price'] = $price;
     $arr_return['category'] = Tools::htmlentitiesUTF8(strip_tags($category_path));
     if (substr(_PS_VERSION_, 0, 3) == '1.3') {
         if (!Configuration::get('PS_SHOP_DOMAIN')) {
             Configuration::updateValue('PS_SHOP_DOMAIN', $_SERVER['HTTP_HOST']);
         }
         $prefix = 'http://' . Configuration::get('PS_SHOP_DOMAIN') . '/';
         $arr_return['image_url'] = $prefix . $link->getImageLink('', $product->id . '-' . $id_image, 'large');
     } else {
         $arr_return['image_url'] = $link->getImageLink($product->link_rewrite[$lang], $product->id . '-' . $id_image, 'large');
     }
     // Must description added since Twenga-module v1.1
     $arr_return['description'] = is_array($product->description) ? strip_tags($product->description[$lang]) : strip_tags($product->description);
     $arr_return['description'] = trim($arr_return['description'] . ' ' . strip_tags(implode(', ', $str_features)));
     $arr_return['description'] = Tools::htmlentitiesUTF8($arr_return['description']);
     $arr_return['brand'] = Manufacturer::getNameById($product->id_manufacturer);
     $arr_return['merchant_id'] = $product->id;
     $arr_return['manufacturer_id'] = $product->id_manufacturer;
     $arr_return['shipping_cost'] = 'NC';
     $arr_return['in_stock'] = $quantity > 0 ? 'Y' : 'N';
     $arr_return['stock_detail'] = $quantity;
     $arr_return['condition'] = $condition;
     $arr_return['upc_ean'] = $upc_ean;
     $arr_return['eco_tax'] = $product->ecotax;
     // for prestashop 1.4 and previous version these fields are not managed.
     // So default values are set.
     $arr_return['product_type'] = '1';
     $arr_return['isbn'] = '';
     return $arr_return;
 }
Ejemplo n.º 30
0
 public function postProduct($iId, $type, $id_attribute = 0, $title = '', $overrideCategories = false)
 {
     $mResult = false;
     $product = new Product((int) $iId, true, (int) $this->_configuration['FBWALLPOSTS_LANG_ID']);
     if ($product && Validate::isLoadedObject($product)) {
         // use case - post in FB now for active product or forced product
         if ($product->active || $overrideCategories) {
             if (!$overrideCategories) {
                 if (!$this->productIsInModuleCategories((int) $product->id)) {
                     return $mResult;
                 }
             }
             if (version_compare(_PS_VERSION_, '1.5', '>')) {
                 $link = Context::getContext()->link;
             } else {
                 $link = new Link();
             }
             /* Image */
             $image = Image::getCover((int) $product->id);
             if ($image) {
                 if ($this->_configuration['FBWALLPOSTS_IMG_SIZE']) {
                     $image_link = $link->getImageLink($product->link_rewrite, (int) $product->id . '-' . (int) $image['id_image'], $this->_configuration['FBWALLPOSTS_IMG_SIZE']);
                 } else {
                     $image_link = $link->getImageLink($product->link_rewrite, (int) $product->id . '-' . (int) $image['id_image']);
                 }
                 /* Before version 1.4 */
                 if (strpos($image_link, 'http://') === FALSE && strpos($image_link, 'https://') === FALSE && version_compare(_PS_VERSION_, '1.4', '<')) {
                     $image_link = 'http://' . $_SERVER['HTTP_HOST'] . $image_link;
                 }
             } else {
                 $image_link = false;
             }
             /* Product URL */
             $category = new Category((int) $product->id_category_default, (int) $this->_configuration['FBWALLPOSTS_LANG_ID']);
             if (version_compare(_PS_VERSION_, '1.5.5', '>=')) {
                 $product_url = $link->getProductLink((int) $product->id, null, null, null, (int) $this->_configuration['FBWALLPOSTS_LANG_ID'], null, 0, false);
             } elseif (version_compare(_PS_VERSION_, '1.5', '>')) {
                 if (Configuration::get('PS_REWRITING_SETTINGS')) {
                     $product_url = $link->getProductLink((int) $product->id, null, null, null, (int) $this->_configuration['FBWALLPOSTS_LANG_ID'], null, 0, true);
                 } else {
                     $product_url = $link->getProductLink((int) $product->id, null, null, null, (int) $this->_configuration['FBWALLPOSTS_LANG_ID'], null, 0, false);
                 }
             } else {
                 $product_url = $link->getProductLink((int) $product->id, $product->link_rewrite, $category->link_rewrite, $product->ean13, (int) $this->_configuration['FBWALLPOSTS_LANG_ID']);
             }
             /* Product description */
             $product_description = strip_tags($product->{$this->_configuration['FBWALLPOSTS_P_DESCR_TYPE']});
             if ($type == 'free') {
                 $mResult = $this->createFBPost($title, $product->name, $product_url, $product_description, $image_link);
             } elseif ($type == 'new') {
                 $mResult = $this->createFBPost($this->_configuration['FBWALLPOSTS_NEW_PROD_TXT'], $product->name, $product_url, $product_description, $image_link);
             } elseif ($type == 'stock' && (int) $id_attribute == 0) {
                 $this->deleteProductFromOOS((int) $product->id, 0);
                 $mResult = $this->createFBPost($this->_configuration['FBWALLPOSTS_STOCK_PROD_TXT'], $product->name, $product_url, $product_description, $image_link);
             } elseif ($type == 'stock' && (int) $id_attribute != 0) {
                 // Version 1.x to 1.4
                 if (version_compare(_PS_VERSION_, '1.5', '<')) {
                     /* Attribute names */
                     if (Tools::getValue('attribute_combinaison_list') || Tools::getValue('attribute_combination_list')) {
                         if (Tools::getValue('attribute_combinaison_list')) {
                             $combo_list = Tools::getValue('attribute_combinaison_list');
                         } elseif (Tools::getValue('attribute_combination_list')) {
                             $combo_list = Tools::getValue('attribute_combination_list');
                         }
                         $attributes_txt = ' -';
                         $combo_labels = $this->getProductComboAttributes($combo_list, (int) $this->_configuration['FBWALLPOSTS_LANG_ID']);
                         if ($combo_labels && is_array($combo_labels) && sizeof($combo_labels)) {
                             foreach ($combo_labels as $c) {
                                 $attributes_txt .= ' ' . stripslashes($c['name']);
                             }
                         }
                     } else {
                         $attributes_txt = '';
                     }
                 } else {
                     /* Attribute names */
                     $attributes_txt = ' -';
                     $combination = new Combination((int) $id_attribute);
                     $combo_labels = $combination->getAttributesName((int) $this->_configuration['FBWALLPOSTS_LANG_ID']);
                     if ($combo_labels && is_array($combo_labels) && sizeof($combo_labels)) {
                         foreach ($combo_labels as $c) {
                             $attributes_txt .= ' ' . stripslashes($c['name']);
                         }
                     } else {
                         $attributes_txt = '';
                     }
                 }
                 $this->deleteProductFromOOS((int) $product->id, (int) $id_attribute);
                 $mResult = $this->createFBPost($this->_configuration['FBWALLPOSTS_STOCK_PROD_TXT'], $product->name . $attributes_txt, $product_url, $product_description, $image_link);
             }
         }
     }
     unset($product);
     return $mResult;
 }