function regenerate_level_depth()
{
    $category = new Category();
    $cats = $category->getSimpleCategories((int) Configuration::get('PS_LANG_DEFAULT'));
    foreach ($cats as $cat) {
        $category = new Category((int) $cat['id_category']);
        $catParent = new Category((int) $category->id_parent);
        $category->level_depth = $catParent->level_depth + 1;
        Db::getInstance()->Execute('UPDATE `' . _DB_PREFIX_ . 'category` SET `level_depth` = ' . (int) $category->level_depth . ' WHERE `id_category` = ' . (int) $category->id);
    }
    Category::regenerateEntireNtree();
}
 public function processPosition()
 {
     if ($this->tabAccess['edit'] !== '1') {
         $this->errors[] = Tools::displayError('You do not have permission to edit here.');
     } else {
         if (!Validate::isLoadedObject($object = new Category((int) Tools::getValue($this->identifier, Tools::getValue('id_category_to_move', 1))))) {
             $this->errors[] = Tools::displayError('An error occurred while updating status for object.') . ' <b>' . $this->table . '</b> ' . Tools::displayError('(cannot load object)');
         }
     }
     if (!$object->updatePosition((int) Tools::getValue('way'), (int) Tools::getValue('position'))) {
         $this->errors[] = Tools::displayError('Failed to update the position.');
     } else {
         $object->regenerateEntireNtree();
         Tools::redirectAdmin(self::$currentIndex . '&' . $this->table . 'Orderby=position&' . $this->table . 'Orderway=asc&conf=5' . (($id_category = (int) Tools::getValue($this->identifier, Tools::getValue('id_category_parent', 1))) ? '&' . $this->identifier . '=' . $id_category : '') . '&token=' . Tools::getAdminTokenLite('AdminCategories'));
     }
 }
Example #3
0
    public static function checkAndFix()
    {
        $db = Db::getInstance();
        $logs = array();
        // Remove doubles in the configuration
        $filtered_configuration = array();
        $result = $db->ExecuteS('SELECT * FROM ' . _DB_PREFIX_ . 'configuration');
        foreach ($result as $row) {
            $key = $row['id_shop_group'] . '-|-' . $row['id_shop'] . '-|-' . $row['name'];
            if (in_array($key, $filtered_configuration)) {
                $query = 'DELETE FROM ' . _DB_PREFIX_ . 'configuration WHERE id_configuration = ' . (int) $row['id_configuration'];
                $db->Execute($query);
                $logs[$query] = 1;
            } else {
                $filtered_configuration[] = $key;
            }
        }
        unset($filtered_configuration);
        // Remove inexisting or monolanguage configuration value from configuration_lang
        $query = 'DELETE FROM `' . _DB_PREFIX_ . 'configuration_lang`
		WHERE `id_configuration` NOT IN (SELECT `id_configuration` FROM `' . _DB_PREFIX_ . 'configuration`)
		OR `id_configuration` IN (SELECT `id_configuration` FROM `' . _DB_PREFIX_ . 'configuration` WHERE name IS NULL OR name = "")';
        if ($db->Execute($query)) {
            if ($affected_rows = $db->Affected_Rows()) {
                $logs[$query] = $affected_rows;
            }
        }
        // Simple Cascade Delete
        $queries = self::getCheckAndFixQueries();
        $queries = self::bulle($queries);
        foreach ($queries as $query_array) {
            // If this is a module and the module is not installed, we continue
            if (isset($query_array[4]) && !Module::isInstalled($query_array[4])) {
                continue;
            }
            $query = 'DELETE FROM `' . _DB_PREFIX_ . $query_array[0] . '` WHERE `' . $query_array[1] . '` NOT IN (SELECT `' . $query_array[3] . '` FROM `' . _DB_PREFIX_ . $query_array[2] . '`)';
            if ($db->Execute($query)) {
                if ($affected_rows = $db->Affected_Rows()) {
                    $logs[$query] = $affected_rows;
                }
            }
        }
        // _lang table cleaning
        $tables = Db::getInstance()->executeS('SHOW TABLES LIKE "' . preg_replace('/([%_])/', '\\$1', _DB_PREFIX_) . '%_\\_lang"');
        foreach ($tables as $table) {
            $table_lang = current($table);
            $table = str_replace('_lang', '', $table_lang);
            $id_table = 'id_' . preg_replace('/^' . _DB_PREFIX_ . '/', '', $table);
            $query = 'DELETE FROM `' . bqSQL($table_lang) . '` WHERE `' . bqSQL($id_table) . '` NOT IN (SELECT `' . bqSQL($id_table) . '` FROM `' . bqSQL($table) . '`)';
            if ($db->Execute($query)) {
                if ($affected_rows = $db->Affected_Rows()) {
                    $logs[$query] = $affected_rows;
                }
            }
            $query = 'DELETE FROM `' . bqSQL($table_lang) . '` WHERE `id_lang` NOT IN (SELECT `id_lang` FROM `' . _DB_PREFIX_ . 'lang`)';
            if ($db->Execute($query)) {
                if ($affected_rows = $db->Affected_Rows()) {
                    $logs[$query] = $affected_rows;
                }
            }
        }
        // _shop table cleaning
        $tables = Db::getInstance()->executeS('SHOW TABLES LIKE "' . preg_replace('/([%_])/', '\\$1', _DB_PREFIX_) . '%_\\_shop"');
        foreach ($tables as $table) {
            $table_shop = current($table);
            $table = str_replace('_shop', '', $table_shop);
            $id_table = 'id_' . preg_replace('/^' . _DB_PREFIX_ . '/', '', $table);
            if (in_array($table_shop, array(_DB_PREFIX_ . 'carrier_tax_rules_group_shop'))) {
                continue;
            }
            $query = 'DELETE FROM `' . bqSQL($table_shop) . '` WHERE `' . bqSQL($id_table) . '` NOT IN (SELECT `' . bqSQL($id_table) . '` FROM `' . bqSQL($table) . '`)';
            if ($db->Execute($query)) {
                if ($affected_rows = $db->Affected_Rows()) {
                    $logs[$query] = $affected_rows;
                }
            }
            $query = 'DELETE FROM `' . bqSQL($table_shop) . '` WHERE `id_shop` NOT IN (SELECT `id_shop` FROM `' . _DB_PREFIX_ . 'shop`)';
            if ($db->Execute($query)) {
                if ($affected_rows = $db->Affected_Rows()) {
                    $logs[$query] = $affected_rows;
                }
            }
        }
        // stock_available
        $query = 'DELETE FROM `' . _DB_PREFIX_ . 'stock_available` WHERE `id_shop` NOT IN (SELECT `id_shop` FROM `' . _DB_PREFIX_ . 'shop`) AND `id_shop_group` NOT IN (SELECT `id_shop_group` FROM `' . _DB_PREFIX_ . 'shop_group`)';
        if ($db->Execute($query)) {
            if ($affected_rows = $db->Affected_Rows()) {
                $logs[$query] = $affected_rows;
            }
        }
        Category::regenerateEntireNtree();
        // @Todo: Remove attachment files, images...
        Image::clearTmpDir();
        self::clearAllCaches();
        return $logs;
    }
