Example #1
0
 public function categoryImport()
 {
     $catMoved = array();
     $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 (!isset($info['id']) || (int) $info['id'] < 2) {
             continue;
         }
         self::setDefaultValues($info);
         $category = new Category();
         self::array_walk($info, array('AdminImport', 'fillInfo'), $category);
         if (isset($category->parent) and is_numeric($category->parent)) {
             if (isset($catMoved[$category->parent])) {
                 $category->parent = $catMoved[$category->parent];
             }
             $category->id_parent = $category->parent;
         } elseif (isset($category->parent) and is_string($category->parent)) {
             $categoryParent = Category::searchByName($defaultLanguageId, $category->parent, true);
             if ($categoryParent['id_category']) {
                 $category->id_parent = (int) $categoryParent['id_category'];
             } else {
                 $categoryToCreate = new Category();
                 $categoryToCreate->name = self::createMultiLangField($category->parent);
                 $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()) {
                     $category->id_parent = $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();
                 }
             }
         }
         if (isset($category->link_rewrite) and !empty($category->link_rewrite[$defaultLanguageId])) {
             $valid_link = Validate::isLinkRewrite($category->link_rewrite[$defaultLanguageId]);
         } else {
             $valid_link = false;
         }
         $bak = $category->link_rewrite[$defaultLanguageId];
         if (isset($category->link_rewrite) and empty($category->link_rewrite[$defaultLanguageId]) or !$valid_link) {
             $category->link_rewrite = Tools::link_rewrite($category->name[$defaultLanguageId]);
             if ($category->link_rewrite == '') {
                 $category->link_rewrite = 'friendly-url-autogeneration-failed';
                 $this->_warnings[] = Tools::displayError('URL rewriting failed to auto-generate a friendly URL for: ') . $category->name[$defaultLanguageId];
             }
             $category->link_rewrite = self::createMultiLangField($category->link_rewrite);
         }
         if (!$valid_link) {
             $this->_warnings[] = Tools::displayError('Rewrite link for') . ' ' . $bak . (isset($info['id']) ? ' (ID ' . $info['id'] . ') ' : '') . ' ' . Tools::displayError('was re-written as') . ' ' . $category->link_rewrite[$defaultLanguageId];
         }
         $res = false;
         if (($fieldError = $category->validateFields(UNFRIENDLY_ERROR, true)) === true and ($langFieldError = $category->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true) {
             $categoryAlreadyCreated = Category::searchByNameAndParentCategoryId($defaultLanguageId, $category->name[$defaultLanguageId], $category->id_parent);
             // If category already in base, get id category back
             if ($categoryAlreadyCreated['id_category']) {
                 $catMoved[$category->id] = (int) $categoryAlreadyCreated['id_category'];
                 $category->id = (int) $categoryAlreadyCreated['id_category'];
             }
             /* No automatic nTree regeneration for import */
             $category->doNotRegenerateNTree = true;
             // If id category AND id category already in base, and not root category, trying to update
             if ($category->id and $category->categoryExists($category->id) and $category->id != 1) {
                 $res = $category->update();
             }
             if ($category->id == 1) {
                 $this->_errors[] = Tools::displayError('Root category cannot be modify');
             }
             // If no id_category or update failed
             if (!$res) {
                 $res = $category->add();
             }
         }
         //copying images of categories
         if (isset($category->image) and !empty($category->image)) {
             if (!self::copyImg($category->id, NULL, $category->image, 'categories')) {
                 $this->_warnings[] = $category->image . ' ' . Tools::displayError('Cannot be copied');
             }
         }
         // 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();
         }
     }
     /* Import has finished, we can regenerate the categories nested tree */
     Category::regenerateEntireNtree();
     $this->closeCsvFile($handle);
 }
