Example #1
0
 public function displayContent($params)
 {
     $alias_shop = (int) Tools::getValue('ash');
     if (!empty($alias_shop)) {
         $_s = AphStore::getByAlias($alias_shop, Context::getContext()->language->id);
         $id_shop = $_s['id_shop'];
     } else {
         $id_shop = (int) Tools::getValue('ids');
     }
     $shop = new AphStore($id_shop, Context::getContext()->language->id);
     $this->nbOffers = AphOffer::getOffers('store', $id_shop, Context::getContext()->language->id, true, NULL, (int) Configuration::get('APH_OFFERS_PER_PAGE'), $this->orderBy, $this->orderWay, true);
     $this->pagination((int) $this->nbOffers);
     // Pagination must be call after "getStoresByProduct"
     $this->offerSort();
     $id_currency = Validate::isLoadedObject(Context::getContext()->currency) ? (int) Context::getContext()->currency->id : (int) Configuration::get('PS_CURRENCY_DEFAULT');
     $offers = AphOffer::getOffers('store', $id_shop, Context::getContext()->language->id, true, NULL, (int) Configuration::get('APH_OFFERS_PER_PAGE'), $this->orderBy, $this->orderWay);
     foreach ($offers as &$offer) {
         $offer = new AphOffer($offer['id_offer'], (int) Context::getContext()->language->id, (int) $id_shop);
         $offer['price_from'] = Tools::displayPrice($offer->price_wt, $id_currency);
         error_log($o->reduction . ' ' . $o->id);
         $offer['new_price'] = $o->price_wt < 0 ? $o->reduction_type == 'percentage' ? '-' . intval(round($o->reduction)) . '%' : '-' . Tools::displayPrice($o['reduction'], (int) Context::getContext()->currency->id) : Tools::displayPrice($o->price_wt, (int) Context::getContext()->currency->id) . ' ';
         $offer['url'] = Context::getContext()->link->getModuleLink('blockoffers', 'offer', array('aof' => $offer['link_rewrite'], 'ido' => $offer['id_offer']));
         $offer['img_link_rewrite'] = Tools::link_rewrite($offer['legend']);
     }
     $this->context->smarty->assign(array('offers' => $offers, 'nb_offers' => $this->nbOffers));
     $this->context->controller->addJS($this->_path . 'blockoffer.js');
     return $this->display(__FILE__, 'blockoffers.tpl', $this->getCacheId());
 }
    /**
     * Permet de récupérer le code_iso d'une langue à partir d'un nom de dossier
     * @param string $sFolderName
     * @return array
     */
    public static function getIsoCodeByFolderName($sFolderName)
    {
        $sSQL = '
			SELECT l.`iso_code`
			FROM `' . _DB_PREFIX_ . 'now_language_link` ll
			' . Shop::addSqlAssociation('now_language_link', 'll') . '
			INNER JOIN `' . _DB_PREFIX_ . 'lang` l ON (l.`id_lang` = ll.`id_lang`)
			WHERE ll.`folder_name` = "' . Tools::link_rewrite($sFolderName) . '"';
        $result = Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue($sSQL);
        return $result;
    }
Example #3
0
 public function initContent()
 {
     parent::initContent();
     $shop = NULL;
     $alias_offer = (int) Tools::getValue('aof');
     if (!empty($alias_offer)) {
         $_o = AphOffer::getByAlias($alias_offer, Context::getContext()->language->id);
         $id_offer = $_o['id_offer'];
     } else {
         $id_offer = (int) Tools::getValue('ido');
     }
     $offer = new AphOffer($id_offer, Context::getContext()->language->id);
     $offer->new_price = $offer->price_wt < 0 ? $offer->reduction_type == 'percentage' ? '-' . intval($offer->reduction * 100) . '%' : '-' . Tools::displayPrice($offer['reduction'], (int) Context::getContext()->currency->id) : Tools::displayPrice($offer->price_wt, (int) Context::getContext()->currency->id) . ' ';
     $cover = NULL;
     $images = AphOfferImage::getImages(Context::getContext()->language->id, $id_offer);
     foreach ($images as &$image) {
         if (!empty($image['cover'])) {
             $cover = $image;
         }
     }
     if (empty($cover) && !empty($images)) {
         $cover = $images[0];
     }
     $this->context->smarty->tpl_vars['meta_title']->value = $offer->name;
     $this->context->smarty->tpl_vars['meta_description']->value = $offer->meta_description;
     $shops = AphOffer::getShopsLight(Context::getContext()->language->id, $offer->id);
     foreach ($shops as &$shop) {
         $shop['link'] = Context::getContext()->link->getModuleLink('blockshops', 'shop', array('ash' => $shop['uri'], 'ids' => $shop['id_shop']));
     }
     /*$products = AphOffer::getProductsLight(Context::getContext()->language->id, $offer->id);
     		foreach ($products as &$product) {
     			$product['link'] = Context::getContext()->link->getProductLink((int)$product['id_product'], $product['link_rewrite']);
     		}*/
     $products_by_category = array();
     $ps = AphOffer::getProductsLight(Context::getContext()->language->id, $offer->id);
     foreach ($ps as &$p) {
         $product = new Product($p['id_product'], false, Context::getContext()->language->id);
         $category = new Category($product->id_category_default, Context::getContext()->language->id);
         if (empty($products_by_category[$category->id])) {
             $products_by_category[$category->id] = array('id_category' => $category->id, 'name' => $category->name, 'class' => Tools::link_rewrite($category->name), 'products' => array());
         }
         $products_by_category[$category->id]['products'][$product->id] = array('id_product' => $product->id, 'name' => $product->name, 'link' => Context::getContext()->link->getProductLink((int) $product->id, $product->link_rewrite, $category->id, $product->ean13));
     }
     $this->context->smarty->assign(array('offer' => $offer, 'cover' => $cover, 'images' => $images, 'shops' => $shops, 'products_by_category' => $products_by_category));
     $this->setTemplate('offer.tpl');
 }
Example #4
0
 public function initContent()
 {
     parent::initContent();
     $shop = NULL;
     $alias_shop = (int) Tools::getValue('ash');
     if (!empty($alias_shop)) {
         $_s = AphStore::getByAlias($alias_shop, Context::getContext()->language->id);
         $id_shop = $_s['id_shop'];
     } else {
         $id_shop = (int) Tools::getValue('ids');
     }
     $shop = new AphStore($id_shop, Context::getContext()->language->id);
     $cover = NULL;
     $images = AphStoreImage::getImages(Context::getContext()->language->id, $id_shop);
     foreach ($images as &$image) {
         if (!empty($image['cover'])) {
             $cover = $image;
         }
     }
     if (empty($cover) && !empty($images)) {
         $cover = $images[0];
     }
     $this->context->smarty->tpl_vars['meta_title']->value = $shop->name;
     $this->context->smarty->tpl_vars['meta_description']->value = $shop->meta_description;
     $products_by_category = array();
     $categories = Category::getAllCategoriesName(NULL, Context::getContext()->language->id, true);
     if (!empty($categories)) {
         foreach ($categories as &$category) {
             if (Configuration::get('PS_ROOT_CATEGORY') == $category['id_category'] || Configuration::get('PS_HOME_CATEGORY') == $category['id_category']) {
                 continue;
             }
             $products = AphStore::getProductsByStore($id_shop, Context::getContext()->language->id, NULL, NULL, 'name', 'desc', $category['id_category'], true);
             foreach ($products as &$product) {
                 if (empty($products_by_category[$category['id_category']])) {
                     $products_by_category[$category['id_category']] = array('id_category' => $category['id_category'], 'name' => $category['name'], 'class' => Tools::link_rewrite($category['name']), 'products' => array());
                 }
                 $products_by_category[$category['id_category']]['products'][$product['id_product']] = array('id_product' => $product['id_product'], 'name' => $product['name'], 'link' => Context::getContext()->link->getProductLink((int) $product['id_product'], $product['link_rewrite'], $category['id_category'], $product['ean13']));
             }
         }
     }
     $this->context->smarty->assign(array('shop' => $shop, 'cover' => $cover, 'images' => $images, 'products_by_category' => $products_by_category));
     $this->context->controller->addCSS('/themes/aphrodinet/css/shop.css', 'all');
     $this->setTemplate('shop.tpl');
 }
Example #5
0
 public function initContent()
 {
     parent::initContent();
     $this->module->nbOffers = AphOffer::getOffers(NULL, NULL, Context::getContext()->language->id, true, NULL, (int) Configuration::get('APH_OFFERS_PER_PAGE'), $this->module->orderBy, $this->module->orderWay, true);
     $this->module->pagination((int) $this->module->nbOffers);
     // Pagination must be call after "getStoresByProduct"
     $this->module->offerSort();
     $id_currency = Validate::isLoadedObject(Context::getContext()->currency) ? (int) Context::getContext()->currency->id : (int) Configuration::get('PS_CURRENCY_DEFAULT');
     $offers = AphOffer::getOffers(NULL, NULL, Context::getContext()->language->id, true, NULL, (int) Configuration::get('APH_OFFERS_PER_PAGE'), $this->module->orderBy, $this->module->orderWay);
     foreach ($offers as &$offer) {
         $o = new AphOffer($offer['id_offer'], (int) Context::getContext()->language->id, (int) $id_shop);
         $offer['description_short'] = $o->description_short;
         $offer['available_from_date'] = $o->available_from_date;
         $offer['available_to_date'] = $o->available_to_date;
         $offer['price_from'] = Tools::displayPrice($o->price_wt, $id_currency);
         $offer['new_price'] = $o->price_wt < 0 ? $o->reduction_type == 'percentage' ? '-' . intval(round($o->reduction)) . '%' : '-' . Tools::displayPrice($o->reduction, (int) Context::getContext()->currency->id) : Tools::displayPrice($o->price_wt, (int) Context::getContext()->currency->id) . ' ';
         $offer['url'] = Context::getContext()->link->getModuleLink('blockoffers', 'offer', array('aof' => $offer['link_rewrite'], 'ido' => $offer['id_offer']));
         $offer['img_link_rewrite'] = Tools::link_rewrite($offer['legend']);
     }
     $this->context->smarty->assign(array('offers' => $offers, 'nb_offers' => $this->module->nbOffers));
     $this->context->controller->addJS('blockoffers.js');
     $this->setTemplate('blockoffers.tpl');
 }
Example #6
0
 protected function generateCategoriesMenu($categories, $is_children = 0)
 {
     $html = '';
     foreach ($categories as $key => $category) {
         if ($category['level_depth'] > 1) {
             $cat = new Category($category['id_category']);
             $link = Tools::HtmlEntitiesUTF8($cat->getLink());
         } else {
             $link = $this->context->link->getPageLink('index');
         }
         /* Whenever a category is not active we shouldnt display it to customer */
         if ((bool) $category['active'] === false) {
             continue;
         }
         $html .= '<li' . ($this->page_name == 'category' && (int) Tools::getValue('id_category') == (int) $category['id_category'] ? ' class="sfHoverForce ' . Tools::link_rewrite($category['name']) . '"' : ' class="' . Tools::link_rewrite($category['name']) . '"') . '>';
         $html .= '<a href="' . $link . '" title="' . $category['name'] . '"><img src="/themes/aphrodinet/img/menu-icon-' . strtolower($category['name']) . '.png" /><br/>' . $category['name'] . '</a>';
         if (isset($category['children']) && !empty($category['children'])) {
             $html .= '<ul>';
             $html .= $this->generateCategoriesMenu($category['children'], 1);
             if ((int) $category['level_depth'] > 1 && !$is_children) {
                 $files = scandir(_PS_CAT_IMG_DIR_);
                 if (count(preg_grep('/^' . $category['id_category'] . '-([0-9])?_thumb.jpg/i', $files)) > 0) {
                     $html .= '<li class="category-thumbnail">';
                     foreach ($files as $file) {
                         if (preg_match('/^' . $category['id_category'] . '-([0-9])?_thumb.jpg/i', $file) === 1) {
                             $html .= '<div><img src="' . $this->context->link->getMediaLink(_THEME_CAT_DIR_ . $file) . '" alt="' . Tools::SafeOutput($category['name']) . '" title="' . Tools::SafeOutput($category['name']) . '" class="imgm" /></div>';
                         }
                     }
                     $html .= '</li>';
                 }
             }
             $html .= '</ul>';
         }
         $html .= '</li>';
     }
     return $html;
 }