Example #4
0
 public function delete()
 {
     if ((int) $this->id === 0 || (int) $this->id === (int) Configuration::get('PS_ROOT_CATEGORY')) {
         return false;
     }
     $this->clearCache();
     $deleted_children = $all_cat = $this->getAllChildren();
     $all_cat[] = $this;
     foreach ($all_cat as $cat) {
         /** @var Category $cat */
         $cat->deleteLite();
         if (!$this->hasMultishopEntries()) {
             $cat->deleteImage();
             $cat->cleanGroups();
             $cat->cleanAssoProducts();
             // Delete associated restrictions on cart rules
             CartRule::cleanProductRuleIntegrity('categories', array($cat->id));
             Category::cleanPositions($cat->id_parent);
             /* Delete Categories in GroupReduction */
             if (GroupReduction::getGroupsReductionByCategoryId((int) $cat->id)) {
                 GroupReduction::deleteCategory($cat->id);
             }
         }
     }
     /* Rebuild the nested tree */
     if (!$this->hasMultishopEntries() && (!isset($this->doNotRegenerateNTree) || !$this->doNotRegenerateNTree)) {
         Category::regenerateEntireNtree();
     }
     Hook::exec('actionCategoryDelete', array('category' => $this, 'deleted_children' => $deleted_children));
     return true;
 }
Example #5
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);
 }
 public function categoryImport($offset = false, $limit = false, &$crossStepsVariables = false, $validateOnly = false)
 {
     $this->receiveTab();
     $handle = $this->openCsvFile($offset);
     if (!$handle) {
         return false;
     }
     $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();
     $force_ids = Tools::getValue('forceIDs');
     $regenerate = Tools::getValue('regenerate');
     $shop_is_feature_active = Shop::isFeatureActive();
     $cat_moved = array();
     if ($crossStepsVariables !== false && array_key_exists('cat_moved', $crossStepsVariables)) {
         $cat_moved = $crossStepsVariables['cat_moved'];
     }
     $line_count = 0;
     for ($current_line = 0; ($line = fgetcsv($handle, MAX_LINE_SIZE, $this->separator)) && (!$limit || $current_line < $limit); $current_line++) {
         $line_count++;
         if ($this->convert) {
             $line = $this->utf8EncodeArray($line);
         }
         if (count($line) == 1 && $line[0] == null) {
             $this->warnings[] = $this->l('There is an empty row in the file that won\'t be imported.');
             continue;
         }
         $info = AdminImportController::getMaskedRow($line);
         $this->categoryImportOne($info, $default_language_id, $id_lang, $force_ids, $regenerate, $shop_is_feature_active, $cat_moved, $validateOnly);
     }
     if (!$validateOnly) {
         /* Import has finished, we can regenerate the categories nested tree */
         Category::regenerateEntireNtree();
     }
     $this->closeCsvFile($handle);
     if ($crossStepsVariables !== false) {
         $crossStepsVariables['cat_moved'] = $cat_moved;
     }
     return $line_count;
 }