Example #2
0
 /**
 * Search with Pathes for categories
 *
 * @param int $id_lang Language ID
 * @param string $path of category
 * @param bool $object_to_create a category
 *    * @param bool $method_to_create a category
 * @return array Corresponding categories
 */
 public static function searchByPath($id_lang, $path, $object_to_create = false, $method_to_create = false)
 {
     $categories = explode('/', trim($path));
     $category = $id_parent_category = false;
     if (is_array($categories) && count($categories)) {
         foreach ($categories as $category_name) {
             if ($id_parent_category) {
                 $category = Category::searchByNameAndParentCategoryId($id_lang, $category_name, $id_parent_category);
             } else {
                 $category = Category::searchByName($id_lang, $category_name, true, true);
             }
             if (!$category && $object_to_create && $method_to_create) {
                 call_user_func_array(array($object_to_create, $method_to_create), array($id_lang, $category_name, $id_parent_category));
                 $category = Category::searchByPath($id_lang, $category_name);
             }
             if (isset($category['id_category']) && $category['id_category']) {
                 $id_parent_category = (int) $category['id_category'];
             }
         }
     }
     return $category;
 }
    protected function categoryImportOne($info, $default_language_id, $id_lang, $force_ids, $regenerate, $shop_is_feature_active, &$cat_moved, $validateOnly = false)
    {
        $tab_categ = array(Configuration::get('PS_HOME_CATEGORY'), Configuration::get('PS_ROOT_CATEGORY'));
        if (isset($info['id']) && in_array((int) $info['id'], $tab_categ)) {
            $this->errors[] = Tools::displayError('The category ID must be unique. It can\'t be the same as the one for Root or Home category.');
            return;
        }
        AdminImportController::setDefaultValues($info);
        if ($force_ids && isset($info['id']) && (int) $info['id']) {
            $category = new Category((int) $info['id']);
        } else {
            if (isset($info['id']) && (int) $info['id'] && Category::existsInDatabase((int) $info['id'], 'category')) {
                $category = new Category((int) $info['id']);
            } else {
                $category = new Category();
            }
        }
        AdminImportController::arrayWalk($info, array('AdminImportController', 'fillInfo'), $category);
        // Parent category
        if (isset($category->parent) && is_numeric($category->parent)) {
            // Validation for parenting itself
            if ($validateOnly && $category->parent == $category->id || isset($info['id']) && $category->parent == (int) $info['id']) {
                $this->errors[] = sprintf(Tools::displayError('The category ID must be unique. It can\'t be the same as the one for the parent category (ID: %1$s).'), isset($info['id']) && !empty($info['id']) ? $info['id'] : 'null');
                return;
            }
            if (isset($cat_moved[$category->parent])) {
                $category->parent = $cat_moved[$category->parent];
            }
            $category->id_parent = $category->parent;
        } elseif (isset($category->parent) && is_string($category->parent)) {
            // Validation for parenting itself
            if ($validateOnly && isset($category->name) && $category->parent == $category->name) {
                $this->errors[] = sprintf(Tools::displayError('A category can\'t be its own parent. You should rename it (current name: %1$s).'), $category->parent);
                return;
            }
            $category_parent = Category::searchByName($id_lang, $category->parent, true);
            if ($category_parent['id_category']) {
                $category->id_parent = (int) $category_parent['id_category'];
                $category->level_depth = (int) $category_parent['level_depth'] + 1;
            } else {
                $category_to_create = new Category();
                $category_to_create->name = AdminImportController::createMultiLangField($category->parent);
                $category_to_create->active = 1;
                $category_link_rewrite = Tools::link_rewrite($category_to_create->name[$id_lang]);
                $category_to_create->link_rewrite = AdminImportController::createMultiLangField($category_link_rewrite);
                $category_to_create->id_parent = Configuration::get('PS_HOME_CATEGORY');
                // Default parent is home for unknown category to create
                if (($field_error = $category_to_create->validateFields(UNFRIENDLY_ERROR, true)) === true && ($lang_field_error = $category_to_create->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true && !$validateOnly && $category_to_create->add()) {
                    $category->id_parent = $category_to_create->id;
                } else {
                    if (!$validateOnly) {
                        $this->errors[] = sprintf($this->trans('%1$s (ID: %2$s) cannot be saved', array(), 'Admin.Parameters.Notification'), $category_to_create->name[$id_lang], 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();
                    }
                }
            }
        }
        if (isset($category->link_rewrite) && !empty($category->link_rewrite[$default_language_id])) {
            $valid_link = Validate::isLinkRewrite($category->link_rewrite[$default_language_id]);
        } else {
            $valid_link = false;
        }
        if (!$shop_is_feature_active) {
            $category->id_shop_default = 1;
        } else {
            $category->id_shop_default = (int) Context::getContext()->shop->id;
        }
        $bak = $category->link_rewrite[$default_language_id];
        if (isset($category->link_rewrite) && empty($category->link_rewrite[$default_language_id]) || !$valid_link) {
            $category->link_rewrite = Tools::link_rewrite($category->name[$default_language_id]);
            if ($category->link_rewrite == '') {
                $category->link_rewrite = 'friendly-url-autogeneration-failed';
                $this->warnings[] = sprintf($this->trans('URL rewriting failed to auto-generate a friendly URL for: %s', array(), 'Admin.Parameters.Notification'), $category->name[$default_language_id]);
            }
            $category->link_rewrite = AdminImportController::createMultiLangField($category->link_rewrite);
        }
        if (!$valid_link) {
            $this->informations[] = sprintf($this->trans('Rewrite link for %1$s (ID %2$s): re-written as %3$s.', array(), 'Admin.Parameters.Notification'), $bak, isset($info['id']) && !empty($info['id']) ? $info['id'] : 'null', $category->link_rewrite[$default_language_id]);
        }
        $res = false;
        if (($field_error = $category->validateFields(UNFRIENDLY_ERROR, true)) === true && ($lang_field_error = $category->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true && empty($this->errors)) {
            $category_already_created = Category::searchByNameAndParentCategoryId($id_lang, $category->name[$id_lang], $category->id_parent);
            // If category already in base, get id category back
            if ($category_already_created['id_category']) {
                $cat_moved[$category->id] = (int) $category_already_created['id_category'];
                $category->id = (int) $category_already_created['id_category'];
                if (Validate::isDate($category_already_created['date_add'])) {
                    $category->date_add = $category_already_created['date_add'];
                }
            }
            if ($category->id && $category->id == $category->id_parent) {
                $this->errors[] = sprintf($this->trans('A category cannot be its own parent. The parent category ID is either missing or unknown (ID: %1$s).', array(), 'Admin.Parameters.Notification'), isset($info['id']) && !empty($info['id']) ? $info['id'] : 'null');
                return;
            }
            /* No automatic nTree regeneration for import */
            $category->doNotRegenerateNTree = true;
            // If id category AND id category already in base, trying to update
            $categories_home_root = array(Configuration::get('PS_ROOT_CATEGORY'), Configuration::get('PS_HOME_CATEGORY'));
            if ($category->id && $category->categoryExists($category->id) && !in_array($category->id, $categories_home_root) && !$validateOnly) {
                $res = $category->update();
            }
            if ($category->id == Configuration::get('PS_ROOT_CATEGORY')) {
                $this->errors[] = $this->trans('The root category cannot be modified.', array(), 'Admin.Parameters.Notification');
            }
            // If no id_category or update failed
            $category->force_id = (bool) $force_ids;
            if (!$res && !$validateOnly) {
                $res = $category->add();
            }
        }
        // ValidateOnly mode : stops here
        if ($validateOnly) {
            return;
        }
        //copying images of categories
        if (isset($category->image) && !empty($category->image)) {
            if (!AdminImportController::copyImg($category->id, null, $category->image, 'categories', !$regenerate)) {
                $this->warnings[] = $category->image . ' ' . $this->trans('cannot be copied.', array(), 'Admin.Parameters.Notification');
            }
        }
        // If both failed, mysql error
        if (!$res) {
            $this->errors[] = sprintf(Tools::displayError('%1$s (ID: %2$s) cannot be ' . ($validateOnly ? 'validated' : 'saved')), isset($info['name']) && !empty($info['name']) ? Tools::safeOutput($info['name']) : 'No Name', isset($info['id']) && !empty($info['id']) ? Tools::safeOutput($info['id']) : 'No ID');
            $error_tmp = ($field_error !== true ? $field_error : '') . (isset($lang_field_error) && $lang_field_error !== true ? $lang_field_error : '') . Db::getInstance()->getMsgError();
            if ($error_tmp != '') {
                $this->errors[] = $error_tmp;
            }
        } else {
            // Associate category to shop
            if ($shop_is_feature_active) {
                Db::getInstance()->execute('
					DELETE FROM ' . _DB_PREFIX_ . 'category_shop
					WHERE id_category = ' . (int) $category->id);
                if (!$shop_is_feature_active) {
                    $info['shop'] = 1;
                } elseif (!isset($info['shop']) || empty($info['shop'])) {
                    $info['shop'] = implode($this->multiple_value_separator, Shop::getContextListShopID());
                }
                // Get shops for each attributes
                $info['shop'] = explode($this->multiple_value_separator, $info['shop']);
                foreach ($info['shop'] as $shop) {
                    if (!empty($shop) && !is_numeric($shop)) {
                        $category->addShop(Shop::getIdByName($shop));
                    } elseif (!empty($shop)) {
                        $category->addShop($shop);
                    }
                }
            }
        }
    }
    public function categoryImport()
    {
        $cat_moved = array();
        $this->receiveTab();
        $handle = $this->openCsvFile();
        $default_language_id = (int) Configuration::get('PS_LANG_DEFAULT');
        $id_lang = Language::getIdByIso(Tools::getValue('iso_lang'));
        if (!Validate::isUnsignedId($id_lang)) {
            $id_lang = $default_language_id;
        }
        AdminImportController::setLocale();
        for ($current_line = 0; $line = fgetcsv($handle, MAX_LINE_SIZE, $this->separator); $current_line++) {
            if (Tools::getValue('convert')) {
                $line = $this->utf8EncodeArray($line);
            }
            $info = AdminImportController::getMaskedRow($line);
            $tab_categ = array(Configuration::get('PS_HOME_CATEGORY'), Configuration::get('PS_ROOT_CATEGORY'));
            if (isset($info['id']) && in_array((int) $info['id'], $tab_categ)) {
                $this->errors[] = Tools::displayError('The category ID cannot be the same as the Root category ID or the Home category ID.');
                continue;
            }
            AdminImportController::setDefaultValues($info);
            if (Tools::getValue('forceIDs') && isset($info['id']) && (int) $info['id']) {
                $category = new Category((int) $info['id']);
            } else {
                if (isset($info['id']) && (int) $info['id'] && Category::existsInDatabase((int) $info['id'], 'category')) {
                    $category = new Category((int) $info['id']);
                } else {
                    $category = new Category();
                }
            }
            AdminImportController::arrayWalk($info, array('AdminImportController', 'fillInfo'), $category);
            if (isset($category->parent) && is_numeric($category->parent)) {
                if (isset($cat_moved[$category->parent])) {
                    $category->parent = $cat_moved[$category->parent];
                }
                $category->id_parent = $category->parent;
            } elseif (isset($category->parent) && is_string($category->parent)) {
                $category_parent = Category::searchByName($id_lang, $category->parent, true);
                if ($category_parent['id_category']) {
                    $category->id_parent = (int) $category_parent['id_category'];
                    $category->level_depth = (int) $category_parent['level_depth'] + 1;
                } else {
                    $category_to_create = new Category();
                    $category_to_create->name = AdminImportController::createMultiLangField($category->parent);
                    $category_to_create->active = 1;
                    $category_link_rewrite = Tools::link_rewrite($category_to_create->name[$id_lang]);
                    $category_to_create->link_rewrite = AdminImportController::createMultiLangField($category_link_rewrite);
                    $category_to_create->id_parent = Configuration::get('PS_HOME_CATEGORY');
                    // Default parent is home for unknown category to create
                    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()) {
                        $category->id_parent = $category_to_create->id;
                    } else {
                        $this->errors[] = sprintf(Tools::displayError('%1$s (ID: %2$s) cannot be saved'), $category_to_create->name[$id_lang], isset($category_to_create->id) && !empty($category_to_create->id) ? $category_to_create->id : 'null');
                        $this->errors[] = ($field_error !== true ? $field_error : '') . (isset($lang_field_error) && $lang_field_error !== true ? $lang_field_error : '') . Db::getInstance()->getMsgError();
                    }
                }
            }
            if (isset($category->link_rewrite) && !empty($category->link_rewrite[$default_language_id])) {
                $valid_link = Validate::isLinkRewrite($category->link_rewrite[$default_language_id]);
            } else {
                $valid_link = false;
            }
            if (!Shop::isFeatureActive()) {
                $category->id_shop_default = 1;
            } else {
                $category->id_shop_default = (int) Context::getContext()->shop->id;
            }
            $bak = $category->link_rewrite[$default_language_id];
            if (isset($category->link_rewrite) && empty($category->link_rewrite[$default_language_id]) || !$valid_link) {
                $category->link_rewrite = Tools::link_rewrite($category->name[$default_language_id]);
                if ($category->link_rewrite == '') {
                    $category->link_rewrite = 'friendly-url-autogeneration-failed';
                    $this->warnings[] = sprintf(Tools::displayError('URL rewriting failed to auto-generate a friendly URL for: %s'), $category->name[$default_language_id]);
                }
                $category->link_rewrite = AdminImportController::createMultiLangField($category->link_rewrite);
            }
            if (!$valid_link) {
                $this->warnings[] = sprintf(Tools::displayError('Rewrite link for %1$s (ID: %2$s) was re-written as %3$s.'), $bak, isset($info['id']) && !empty($info['id']) ? $info['id'] : 'null', $category->link_rewrite[$default_language_id]);
            }
            $res = false;
            if (($field_error = $category->validateFields(UNFRIENDLY_ERROR, true)) === true && ($lang_field_error = $category->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true && empty($this->errors)) {
                $category_already_created = Category::searchByNameAndParentCategoryId($id_lang, $category->name[$id_lang], $category->id_parent);
                // If category already in base, get id category back
                if ($category_already_created['id_category']) {
                    $cat_moved[$category->id] = (int) $category_already_created['id_category'];
                    $category->id = (int) $category_already_created['id_category'];
                    if (Validate::isDate($category_already_created['date_add'])) {
                        $category->date_add = $category_already_created['date_add'];
                    }
                }
                if ($category->id && $category->id == $category->id_parent) {
                    $this->errors[] = Tools::displayError('A category cannot be its own parent');
                    continue;
                }
                /* No automatic nTree regeneration for import */
                $category->doNotRegenerateNTree = true;
                // If id category AND id category already in base, trying to update
                $categories_home_root = array(Configuration::get('PS_ROOT_CATEGORY'), Configuration::get('PS_HOME_CATEGORY'));
                if ($category->id && $category->categoryExists($category->id) && !in_array($category->id, $categories_home_root)) {
                    $res = $category->update();
                }
                if ($category->id == Configuration::get('PS_ROOT_CATEGORY')) {
                    $this->errors[] = Tools::displayError('The root category cannot be modified.');
                }
                // If no id_category or update failed
                $category->force_id = (bool) Tools::getValue('forceIDs');
                if (!$res) {
                    $res = $category->add();
                }
            }
            //copying images of categories
            if (isset($category->image) && !empty($category->image)) {
                if (!AdminImportController::copyImg($category->id, null, $category->image, 'categories', !Tools::getValue('regenerate'))) {
                    $this->warnings[] = $category->image . ' ' . Tools::displayError('cannot be copied.');
                }
            }
            // If both failed, mysql error
            if (!$res) {
                $this->errors[] = sprintf(Tools::displayError('%1$s (ID: %2$s) cannot be saved'), isset($info['name']) && !empty($info['name']) ? Tools::safeOutput($info['name']) : 'No Name', isset($info['id']) && !empty($info['id']) ? Tools::safeOutput($info['id']) : 'No ID');
                $error_tmp = ($field_error !== true ? $field_error : '') . (isset($lang_field_error) && $lang_field_error !== true ? $lang_field_error : '') . Db::getInstance()->getMsgError();
                if ($error_tmp != '') {
                    $this->errors[] = $error_tmp;
                }
            } else {
                // Associate category to shop
                if (Shop::isFeatureActive()) {
                    Db::getInstance()->execute('
						DELETE FROM ' . _DB_PREFIX_ . 'category_shop
						WHERE id_category = ' . (int) $category->id);
                    if (!Shop::isFeatureActive()) {
                        $info['shop'] = 1;
                    } elseif (!isset($info['shop']) || empty($info['shop'])) {
                        $info['shop'] = implode($this->multiple_value_separator, Shop::getContextListShopID());
                    }
                    // Get shops for each attributes
                    $info['shop'] = explode($this->multiple_value_separator, $info['shop']);
                    foreach ($info['shop'] as $shop) {
                        if (!empty($shop) && !is_numeric($shop)) {
                            $category->addShop(Shop::getIdByName($shop));
                        } elseif (!empty($shop)) {
                            $category->addShop($shop);
                        }
                    }
                }
            }
        }
        /* Import has finished, we can regenerate the categories nested tree */
        Category::regenerateEntireNtree();
        $this->closeCsvFile($handle);
    }
Example #5
0
 public static function isBook($cart_products)
 {
     //Этот способ находит книги во вложенных категориях 20.06.2015
     $books_cat_ru_name = "Книги";
     $parent_for_books_cat_id = 2;
     $books_KNIGI_lang = 1;
     //echo "поиск категории Книги";
     $bookscat = Category::searchByNameAndParentCategoryId($books_KNIGI_lang, $books_cat_ru_name, $parent_for_books_cat_id);
     //var_dump($bookscat);
     $books_cat_id = $bookscat["id_category"];
     $books_nleft = $bookscat["nleft"];
     $books_nright = $bookscat["nright"];
     //$cart_products = $cart->getProducts();
     if (!empty($cart_products)) {
         $all_books = true;
         foreach ($cart_products as $key => $cart_product) {
             $product = new Product($cart_product['id_product']);
             $categories = $product->getCategories();
             //var_dump($categories);
             if (!empty($categories)) {
                 $product_is_book = false;
                 foreach ($categories as $key => $category) {
                     //echo $category;
                     if ($category == $books_cat_id) {
                         $product_is_book = true;
                         //echo "это в самих книгах";
                         break;
                     }
                     /*искать родителей до рута. если id родителя любого уровня = $books_cat_id, значить это книги*/
                     //echo "nleft ".$books_nleft;
                     //echo "nright ".$books_nright;
                     //echo "<br/><br/>";
                     $current_cat_id = $category;
                     while (1) {
                         $current_cat = new Category($current_cat_id);
                         //var_dump($current_cat->id_parent);
                         if ($current_cat->is_root_category == 1) {
                             //echo "это корневая категория";
                             break;
                         }
                         if ($current_cat->id_parent == $books_cat_id) {
                             $product_is_book = true;
                             //echo " это книга";
                             break;
                         }
                         $current_cat_id = $current_cat->id_parent;
                     }
                     if ($category >= $books_nleft and $category <= $books_nright) {
                         $product_is_book = true;
                         //echo " это книга";
                         break;
                     }
                     //echo " не книга";
                 }
             }
             if (!$product_is_book) {
                 $all_books = false;
                 break;
             }
         }
     }
     return $all_books;
 }
Example #6
0
	/**
	 *
	 * @param int $id_zone
	 * @param Array $groups group of the customer
	 * @return Array
	 */
	public static function getCarriersForOrder($id_zone, $groups = null, $cart = null)
	{
		
		$context = Context::getContext();
		$id_lang = $context->language->id;
		if (is_null($cart))
			$cart = $context->cart;
		$id_currency = $context->currency->id;

		if (is_array($groups) && !empty($groups))
			$result = Carrier::getCarriers($id_lang, true, false, (int)$id_zone, $groups, self::PS_CARRIERS_AND_CARRIER_MODULES_NEED_RANGE);
		else
			$result = Carrier::getCarriers($id_lang, true, false, (int)$id_zone, array(Configuration::get('PS_UNIDENTIFIED_GROUP')), self::PS_CARRIERS_AND_CARRIER_MODULES_NEED_RANGE);
		$results_array = array();
                
               // var_dump($result);
		foreach ($result as $k => $row)
		{
			$carrier = new Carrier((int)$row['id_carrier']);
			$shipping_method = $carrier->getShippingMethod();
			if ($shipping_method != Carrier::SHIPPING_METHOD_FREE)
			{
				// Get only carriers that are compliant with shipping method
				if (($shipping_method == Carrier::SHIPPING_METHOD_WEIGHT && $carrier->getMaxDeliveryPriceByWeight($id_zone) === false)
					|| ($shipping_method == Carrier::SHIPPING_METHOD_PRICE && $carrier->getMaxDeliveryPriceByPrice($id_zone) === false))
				{
					unset($result[$k]);
					continue;
				}

				// If out-of-range behavior carrier is set on "Desactivate carrier"
				if ($row['range_behavior'])
				{
					// Get id zone
					if (!$id_zone)
							$id_zone = Country::getIdZone(Country::getDefaultCountryId());

					// Get only carriers that have a range compatible with cart
					if (($shipping_method == Carrier::SHIPPING_METHOD_WEIGHT
						&& (!Carrier::checkDeliveryPriceByWeight($row['id_carrier'], $cart->getTotalWeight(), $id_zone)))
						|| ($shipping_method == Carrier::SHIPPING_METHOD_PRICE
						&& (!Carrier::checkDeliveryPriceByPrice($row['id_carrier'], $cart->getOrderTotal(true, Cart::BOTH_WITHOUT_SHIPPING), $id_zone, $id_currency))))
					{
						unset($result[$k]);
						continue;
					}
				}
			}

			$row['name'] = (strval($row['name']) != '0' ? $row['name'] : Configuration::get('PS_SHOP_NAME'));
			$row['price'] = (($shipping_method == Carrier::SHIPPING_METHOD_FREE) ? 0 : $cart->getPackageShippingCost((int)$row['id_carrier'], true, null, null, $id_zone));
			$row['price_tax_exc'] = (($shipping_method == Carrier::SHIPPING_METHOD_FREE) ? 0 : $cart->getPackageShippingCost((int)$row['id_carrier'], false, null, null, $id_zone));
			$row['img'] = file_exists(_PS_SHIP_IMG_DIR_.(int)$row['id_carrier']).'.jpg' ? _THEME_SHIP_DIR_.(int)$row['id_carrier'].'.jpg' : '';

			// If price is false, then the carrier is unavailable (carrier module)
			if ($row['price'] === false)
			{
                            $row['price'] = 0;
//				unset($result[$k]);
//				continue;
			}

			//Проверка, если способ доставки - DP, то этот способ доставки доступен, если в корзине только книги
			$log = '';
			$DeutschePostCarrierName = "Deutsche Post"; //название службы доставки "Deutsche post"
			
			$books_cat_ru_name = "Книги";
			$parent_for_books_cat_id = 2;
			$books_KNIGI_lang = 1;

			if ($row['name'] == $DeutschePostCarrierName) {
				//echo "поиск категории Книги";
				$bookscat = Category::searchByNameAndParentCategoryId($books_KNIGI_lang,$books_cat_ru_name,$parent_for_books_cat_id);
				//var_dump($bookscat);
				$books_cat_id = $bookscat["id_category"];
				/*
				id_category"]=> string(1) "3" ["id_parent"]=> string(1) "2" ["id_shop_default"]=> string(1) "1" ["level_depth"]=> string(1) "2" ["nleft"]=> string(1) "3" ["nright"]=> string(3) "102" ["active"]=> string(1) "1" ["date_add"]=> string(19) "2015-02-19 21:05:41" ["date_upd"]=> string(19) "2015-02-19 21:05:41" ["position"]=> string(1) "0" ["is_root_category"]=> string(1) "0" ["id_shop"]=> string(1) "1" ["id_lang"]=> string(1) "1" ["name"]=> string(10) "Книги" ["description"]=> string(0) "" ["link_rewrite"]=> string(5) "knigi" ["meta_title"]=> string(0) "" ["meta_keywords"]=> string(0) "" ["meta_description"]=> string(0) "" }

				*/
				/*
				$books_cat_id = 12; //id категории книги
				$BooksCategory = new Category($books_cat_id);
				$interval = $BooksCategory->getInterval($books_cat_id);
				
				$books_nleft = $interval['nleft'];//21;
				$books_nright = $interval['nright'];//134;
				*/
				$books_nleft = $bookscat["nleft"];
				$books_nright = $bookscat["nright"];
				$cart_products = $cart->getProducts();
				if (!empty($cart_products))
				{ 
					$all_books = true;
					foreach ($cart_products as $key => $cart_product)
					{
						$product = new Product($cart_product['id_product']);
						$categories = $product->getCategories();
						//var_dump($categories);
						if (!empty($categories))
						{
							$product_is_book = false;
							foreach ($categories as $key => $category) 
							{
								//echo $category;
								if ($category == $books_cat_id)
								{
									$product_is_book = true;
									//echo "это в самих книгах";
									break;
								}

								/*искать родителей до рута. если id родителя любого уровня = $books_cat_id, значить это книги*/
								//echo "nleft ".$books_nleft;
								//echo "nright ".$books_nright;
								//echo "<br/><br/>";
								$current_cat_id = $category;
								while (1)
								{
									$current_cat = new Category($current_cat_id);
									//var_dump($current_cat->id_parent);
									if ($current_cat->is_root_category == 1){
										//echo "это корневая категория";
										break;
									}
									if ($current_cat->id_parent == $books_cat_id)
									{
										$product_is_book = true;
										//echo " это книга";
										break;
									}
									$current_cat_id = $current_cat->id_parent;
									
								}
								
								
								if ($category >= $books_nleft AND $category <= $books_nright)
								{
									$product_is_book = true;
									//echo " это книга";
									break;
								}
								//echo " не книга";
							}
						}
						if (!$product_is_book) {
							$all_books = false;
							break;
						}
					}
					if (!$all_books){
						unset($result[$k]);
						continue;
					}
				}
				
			}
			//Конец проверки

			$results_array[] = $row;
		}


		// if we have to sort carriers by price
		$prices = array();
		if (Configuration::get('PS_CARRIER_DEFAULT_SORT') == Carrier::SORT_BY_PRICE)
		{
			foreach ($results_array as $r)
				$prices[] = $r['price'];
			if (Configuration::get('PS_CARRIER_DEFAULT_ORDER') == Carrier::SORT_BY_ASC)
				array_multisort($prices, SORT_ASC, SORT_NUMERIC, $results_array);
			else
				array_multisort($prices, SORT_DESC, SORT_NUMERIC, $results_array);
		}

		return $results_array;
	}
 public function addCategory($name, $parent_cat = false, $group_ids, $ishotel = false, $hotel_id = false)
 {
     if (!$parent_cat) {
         $parent_cat = Category::getRootCategory()->id;
     }
     if ($ishotel && $hotel_id) {
         $cat_id_hotel = Db::getInstance()->getValue('SELECT `id_category` FROM `' . _DB_PREFIX_ . 'htl_branch_info` WHERE id=' . $hotel_id);
         if ($cat_id_hotel) {
             $obj_cat = new Category($cat_id_hotel);
             $obj_cat->name = array();
             $obj_cat->description = array();
             $obj_cat->link_rewrite = array();
             foreach (Language::getLanguages(true) as $lang) {
                 $obj_cat->name[$lang['id_lang']] = $name;
                 $obj_cat->description[$lang['id_lang']] = $this->l('this category are for hotels only');
                 $obj_cat->link_rewrite[$lang['id_lang']] = $this->l(Tools::link_rewrite($name));
             }
             $obj_cat->id_parent = $parent_cat;
             $obj_cat->groupBox = $group_ids;
             $obj_cat->save();
             $cat_id = $obj_cat->id;
             return $cat_id;
         }
     }
     $check_category_exists = Category::searchByNameAndParentCategoryId($this->context->language->id, $name, $parent_cat);
     if ($check_category_exists) {
         return $check_category_exists['id_category'];
     } else {
         $obj = new Category();
         $obj->name = array();
         $obj->description = array();
         $obj->link_rewrite = array();
         foreach (Language::getLanguages(true) as $lang) {
             $obj->name[$lang['id_lang']] = $name;
             $obj->description[$lang['id_lang']] = $this->l('this category are for hotels only');
             $obj->link_rewrite[$lang['id_lang']] = $this->l(Tools::link_rewrite($name));
         }
         $obj->id_parent = $parent_cat;
         $obj->groupBox = $group_ids;
         $obj->add();
         $cat_id = $obj->id;
         return $cat_id;
     }
 }