Example #7
0
 public function lower($strIn)
 {
     $strOut = Tools::link_rewrite($strIn);
     return strtolower(str_replace('-', ' ', $strOut));
 }
 public function productImportCreateCat($default_language_id, $category_name, $id_parent_category = null)
 {
     $category_to_create = new Category();
     $shop_is_feature_active = Shop::isFeatureActive();
     if (!$shop_is_feature_active) {
         $category_to_create->id_shop_default = 1;
     } else {
         $category_to_create->id_shop_default = (int) Context::getContext()->shop->id;
     }
     $category_to_create->name = AdminImportController::createMultiLangField(trim($category_name));
     $category_to_create->active = 1;
     $category_to_create->id_parent = (int) $id_parent_category ? (int) $id_parent_category : (int) Configuration::get('PS_HOME_CATEGORY');
     // Default parent is home for unknown category to create
     $category_link_rewrite = Tools::link_rewrite($category_to_create->name[$default_language_id]);
     $category_to_create->link_rewrite = AdminImportController::createMultiLangField($category_link_rewrite);
     if (($field_error = $category_to_create->validateFields(UNFRIENDLY_ERROR, true)) !== true || ($lang_field_error = $category_to_create->validateFieldsLang(UNFRIENDLY_ERROR, true)) !== true || !$category_to_create->add()) {
         $this->errors[] = sprintf($this->trans('%1$s (ID: %2$s) cannot be saved', array(), 'Admin.Parameters.Notification'), $category_to_create->name[$default_language_id], isset($category_to_create->id) && !empty($category_to_create->id) ? $category_to_create->id : 'null');
         if ($field_error !== true || isset($lang_field_error) && $lang_field_error !== true) {
             $this->errors[] = ($field_error !== true ? $field_error : '') . (isset($lang_field_error) && $lang_field_error !== true ? $lang_field_error : '') . Db::getInstance()->getMsgError();
         }
     }
 }
 public function postProcess()
 {
     $SmartBlogPost = new SmartBlogPost();
     $BlogPostCategory = new BlogPostCategory();
     if (Tools::isSubmit('deletesmart_blog_post') && Tools::getValue('id_smart_blog_post') != '') {
         $SmartBlogPost = new SmartBlogPost((int) Tools::getValue('id_smart_blog_post'));
         if (!$SmartBlogPost->delete()) {
             $this->errors[] = Tools::displayError('An error occurred while deleting the object.') . ' <b>' . $this->table . ' (' . Db::getInstance()->getMsgError() . ')</b>';
         } else {
             Hook::exec('actionsbdeletepost', array('SmartBlogPost' => $SmartBlogPost));
             Tools::redirectAdmin($this->context->link->getAdminLink('AdminBlogPost'));
         }
     } elseif (Tools::getValue('deleteImage')) {
         $this->processForceDeleteImage();
         if (Tools::isSubmit('forcedeleteImage')) {
             Tools::redirectAdmin(self::$currentIndex . '&token=' . Tools::getAdminTokenLite('AdminBlogPost') . '&conf=7');
         }
     } elseif (Tools::isSubmit('submitAddsmart_blog_post')) {
         parent::validateRules();
         if (count($this->errors)) {
             return false;
         }
         if (!($id_smart_blog_post = (int) Tools::getValue('id_smart_blog_post'))) {
             $SmartBlogPost = new $SmartBlogPost();
             $id_lang_default = Configuration::get('PS_LANG_DEFAULT');
             $languages = Language::getLanguages(false);
             foreach ($languages as $language) {
                 $title = Tools::link_rewrite(Tools::getValue('meta_title_' . $language['id_lang']));
                 $SmartBlogPost->meta_title[$language['id_lang']] = $title;
                 $SmartBlogPost->meta_keyword[$language['id_lang']] = (string) Tools::getValue('meta_keyword_' . $language['id_lang']);
                 $SmartBlogPost->meta_description[$language['id_lang']] = Tools::getValue('meta_description_' . $language['id_lang']);
                 $SmartBlogPost->short_description[$language['id_lang']] = (string) Tools::getValue('short_description_' . $language['id_lang']);
                 $SmartBlogPost->content[$language['id_lang']] = Tools::getValue('content_' . $language['id_lang']);
                 if (Tools::getValue('link_rewrite_' . $language['id_lang']) == '' && Tools::getValue('link_rewrite_' . $language['id_lang']) == null) {
                     $SmartBlogPost->link_rewrite[$language['id_lang']] = Tools::link_rewrite(Tools::getValue('meta_title_' . $id_lang_default));
                 } else {
                     $SmartBlogPost->link_rewrite[$language['id_lang']] = Tools::link_rewrite(Tools::getValue('link_rewrite_' . $language['id_lang']));
                 }
             }
             $SmartBlogPost->id_parent = Tools::getValue('id_parent');
             $SmartBlogPost->position = 0;
             $SmartBlogPost->active = Tools::getValue('active');
             $SmartBlogPost->id_category = Tools::getValue('id_category');
             $SmartBlogPost->comment_status = Tools::getValue('comment_status');
             $SmartBlogPost->id_author = $this->context->employee->id;
             $SmartBlogPost->created = Date('y-m-d H:i:s');
             $SmartBlogPost->modified = Date('y-m-d H:i:s');
             $SmartBlogPost->available = 1;
             $SmartBlogPost->is_featured = Tools::getValue('is_featured');
             $SmartBlogPost->viewed = 1;
             $SmartBlogPost->post_type = Tools::getValue('post_type');
             if (!$SmartBlogPost->save()) {
                 $this->errors[] = Tools::displayError('An error has occurred: Can\'t save the current object');
             } else {
                 Hook::exec('actionsbnewpost', array('SmartBlogPost' => $SmartBlogPost));
                 $this->updateTags($languages, $SmartBlogPost);
                 $this->processImage($_FILES, $SmartBlogPost->id);
                 Tools::redirectAdmin($this->context->link->getAdminLink('AdminBlogPost'));
             }
         } elseif ($id_smart_blog_post = Tools::getValue('id_smart_blog_post')) {
             $SmartBlogPost = new $SmartBlogPost($id_smart_blog_post);
             $languages = Language::getLanguages(false);
             foreach ($languages as $language) {
                 $title = Tools::link_rewrite(Tools::getValue('meta_title_' . $language['id_lang']));
                 $SmartBlogPost->meta_title[$language['id_lang']] = $title;
                 $SmartBlogPost->meta_keyword[$language['id_lang']] = Tools::getValue('meta_keyword_' . $language['id_lang']);
                 $SmartBlogPost->meta_description[$language['id_lang']] = Tools::getValue('meta_description_' . $language['id_lang']);
                 $SmartBlogPost->short_description[$language['id_lang']] = Tools::getValue('short_description_' . $language['id_lang']);
                 $SmartBlogPost->content[$language['id_lang']] = Tools::getValue('content_' . $language['id_lang']);
                 $SmartBlogPost->link_rewrite[$language['id_lang']] = Tools::link_rewrite(Tools::getValue('link_rewrite_' . $language['id_lang']));
             }
             $SmartBlogPost->is_featured = Tools::getValue('is_featured');
             $SmartBlogPost->id_parent = Tools::getValue('id_parent');
             $SmartBlogPost->active = Tools::getValue('active');
             $SmartBlogPost->id_category = Tools::getValue('id_category');
             $SmartBlogPost->comment_status = Tools::getValue('comment_status');
             $SmartBlogPost->id_author = $this->context->employee->id;
             $SmartBlogPost->modified = Date('y-m-d H:i:s');
             if (!$SmartBlogPost->update()) {
                 $this->errors[] = Tools::displayError('An error occurred while updating an object.') . ' <b>' . $this->table . ' (' . Db::getInstance()->getMsgError() . ')</b>';
             } else {
                 Hook::exec('actionsbupdatepost', array('SmartBlogPost' => $SmartBlogPost));
             }
             $this->updateTags($languages, $SmartBlogPost);
             $this->processImage($_FILES, $SmartBlogPost->id_smart_blog_post);
             Tools::redirectAdmin($this->context->link->getAdminLink('AdminBlogPost'));
         }
     } elseif (Tools::isSubmit('statussmart_blog_post') && Tools::getValue($this->identifier)) {
         if ($this->tabAccess['edit'] === '1') {
             if (Validate::isLoadedObject($object = $this->loadObject())) {
                 if ($object->toggleStatus()) {
                     Hook::exec('actionsbtogglepost', array('SmartBlogPost' => $this->object));
                     $identifier = (int) $object->id_parent ? '&id_smart_blog_post=' . (int) $object->id_parent : '';
                     Tools::redirectAdmin($this->context->link->getAdminLink('AdminBlogPost'));
                 } else {
                     $this->errors[] = Tools::displayError('An error occurred while updating the status.');
                 }
             } else {
                 $this->errors[] = Tools::displayError('An error occurred while updating the status for an object.') . ' <b>' . $this->table . '</b> ' . Tools::displayError('(cannot load object)');
             }
         } else {
             $this->errors[] = Tools::displayError('You do not have permission to edit this.');
         }
     } elseif (Tools::isSubmit('smart_blog_postOrderby') && Tools::isSubmit('smart_blog_postOrderway')) {
         $this->_defaultOrderBy = Tools::getValue('smart_blog_postOrderby');
         $this->_defaultOrderWay = Tools::getValue('smart_blog_postOrderway');
     }
 }
 /**
  * Method processAddAttachments() : Change name of file which are uploaded for this product
  * Rules:
  *      - For the first upload the filename has been : name-of-product.extention
  *      - For the second upload : name-of-product-1.extention
  *      - ...
  *
  * @module now_seo_links
  * @return void
  *
  * @see AdminProductsControllerCore::processAddAttachments()
  */
 public function processAddAttachments()
 {
     $languages = Language::getLanguages(false);
     $is_attachment_name_valid = false;
     foreach ($languages as $language) {
         $attachment_name_lang = Tools::getValue('attachment_name_' . (int) $language['id_lang']);
         if (Tools::strlen($attachment_name_lang) > 0) {
             $is_attachment_name_valid = true;
         }
         if (!Validate::isGenericName(Tools::getValue('attachment_name_' . (int) $language['id_lang']))) {
             $this->errors[] = Tools::displayError('Invalid Name');
         } elseif (Tools::strlen(Tools::getValue('attachment_name_' . (int) $language['id_lang'])) > 32) {
             $this->errors[] = sprintf(Tools::displayError('The name is too long (%d chars max).'), 32);
         }
         if (!Validate::isCleanHtml(Tools::getValue('attachment_description_' . (int) $language['id_lang']))) {
             $this->errors[] = Tools::displayError('Invalid description');
         }
     }
     if (!$is_attachment_name_valid) {
         $this->errors[] = Tools::displayError('An attachment name is required.');
     }
     if (empty($this->errors)) {
         if (isset($_FILES['attachment_file']) && is_uploaded_file($_FILES['attachment_file']['tmp_name'])) {
             if ($_FILES['attachment_file']['size'] > Configuration::get('PS_ATTACHMENT_MAXIMUM_SIZE') * 1024 * 1024) {
                 $this->errors[] = sprintf($this->l('The file is too large. Maximum size allowed is: %1$d kB. The file you\'re trying to upload is: %2$d kB.'), Configuration::get('PS_ATTACHMENT_MAXIMUM_SIZE') * 1024, number_format($_FILES['attachment_file']['size'] / 1024, 2, '.', ''));
             } else {
                 do {
                     $uniqid = sha1(microtime());
                 } while (file_exists(_PS_DOWNLOAD_DIR_ . $uniqid));
                 if (!copy($_FILES['attachment_file']['tmp_name'], _PS_DOWNLOAD_DIR_ . $uniqid)) {
                     $this->errors[] = $this->l('File copy failed');
                 }
                 @unlink($_FILES['attachment_file']['tmp_name']);
             }
         } elseif ((int) $_FILES['attachment_file']['error'] === 1) {
             $max_upload = (int) ini_get('upload_max_filesize');
             $max_post = (int) ini_get('post_max_size');
             $upload_mb = min($max_upload, $max_post);
             $this->errors[] = sprintf($this->l('The file %1$s exceeds the size allowed by the server. The limit is set to %2$d MB.'), '<b>' . $_FILES['attachment_file']['name'] . '</b> ', '<b>' . $upload_mb . '</b>');
         } else {
             $this->errors[] = Tools::displayError('The file is missing.');
         }
         if (empty($this->errors) && isset($uniqid)) {
             $attachment = new Attachment();
             foreach ($languages as $language) {
                 if (Tools::getIsset('attachment_name_' . (int) $language['id_lang'])) {
                     $attachment->name[(int) $language['id_lang']] = Tools::getValue('attachment_name_' . (int) $language['id_lang']);
                 }
                 if (Tools::getIsset('attachment_description_' . (int) $language['id_lang'])) {
                     $attachment->description[(int) $language['id_lang']] = Tools::getValue('attachment_description_' . (int) $language['id_lang']);
                 }
             }
             if (Tools::getIsset('name_' . (int) Configuration::get('PS_LANG_DEFAULT'))) {
                 $sFilename = $_FILES['attachment_file']['name'];
                 $sExtention = substr($sFilename, strrpos($sFilename, '.') + 1);
                 $attachment->file_name = Tools::link_rewrite(trim(Tools::getValue('name_' . (int) Configuration::get('PS_LANG_DEFAULT'))));
                 // On regarde si c'est le premier document joint au produit ou pas
                 $aAttachmentOfProduct = $attachment->getAttachments(Context::getContext()->language->id, (int) Tools::getValue('id_product'));
                 $iNb = count($aAttachmentOfProduct);
                 if ($iNb > 0) {
                     $attachment->file_name .= '-' . $iNb;
                 }
                 $attachment->file_name .= '.' . $sExtention;
             }
             $attachment->file = $uniqid;
             $attachment->mime = $_FILES['attachment_file']['type'];
             if (empty($attachment->mime) || Tools::strlen($attachment->mime) > 128) {
                 $this->errors[] = Tools::displayError('Invalid file extension');
             }
             if (!Validate::isGenericName($attachment->file_name)) {
                 $this->errors[] = Tools::displayError('Invalid file name');
             }
             if (Tools::strlen($attachment->file_name) > 128) {
                 $this->errors[] = Tools::displayError('The file name is too long.');
             }
             if (empty($this->errors)) {
                 $res = $attachment->add();
                 if (!$res) {
                     $this->errors[] = Tools::displayError('This attachment was unable to be loaded into the database.');
                 } else {
                     $id_product = (int) Tools::getValue($this->identifier);
                     $res = $attachment->attachProduct($id_product);
                     if (!$res) {
                         $this->errors[] = Tools::displayError('We were unable to associate this attachment to a product.');
                     }
                 }
             } else {
                 $this->errors[] = Tools::displayError('Invalid file');
             }
         }
     }
 }