Example #7
0
    public static function checkAndFix()
    {
        $db = Db::getInstance();
        $logs = array();
        // Remove doubles in the configuration
        $filtered_configuration = array();
        $result = $db->ExecuteS('SELECT * FROM ' . _DB_PREFIX_ . 'configuration');
        foreach ($result as $row) {
            $key = $row['id_shop_group'] . '-|-' . $row['id_shop'] . '-|-' . $row['name'];
            if (in_array($key, $filtered_configuration)) {
                $query = 'DELETE FROM ' . _DB_PREFIX_ . 'configuration WHERE id_configuration = ' . (int) $row['id_configuration'];
                $db->Execute($query);
                $logs[$query] = 1;
            } else {
                $filtered_configuration[] = $key;
            }
        }
        unset($filtered_configuration);
        // Remove inexisting or monolanguage configuration value from configuration_lang
        $query = 'DELETE FROM `' . _DB_PREFIX_ . 'configuration_lang`
		WHERE `id_configuration` NOT IN (SELECT `id_configuration` FROM `' . _DB_PREFIX_ . 'configuration`)
		OR `id_configuration` IN (SELECT `id_configuration` FROM `' . _DB_PREFIX_ . 'configuration` WHERE name IS NULL OR name = "")';
        if ($db->Execute($query)) {
            if ($affected_rows = $db->Affected_Rows()) {
                $logs[$query] = $affected_rows;
            }
        }
        // Simple Cascade Delete
        $queries = array(array('access', 'id_profile', 'profile', 'id_profile'), array('access', 'id_tab', 'tab', 'id_tab'), array('accessory', 'id_product_1', 'product', 'id_product'), array('accessory', 'id_product_2', 'product', 'id_product'), array('address_format', 'id_country', 'country', 'id_country'), array('attribute', 'id_attribute_group', 'attribute_group', 'id_attribute_group'), array('carrier_group', 'id_carrier', 'carrier', 'id_carrier'), array('carrier_group', 'id_group', 'group', 'id_group'), array('carrier_zone', 'id_carrier', 'carrier', 'id_carrier'), array('carrier_zone', 'id_zone', 'zone', 'id_zone'), array('cart_cart_rule', 'id_cart', 'cart', 'id_cart'), array('cart_product', 'id_cart', 'cart', 'id_cart'), array('cart_rule_carrier', 'id_cart_rule', 'cart_rule', 'id_cart_rule'), array('cart_rule_carrier', 'id_carrier', 'carrier', 'id_carrier'), array('cart_rule_combination', 'id_cart_rule_1', 'cart_rule', 'id_cart_rule'), array('cart_rule_combination', 'id_cart_rule_2', 'cart_rule', 'id_cart_rule'), array('cart_rule_country', 'id_cart_rule', 'cart_rule', 'id_cart_rule'), array('cart_rule_country', 'id_country', 'country', 'id_country'), array('cart_rule_group', 'id_cart_rule', 'cart_rule', 'id_cart_rule'), array('cart_rule_group', 'id_group', 'group', 'id_group'), array('cart_rule_product_rule_group', 'id_cart_rule', 'cart_rule', 'id_cart_rule'), array('cart_rule_product_rule', 'id_product_rule_group', 'cart_rule_product_rule_group', 'id_product_rule_group'), array('cart_rule_product_rule_value', 'id_product_rule', 'cart_rule_product_rule', 'id_product_rule'), array('category_group', 'id_category', 'category', 'id_category'), array('category_group', 'id_group', 'group', 'id_group'), array('category_product', 'id_category', 'category', 'id_category'), array('category_product', 'id_product', 'product', 'id_product'), array('cms', 'id_cms_category', 'cms_category', 'id_cms_category'), array('cms_block', 'id_cms_category', 'cms_category', 'id_cms_category', 'blockcms'), array('cms_block_page', 'id_cms', 'cms', 'id_cms', 'blockcms'), array('cms_block_page', 'id_cms_block', 'cms_block', 'id_cms_block', 'blockcms'), array('compare', 'id_customer', 'customer', 'id_customer'), array('compare_product', 'id_compare', 'compare', 'id_compare'), array('compare_product', 'id_product', 'product', 'id_product'), array('connections', 'id_shop_group', 'shop_group', 'id_shop_group'), array('connections', 'id_shop', 'shop', 'id_shop'), array('connections_page', 'id_connections', 'connections', 'id_connections'), array('connections_page', 'id_page', 'page', 'id_page'), array('connections_source', 'id_connections', 'connections', 'id_connections'), array('customer', 'id_shop_group', 'shop_group', 'id_shop_group'), array('customer', 'id_shop', 'shop', 'id_shop'), array('customer_group', 'id_group', 'group', 'id_group'), array('customer_group', 'id_customer', 'customer', 'id_customer'), array('customer_message', 'id_customer_thread', 'customer_thread', 'id_customer_thread'), array('customer_thread', 'id_shop', 'shop', 'id_shop'), array('customization', 'id_cart', 'cart', 'id_cart'), array('customization_field', 'id_product', 'product', 'id_product'), array('customized_data', 'id_customization', 'customization', 'id_customization'), array('delivery', 'id_shop', 'shop', 'id_shop'), array('delivery', 'id_shop_group', 'shop_group', 'id_shop_group'), array('delivery', 'id_carrier', 'carrier', 'id_carrier'), array('delivery', 'id_zone', 'zone', 'id_zone'), array('editorial', 'id_shop', 'shop', 'id_shop', 'editorial'), array('favorite_product', 'id_product', 'product', 'id_product', 'favoriteproducts'), array('favorite_product', 'id_customer', 'customer', 'id_customer', 'favoriteproducts'), array('favorite_product', 'id_shop', 'shop', 'id_shop', 'favoriteproducts'), array('feature_product', 'id_feature', 'feature', 'id_feature'), array('feature_product', 'id_product', 'product', 'id_product'), array('feature_value', 'id_feature', 'feature', 'id_feature'), array('group_reduction', 'id_group', 'group', 'id_group'), array('group_reduction', 'id_category', 'category', 'id_category'), array('homeslider', 'id_shop', 'shop', 'id_shop', 'homeslider'), array('homeslider', 'id_homeslider_slides', 'homeslider_slides', 'id_homeslider_slides', 'homeslider'), array('hook_module', 'id_hook', 'hook', 'id_hook'), array('hook_module', 'id_module', 'module', 'id_module'), array('hook_module_exceptions', 'id_hook', 'hook', 'id_hook'), array('hook_module_exceptions', 'id_module', 'module', 'id_module'), array('hook_module_exceptions', 'id_shop', 'shop', 'id_shop'), array('image', 'id_product', 'product', 'id_product'), array('message', 'id_cart', 'cart', 'id_cart'), array('message_readed', 'id_message', 'message', 'id_message'), array('message_readed', 'id_employee', 'employee', 'id_employee'), array('module_access', 'id_profile', 'profile', 'id_profile'), array('module_access', 'id_module', 'module', 'id_module'), array('module_country', 'id_module', 'module', 'id_module'), array('module_country', 'id_country', 'country', 'id_country'), array('module_country', 'id_shop', 'shop', 'id_shop'), array('module_currency', 'id_module', 'module', 'id_module'), array('module_currency', 'id_currency', 'currency', 'id_currency'), array('module_currency', 'id_shop', 'shop', 'id_shop'), array('module_group', 'id_module', 'module', 'id_module'), array('module_group', 'id_group', 'group', 'id_group'), array('module_group', 'id_shop', 'shop', 'id_shop'), array('module_preference', 'id_employee', 'employee', 'id_employee'), array('orders', 'id_shop', 'shop', 'id_shop'), array('orders', 'id_shop_group', 'group_shop', 'id_shop_group'), array('order_carrier', 'id_order', 'orders', 'id_order'), array('order_cart_rule', 'id_order', 'orders', 'id_order'), array('order_detail', 'id_order', 'orders', 'id_order'), array('order_detail_tax', 'id_order_detail', 'order_detail', 'id_order_detail'), array('order_history', 'id_order', 'orders', 'id_order'), array('order_invoice', 'id_order', 'orders', 'id_order'), array('order_invoice_payment', 'id_order', 'orders', 'id_order'), array('order_invoice_tax', 'id_order_invoice', 'order_invoice', 'id_order_invoice'), array('order_return', 'id_order', 'orders', 'id_order'), array('order_return_detail', 'id_order_return', 'order_return', 'id_order_return'), array('order_slip', 'id_order', 'orders', 'id_order'), array('order_slip_detail', 'id_order_slip', 'order_slip', 'id_order_slip'), array('pack', 'id_product_pack', 'product', 'id_product'), array('pack', 'id_product_item', 'product', 'id_product'), array('page', 'id_page_type', 'page_type', 'id_page_type'), array('page_viewed', 'id_shop', 'shop', 'id_shop'), array('page_viewed', 'id_shop_group', 'shop_group', 'id_shop_group'), array('page_viewed', 'id_date_range', 'date_range', 'id_date_range'), array('product_attachment', 'id_attachment', 'attachment', 'id_attachment'), array('product_attachment', 'id_product', 'product', 'id_product'), array('product_attribute', 'id_product', 'product', 'id_product'), array('product_attribute_combination', 'id_product_attribute', 'product_attribute', 'id_product_attribute'), array('product_attribute_combination', 'id_attribute', 'attribute', 'id_attribute'), array('product_attribute_image', 'id_image', 'image', 'id_image'), array('product_attribute_image', 'id_product_attribute', 'product_attribute', 'id_product_attribute'), array('product_carrier', 'id_product', 'product', 'id_product'), array('product_carrier', 'id_shop', 'shop', 'id_shop'), array('product_carrier', 'id_carrier_reference', 'carrier', 'id_reference'), array('product_country_tax', 'id_product', 'product', 'id_product'), array('product_country_tax', 'id_country', 'country', 'id_country'), array('product_country_tax', 'id_tax', 'tax', 'id_tax'), array('product_download', 'id_product', 'product', 'id_product'), array('product_group_reduction_cache', 'id_product', 'product', 'id_product'), array('product_group_reduction_cache', 'id_group', 'group', 'id_group'), array('product_sale', 'id_product', 'product', 'id_product'), array('product_supplier', 'id_product', 'product', 'id_product'), array('product_supplier', 'id_supplier', 'supplier', 'id_supplier'), array('product_tag', 'id_product', 'product', 'id_product'), array('product_tag', 'id_tag', 'tag', 'id_tag'), array('range_price', 'id_carrier', 'carrier', 'id_carrier'), array('range_weight', 'id_carrier', 'carrier', 'id_carrier'), array('referrer_cache', 'id_referrer', 'referrer', 'id_referrer'), array('referrer_cache', 'id_connections_source', 'connections_source', 'id_connections_source'), array('scene_category', 'id_scene', 'scene', 'id_scene'), array('scene_category', 'id_category', 'category', 'id_category'), array('scene_products', 'id_scene', 'scene', 'id_scene'), array('scene_products', 'id_product', 'product', 'id_product'), array('search_index', 'id_product', 'product', 'id_product'), array('search_word', 'id_lang', 'lang', 'id_lang'), array('search_word', 'id_shop', 'shop', 'id_shop'), array('shop_url', 'id_shop', 'shop', 'id_shop'), array('specific_price_priority', 'id_product', 'product', 'id_product'), array('stock', 'id_warehouse', 'warehouse', 'id_warehouse'), array('stock', 'id_product', 'product', 'id_product'), array('stock_available', 'id_product', 'product', 'id_product'), array('stock_mvt', 'id_stock', 'stock', 'id_stock'), array('tab_module_preference', 'id_employee', 'employee', 'id_employee'), array('tab_module_preference', 'id_tab', 'tab', 'id_tab'), array('tax_rule', 'id_country', 'country', 'id_country'), array('theme_specific', 'id_theme', 'theme', 'id_theme'), array('theme_specific', 'id_shop', 'shop', 'id_shop'), array('warehouse_carrier', 'id_warehouse', 'warehouse', 'id_warehouse'), array('warehouse_carrier', 'id_carrier', 'carrier', 'id_carrier'), array('warehouse_product_location', 'id_product', 'product', 'id_product'), array('warehouse_product_location', 'id_warehouse', 'warehouse', 'id_warehouse'));
        $queries = self::bulle($queries);
        foreach ($queries as $query_array) {
            // If this is a module and the module is not installed, we continue
            if (isset($query_array[4]) && !Module::isInstalled($query_array[4])) {
                continue;
            }
            $query = 'DELETE FROM `' . _DB_PREFIX_ . $query_array[0] . '` WHERE `' . $query_array[1] . '` NOT IN (SELECT `' . $query_array[3] . '` FROM `' . _DB_PREFIX_ . $query_array[2] . '`)';
            if ($db->Execute($query)) {
                if ($affected_rows = $db->Affected_Rows()) {
                    $logs[$query] = $affected_rows;
                }
            }
        }
        // _lang table cleaning
        $tables = Db::getInstance()->executeS('SHOW TABLES LIKE "' . preg_replace('/([%_])/', '\\$1', _DB_PREFIX_) . '%_\\_lang"');
        foreach ($tables as $table) {
            $table_lang = current($table);
            $table = str_replace('_lang', '', $table_lang);
            $id_table = 'id_' . preg_replace('/^' . _DB_PREFIX_ . '/', '', $table);
            $query = 'DELETE FROM `' . bqSQL($table_lang) . '` WHERE `' . bqSQL($id_table) . '` NOT IN (SELECT `' . bqSQL($id_table) . '` FROM `' . bqSQL($table) . '`)';
            if ($db->Execute($query)) {
                if ($affected_rows = $db->Affected_Rows()) {
                    $logs[$query] = $affected_rows;
                }
            }
            $query = 'DELETE FROM `' . bqSQL($table_lang) . '` WHERE `id_lang` NOT IN (SELECT `id_lang` FROM `' . _DB_PREFIX_ . 'lang`)';
            if ($db->Execute($query)) {
                if ($affected_rows = $db->Affected_Rows()) {
                    $logs[$query] = $affected_rows;
                }
            }
        }
        // _shop table cleaning
        $tables = Db::getInstance()->executeS('SHOW TABLES LIKE "' . preg_replace('/([%_])/', '\\$1', _DB_PREFIX_) . '%_\\_shop"');
        foreach ($tables as $table) {
            $table_shop = current($table);
            $table = str_replace('_shop', '', $table_shop);
            $id_table = 'id_' . preg_replace('/^' . _DB_PREFIX_ . '/', '', $table);
            if (in_array($table_shop, array(_DB_PREFIX_ . 'carrier_tax_rules_group_shop'))) {
                continue;
            }
            $query = 'DELETE FROM `' . bqSQL($table_shop) . '` WHERE `' . bqSQL($id_table) . '` NOT IN (SELECT `' . bqSQL($id_table) . '` FROM `' . bqSQL($table) . '`)';
            if ($db->Execute($query)) {
                if ($affected_rows = $db->Affected_Rows()) {
                    $logs[$query] = $affected_rows;
                }
            }
            $query = 'DELETE FROM `' . bqSQL($table_shop) . '` WHERE `id_shop` NOT IN (SELECT `id_shop` FROM `' . _DB_PREFIX_ . 'shop`)';
            if ($db->Execute($query)) {
                if ($affected_rows = $db->Affected_Rows()) {
                    $logs[$query] = $affected_rows;
                }
            }
        }
        // stock_available
        $query = 'DELETE FROM `' . _DB_PREFIX_ . 'stock_available` WHERE `id_shop` NOT IN (SELECT `id_shop` FROM `' . _DB_PREFIX_ . 'shop`) AND `id_shop_group` NOT IN (SELECT `id_shop_group` FROM `' . _DB_PREFIX_ . 'shop_group`)';
        if ($db->Execute($query)) {
            if ($affected_rows = $db->Affected_Rows()) {
                $logs[$query] = $affected_rows;
            }
        }
        Category::regenerateEntireNtree();
        // @Todo: Remove attachment files, images...
        Image::clearTmpDir();
        self::clearAllCaches();
        return $logs;
    }