Example #11
0
 private function makeMenu()
 {
     global $cookie, $page_name;
     foreach ($this->getMenuItems() as $item) {
         $id = (int) substr($item, 3, strlen($item));
         switch (substr($item, 0, 3)) {
             case 'CAT':
                 $this->getCategory($id, $cookie->id_lang);
                 break;
             case 'PRD':
                 $selected = $page_name == 'product' && Tools::getValue('id_product') == $id ? ' class="sfHover"' : '';
                 $product = new Product($id, true, $cookie->id_lang);
                 if (!is_null($product->id)) {
                     $this->_menu .= '<li' . $selected . '><a href="' . $product->getLink() . '">' . $product->name . '</a></li>' . PHP_EOL;
                 }
                 break;
             case 'CMS':
                 $selected = $page_name == 'cms' && Tools::getValue('id_cms') == $id ? ' class="sfHover"' : '';
                 $cms = CMS::getLinks($cookie->id_lang, array($id));
                 if (count($cms)) {
                     $this->_menu .= '<li' . $selected . '><a href="' . $cms[0]['link'] . '">' . $cms[0]['meta_title'] . '</a></li>' . PHP_EOL;
                 }
                 break;
             case 'MAN':
                 $selected = $page_name == 'manufacturer' && Tools::getValue('id_manufacturer') == $id ? ' class="sfHover"' : '';
                 $manufacturer = new Manufacturer($id, $cookie->id_lang);
                 if (!is_null($manufacturer->id)) {
                     if (intval(Configuration::get('PS_REWRITING_SETTINGS'))) {
                         $manufacturer->link_rewrite = Tools::link_rewrite($manufacturer->name, false);
                     } else {
                         $manufacturer->link_rewrite = 0;
                     }
                     $link = new Link();
                     $this->_menu .= '<li' . $selected . '><a href="' . $link->getManufacturerLink($id, $manufacturer->link_rewrite) . '">' . $manufacturer->name . '</a></li>' . PHP_EOL;
                 }
                 break;
             case 'SUP':
                 $selected = $page_name == 'supplier' && Tools::getValue('id_supplier') == $id ? ' class="sfHover"' : '';
                 $supplier = new Supplier($id, $cookie->id_lang);
                 if (!is_null($supplier->id)) {
                     $link = new Link();
                     $this->_menu .= '<li' . $selected . '><a href="' . $link->getSupplierLink($id, $supplier->link_rewrite) . '">' . $supplier->name . '</a></li>' . PHP_EOL;
                 }
                 break;
             case 'LNK':
                 $link = MenuTopLinks::get($id, $cookie->id_lang);
                 if (count($link)) {
                     $this->_menu .= '<li><a href="' . $link[0]['link'] . '"' . ($link[0]['new_window'] ? ' target="_blank"' : '') . '>' . $link[0]['label'] . '</a></li>' . PHP_EOL;
                 }
                 break;
         }
     }
 }
Example #12
0
 /**
  * Get the combination url anchor of the product
  *
  * @param integer $id_product_attribute
  * @return string
  */
 public function getAnchor($id_product_attribute)
 {
     $attributes = Product::getAttributesParams($this->id, $id_product_attribute);
     $anchor = '#';
     foreach ($attributes as &$a) {
         foreach ($a as &$b) {
             $b = str_replace('-', '_', Tools::link_rewrite($b));
         }
         $anchor .= '/' . $a['group'] . '-' . $a['name'];
     }
     return $anchor;
 }
Example #13
0
function add_new_category($category_name,$parent_id){
    global $webService;        
    $xml = $webService -> get(array('url' => PS_SHOP_PATH . '/api/categories?schema=synopsis'));
	$resources = $xml -> children() -> children();
        unset($resources->level_depth);
        unset($resources->nb_products_recursive);
	$resources->id_parent  = $parent_id;
	$resources->active = 1;
	$resources->name->language[0] = $category_name;
        $resources->link_rewrite->language[0] = Tools::link_rewrite($category_name);
	$resources->name->language[1] = $category_name;
        $resources->link_rewrite->language[1] = Tools::link_rewrite($category_name);
        try {
		$opt = array('resource' => 'categories');
		$opt['postXml'] = $xml->asXML();
                $xml = $webService->add($opt);
                $result1 = $xml->children()->children();
                return $result1->{'id'};
	}catch (PrestaShopWebserviceException $ex) {
		echo "<b>Error al setear la cantidad  ->Error : </b>".$ex->getMessage().'<br>';
	}
}
Example #14
0
 private function AddProduct($ref, $weight, $price, $cats, $name, $description, $cat_name, $images, $colors_prod, $sizes_prod, $table_content)
 {
     $ref_id = $ref . "00";
     $id_product = (int) Db::getInstance()->getValue('SELECT id_product FROM ' . _DB_PREFIX_ . 'product WHERE reference = ' . $ref_id);
     $product = $id_product ? new Product((int) $id_product, true) : new Product();
     $product->reference = $ref_id;
     $product->available_for_order = 1;
     $product->available_now = 1;
     $product->show_price = 1;
     $product->out_of_stock = 1;
     $product->condition = "new";
     $product->id_tax_rules_group = 6;
     $price = $this->CalculatePrice($price, $weight);
     $product->price = floatval($price);
     $product->active = (int) "1";
     $product->quantity = (int) "10";
     $product->weight = floatval($weight);
     $product->minimal_quantity = (int) "1";
     $product->name[1] = utf8_encode($name);
     $description_trans = $this->GetDescTrans($description, $table_content);
     $product->description[1] = utf8_encode($description_trans);
     $product->description[2] = utf8_encode($description_trans);
     $product->description_short[1] = utf8_encode("");
     $product->link_rewrite[1] = Tools::link_rewrite($name);
     if (!isset($product->date_add) || empty($product->date_add)) {
         $product->date_add = date('Y-m-d H:i:s');
     }
     $product->date_upd = date('Y-m-d H:i:s');
     array_unshift($cats, "Home");
     /*
     foreach ($cats as $cat ) 
     {
         
         $this->AddCategory($cat,$cats);
     }
     */
     $cat_id = $this->GetCatId($cat_name);
     $product->id_category_default = $cat_id;
     $all_cat_id = $this->GetAllCatId($cats);
     $product->category = $all_cat_id;
     $product->save();
     $id_product = $product->id;
     $product->updateCategories($all_cat_id, true);
     $this->DeleteProductAttr($id_product);
     foreach ($colors_prod as $col) {
         if (strlen($col) < 4 && strtolower($col) != "red") {
             $size_trans = $this->GetSizeTrans($col);
             if ($size_trans != "nije prevedeno") {
                 $this->AddSize($size_trans);
                 $this->ConnectProductSize($id_product, $size_trans);
             }
         } else {
             $color_trans = $this->GetColorTrans($col);
             $this->ConnectProductColor($id_product, $color_trans);
         }
     }
     foreach ($sizes_prod as $siz) {
         $size_trans = $this->GetSizeTrans($siz);
         if ($size_trans != "nije prevedeno") {
             $this->AddSize($size_trans);
             $this->ConnectProductSize($id_product, $size_trans);
         }
         $this->UpdateStock($id_product);
     }
     $image = new Image();
     $image->id_product = $id_product;
     $image->position = Image::getHighestPosition($id_product) + 1;
     $image->cover = 1;
     // or false;
     foreach ($images as $url) {
         $this->AddImage($product, $url);
     }
     return 'Proizvod <b>' . $product->name[1] . '</b> ' . ($id_product ? 'promjenjen' : 'dodan') . '<br />';
 }
Example #15
0
 protected function makeMenu()
 {
     $menu_items = $this->getMenuItems();
     $id_lang = (int) $this->context->language->id;
     $id_shop = (int) Shop::getContextShopID();
     foreach ($menu_items as $item) {
         if (!$item) {
             continue;
         }
         preg_match($this->pattern, $item, $value);
         $id = (int) substr($item, strlen($value[1]), strlen($item));
         switch (substr($item, 0, strlen($value[1]))) {
             case 'CAT':
                 $this->_menu .= $this->generateCategoriesMenu(Category::getNestedCategories($id, $id_lang, false, $this->user_groups));
                 break;
             case 'PRD':
                 $selected = $this->page_name == 'product' && Tools::getValue('id_product') == $id ? ' class="sfHover"' : '';
                 $product = new Product((int) $id, true, (int) $id_lang);
                 if (!is_null($product->id)) {
                     $this->_menu .= '<li' . $selected . '><a href="' . Tools::HtmlEntitiesUTF8($product->getLink()) . '" title="' . $product->name . '">' . $product->name . '</a></li>' . PHP_EOL;
                 }
                 break;
             case 'CMS':
                 $selected = $this->page_name == 'cms' && Tools::getValue('id_cms') == $id ? ' class="sfHover"' : '';
                 $cms = CMS::getLinks((int) $id_lang, array($id));
                 if (count($cms)) {
                     $this->_menu .= '<li' . $selected . '><a href="' . Tools::HtmlEntitiesUTF8($cms[0]['link']) . '" title="' . Tools::safeOutput($cms[0]['meta_title']) . '">' . Tools::safeOutput($cms[0]['meta_title']) . '</a></li>' . PHP_EOL;
                 }
                 break;
             case 'CMS_CAT':
                 $category = new CMSCategory((int) $id, (int) $id_lang);
                 if (count($category)) {
                     $this->_menu .= '<li><a href="' . Tools::HtmlEntitiesUTF8($category->getLink()) . '" title="' . $category->name . '">' . $category->name . '</a>';
                     $this->getCMSMenuItems($category->id);
                     $this->_menu .= '</li>' . PHP_EOL;
                 }
                 break;
                 // Case to handle the option to show all Manufacturers
             // Case to handle the option to show all Manufacturers
             case 'ALLMAN':
                 $link = new Link();
                 $this->_menu .= '<li><a href="' . $link->getPageLink('manufacturer') . '" title="' . $this->l('All manufacturers') . '">' . $this->l('All manufacturers') . '</a><ul>' . PHP_EOL;
                 $manufacturers = Manufacturer::getManufacturers();
                 foreach ($manufacturers as $key => $manufacturer) {
                     $this->_menu .= '<li><a href="' . $link->getManufacturerLink((int) $manufacturer['id_manufacturer'], $manufacturer['link_rewrite']) . '" title="' . Tools::safeOutput($manufacturer['name']) . '">' . Tools::safeOutput($manufacturer['name']) . '</a></li>' . PHP_EOL;
                 }
                 $this->_menu .= '</ul>';
                 break;
             case 'MAN':
                 $selected = $this->page_name == 'manufacturer' && Tools::getValue('id_manufacturer') == $id ? ' class="sfHover"' : '';
                 $manufacturer = new Manufacturer((int) $id, (int) $id_lang);
                 if (!is_null($manufacturer->id)) {
                     if (intval(Configuration::get('PS_REWRITING_SETTINGS'))) {
                         $manufacturer->link_rewrite = Tools::link_rewrite($manufacturer->name);
                     } else {
                         $manufacturer->link_rewrite = 0;
                     }
                     $link = new Link();
                     $this->_menu .= '<li' . $selected . '><a href="' . Tools::HtmlEntitiesUTF8($link->getManufacturerLink((int) $id, $manufacturer->link_rewrite)) . '" title="' . Tools::safeOutput($manufacturer->name) . '">' . Tools::safeOutput($manufacturer->name) . '</a></li>' . PHP_EOL;
                 }
                 break;
                 // Case to handle the option to show all Suppliers
             // Case to handle the option to show all Suppliers
             case 'ALLSUP':
                 $link = new Link();
                 $this->_menu .= '<li><a href="' . $link->getPageLink('supplier') . '" title="' . $this->l('All suppliers') . '">' . $this->l('All suppliers') . '</a><ul>' . PHP_EOL;
                 $suppliers = Supplier::getSuppliers();
                 foreach ($suppliers as $key => $supplier) {
                     $this->_menu .= '<li><a href="' . $link->getSupplierLink((int) $supplier['id_supplier'], $supplier['link_rewrite']) . '" title="' . Tools::safeOutput($supplier['name']) . '">' . Tools::safeOutput($supplier['name']) . '</a></li>' . PHP_EOL;
                 }
                 $this->_menu .= '</ul>';
                 break;
             case 'SUP':
                 $selected = $this->page_name == 'supplier' && Tools::getValue('id_supplier') == $id ? ' class="sfHover"' : '';
                 $supplier = new Supplier((int) $id, (int) $id_lang);
                 if (!is_null($supplier->id)) {
                     $link = new Link();
                     $this->_menu .= '<li' . $selected . '><a href="' . Tools::HtmlEntitiesUTF8($link->getSupplierLink((int) $id, $supplier->link_rewrite)) . '" title="' . $supplier->name . '">' . $supplier->name . '</a></li>' . PHP_EOL;
                 }
                 break;
             case 'SHOP':
                 $selected = $this->page_name == 'index' && $this->context->shop->id == $id ? ' class="sfHover"' : '';
                 $shop = new Shop((int) $id);
                 if (Validate::isLoadedObject($shop)) {
                     $link = new Link();
                     $this->_menu .= '<li' . $selected . '><a href="' . Tools::HtmlEntitiesUTF8($shop->getBaseURL()) . '" title="' . $shop->name . '">' . $shop->name . '</a></li>' . PHP_EOL;
                 }
                 break;
             case 'LNK':
                 $link = MenuTopLinks::get((int) $id, (int) $id_lang, (int) $id_shop);
                 if (count($link)) {
                     if (!isset($link[0]['label']) || $link[0]['label'] == '') {
                         $default_language = Configuration::get('PS_LANG_DEFAULT');
                         $link = MenuTopLinks::get($link[0]['id_linksmenutop'], $default_language, (int) Shop::getContextShopID());
                     }
                     $this->_menu .= '<li><a href="' . Tools::HtmlEntitiesUTF8($link[0]['link']) . '"' . ($link[0]['new_window'] ? ' onclick="return !window.open(this.href);"' : '') . ' title="' . Tools::safeOutput($link[0]['label']) . '">' . Tools::safeOutput($link[0]['label']) . '</a></li>' . PHP_EOL;
                 }
                 break;
         }
     }
 }
 /**
  * Get and assign attributes combinations informations
  */
 protected function assignAttributesCombinations()
 {
     $attributes_combinations = Product::getAttributesInformationsByProduct($this->product->id);
     foreach ($attributes_combinations as &$ac) {
         foreach ($ac as &$val) {
             $val = str_replace('-', '_', Tools::link_rewrite($val));
         }
     }
     $this->context->smarty->assign('attributesCombinations', $attributes_combinations);
 }
Example #17
0
 public function getLink()
 {
     return Tools::link_rewrite($this->name);
 }
 private function makeMenu()
 {
     $menu = '';
     $menu_items = $this->getMenuItems();
     $id_lang = (int) $this->context->language->id;
     $id_shop = (int) Shop::getContextShopID();
     $head = $this->_itemHead;
     $tail = $this->_itemTail;
     foreach ($menu_items as $item) {
         if (!$item) {
             continue;
         }
         preg_match($this->pattern, $item, $value);
         $id = (int) substr($item, strlen($value[1]), strlen($item));
         switch (substr($item, 0, strlen($value[1]))) {
             case 'CAT':
                 $this->getCategory($menu, (int) $id);
                 break;
             case 'PRD':
                 $selected = $this->page_name == 'product' && Tools::getValue('id_product') == $id ? ' active' : '';
                 $product = new Product((int) $id, true, (int) $id_lang);
                 if (!is_null($product->id)) {
                     $menu .= $head . '<li class="' . $this->_itemClass . $selected . '"><a href="' . $product->getLink() . '"><span>' . $product->name . '</span></a></li>' . $tail . PHP_EOL;
                 }
                 break;
             case 'CMS':
                 $selected = $this->page_name == 'cms' && Tools::getValue('id_cms') == $id ? ' active' : '';
                 $cms = CMS::getLinks((int) $id_lang, array($id));
                 if (count($cms)) {
                     $menu .= $head . '<li class="' . $this->_itemClass . $selected . '"><a href="' . $cms[0]['link'] . '"><span>' . $cms[0]['meta_title'] . '</span></a></li>' . $tail . PHP_EOL;
                 }
                 break;
             case 'CMS_CAT':
                 $category = new CMSCategory((int) $id, (int) $id_lang);
                 if (count($category)) {
                     $menu .= $head . '<li class="' . $this->_itemClass . $selected . '"><a href="' . $category->getLink() . '"><span>' . $category->name . '</span></a>';
                     $this->getCMSMenuItems($menu, $category->id);
                     $menu .= '</li>' . $tail . PHP_EOL;
                 }
                 break;
             case 'MAN':
                 $selected = $this->page_name == 'manufacturer' && Tools::getValue('id_manufacturer') == $id ? ' active' : '';
                 $manufacturer = new Manufacturer((int) $id, (int) $id_lang);
                 if (!is_null($manufacturer->id)) {
                     if (intval(Configuration::get('PS_REWRITING_SETTINGS'))) {
                         $manufacturer->link_rewrite = Tools::link_rewrite($manufacturer->name, false);
                     } else {
                         $manufacturer->link_rewrite = 0;
                     }
                     $link = new Link();
                     $menu .= $head . '<li class="' . $this->_itemClass . $selected . '"><a href="' . $link->getManufacturerLink((int) $id, $manufacturer->link_rewrite) . '"><span>' . $manufacturer->name . '</span></a></li>' . $tail . PHP_EOL;
                 }
                 break;
             case 'SUP':
                 $selected = $this->page_name == 'supplier' && Tools::getValue('id_supplier') == $id ? ' active' : '';
                 $supplier = new Supplier((int) $id, (int) $id_lang);
                 if (!is_null($supplier->id)) {
                     $link = new Link();
                     $menu .= $head . '<li class="' . $this->_itemClass . $selected . '"><a href="' . $link->getSupplierLink((int) $id, $supplier->link_rewrite) . '"><span>' . $supplier->name . '</span></a></li>' . $tail . PHP_EOL;
                 }
                 break;
             case 'SHOP':
                 $selected = $this->page_name == 'index' && $this->context->shop->id == $id ? ' active' : '';
                 $shop = new Shop((int) $id);
                 if (Validate::isLoadedObject($shop)) {
                     $link = new Link();
                     $menu .= $head . '<li class="' . $this->_itemClass . $selected . '"><a href="' . $shop->getBaseURL() . '"><span>' . $shop->name . '</span></a></li>' . $tail . PHP_EOL;
                 }
                 break;
             case 'LNK':
                 $link = MenuTopLinks_mod::get((int) $id, (int) $id_lang, (int) $id_shop);
                 if (count($link)) {
                     if (!isset($link[0]['label']) || $link[0]['label'] == '') {
                         $default_language = Configuration::get('PS_LANG_DEFAULT');
                         $link = MenuTopLinks_mod::get($link[0]['id_linksmenutop'], $default_language, (int) Shop::getContextShopID());
                     }
                     $menu .= $head . '<li class="' . $this->_itemClass . $selected . '"><a href="' . $link[0]['link'] . '"' . ($link[0]['new_window'] ? ' target="_blank"' : '') . '><span>' . $link[0]['label'] . '</span></a></li>' . $tail . PHP_EOL;
                 }
                 break;
         }
     }
     return $menu;
 }
Example #19
0
 private function copyImg($item, $className)
 {
     require_once '../../images.inc.php';
     $identifier = $this->supportedImports[strtolower($className)]['identifier'];
     $matchId = $this->getMatchId(strtolower($className));
     $matchIdLang = $this->getMatchIdLang();
     switch ($className) {
         default:
         case 'Product':
             $path = _PS_PROD_IMG_DIR_;
             $type = 'products';
             break;
         case 'Category':
             $path = _PS_CAT_IMG_DIR_;
             $type = 'categories';
             break;
         case 'Manufacturer':
             $path = _PS_MANU_IMG_DIR_;
             $type = 'manufacturers';
             break;
         case 'Supplier':
             $path = _PS_SUPP_IMG_DIR_;
             $type = 'suppliers';
             break;
     }
     $cover = 1;
     if (array_key_exists($item[$identifier], $matchId)) {
         if (array_key_exists('images', $item) && !is_null($item['images'])) {
             foreach ($item['images'] as $key => $image) {
                 $tmpfile = tempnam(_PS_TMP_IMG_DIR_, 'import');
                 if (@copy(str_replace(' ', '%20', $image), $tmpfile)) {
                     $imagesTypes = ImageType::getImagesTypes($type);
                     ImageManager::resize($tmpfile, $path . (int) $matchId[$item[$identifier]] . '.jpg');
                     if ($className == 'Product') {
                         $image = new Image();
                         $image->id_product = (int) $matchId[$item[$identifier]];
                         $image->cover = $cover;
                         $image->position = Image::getHighestPosition((int) $matchId[$item[$identifier]]) + 1;
                         $legend = array();
                         foreach ($item['name'] as $key => $val) {
                             if (array_key_exists($key, $matchIdLang)) {
                                 $legend[$matchIdLang[$key]] = Tools::link_rewrite($val);
                             } else {
                                 $legend[Configuration::get('PS_LANG_DEFAULT')] = Tools::link_rewrite($val);
                             }
                         }
                         $image->legend = $legend;
                         $image->add();
                         ImageManager::resize($tmpfile, $path . (int) $matchId[$item[$identifier]] . '-' . (int) $image->id . '.jpg');
                         foreach ($imagesTypes as $k => $imageType) {
                             ImageManager::resize($tmpfile, $path . (int) $matchId[$item[$identifier]] . '-' . (int) $image->id . '-' . stripslashes($imageType['name']) . '.jpg', $imageType['width'], $imageType['height']);
                         }
                     } else {
                         foreach ($imagesTypes as $imageType) {
                             ImageManager::resize($tmpfile, $path . (int) $matchId[$item[$identifier]] . '-' . stripslashes($imageType['name']) . '.jpg', $imageType['width'], $imageType['height']);
                         }
                     }
                 } else {
                     @unlink($tmpfile);
                 }
                 @unlink($tmpfile);
                 $cover = 0;
             }
         }
     }
 }
Example #20
0
    /**
     * Return suppliers
     *
     * @return array Suppliers
     */
    public static function getSuppliers($get_nb_products = false, $id_lang = 0, $active = true, $p = false, $n = false, $all_groups = false)
    {
        if (!$id_lang) {
            $id_lang = Configuration::get('PS_LANG_DEFAULT');
        }
        $query = new DbQuery();
        $query->select('s.*, sl.`description`');
        $query->from('supplier', 's');
        $query->leftJoin('supplier_lang', 'sl', 's.`id_supplier` = sl.`id_supplier` AND sl.`id_lang` = ' . (int) $id_lang);
        $query->join(Shop::addSqlAssociation('supplier', 's'));
        if ($active) {
            $query->where('s.`active` = 1');
        }
        $query->orderBy(' s.`name` ASC');
        $query->limit($n, ($p - 1) * $n);
        $query->groupBy('s.id_supplier');
        $suppliers = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($query);
        if ($suppliers === false) {
            return false;
        }
        if ($get_nb_products) {
            $sql_groups = '';
            if (!$all_groups) {
                $groups = FrontController::getCurrentCustomerGroups();
                $sql_groups = count($groups) ? 'IN (' . implode(',', $groups) . ')' : '= 1';
            }
            foreach ($suppliers as $key => $supplier) {
                $sql = '
					SELECT DISTINCT(ps.`id_product`)
					FROM `' . _DB_PREFIX_ . 'product_supplier` ps
					JOIN `' . _DB_PREFIX_ . 'product` p ON (ps.`id_product`= p.`id_product`)
					' . Shop::addSqlAssociation('product', 'p') . '
					WHERE ps.`id_supplier` = ' . (int) $supplier['id_supplier'] . '
					AND ps.id_product_attribute = 0' . ($active ? ' AND product_shop.`active` = 1' : '') . ($all_groups ? '' : '
					AND ps.`id_product` IN (
						SELECT cp.`id_product`
						FROM `' . _DB_PREFIX_ . 'category_group` cg
						LEFT JOIN `' . _DB_PREFIX_ . 'category_product` cp ON (cp.`id_category` = cg.`id_category`)
						WHERE cg.`id_group` ' . $sql_groups . '
					)');
                $result = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($sql);
                $suppliers[$key]['nb_products'] = count($result);
            }
        }
        $nb_suppliers = count($suppliers);
        $rewrite_settings = (int) Configuration::get('PS_REWRITING_SETTINGS');
        for ($i = 0; $i < $nb_suppliers; $i++) {
            if ($rewrite_settings) {
                $suppliers[$i]['link_rewrite'] = Tools::link_rewrite($suppliers[$i]['name'], false);
            } else {
                $suppliers[$i]['link_rewrite'] = 0;
            }
        }
        return $suppliers;
    }
Example #21
0
 /**
  * Generic function which allows logo upload
  *
  * @param $field_name
  * @param $logo_prefix
  *
  * @return bool
  */
 protected function updateLogo($field_name, $logo_prefix)
 {
     $id_shop = Context::getContext()->shop->id;
     if (isset($_FILES[$field_name]['tmp_name']) && $_FILES[$field_name]['tmp_name']) {
         if ($error = ImageManager::validateUpload($_FILES[$field_name], Tools::getMaxUploadSize())) {
             $this->errors[] = $error;
             return false;
         }
         $tmp_name = tempnam(_PS_TMP_IMG_DIR_, 'PS');
         if (!$tmp_name || !move_uploaded_file($_FILES[$field_name]['tmp_name'], $tmp_name)) {
             return false;
         }
         $ext = $field_name == 'PS_STORES_ICON' ? '.gif' : '.jpg';
         $logo_name = Tools::link_rewrite(Context::getContext()->shop->name) . '-' . Configuration::get('PS_IMG_UPDATE_TIME') . '-' . (int) $id_shop . $ext;
         if (Context::getContext()->shop->getContext() == Shop::CONTEXT_ALL || $id_shop == 0 || Shop::isFeatureActive() == false) {
             $logo_name = Tools::link_rewrite(Context::getContext()->shop->name) . '-' . Configuration::get('PS_IMG_UPDATE_TIME') . $ext;
         }
         if ($field_name == 'PS_STORES_ICON') {
             if (!@ImageManager::resize($tmp_name, _PS_IMG_DIR_ . $logo_name, null, null, 'gif', true)) {
                 $this->errors[] = Tools::displayError('An error occurred while attempting to copy your logo.');
             }
         } else {
             if (!@ImageManager::resize($tmp_name, _PS_IMG_DIR_ . $logo_name)) {
                 $this->errors[] = Tools::displayError('An error occurred while attempting to copy your logo.');
             }
         }
         if (!count($this->errors) && @filemtime(_PS_IMG_DIR_ . Configuration::get($field_name))) {
             @unlink(_PS_IMG_DIR_ . Configuration::get($field_name));
         }
         Configuration::updateValue($field_name, $logo_name);
         @unlink($tmp_name);
     }
 }
Example #22
0
 private function combinationUrlPrepare($val)
 {
     return str_replace(Configuration::get('PS_ATTRIBUTE_ANCHOR_SEPARATOR'), '_', Tools::link_rewrite(str_replace(array(',', '.'), '-', $val)));
 }
Example #23
0
 /**
  * Get and assign attributes combinations informations
  */
 protected function assignAttributesCombinations()
 {
     $attributes_combinations = Product::getAttributesInformationsByProduct($this->product->id);
     if (is_array($attributes_combinations) && count($attributes_combinations)) {
         foreach ($attributes_combinations as &$ac) {
             foreach ($ac as &$val) {
                 $val = str_replace(Configuration::get('PS_ATTRIBUTE_ANCHOR_SEPARATOR'), '_', Tools::link_rewrite(str_replace(array(',', '.'), '-', $val)));
             }
         }
     } else {
         $attributes_combinations = array();
     }
     $this->context->smarty->assign(array('attributesCombinations' => $attributes_combinations, 'attribute_anchor_separator' => Configuration::get('PS_ATTRIBUTE_ANCHOR_SEPARATOR')));
 }
Example #24
0
 public static function createCategoryByName($name)
 {
     $pkjexibgr = "category";
     $xsbkgsfmjfk = "languages";
     ${${"GLOBALS"}["zfyckhwlz"]} = new Category();
     ${$xsbkgsfmjfk} = Language::getLanguages(false);
     ${"GLOBALS"}["fhhbltrliet"] = "languages";
     foreach (${${"GLOBALS"}["fhhbltrliet"]} as ${${"GLOBALS"}["guqxwfmuy"]}) {
         ${"GLOBALS"}["lbxiabbx"] = "lang";
         ${"GLOBALS"}["ymymmnsjbdcr"] = "lang";
         $category->name[${${"GLOBALS"}["ymymmnsjbdcr"]}["id_lang"]] = ${${"GLOBALS"}["bckwbspoink"]};
         $jnfdwkld = "name";
         $category->link_rewrite[${${"GLOBALS"}["lbxiabbx"]}["id_lang"]] = Tools::link_rewrite(${$jnfdwkld});
     }
     $category->id_parent = 2;
     $category->id_shop_default = 1;
     $category->level = 2;
     $category->is_root_category = 0;
     $category->position = 0;
     $category->active = 1;
     $category->save();
     return ${$pkjexibgr};
 }