function generate_ntree()
{
    Category::regenerateEntireNtree();
}
    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);
    }
 public function getTree($resultParents, $resultIds, $maxDepth, $id_category = null, $currentDepth = 0)
 {
     /* FIX BY SGREGORI */
     global $_GET;
     if (!empty($_GET['category_fix'])) {
         Category::regenerateEntireNtree();
         echo "<script>alert('regenerating categories OK ');</script>";
     }
     /* FIX BY SGREGORI */
     if (is_null($id_category)) {
         $id_category = $this->context->shop->getCategory();
     }
     $children = array();
     if (isset($resultParents[$id_category]) && count($resultParents[$id_category]) && ($maxDepth == 0 || $currentDepth < $maxDepth)) {
         foreach ($resultParents[$id_category] as $subcat) {
             $children[] = $this->getTree($resultParents, $resultIds, $maxDepth, $subcat['id_category'], $currentDepth + 1);
         }
     }
     if (isset($resultIds[$id_category])) {
         $link = $this->context->link->getCategoryLink($id_category, $resultIds[$id_category]['link_rewrite']);
         $name = $resultIds[$id_category]['name'];
         $desc = $resultIds[$id_category]['description'];
     } else {
         $link = $name = $desc = '';
     }
     $return = array('id' => $id_category, 'link' => $link, 'name' => $name, 'desc' => $desc, 'children' => $children);
     return $return;
 }
 public function postProcess($token = NULL)
 {
     global $cookie, $currentIndex;
     $this->tabAccess = Profile::getProfileAccess($cookie->profile, $this->id);
     if (Tools::isSubmit('submitAdd' . $this->table)) {
         if ($id_category = (int) Tools::getValue('id_category')) {
             if (!Category::checkBeforeMove($id_category, (int) Tools::getValue('id_parent'))) {
                 $this->_errors[] = Tools::displayError('Category cannot be moved here');
                 return false;
             }
         }
     } elseif (isset($_GET['delete' . $this->table])) {
         if ($this->tabAccess['delete'] === '1') {
             if (Validate::isLoadedObject($object = $this->loadObject()) and isset($this->fieldImageSettings)) {
                 // check if request at least one object with noZeroObject
                 if (isset($object->noZeroObject) and sizeof($taxes = call_user_func(array($this->className, $object->noZeroObject))) <= 1) {
                     $this->_errors[] = Tools::displayError('You need at least one object.') . ' <b>' . $this->table . '</b><br />' . Tools::displayError('You cannot delete all of the items.');
                 } else {
                     if ($this->deleted) {
                         $object->deleteImage();
                         $object->deleted = 1;
                         if ($object->update()) {
                             Tools::redirectAdmin($currentIndex . '&conf=1&token=' . Tools::getValue('token') . '&id_category=' . (int) $object->id_parent);
                         }
                     } elseif ($object->delete()) {
                         Tools::redirectAdmin($currentIndex . '&conf=1&token=' . Tools::getValue('token') . '&id_category=' . (int) $object->id_parent);
                     }
                     $this->_errors[] = Tools::displayError('An error occurred during deletion.');
                 }
             } else {
                 $this->_errors[] = Tools::displayError('An error occurred while deleting object.') . ' <b>' . $this->table . '</b> ' . Tools::displayError('(cannot load object)');
             }
         } else {
             $this->_errors[] = Tools::displayError('You do not have permission to delete here.');
         }
     } elseif (isset($_GET['position'])) {
         if ($this->tabAccess['edit'] !== '1') {
             $this->_errors[] = Tools::displayError('You do not have permission to edit here.');
         } elseif (!Validate::isLoadedObject($object = new Category((int) Tools::getValue($this->identifier, Tools::getValue('id_category_to_move', 1))))) {
             $this->_errors[] = Tools::displayError('An error occurred while updating status for object.') . ' <b>' . $this->table . '</b> ' . Tools::displayError('(cannot load object)');
         }
         if (!$object->updatePosition((int) Tools::getValue('way'), (int) Tools::getValue('position'))) {
             $this->_errors[] = Tools::displayError('Failed to update the position.');
         } else {
             $object->regenerateEntireNtree();
             Tools::redirectAdmin($currentIndex . '&' . $this->table . 'Orderby=position&' . $this->table . 'Orderway=asc&conf=5' . (($id_category = (int) Tools::getValue($this->identifier, Tools::getValue('id_category_parent', 1))) ? '&' . $this->identifier . '=' . $id_category : '') . '&token=' . Tools::getAdminTokenLite('AdminCatalog'));
         }
     } elseif (Tools::getValue('submitDel' . $this->table)) {
         if ($this->tabAccess['delete'] === '1') {
             if (isset($_POST[$this->table . 'Box'])) {
                 $category = new Category();
                 $result = true;
                 $result = $category->deleteSelection(Tools::getValue($this->table . 'Box'));
                 if ($result) {
                     $category->cleanPositions((int) Tools::getValue('id_category'));
                     Tools::redirectAdmin($currentIndex . '&conf=2&token=' . Tools::getAdminTokenLite('AdminCatalog') . '&id_category=' . (int) Tools::getValue('id_category'));
                 }
                 $this->_errors[] = Tools::displayError('An error occurred while deleting selection.');
             } else {
                 $this->_errors[] = Tools::displayError('You must select at least one element to delete.');
             }
         } else {
             $this->_errors[] = Tools::displayError('You do not have permission to delete here.');
         }
         return;
     }
     parent::postProcess();
 }