Example #25
0
    public function getFilterBlock($selected_filters = array())
    {
        global $cookie;
        static $cache = null;
        $id_lang = Context::getContext()->language->id;
        $currency = Context::getContext()->currency;
        $id_shop = (int) Context::getContext()->shop->id;
        $alias = 'product_shop';
        if (is_array($cache)) {
            return $cache;
        }
        $id_parent = (int) Tools::getValue('id_category', Tools::getValue('id_category_layered', 1));
        if ($id_parent == 1) {
            return;
        }
        $parent = new Category((int) $id_parent, $id_lang);
        /* Get the filters for the current category */
        $filters = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS('SELECT * FROM ' . _DB_PREFIX_ . 'layered_category
			WHERE id_category = ' . (int) $id_parent . '
				AND id_shop = ' . $id_shop . '
			GROUP BY `type`, id_value ORDER BY position ASC');
        // Remove all empty selected filters
        foreach ($selected_filters as $key => $value) {
            switch ($key) {
                case 'price':
                case 'weight':
                    if ($value[0] === '' && $value[1] === '') {
                        unset($selected_filters[$key]);
                    }
                    break;
                default:
                    if ($value == '') {
                        unset($selected_filters[$key]);
                    }
                    break;
            }
        }
        $filter_blocks = array();
        foreach ($filters as $filter) {
            $sql_query = array('select' => '', 'from' => '', 'join' => '', 'where' => '', 'group' => '', 'second_query' => '');
            switch ($filter['type']) {
                // conditions + quantities + weight + price
                case 'price':
                case 'weight':
                case 'condition':
                case 'quantity':
                    $sql_query['select'] = 'SELECT p.`id_product`, product_shop.`condition`, p.`id_manufacturer`, sa.`quantity`, p.`weight` ';
                    $sql_query['from'] = '
					FROM ' . _DB_PREFIX_ . 'product p ';
                    $sql_query['join'] = '
					INNER JOIN ' . _DB_PREFIX_ . 'category_product cp ON (cp.id_product = p.id_product)
					INNER JOIN ' . _DB_PREFIX_ . 'category c ON (c.id_category = cp.id_category AND
					' . (Configuration::get('PS_LAYERED_FULL_TREE') ? 'c.nleft >= ' . (int) $parent->nleft . '
					AND c.nright <= ' . (int) $parent->nright : 'c.id_category = ' . (int) $id_parent) . '
					AND c.active = 1) ';
                    $sql_query['join'] .= 'LEFT JOIN `' . _DB_PREFIX_ . 'stock_available` sa
						ON (sa.id_product = p.id_product AND sa.id_shop = ' . (int) $this->context->shop->id . ') ';
                    $sql_query['where'] = 'WHERE product_shop.`active` = 1 AND product_shop.`visibility` IN ("both", "catalog") ';
                    $sql_query['group'] = ' GROUP BY p.id_product ';
                    break;
                case 'manufacturer':
                    $sql_query['select'] = 'SELECT m.name, COUNT(DISTINCT p.id_product) nbr, m.id_manufacturer ';
                    $sql_query['from'] = '
					FROM `' . _DB_PREFIX_ . 'category_product` cp
					INNER JOIN  `' . _DB_PREFIX_ . 'category` c ON (c.id_category = cp.id_category)
					INNER JOIN ' . _DB_PREFIX_ . 'product p ON (p.id_product = cp.id_product)
					INNER JOIN ' . _DB_PREFIX_ . 'manufacturer m ON (m.id_manufacturer = p.id_manufacturer) ';
                    $sql_query['where'] = 'WHERE 
					' . (Configuration::get('PS_LAYERED_FULL_TREE') ? 'c.nleft >= ' . (int) $parent->nleft . '
					AND c.nright <= ' . (int) $parent->nright : 'c.id_category = ' . (int) $id_parent) . '
					AND c.active = 1
					AND ' . $alias . '.active = 1 AND ' . $alias . '.`visibility` IN ("both", "catalog")';
                    $sql_query['group'] = ' GROUP BY p.id_manufacturer ORDER BY m.name';
                    if (!Configuration::get('PS_LAYERED_HIDE_0_VALUES')) {
                        $sql_query['second_query'] = '
							SELECT m.name, 0 nbr, m.id_manufacturer 
							
							FROM `' . _DB_PREFIX_ . 'category_product` cp' . Shop::addSqlAssociation('product', 'cp') . '
							INNER JOIN  `' . _DB_PREFIX_ . 'category` c ON (c.id_category = cp.id_category)
							INNER JOIN ' . _DB_PREFIX_ . 'product p ON (p.id_product = cp.id_product)
							INNER JOIN ' . _DB_PREFIX_ . 'manufacturer m ON (m.id_manufacturer = p.id_manufacturer) 
							
							WHERE ' . (Configuration::get('PS_LAYERED_FULL_TREE') ? 'c.nleft >= ' . (int) $parent->nleft . '
							AND c.nright <= ' . (int) $parent->nright : 'c.id_category = ' . (int) $id_parent) . '
							AND c.active = 1
							AND ' . $alias . '.active = 1 AND ' . $alias . '.`visibility` IN ("both", "catalog")
							GROUP BY p.id_manufacturer ORDER BY m.name';
                    }
                    break;
                case 'id_attribute_group':
                    // attribute group
                    $sql_query['select'] = '
					SELECT COUNT(DISTINCT p.id_product) nbr, lpa.id_attribute_group,
					a.color, al.name attribute_name, agl.public_name attribute_group_name , lpa.id_attribute, ag.is_color_group,
					liagl.url_name name_url_name, liagl.meta_title name_meta_title, lial.url_name value_url_name, lial.meta_title value_meta_title';
                    $sql_query['from'] = '
					FROM ' . _DB_PREFIX_ . 'layered_product_attribute lpa
					INNER JOIN ' . _DB_PREFIX_ . 'attribute a
					ON a.id_attribute = lpa.id_attribute
					INNER JOIN ' . _DB_PREFIX_ . 'attribute_lang al
					ON al.id_attribute = a.id_attribute
					AND al.id_lang = ' . (int) $id_lang . '
					INNER JOIN ' . _DB_PREFIX_ . 'product as p
					ON p.id_product = lpa.id_product
					INNER JOIN ' . _DB_PREFIX_ . 'attribute_group ag
					ON ag.id_attribute_group = lpa.id_attribute_group
					INNER JOIN ' . _DB_PREFIX_ . 'attribute_group_lang agl
					ON agl.id_attribute_group = lpa.id_attribute_group
					AND agl.id_lang = ' . (int) $id_lang . '
					LEFT JOIN ' . _DB_PREFIX_ . 'layered_indexable_attribute_group_lang_value liagl
					ON (liagl.id_attribute_group = lpa.id_attribute_group AND liagl.id_lang = ' . (int) $id_lang . ')
					LEFT JOIN ' . _DB_PREFIX_ . 'layered_indexable_attribute_lang_value lial
					ON (lial.id_attribute = lpa.id_attribute AND lial.id_lang = ' . (int) $id_lang . ') ';
                    $sql_query['where'] = 'WHERE a.id_attribute_group = ' . (int) $filter['id_value'];
                    $sql_query['where'] .= ' AND lpa.`id_shop` = ' . (int) Context::getContext()->shop->id;
                    $sql_query['where'] .= ' AND ' . $alias . '.active = 1 AND ' . $alias . '.`visibility` IN ("both", "catalog")
					AND p.id_product IN (
						SELECT id_product
						FROM ' . _DB_PREFIX_ . 'category_product cp
						INNER JOIN ' . _DB_PREFIX_ . 'category c ON (c.id_category = cp.id_category AND 
						' . (Configuration::get('PS_LAYERED_FULL_TREE') ? 'c.nleft >= ' . (int) $parent->nleft . '
						AND c.nright <= ' . (int) $parent->nright : 'c.id_category = ' . (int) $id_parent) . '
						AND c.active = 1)
					) ';
                    $sql_query['group'] = '
					GROUP BY lpa.id_attribute
					ORDER BY ag.`position` ASC, a.`position` ASC';
                    if (!Configuration::get('PS_LAYERED_HIDE_0_VALUES')) {
                        $sql_query['second_query'] = '
							SELECT 0 nbr, lpa.id_attribute_group,
								a.color, al.name attribute_name, agl.public_name attribute_group_name , lpa.id_attribute, ag.is_color_group,
								liagl.url_name name_url_name, liagl.meta_title name_meta_title, lial.url_name value_url_name, lial.meta_title value_meta_title
							FROM ' . _DB_PREFIX_ . 'layered_product_attribute lpa' . Shop::addSqlAssociation('product', 'lpa') . '
							INNER JOIN ' . _DB_PREFIX_ . 'attribute a
								ON a.id_attribute = lpa.id_attribute
							INNER JOIN ' . _DB_PREFIX_ . 'attribute_lang al
								ON al.id_attribute = a.id_attribute AND al.id_lang = ' . (int) $id_lang . '
							INNER JOIN ' . _DB_PREFIX_ . 'product as p
								ON p.id_product = lpa.id_product
							INNER JOIN ' . _DB_PREFIX_ . 'attribute_group ag
								ON ag.id_attribute_group = lpa.id_attribute_group
							INNER JOIN ' . _DB_PREFIX_ . 'attribute_group_lang agl
								ON agl.id_attribute_group = lpa.id_attribute_group
							AND agl.id_lang = ' . (int) $id_lang . '
							LEFT JOIN ' . _DB_PREFIX_ . 'layered_indexable_attribute_group_lang_value liagl
								ON (liagl.id_attribute_group = lpa.id_attribute_group AND liagl.id_lang = ' . (int) $id_lang . ')
							LEFT JOIN ' . _DB_PREFIX_ . 'layered_indexable_attribute_lang_value lial
								ON (lial.id_attribute = lpa.id_attribute AND lial.id_lang = ' . (int) $id_lang . ')
							WHERE ' . $alias . '.active = 1 AND ' . $alias . '.`visibility` IN ("both", "catalog")
							AND a.id_attribute_group = ' . (int) $filter['id_value'] . '
							AND lpa.`id_shop` = ' . (int) Context::getContext()->shop->id . '
							GROUP BY lpa.id_attribute
							ORDER BY id_attribute_group, id_attribute';
                    }
                    break;
                case 'id_feature':
                    $sql_query['select'] = 'SELECT fl.name feature_name, fp.id_feature, fv.id_feature_value, fvl.value,
					COUNT(DISTINCT p.id_product) nbr,
					lifl.url_name name_url_name, lifl.meta_title name_meta_title, lifvl.url_name value_url_name, lifvl.meta_title value_meta_title ';
                    $sql_query['from'] = '
					FROM ' . _DB_PREFIX_ . 'feature_product fp
					INNER JOIN ' . _DB_PREFIX_ . 'product p ON (p.id_product = fp.id_product)
					LEFT JOIN ' . _DB_PREFIX_ . 'feature_lang fl ON (fl.id_feature = fp.id_feature AND fl.id_lang = ' . $id_lang . ')
					INNER JOIN ' . _DB_PREFIX_ . 'feature_value fv ON (fv.id_feature_value = fp.id_feature_value AND (fv.custom IS NULL OR fv.custom = 0))
					LEFT JOIN ' . _DB_PREFIX_ . 'feature_value_lang fvl ON (fvl.id_feature_value = fp.id_feature_value AND fvl.id_lang = ' . $id_lang . ')
					LEFT JOIN ' . _DB_PREFIX_ . 'layered_indexable_feature_lang_value lifl
					ON (lifl.id_feature = fp.id_feature AND lifl.id_lang = ' . $id_lang . ')
					LEFT JOIN ' . _DB_PREFIX_ . 'layered_indexable_feature_value_lang_value lifvl
					ON (lifvl.id_feature_value = fp.id_feature_value AND lifvl.id_lang = ' . $id_lang . ') ';
                    $sql_query['where'] = 'WHERE ' . $alias . '.`active` = 1 AND ' . $alias . '.`visibility` IN ("both", "catalog")
					AND fp.id_feature = ' . (int) $filter['id_value'] . '
					AND p.id_product IN (
					SELECT id_product
					FROM ' . _DB_PREFIX_ . 'category_product cp
					INNER JOIN ' . _DB_PREFIX_ . 'category c ON (c.id_category = cp.id_category AND
					' . (Configuration::get('PS_LAYERED_FULL_TREE') ? 'c.nleft >= ' . (int) $parent->nleft . '
					AND c.nright <= ' . (int) $parent->nright : 'c.id_category = ' . (int) $id_parent) . '
					AND c.active = 1)) ';
                    $sql_query['group'] = 'GROUP BY fv.id_feature_value ';
                    if (!Configuration::get('PS_LAYERED_HIDE_0_VALUES')) {
                        $sql_query['second_query'] = '
							SELECT fl.name feature_name, fp.id_feature, fv.id_feature_value, fvl.value,
							0 nbr,
							lifl.url_name name_url_name, lifl.meta_title name_meta_title, lifvl.url_name value_url_name, lifvl.meta_title value_meta_title
					
							FROM ' . _DB_PREFIX_ . 'feature_product fp' . Shop::addSqlAssociation('product', 'fp') . '
							INNER JOIN ' . _DB_PREFIX_ . 'product p ON (p.id_product = fp.id_product)
							LEFT JOIN ' . _DB_PREFIX_ . 'feature_lang fl ON (fl.id_feature = fp.id_feature AND fl.id_lang = ' . (int) $id_lang . ')
							INNER JOIN ' . _DB_PREFIX_ . 'feature_value fv ON (fv.id_feature_value = fp.id_feature_value AND (fv.custom IS NULL OR fv.custom = 0))
							LEFT JOIN ' . _DB_PREFIX_ . 'feature_value_lang fvl ON (fvl.id_feature_value = fp.id_feature_value AND fvl.id_lang = ' . (int) $id_lang . ')
							LEFT JOIN ' . _DB_PREFIX_ . 'layered_indexable_feature_lang_value lifl
								ON (lifl.id_feature = fp.id_feature AND lifl.id_lang = ' . (int) $id_lang . ')
							LEFT JOIN ' . _DB_PREFIX_ . 'layered_indexable_feature_value_lang_value lifvl
								ON (lifvl.id_feature_value = fp.id_feature_value AND lifvl.id_lang = ' . (int) $id_lang . ')
							WHERE ' . $alias . '.`active` = 1 AND ' . $alias . '.`visibility` IN ("both", "catalog")
							AND fp.id_feature = ' . (int) $filter['id_value'] . '
							GROUP BY fv.id_feature_value';
                    }
                    break;
                case 'category':
                    $depth = Configuration::get('PS_LAYERED_FILTER_CATEGORY_DEPTH');
                    if ($depth === false) {
                        $depth = 1;
                    }
                    $sql_query['select'] = '
					SELECT c.id_category, c.id_parent, cl.name, (SELECT count(DISTINCT p.id_product) # ';
                    $sql_query['from'] = '
					FROM ' . _DB_PREFIX_ . 'category_product cp
					LEFT JOIN ' . _DB_PREFIX_ . 'product p ON (p.id_product = cp.id_product) ';
                    $sql_query['where'] = '
					WHERE cp.id_category = c.id_category
					AND ' . $alias . '.active = 1 AND ' . $alias . '.`visibility` IN ("both", "catalog")';
                    $sql_query['group'] = ') count_products
					FROM ' . _DB_PREFIX_ . 'category c
					LEFT JOIN ' . _DB_PREFIX_ . 'category_lang cl ON (cl.id_category = c.id_category AND cl.id_lang = ' . $id_lang . ')
					WHERE c.nleft > ' . (int) $parent->nleft . '
					AND c.nright < ' . (int) $parent->nright . '
					' . ($depth ? 'AND c.level_depth <= ' . ($parent->level_depth + (int) $depth) : '') . '
					GROUP BY c.id_category ORDER BY c.nleft, c.position';
            }
            foreach ($filters as $filter_tmp) {
                $method_name = 'get' . ucfirst($filter_tmp['type']) . 'FilterSubQuery';
                if (method_exists('BlockLayered', $method_name) && (!in_array($filter['type'], array('price', 'weight')) && $filter['type'] != $filter_tmp['type'] || $filter['type'] == $filter_tmp['type'])) {
                    if ($filter['type'] == $filter_tmp['type'] && $filter['id_value'] == $filter_tmp['id_value']) {
                        $sub_query_filter = self::$method_name(array(), true);
                    } else {
                        if (!is_null($filter_tmp['id_value'])) {
                            $selected_filters_cleaned = $this->cleanFilterByIdValue(@$selected_filters[$filter_tmp['type']], $filter_tmp['id_value']);
                        } else {
                            $selected_filters_cleaned = @$selected_filters[$filter_tmp['type']];
                        }
                        $sub_query_filter = self::$method_name($selected_filters_cleaned, $filter['type'] == $filter_tmp['type']);
                    }
                    foreach ($sub_query_filter as $key => $value) {
                        $sql_query[$key] .= $value;
                    }
                }
            }
            $products = false;
            if (!empty($sql_query['from'])) {
                $sql_query['from'] .= Shop::addSqlAssociation('product', 'p');
                $products = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($sql_query['select'] . "\n" . $sql_query['from'] . "\n" . $sql_query['join'] . "\n" . $sql_query['where'] . "\n" . $sql_query['group']);
            }
            foreach ($filters as $filter_tmp) {
                $method_name = 'filterProductsBy' . ucfirst($filter_tmp['type']);
                if (method_exists('BlockLayered', $method_name) && (!in_array($filter['type'], array('price', 'weight')) && $filter['type'] != $filter_tmp['type'] || $filter['type'] == $filter_tmp['type'])) {
                    if ($filter['type'] == $filter_tmp['type']) {
                        $products = self::$method_name(array(), $products);
                    } else {
                        $products = self::$method_name(@$selected_filters[$filter_tmp['type']], $products);
                    }
                }
            }
            if (!empty($sql_query['second_query'])) {
                $res = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($sql_query['second_query']);
                if ($res) {
                    $products = array_merge($products, $res);
                }
            }
            switch ($filter['type']) {
                case 'price':
                    $price_array = array('type_lite' => 'price', 'type' => 'price', 'id_key' => 0, 'name' => $this->l('Price'), 'slider' => true, 'max' => '0', 'min' => null, 'values' => array('1' => 0), 'unit' => $currency->sign, 'format' => $currency->format, 'filter_show_limit' => $filter['filter_show_limit'], 'filter_type' => $filter['filter_type']);
                    if (isset($products) && $products) {
                        foreach ($products as $product) {
                            if (is_null($price_array['min'])) {
                                $price_array['min'] = $product['price_min'];
                                $price_array['values'][0] = $product['price_min'];
                            } else {
                                if ($price_array['min'] > $product['price_min']) {
                                    $price_array['min'] = $product['price_min'];
                                    $price_array['values'][0] = $product['price_min'];
                                }
                            }
                            if ($price_array['max'] < $product['price_max']) {
                                $price_array['max'] = $product['price_max'];
                                $price_array['values'][1] = $product['price_max'];
                            }
                        }
                    }
                    if ($price_array['max'] != $price_array['min'] && $price_array['min'] != null) {
                        if ($filter['filter_type'] == 2) {
                            $price_array['list_of_values'] = array();
                            $nbr_of_value = $filter['filter_show_limit'];
                            if ($nbr_of_value < 2) {
                                $nbr_of_value = 4;
                            }
                            $delta = ($price_array['max'] - $price_array['min']) / $nbr_of_value;
                            $current_step = $price_array['min'];
                            for ($i = 0; $i < $nbr_of_value; $i++) {
                                $price_array['list_of_values'][] = array((int) ($price_array['min'] + $i * $delta), (int) ($price_array['min'] + ($i + 1) * $delta));
                            }
                        }
                        if (isset($selected_filters['price']) && isset($selected_filters['price'][0]) && isset($selected_filters['price'][1])) {
                            $price_array['values'][0] = $selected_filters['price'][0];
                            $price_array['values'][1] = $selected_filters['price'][1];
                        }
                        $filter_blocks[] = $price_array;
                    }
                    break;
                case 'weight':
                    $weight_array = array('type_lite' => 'weight', 'type' => 'weight', 'id_key' => 0, 'name' => $this->l('Weight'), 'slider' => true, 'max' => '0', 'min' => null, 'values' => array('1' => 0), 'unit' => Configuration::get('PS_WEIGHT_UNIT'), 'format' => 5, 'filter_show_limit' => $filter['filter_show_limit'], 'filter_type' => $filter['filter_type']);
                    if (isset($products) && $products) {
                        foreach ($products as $product) {
                            if (is_null($weight_array['min'])) {
                                $weight_array['min'] = $product['weight'];
                                $weight_array['values'][0] = $product['weight'];
                            } else {
                                if ($weight_array['min'] > $product['weight']) {
                                    $weight_array['min'] = $product['weight'];
                                    $weight_array['values'][0] = $product['weight'];
                                }
                            }
                            if ($weight_array['max'] < $product['weight']) {
                                $weight_array['max'] = $product['weight'];
                                $weight_array['values'][1] = $product['weight'];
                            }
                        }
                    }
                    if ($weight_array['max'] != $weight_array['min'] && $weight_array['min'] != null) {
                        if (isset($selected_filters['weight']) && isset($selected_filters['weight'][0]) && isset($selected_filters['weight'][1])) {
                            $weight_array['values'][0] = $selected_filters['weight'][0];
                            $weight_array['values'][1] = $selected_filters['weight'][1];
                        }
                        $filter_blocks[] = $weight_array;
                    }
                    break;
                case 'condition':
                    $condition_array = array('new' => array('name' => $this->l('New'), 'nbr' => 0), 'used' => array('name' => $this->l('Used'), 'nbr' => 0), 'refurbished' => array('name' => $this->l('Refurbished'), 'nbr' => 0));
                    if (isset($products) && $products) {
                        foreach ($products as $product) {
                            if (isset($selected_filters['condition']) && in_array($product['condition'], $selected_filters['condition'])) {
                                $condition_array[$product['condition']]['checked'] = true;
                            }
                        }
                    }
                    foreach ($condition_array as $key => $condition) {
                        if (isset($selected_filters['condition']) && in_array($key, $selected_filters['condition'])) {
                            $condition_array[$key]['checked'] = true;
                        }
                    }
                    if (isset($products) && $products) {
                        foreach ($products as $product) {
                            if (isset($condition_array[$product['condition']])) {
                                $condition_array[$product['condition']]['nbr']++;
                            }
                        }
                    }
                    $filter_blocks[] = array('type_lite' => 'condition', 'type' => 'condition', 'id_key' => 0, 'name' => $this->l('Condition'), 'values' => $condition_array, 'filter_show_limit' => $filter['filter_show_limit'], 'filter_type' => $filter['filter_type']);
                    break;
                case 'quantity':
                    $quantity_array = array(0 => array('name' => $this->l('Not available'), 'nbr' => 0), 1 => array('name' => $this->l('In stock'), 'nbr' => 0));
                    foreach ($quantity_array as $key => $quantity) {
                        if (isset($selected_filters['quantity']) && in_array($key, $selected_filters['quantity'])) {
                            $quantity_array[$key]['checked'] = true;
                        }
                    }
                    if (isset($products) && $products) {
                        foreach ($products as $product) {
                            $quantity_array[(int) ($product['quantity'] > 0)]['nbr']++;
                        }
                    }
                    $filter_blocks[] = array('type_lite' => 'quantity', 'type' => 'quantity', 'id_key' => 0, 'name' => $this->l('Availability'), 'values' => $quantity_array, 'filter_show_limit' => $filter['filter_show_limit'], 'filter_type' => $filter['filter_type']);
                    break;
                case 'manufacturer':
                    if (isset($products) && $products) {
                        $manufaturers_array = array();
                        foreach ($products as $manufacturer) {
                            if (!isset($manufaturers_array[$manufacturer['id_manufacturer']])) {
                                $manufaturers_array[$manufacturer['id_manufacturer']] = array('name' => $manufacturer['name'], 'nbr' => $manufacturer['nbr']);
                            }
                            if (isset($selected_filters['manufacturer']) && in_array((int) $manufacturer['id_manufacturer'], $selected_filters['manufacturer'])) {
                                $manufaturers_array[$manufacturer['id_manufacturer']]['checked'] = true;
                            }
                        }
                        $filter_blocks[] = array('type_lite' => 'manufacturer', 'type' => 'manufacturer', 'id_key' => 0, 'name' => $this->l('Manufacturer'), 'values' => $manufaturers_array, 'filter_show_limit' => $filter['filter_show_limit'], 'filter_type' => $filter['filter_type']);
                    }
                    break;
                case 'id_attribute_group':
                    $attributes_array = array();
                    if (isset($products) && $products) {
                        foreach ($products as $attributes) {
                            if (!isset($attributes_array[$attributes['id_attribute_group']])) {
                                $attributes_array[$attributes['id_attribute_group']] = array('type_lite' => 'id_attribute_group', 'type' => 'id_attribute_group', 'id_key' => (int) $attributes['id_attribute_group'], 'name' => $attributes['attribute_group_name'], 'is_color_group' => (bool) $attributes['is_color_group'], 'values' => array(), 'url_name' => $attributes['name_url_name'], 'meta_title' => $attributes['name_meta_title'], 'filter_show_limit' => $filter['filter_show_limit'], 'filter_type' => $filter['filter_type']);
                            }
                            if (!isset($attributes_array[$attributes['id_attribute_group']]['values'][$attributes['id_attribute']])) {
                                $attributes_array[$attributes['id_attribute_group']]['values'][$attributes['id_attribute']] = array('color' => $attributes['color'], 'name' => $attributes['attribute_name'], 'nbr' => (int) $attributes['nbr'], 'url_name' => $attributes['value_url_name'], 'meta_title' => $attributes['value_meta_title']);
                            }
                            if (isset($selected_filters['id_attribute_group'][$attributes['id_attribute']])) {
                                $attributes_array[$attributes['id_attribute_group']]['values'][$attributes['id_attribute']]['checked'] = true;
                            }
                        }
                        $filter_blocks = array_merge($filter_blocks, $attributes_array);
                    }
                    break;
                case 'id_feature':
                    $feature_array = array();
                    if (isset($products) && $products) {
                        foreach ($products as $feature) {
                            if (!isset($feature_array[$feature['id_feature']])) {
                                $feature_array[$feature['id_feature']] = array('type_lite' => 'id_feature', 'type' => 'id_feature', 'id_key' => (int) $feature['id_feature'], 'values' => array(), 'name' => $feature['feature_name'], 'url_name' => $feature['name_url_name'], 'meta_title' => $feature['name_meta_title'], 'filter_show_limit' => $filter['filter_show_limit'], 'filter_type' => $filter['filter_type']);
                            }
                            if (!isset($feature_array[$feature['id_feature']]['values'][$feature['id_feature_value']])) {
                                $feature_array[$feature['id_feature']]['values'][$feature['id_feature_value']] = array('nbr' => (int) $feature['nbr'], 'name' => $feature['value'], 'url_name' => $feature['value_url_name'], 'meta_title' => $feature['value_meta_title']);
                            }
                            if (isset($selected_filters['id_feature'][$feature['id_feature_value']])) {
                                $feature_array[$feature['id_feature']]['values'][$feature['id_feature_value']]['checked'] = true;
                            }
                        }
                        $filter_blocks = array_merge($filter_blocks, $feature_array);
                    }
                    break;
                case 'category':
                    $tmp_array = array();
                    if (isset($products) && $products) {
                        $categories_with_products_count = 0;
                        foreach ($products as $category) {
                            $tmp_array[$category['id_category']] = array('name' => $category['name'], 'nbr' => (int) $category['count_products']);
                            if ((int) $category['count_products']) {
                                $categories_with_products_count++;
                            }
                            if (isset($selected_filters['category']) && in_array($category['id_category'], $selected_filters['category'])) {
                                $tmp_array[$category['id_category']]['checked'] = true;
                            }
                        }
                        if ($categories_with_products_count || !Configuration::get('PS_LAYERED_HIDE_0_VALUES')) {
                            $filter_blocks[] = array('type_lite' => 'category', 'type' => 'category', 'id_key' => 0, 'name' => $this->l('Categories'), 'values' => $tmp_array, 'filter_show_limit' => $filter['filter_show_limit'], 'filter_type' => $filter['filter_type']);
                        }
                    }
                    break;
            }
        }
        // All non indexable attribute and feature
        $non_indexable = array();
        // Get all non indexable attribute groups
        foreach (Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS('
		SELECT public_name
		FROM `' . _DB_PREFIX_ . 'attribute_group_lang` agl
		LEFT JOIN `' . _DB_PREFIX_ . 'layered_indexable_attribute_group` liag
		ON liag.id_attribute_group = agl.id_attribute_group
		WHERE indexable IS NULL OR indexable = 0
		AND id_lang = ' . $id_lang) as $attribute) {
            $non_indexable[] = Tools::link_rewrite($attribute['public_name']);
        }
        // Get all non indexable features
        foreach (Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS('
		SELECT name
		FROM `' . _DB_PREFIX_ . 'feature_lang` fl
		LEFT JOIN  `' . _DB_PREFIX_ . 'layered_indexable_feature` lif
		ON lif.id_feature = fl.id_feature
		WHERE indexable IS NULL OR indexable = 0
		AND id_lang = ' . $id_lang) as $attribute) {
            $non_indexable[] = Tools::link_rewrite($attribute['name']);
        }
        //generate SEO link
        $param_selected = '';
        $param_product_url = '';
        $option_checked_array = array();
        $param_group_selected_array = array();
        $title_values = array();
        $meta_values = array();
        //get filters checked by group
        foreach ($filter_blocks as $type_filter) {
            $filter_name = !empty($type_filter['url_name']) ? $type_filter['url_name'] : $type_filter['name'];
            $filter_meta = !empty($type_filter['meta_title']) ? $type_filter['meta_title'] : '';
            $attr_key = $type_filter['type'] . '_' . $type_filter['id_key'];
            $param_group_selected = '';
            foreach ($type_filter['values'] as $key => $value) {
                if (is_array($value) && array_key_exists('checked', $value)) {
                    $value_name = !empty($value['url_name']) ? $value['url_name'] : $value['name'];
                    $value_meta = !empty($value['meta_title']) ? $value['meta_title'] : $value['name'];
                    $param_group_selected .= '-' . str_replace('-', '_', Tools::link_rewrite($value_name));
                    $param_group_selected_array[Tools::link_rewrite($filter_name)][] = Tools::link_rewrite($value_name);
                    if (!isset($title_values[$filter_name])) {
                        $title_values[$filter_name] = array();
                    }
                    $title_values[$filter_name][] = $value_name;
                    if (!isset($meta_values[$attr_key])) {
                        $meta_values[$attr_key] = array('title' => $filter_meta, 'values' => array());
                    }
                    $meta_values[$attr_key]['values'][] = $value_meta;
                } else {
                    $param_group_selected_array[Tools::link_rewrite($filter_name)][] = array();
                }
            }
            if (!empty($param_group_selected)) {
                $param_selected .= '/' . str_replace('-', '_', Tools::link_rewrite($filter_name)) . $param_group_selected;
                $option_checked_array[Tools::link_rewrite($filter_name)] = $param_group_selected;
            }
            // select only attribute and group attribute to display an unique product combination link
            if (!empty($param_group_selected) && $type_filter['type'] == 'id_attribute_group') {
                $param_product_url .= '/' . str_replace('-', '_', Tools::link_rewrite($filter_name)) . $param_group_selected;
            }
        }
        if ($this->page > 1) {
            $param_selected .= '/page-' . $this->page;
        }
        $blacklist = array('weight', 'price');
        if (!Configuration::get('PS_LAYERED_FILTER_INDEX_CDT')) {
            $blacklist[] = 'condition';
        }
        if (!Configuration::get('PS_LAYERED_FILTER_INDEX_QTY')) {
            $blacklist[] = 'quantity';
        }
        if (!Configuration::get('PS_LAYERED_FILTER_INDEX_MNF')) {
            $blacklist[] = 'manufacturer';
        }
        if (!Configuration::get('PS_LAYERED_FILTER_INDEX_CAT')) {
            $blacklist[] = 'category';
        }
        $global_nofollow = false;
        foreach ($filter_blocks as &$type_filter) {
            $filter_name = !empty($type_filter['url_name']) ? $type_filter['url_name'] : $type_filter['name'];
            if (count($type_filter) > 0 && !isset($type_filter['slider'])) {
                foreach ($type_filter['values'] as $key => $values) {
                    $nofollow = false;
                    if (!empty($values['checked']) && in_array($type_filter['type'], $blacklist)) {
                        $global_nofollow = true;
                    }
                    $option_checked_clone_array = $option_checked_array;
                    // If not filters checked, add parameter
                    $value_name = !empty($values['url_name']) ? $values['url_name'] : $values['name'];
                    if (!in_array(Tools::link_rewrite($value_name), $param_group_selected_array[Tools::link_rewrite($filter_name)])) {
                        // Update parameter filter checked before
                        if (array_key_exists(Tools::link_rewrite($filter_name), $option_checked_array)) {
                            $option_checked_clone_array[Tools::link_rewrite($filter_name)] = $option_checked_clone_array[Tools::link_rewrite($filter_name)] . '-' . str_replace('-', '_', Tools::link_rewrite($value_name));
                            $nofollow = true;
                        } else {
                            $option_checked_clone_array[Tools::link_rewrite($filter_name)] = '-' . str_replace('-', '_', Tools::link_rewrite($value_name));
                        }
                    } else {
                        // Remove selected parameters
                        $option_checked_clone_array[Tools::link_rewrite($filter_name)] = str_replace('-' . str_replace('-', '_', Tools::link_rewrite($value_name)), '', $option_checked_clone_array[Tools::link_rewrite($filter_name)]);
                        if (empty($option_checked_clone_array[Tools::link_rewrite($filter_name)])) {
                            unset($option_checked_clone_array[Tools::link_rewrite($filter_name)]);
                        }
                    }
                    $parameters = '';
                    ksort($option_checked_clone_array);
                    // Order parameters
                    foreach ($option_checked_clone_array as $key_group => $value_group) {
                        $parameters .= '/' . str_replace('-', '_', $key_group) . $value_group;
                    }
                    // Check if there is an non indexable attribute or feature in the url
                    foreach ($non_indexable as $value) {
                        if (strpos($parameters, '/' . $value) !== false) {
                            $nofollow = true;
                        }
                    }
                    $type_filter['values'][$key]['link'] = Context::getContext()->link->getCategoryLink($parent, null, null, ltrim($parameters, '/'));
                    $type_filter['values'][$key]['rel'] = $nofollow ? 'nofollow' : '';
                }
            }
        }
        $n_filters = 0;
        if (isset($selected_filters['price'])) {
            if ($price_array['min'] == $selected_filters['price'][0] && $price_array['max'] == $selected_filters['price'][1]) {
                unset($selected_filters['price']);
            }
        }
        if (isset($selected_filters['weight'])) {
            if ($weight_array['min'] == $selected_filters['weight'][0] && $weight_array['max'] == $selected_filters['weight'][1]) {
                unset($selected_filters['weight']);
            }
        }
        foreach ($selected_filters as $filters) {
            $n_filters += count($filters);
        }
        $cache = array('layered_show_qties' => (int) Configuration::get('PS_LAYERED_SHOW_QTIES'), 'id_category_layered' => (int) $id_parent, 'selected_filters' => $selected_filters, 'n_filters' => (int) $n_filters, 'nbr_filterBlocks' => count($filter_blocks), 'filters' => $filter_blocks, 'title_values' => $title_values, 'meta_values' => $meta_values, 'current_friendly_url' => $param_selected, 'param_product_url' => $param_product_url, 'no_follow' => !empty($param_selected) || $global_nofollow);
        return $cache;
    }
Example #26
0
 protected function getSellerLinkRwrite()
 {
     if (Validate::isLoadedObject($this->seller_info) and !empty($this->seller_info->company)) {
         return $this->seller_info->company;
     }
     if (Validate::isLoadedObject($this->seller)) {
         return $this->seller->lastname + '-' + Tools::link_rewrite($this->seller->firstname);
     }
     return '';
 }
Example #27
0
 public function productImport()
 {
     global $cookie;
     $this->receiveTab();
     $handle = $this->openCsvFile();
     $defaultLanguageId = (int) Configuration::get('PS_LANG_DEFAULT');
     self::setLocale();
     for ($current_line = 0; $line = fgetcsv($handle, MAX_LINE_SIZE, Tools::getValue('separator')); $current_line++) {
         if (Tools::getValue('convert')) {
             $line = $this->utf8_encode_array($line);
         }
         $info = self::getMaskedRow($line);
         if (array_key_exists('id', $info) and (int) $info['id'] and Product::existsInDatabase((int) $info['id'], 'product')) {
             $product = new Product((int) $info['id']);
             $categoryData = Product::getProductCategories((int) $product->id);
             foreach ($categoryData as $tmp) {
                 $product->category[] = $tmp;
             }
         } else {
             $product = new Product();
         }
         self::setEntityDefaultValues($product);
         self::array_walk($info, array('AdminImport', 'fillInfo'), $product);
         if ((int) $product->id_tax_rules_group != 0) {
             if (Validate::isLoadedObject(new TaxRulesGroup($product->id_tax_rules_group))) {
                 $product->tax_rate = TaxRulesGroup::getTaxesRate((int) $product->id_tax_rules_group, Configuration::get('PS_COUNTRY_DEFAULT'), 0, 0);
             } else {
                 $this->_addProductWarning('id_tax_rules_group', $product->id_tax_rules_group, Tools::displayError('Invalid tax rule group ID, you first need a group with this ID.'));
             }
         }
         if (isset($product->manufacturer) and is_numeric($product->manufacturer) and Manufacturer::manufacturerExists((int) $product->manufacturer)) {
             $product->id_manufacturer = (int) $product->manufacturer;
         } elseif (isset($product->manufacturer) and is_string($product->manufacturer) and !empty($product->manufacturer)) {
             if ($manufacturer = Manufacturer::getIdByName($product->manufacturer)) {
                 $product->id_manufacturer = (int) $manufacturer;
             } else {
                 $manufacturer = new Manufacturer();
                 $manufacturer->name = $product->manufacturer;
                 if (($fieldError = $manufacturer->validateFields(UNFRIENDLY_ERROR, true)) === true and ($langFieldError = $manufacturer->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true and $manufacturer->add()) {
                     $product->id_manufacturer = (int) $manufacturer->id;
                 } else {
                     $this->_errors[] = $manufacturer->name . (isset($manufacturer->id) ? ' (' . $manufacturer->id . ')' : '') . ' ' . Tools::displayError('Cannot be saved');
                     $this->_errors[] = ($fieldError !== true ? $fieldError : '') . ($langFieldError !== true ? $langFieldError : '') . mysql_error();
                 }
             }
         }
         if (isset($product->supplier) and is_numeric($product->supplier) and Supplier::supplierExists((int) $product->supplier)) {
             $product->id_supplier = (int) $product->supplier;
         } elseif (isset($product->supplier) and is_string($product->supplier) and !empty($product->supplier)) {
             if ($supplier = Supplier::getIdByName($product->supplier)) {
                 $product->id_supplier = (int) $supplier;
             } else {
                 $supplier = new Supplier();
                 $supplier->name = $product->supplier;
                 if (($fieldError = $supplier->validateFields(UNFRIENDLY_ERROR, true)) === true and ($langFieldError = $supplier->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true and $supplier->add()) {
                     $product->id_supplier = (int) $supplier->id;
                 } else {
                     $this->_errors[] = $supplier->name . (isset($supplier->id) ? ' (' . $supplier->id . ')' : '') . ' ' . Tools::displayError('Cannot be saved');
                     $this->_errors[] = ($fieldError !== true ? $fieldError : '') . ($langFieldError !== true ? $langFieldError : '') . mysql_error();
                 }
             }
         }
         if (isset($product->price_tex) and !isset($product->price_tin)) {
             $product->price = $product->price_tex;
         } elseif (isset($product->price_tin) and !isset($product->price_tex)) {
             $product->price = $product->price_tin;
             // If a tax is already included in price, withdraw it from price
             if ($product->tax_rate) {
                 $product->price = (double) number_format($product->price / (1 + $product->tax_rate / 100), 6, '.', '');
             }
         } elseif (isset($product->price_tin) and isset($product->price_tex)) {
             $product->price = $product->price_tex;
         }
         if (isset($product->category) and is_array($product->category) and sizeof($product->category)) {
             $product->id_category = array();
             // Reset default values array
             foreach ($product->category as $value) {
                 if (is_numeric($value)) {
                     if (Category::categoryExists((int) $value)) {
                         $product->id_category[] = (int) $value;
                     } else {
                         $categoryToCreate = new Category();
                         $categoryToCreate->id = (int) $value;
                         $categoryToCreate->name = self::createMultiLangField($value);
                         $categoryToCreate->active = 1;
                         $categoryToCreate->id_parent = 1;
                         // Default parent is home for unknown category to create
                         if (($fieldError = $categoryToCreate->validateFields(UNFRIENDLY_ERROR, true)) === true and ($langFieldError = $categoryToCreate->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true and $categoryToCreate->add()) {
                             $product->id_category[] = (int) $categoryToCreate->id;
                         } else {
                             $this->_errors[] = $categoryToCreate->name[$defaultLanguageId] . (isset($categoryToCreate->id) ? ' (' . $categoryToCreate->id . ')' : '') . ' ' . Tools::displayError('Cannot be saved');
                             $this->_errors[] = ($fieldError !== true ? $fieldError : '') . ($langFieldError !== true ? $langFieldError : '') . mysql_error();
                         }
                     }
                 } elseif (is_string($value) and !empty($value)) {
                     $category = Category::searchByName($defaultLanguageId, $value, true);
                     if ($category['id_category']) {
                         $product->id_category[] = (int) $category['id_category'];
                     } else {
                         $categoryToCreate = new Category();
                         $categoryToCreate->name = self::createMultiLangField($value);
                         $categoryToCreate->active = 1;
                         $categoryToCreate->id_parent = 1;
                         // Default parent is home for unknown category to create
                         if (($fieldError = $categoryToCreate->validateFields(UNFRIENDLY_ERROR, true)) === true and ($langFieldError = $categoryToCreate->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true and $categoryToCreate->add()) {
                             $product->id_category[] = (int) $categoryToCreate->id;
                         } else {
                             $this->_errors[] = $categoryToCreate->name[$defaultLanguageId] . (isset($categoryToCreate->id) ? ' (' . $categoryToCreate->id . ')' : '') . ' ' . Tools::displayError('Cannot be saved');
                             $this->_errors[] = ($fieldError !== true ? $fieldError : '') . ($langFieldError !== true ? $langFieldError : '') . mysql_error();
                         }
                     }
                 }
             }
         }
         $product->id_category_default = isset($product->id_category[0]) ? (int) $product->id_category[0] : '';
         $link_rewrite = is_array($product->link_rewrite) && count($product->link_rewrite) ? $product->link_rewrite[$defaultLanguageId] : '';
         $valid_link = Validate::isLinkRewrite($link_rewrite);
         if (isset($product->link_rewrite[$defaultLanguageId]) and empty($product->link_rewrite[$defaultLanguageId]) or !$valid_link) {
             $link_rewrite = Tools::link_rewrite($product->name[$defaultLanguageId]);
             if ($link_rewrite == '') {
                 $link_rewrite = 'friendly-url-autogeneration-failed';
             }
         }
         if (!$valid_link) {
             $this->_warnings[] = Tools::displayError('Rewrite link for') . ' ' . $link_rewrite . (isset($info['id']) ? ' (ID ' . $info['id'] . ') ' : '') . ' ' . Tools::displayError('was re-written as') . ' ' . $link_rewrite;
         }
         $product->link_rewrite = self::createMultiLangField($link_rewrite);
         $res = false;
         $fieldError = $product->validateFields(UNFRIENDLY_ERROR, true);
         $langFieldError = $product->validateFieldsLang(UNFRIENDLY_ERROR, true);
         if ($fieldError === true and $langFieldError === true) {
             // check quantity
             if ($product->quantity == NULL) {
                 $product->quantity = 0;
             }
             // If match ref is specified AND ref product AND ref product already in base, trying to update
             if (Tools::getValue('match_ref') == 1 and $product->reference and Product::existsRefInDatabase($product->reference)) {
                 $datas = Db::getInstance()->getRow('SELECT `date_add`, `id_product` FROM `' . _DB_PREFIX_ . 'product` WHERE `reference` = "' . $product->reference . '"');
                 $product->id = pSQL($datas['id_product']);
                 $product->date_add = pSQL($datas['date_add']);
                 $res = $product->update();
             } else {
                 if ($product->id and Product::existsInDatabase((int) $product->id, 'product')) {
                     $datas = Db::getInstance()->getRow('SELECT `date_add` FROM `' . _DB_PREFIX_ . 'product` WHERE `id_product` = ' . (int) $product->id);
                     $product->date_add = pSQL($datas['date_add']);
                     $res = $product->update();
                 }
             }
             // If no id_product or update failed
             if (!$res) {
                 if (isset($product->date_add) && $product->date_add != '') {
                     $res = $product->add(false);
                 } else {
                     $res = $product->add();
                 }
             }
         }
         // If both failed, mysql error
         if (!$res) {
             $this->_errors[] = $info['name'] . (isset($info['id']) ? ' (ID ' . $info['id'] . ')' : '') . ' ' . Tools::displayError('Cannot be saved');
             $this->_errors[] = ($fieldError !== true ? $fieldError : '') . ($langFieldError !== true ? $langFieldError : '') . mysql_error();
         } else {
             // SpecificPrice (only the basic reduction feature is supported by the import)
             if (isset($info['reduction_price']) and $info['reduction_price'] > 0 or isset($info['reduction_percent']) and $info['reduction_percent'] > 0) {
                 $specificPrice = new SpecificPrice();
                 $specificPrice->id_product = (int) $product->id;
                 $specificPrice->id_shop = (int) Shop::getCurrentShop();
                 $specificPrice->id_currency = 0;
                 $specificPrice->id_country = 0;
                 $specificPrice->id_group = 0;
                 $specificPrice->price = 0.0;
                 $specificPrice->from_quantity = 1;
                 $specificPrice->reduction = (isset($info['reduction_price']) and $info['reduction_price']) ? $info['reduction_price'] : $info['reduction_percent'] / 100;
                 $specificPrice->reduction_type = (isset($info['reduction_price']) and $info['reduction_price']) ? 'amount' : 'percentage';
                 $specificPrice->from = (isset($info['reduction_from']) and Validate::isDate($info['reduction_from'])) ? $info['reduction_from'] : '0000-00-00 00:00:00';
                 $specificPrice->to = (isset($info['reduction_to']) and Validate::isDate($info['reduction_to'])) ? $info['reduction_to'] : '0000-00-00 00:00:00';
                 if (!$specificPrice->add()) {
                     $this->_addProductWarning($info['name'], $product->id, $this->l('Discount is invalid'));
                 }
             }
             if (isset($product->tags) and !empty($product->tags)) {
                 // Delete tags for this id product, for no duplicating error
                 Tag::deleteTagsForProduct($product->id);
                 $tag = new Tag();
                 if (!is_array($product->tags)) {
                     $product->tags = self::createMultiLangField($product->tags);
                     foreach ($product->tags as $key => $tags) {
                         $isTagAdded = $tag->addTags($key, $product->id, $tags);
                         if (!$isTagAdded) {
                             $this->_addProductWarning($info['name'], $product->id, $this->l('Tags list') . ' ' . $this->l('is invalid'));
                             break;
                         }
                     }
                 } else {
                     foreach ($product->tags as $key => $tags) {
                         $str = '';
                         foreach ($tags as $one_tag) {
                             $str .= $one_tag . ',';
                         }
                         $str = rtrim($str, ',');
                         $isTagAdded = $tag->addTags($key, $product->id, $str);
                         if (!$isTagAdded) {
                             $this->_addProductWarning($info['name'], $product->id, 'Invalid tag(s) (' . $str . ')');
                             break;
                         }
                     }
                 }
             }
             //delete existing images if "delete_existing_images" is set to 1
             if (isset($product->delete_existing_images)) {
                 if ((bool) $product->delete_existing_images) {
                     $product->deleteImages();
                 } elseif (isset($product->image) and is_array($product->image) and sizeof($product->image)) {
                     $product->deleteImages();
                 }
             }
             if (isset($product->image) and is_array($product->image) and sizeof($product->image)) {
                 $productHasImages = (bool) Image::getImages((int) $cookie->id_lang, (int) $product->id);
                 foreach ($product->image as $key => $url) {
                     if (!empty($url)) {
                         $image = new Image();
                         $image->id_product = (int) $product->id;
                         $image->position = Image::getHighestPosition($product->id) + 1;
                         $image->cover = (!$key and !$productHasImages) ? true : false;
                         $image->legend = self::createMultiLangField($product->name[$defaultLanguageId]);
                         if (($fieldError = $image->validateFields(UNFRIENDLY_ERROR, true)) === true and ($langFieldError = $image->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true and $image->add()) {
                             if (!self::copyImg($product->id, $image->id, $url)) {
                                 $this->_warnings[] = Tools::displayError('Error copying image: ') . $url;
                             }
                         } else {
                             $this->_warnings[] = $image->legend[$defaultLanguageId] . (isset($image->id_product) ? ' (' . $image->id_product . ')' : '') . ' ' . Tools::displayError('Cannot be saved');
                             $this->_errors[] = ($fieldError !== true ? $fieldError : '') . ($langFieldError !== true ? $langFieldError : '') . mysql_error();
                         }
                     }
                 }
             }
             if (isset($product->id_category)) {
                 $product->updateCategories(array_map('intval', $product->id_category));
             }
             $features = get_object_vars($product);
             foreach ($features as $feature => $value) {
                 if (!strncmp($feature, '#F_', 3) and Tools::strlen($product->{$feature})) {
                     $feature_name = str_replace('#F_', '', $feature);
                     $id_feature = Feature::addFeatureImport($feature_name);
                     $id_feature_value = FeatureValue::addFeatureValueImport($id_feature, $product->{$feature});
                     Product::addFeatureProductImport($product->id, $id_feature, $id_feature_value);
                 }
             }
         }
     }
     $this->closeCsvFile($handle);
 }
Example #28
0
    /**
     * Return suppliers
     *
     * @return array Suppliers
     */
    public static function getSuppliers($getNbProducts = false, $id_lang = 0, $active = true, $p = false, $n = false, $all_groups = false)
    {
        if (!$id_lang) {
            $id_lang = Configuration::get('PS_LANG_DEFAULT');
        }
        $query = 'SELECT s.*, sl.`description`';
        $query .= ' FROM `' . _DB_PREFIX_ . 'supplier` as s
		LEFT JOIN `' . _DB_PREFIX_ . 'supplier_lang` sl ON (s.`id_supplier` = sl.`id_supplier` AND sl.`id_lang` = ' . (int) $id_lang . ')
		' . ($active ? ' WHERE s.`active` = 1 ' : '');
        $query .= ' ORDER BY s.`name` ASC' . ($p ? ' LIMIT ' . ((int) $p - 1) * (int) $n . ',' . (int) $n : '');
        $suppliers = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS($query);
        if ($suppliers === false) {
            return false;
        }
        if ($getNbProducts) {
            $sqlGroups = '';
            if (!$all_groups) {
                $groups = FrontController::getCurrentCustomerGroups();
                $sqlGroups = count($groups) ? 'IN (' . implode(',', $groups) . ')' : '= 1';
            }
            foreach ($suppliers as $key => $supplier) {
                $sql = '
					SELECT p.`id_product`
					FROM `' . _DB_PREFIX_ . 'product` p
					LEFT JOIN `' . _DB_PREFIX_ . 'supplier` as m ON (m.`id_supplier`= p.`id_supplier`)
					WHERE m.`id_supplier` = ' . (int) $supplier['id_supplier'] . ($active ? ' AND p.`active` = 1' : '') . ($all_groups ? '' : '
					AND p.`id_product` IN (
						SELECT cp.`id_product`
						FROM `' . _DB_PREFIX_ . 'category_group` cg
						LEFT JOIN `' . _DB_PREFIX_ . 'category_product` cp ON (cp.`id_category` = cg.`id_category`)
						WHERE cg.`id_group` ' . $sqlGroups . '
					)');
                $result = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS($sql);
                $suppliers[$key]['nb_products'] = sizeof($result);
            }
        }
        for ($i = 0; $i < sizeof($suppliers); $i++) {
            if ((int) Configuration::get('PS_REWRITING_SETTINGS')) {
                $suppliers[$i]['link_rewrite'] = Tools::link_rewrite($suppliers[$i]['name'], false);
            } else {
                $suppliers[$i]['link_rewrite'] = 0;
            }
        }
        return $suppliers;
    }
    /**
     * Return suppliers
     *
     * @return array Suppliers
     */
    public static function getSuppliers($getNbProducts = false, $id_lang = 0, $active = false, $p = false, $n = false)
    {
        global $cookie;
        if (!$id_lang) {
            $id_lang = Configuration::get('PS_LANG_DEFAULT');
        }
        $query = 'SELECT s.*, sl.`description`';
        $query .= ' FROM `' . _DB_PREFIX_ . 'supplier` as s
		LEFT JOIN `' . _DB_PREFIX_ . 'supplier_lang` sl ON (s.`id_supplier` = sl.`id_supplier` AND sl.`id_lang` = ' . intval($id_lang) . ')';
        $query .= ' ORDER BY s.`name` ASC' . ($p ? ' LIMIT ' . (intval($p) - 1) * intval($n) . ',' . intval($n) : '');
        $suppliers = Db::getInstance()->ExecuteS($query);
        if ($suppliers === false) {
            return false;
        }
        if ($getNbProducts) {
            foreach ($suppliers as $key => $supplier) {
                $sql = '
					SELECT p.`id_product`
					FROM `' . _DB_PREFIX_ . 'product` p
					LEFT JOIN `' . _DB_PREFIX_ . 'supplier` as m ON (m.`id_supplier`= p.`id_supplier`)
					WHERE m.`id_supplier` = ' . intval($supplier['id_supplier']) . '
					AND p.`id_product` IN (
						SELECT cp.`id_product`
						FROM `' . _DB_PREFIX_ . 'category_group` cg
						LEFT JOIN `' . _DB_PREFIX_ . 'category_product` cp ON (cp.`id_category` = cg.`id_category`)
						WHERE cg.`id_group` ' . (!$cookie->id_customer ? '= 1' : 'IN (SELECT id_group FROM ' . _DB_PREFIX_ . 'customer_group WHERE id_customer = ' . intval($cookie->id_customer) . ')') . '
					)';
                $result = Db::getInstance()->ExecuteS($sql);
                $suppliers[$key]['nb_products'] = sizeof($result);
            }
        }
        for ($i = 0; $i < sizeof($suppliers); $i++) {
            if (intval(Configuration::get('PS_REWRITING_SETTINGS'))) {
                $suppliers[$i]['link_rewrite'] = Tools::link_rewrite($suppliers[$i]['name'], false);
            } else {
                $suppliers[$i]['link_rewrite'] = 0;
            }
        }
        return $suppliers;
    }
Example #30
-1
 public function displayContent()
 {
     $id_product = (int) Tools::getValue('id_product');
     if (!empty($id_product)) {
         $this->nbShops = AphStore::getStoresByProduct($id_product, Context::getContext()->language->id, null, null, $this->orderBy, $this->orderWay, true);
         $this->pagination((int) $this->nbShops);
         // Pagination must be call after "getStoresByProduct"
         $this->shopSort();
         $shops = AphStore::getStoresByProduct($id_product, Context::getContext()->language->id, $this->p, $this->n, $this->orderBy, $this->orderWay);
         $id_currency = Validate::isLoadedObject(Context::getContext()->currency) ? (int) Context::getContext()->currency->id : (int) Configuration::get('PS_CURRENCY_DEFAULT');
         if (!empty($shops)) {
             foreach ($shops as &$shop) {
                 $product = new Product($id_product, (int) Context::getContext()->language->id, (int) $shop['id_shop']);
                 $shop['price_from'] = Tools::displayPrice($product->price, $id_currency);
                 //$url = !empty($ssl) ? 'https://'.$shop['domain_ssl'] : 'http://'.$shop['domain'];
                 //$shop['url'] = $url.$shop['uri'];
                 $shop['url'] = Context::getContext()->link->getModuleLink('blockshops', 'shop', array('ash' => $shop['virtual_uri'], 'ids' => $shop['id_shop']));
                 $shop['img_link_rewrite'] = Tools::link_rewrite($shop['legend']);
             }
         }
     }
     $this->context->smarty->assign(array('shops' => $shops, 'nb_shops' => $this->nbShops));
     $this->context->controller->addJS('blockshops.js');
     //return $this->display(__FILE__, 'blockshops.tpl', $this->getCacheId());
 }