Example #12
0
 static function finishImport()
 {
     Category::regenerateEntireNtree();
 }
        			echo("-Context is set to ".$type.$id_shop." ");
        		break;
        		*/
        case "CONTEXT_SHOP":
            Shop::setContext(Shop::CONTEXT_SHOP, $id_shop);
            echo "-Context is set to " . $type . $id_shop . " ";
            break;
        default:
            Shop::setContext(Shop::CONTEXT_ALL, null);
            echo "-Context is set to " . $type . " ";
    }
    //Fonction locale, copiée depuis la classe category, modifiée pour lui passer le context
    regenerateEntireNtree_1_5($id_shop);
} else {
    echo " Calling routine";
    $category->regenerateEntireNtree();
}
//code v2.4.1
//$id_product=(int)Tools::getValue('id_product');
//$id_lang = (int)Context::getContext()->language->id;
//$product = new Product($id_product, false, $id_lang,$id_shop_source,$context);
/**
 * Re-calculate the values of all branches of the nested tree
 */
function regenerateEntireNtree_1_5($id)
{
    echo " Running regenerateEntireNtree_1_5 routine";
    //$id = Context::getContext()->shop->id;
    $id_shop = $id ? $id : Configuration::get('PS_SHOP_DEFAULT');
    $categories = Db::getInstance()->executeS('
	SELECT c.`id_category`, c.`id_parent`
Example #14
0
    $id_category_parent = (int) Tools::getValue('id_category_parent');
    $way = (int) Tools::getValue('way');
    $positions = Tools::getValue('category');
    if (is_array($positions)) {
        foreach ($positions as $key => $value) {
            $pos = explode('_', $value);
            if (isset($pos[1]) and isset($pos[2]) and ($pos[1] == $id_category_parent and $pos[2] == $id_category_to_move)) {
                $position = $key;
                break;
            }
        }
    }
    $category = new Category($id_category_to_move);
    if (Validate::isLoadedObject($category)) {
        if (isset($position) && $category->updatePosition($way, $position)) {
            Category::regenerateEntireNtree();
            Module::hookExec('categoryUpdate');
            die(true);
        } else {
            die('{"hasError" : true, errors : "Can not update categories position"}');
        }
    } else {
        die('{"hasError" : true, "errors" : "This category can not be loaded"}');
    }
}
if (array_key_exists('ajaxCMSCategoriesPositions', $_POST)) {
    $id_cms_category_to_move = (int) Tools::getValue('id_cms_category_to_move');
    $id_cms_category_parent = (int) Tools::getValue('id_cms_category_parent');
    $way = (int) Tools::getValue('way');
    $positions = Tools::getValue('cms_category');
    if (is_array($positions)) {
    public static function getCategory($categ, $categParent = 0, $idShop, $type)
    {
        $idCategory = Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue('SELECT `id_category`
																FROM `' . _DB_PREFIX_ . 'ec_ecopresto_category_shop`
																WHERE `name` = "' . pSQL(base64_encode($categ)) . '"
																AND `id_shop` = ' . (int) self::getInfoEco('ID_SHOP'));
        if (!$idCategory) {
            if ($categParent == 0) {
                if (version_compare(_PS_VERSION_, '1.5', '>=')) {
                    $categParent = Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue('SELECT `id_category`
															FROM `' . _DB_PREFIX_ . 'category`
															WHERE `is_root_category` = 1');
                } else {
                    $categParent = Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue('SELECT `id_category`
															FROM `' . _DB_PREFIX_ . 'category`
															WHERE `id_parent` = 0');
                }
                $level = 1;
            } else {
                $categLevel = Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue('SELECT `level_depth`
															FROM `' . _DB_PREFIX_ . 'category`
															WHERE `id_category` = ' . (int) $categParent);
                $level = $categLevel + 1;
            }
            $posCateg = Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue('SELECT max(`position`)
														FROM `' . _DB_PREFIX_ . 'category`
														WHERE `id_parent` = ' . (int) $categParent);
            if (version_compare(_PS_VERSION_, '1.4', '>=') && version_compare(_PS_VERSION_, '1.5', '<')) {
                Db::getInstance()->execute('INSERT INTO `' . _DB_PREFIX_ . 'category` (`id_parent`,`active`,`level_depth`,`date_add`,`date_upd`,`position`)
					VALUES (' . (int) $categParent . ',1,' . (int) $level . ',"' . pSQL(date("Y-m-d H:i:s")) . '","' . pSQL(date("Y-m-d H:i:s")) . '",' . (int) ($posCateg + 1) . ')');
            } else {
                Db::getInstance()->insert('category', array('id_parent' => (int) $categParent, 'id_shop_default' => (int) $idShop, 'active' => 1, 'level_depth' => (int) $level, 'date_add' => pSQL(date('Y-m-d H:i:s')), 'date_upd' => pSQL(date('Y-m-d H:i:s')), 'position' => (int) $posCateg + 1));
            }
            $idCategory = Db::getInstance()->Insert_ID();
            $all_lang = Language::getLanguages(true);
            foreach ($all_lang as $lang) {
                if (version_compare(_PS_VERSION_, '1.5', '>=')) {
                    Db::getInstance()->insert('category_lang', array('id_category' => (int) $idCategory, 'id_shop' => (int) $idShop, 'id_lang' => (int) $lang['id_lang'], 'name' => pSQL(self::getIdLangEcoCateg($categ, $lang['id_lang'], $idShop, $type)), 'link_rewrite' => Tools::str2url(self::getIdLangEcoCateg($categ, $lang['id_lang'], $idShop, $type))));
                } else {
                    Db::getInstance()->execute('INSERT INTO `' . _DB_PREFIX_ . 'category_lang` (`id_category`,`id_lang`,`name`,`link_rewrite`)
									VALUES (' . (int) $idCategory . ',' . (int) $lang['id_lang'] . ',"' . pSQL(self::getIdLangEcoCateg($categ, $lang['id_lang'], $idShop, $type)) . '","' . Tools::str2url(self::getIdLangEcoCateg($categ, $lang['id_lang'], $idShop, $type)) . '")');
                }
            }
            if (version_compare(_PS_VERSION_, '1.5', '>=')) {
                $posCategShop = Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue('SELECT max(`position`)
						FROM `' . _DB_PREFIX_ . 'category_shop`
						WHERE `id_shop`=' . (int) $idShop);
                Db::getInstance()->insert('category_shop', array('id_category' => (int) $idCategory, 'id_shop' => (int) $idShop, 'position' => (int) $posCategShop + 1));
            }
            $all_group = Group::getGroups(self::getInfoEco('ID_LANG'));
            foreach ($all_group as $group) {
                Db::getInstance()->execute('INSERT INTO `' . _DB_PREFIX_ . 'category_group` (`id_category`,`id_group`) VALUES (' . (int) $idCategory . ',' . (int) $group['id_group'] . ')');
            }
            if (version_compare(_PS_VERSION_, '1.5', '>=')) {
                Db::getInstance()->insert('ec_ecopresto_category_shop', array('name' => pSQL(base64_encode($categ)), 'id_category' => (int) $idCategory, 'id_shop' => (int) $idShop));
            } else {
                Db::getInstance()->execute('INSERT INTO `' . _DB_PREFIX_ . 'ec_ecopresto_category_shop` (`name`,`id_category`,`id_shop`)
					VALUES ("' . pSQL(base64_encode($categ)) . '",' . (int) $idCategory . ',' . (int) $idShop . ')');
            }
            Category::regenerateEntireNtree();
        }
        return $idCategory;
    }
Example #16
0
 public function update($null_values = false)
 {
     if (Tools::isSubmit('submitAddcategoryAndBackToParent')) {
         $checked_artists_id = array();
         foreach ($_POST as $key => $val) {
             $hasString = strpos($key, 'related_artists');
             if ($hasString !== false) {
                 $checked_artists_id[] = $val;
             }
         }
         $serialize_artists = serialize($checked_artists_id);
         $this->related_artists[1] = $serialize_artists;
     }
     if ($this->id_parent == $this->id) {
         throw new PrestaShopException('a category cannot be its own parent');
     }
     if ($this->is_root_category && $this->id_parent != (int) Configuration::get('PS_ROOT_CATEGORY')) {
         $this->is_root_category = 0;
     }
     // Update group selection
     $this->updateGroup($this->groupBox);
     $this->level_depth = $this->calcLevelDepth();
     // If the parent category was changed, we don't want to have 2 categories with the same position
     $changed = $this->getDuplicatePosition();
     if ($changed) {
         if (Tools::isSubmit('checkBoxShopAsso_category')) {
             foreach (Tools::getValue('checkBoxShopAsso_category') as $id_asso_object => $row) {
                 foreach ($row as $id_shop => $value) {
                     $this->addPosition(Category::getLastPosition((int) $this->id_parent, (int) $id_shop), (int) $id_shop);
                 }
             }
         } else {
             foreach (Shop::getShops(true) as $shop) {
                 $this->addPosition(max(1, Category::getLastPosition((int) $this->id_parent, $shop['id_shop'])), $shop['id_shop']);
             }
         }
     }
     $ret = parent::update($null_values);
     if ($changed && (!isset($this->doNotRegenerateNTree) || !$this->doNotRegenerateNTree)) {
         $this->cleanPositions((int) $this->id_parent);
         Category::regenerateEntireNtree();
         $this->recalculateLevelDepth($this->id);
     }
     Hook::exec('actionCategoryUpdate', array('category' => $this));
     return $ret;
 }