From abfb0cda7d3db8028e14627dfcbf25db2839a2bd Mon Sep 17 00:00:00 2001 From: lLefevre Date: Thu, 27 Oct 2011 10:22:31 +0000 Subject: [PATCH] [*] BO #PSFV-94 : Added AdminCategoriesController --- admin-dev/tabs/AdminCategories.php | 343 ----------- admin-dev/themes/template/categories/form.tpl | 300 +++++++++ .../template/categories/list_header.tpl | 223 +++++++ classes/Category.php | 575 ++++++++++-------- .../admin/AdminCategoriesController.php | 398 ++++++++++++ 5 files changed, 1244 insertions(+), 595 deletions(-) delete mode 100644 admin-dev/tabs/AdminCategories.php create mode 100644 admin-dev/themes/template/categories/form.tpl create mode 100644 admin-dev/themes/template/categories/list_header.tpl create mode 100644 controllers/admin/AdminCategoriesController.php diff --git a/admin-dev/tabs/AdminCategories.php b/admin-dev/tabs/AdminCategories.php deleted file mode 100644 index 2b315d5ab..000000000 --- a/admin-dev/tabs/AdminCategories.php +++ /dev/null @@ -1,343 +0,0 @@ - -* @copyright 2007-2011 PrestaShop SA -* @version Release: $Revision: 7499 $ -* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) -* International Registered Trademark & Property of PrestaShop SA -*/ - -class AdminCategories extends AdminTab -{ - /** @var object Category() instance for navigation*/ - private $_category = null; - - public function __construct() - { - $this->table = 'category'; - $this->className = 'Category'; - $this->lang = true; - $this->add = true; - $this->edit = true; - $this->view = true; - $this->delete = true; - - $this->fieldImageSettings = array('name' => 'image', 'dir' => 'c'); - - $this->fieldsDisplay = array( - 'id_category' => array('title' => $this->l('ID'), 'align' => 'center', 'width' => 30), - 'name' => array('title' => $this->l('Name'), 'width' => 100), - 'description' => array('title' => $this->l('Description'), 'width' => 500, 'maxlength' => 90, 'callback' => 'getDescriptionClean', 'orderby' => false), - 'position' => array('title' => $this->l('Position'), 'width' => 40,'filter_key' => 'position', 'align' => 'center', 'position' => 'position'), - 'active' => array('title' => $this->l('Displayed'), 'active' => 'status', 'align' => 'center', 'type' => 'bool', 'orderby' => false)); - - if ($id_category = Tools::getvalue('id_category')) - $this->_category = new Category($id_category); - else - $this->_category = new Category(1); - - - $this->_filter = 'AND `id_parent` = '.(int)($this->_category->id); - $this->_select = 'position '; - - parent::__construct(); - } - - public function displayList($token = NULL) - { - /* Display list header (filtering, pagination and column names) */ - $this->displayListHeader($token); - if (!sizeof($this->_list)) - echo ''.$this->l('No items found').''; - - /* Show the content of the table */ - $this->displayListContent($token); - - /* Close list table and submit button */ - $this->displayListFooter($token); - } - - public function display($token = NULL) - { - if (((Tools::isSubmit('submitAddcategory') OR Tools::isSubmit('submitAddcategoryAndStay')) AND sizeof($this->_errors)) OR isset($_GET['updatecategory']) OR isset($_GET['addcategory'])) - { - $this->displayForm($this->token); - echo '

'.$this->l('Back to list').'
'; - } - else - { - $this->getList((int)($this->context->language->id), !$this->context->cookie->__get($this->table.'Orderby') ? 'position' : NULL, !$this->context->cookie->__get($this->table.'Orderway') ? 'ASC' : NULL, 0, NULL, $this->context->shop->getID(true)); - echo '

'.(!$this->_listTotal ? ($this->l('There are no subcategories')) : ($this->_listTotal.' '.($this->_listTotal > 1 ? $this->l('subcategories') : $this->l('subcategory')))).' '.$this->l('in category').' "'.stripslashes($this->_category->getName()).'"

'; - if ($this->tabAccess['add'] === '1') - echo ' '.$this->l('Add a new subcategory').''; - echo ' - '.$this->l('Add a new product').''; - - echo '
'; - $this->displayList($token); - echo '
'; - } - } - - public function postProcess($token = NULL) - { - $this->tabAccess = Profile::getProfileAccess($this->context->employee->id_profile, $this->id); - - if (Tools::isSubmit('submitAdd'.$this->table)) - { - if ($id_category = (int)(Tools::getValue('id_category'))) - { - if (!Category::checkBeforeMove($id_category, $this->_category->id_parent)) - { - $this->_errors[] = Tools::displayError('Category cannot be moved here'); - return false; - } - } - } - /* Delete object */ - 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.').' '.$this->table.'
'.Tools::displayError('You cannot delete all of the items.'); - else - { - if ($this->deleted) - { - $object->deleteImage(); - $object->deleted = 1; - if ($object->update()) - Tools::redirectAdmin(self::$currentIndex.'&conf=1&token='.Tools::getValue('token').'&id_category='.(int)($object->id_parent)); - } - elseif ($object->delete()) - Tools::redirectAdmin(self::$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.').' '.$this->table.' '.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.').' '.$this->table.' '.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 - 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')); - } - /* Delete multiple objects */ - 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(self::$currentIndex.'&conf=2&token='.Tools::getAdminTokenLite('AdminCategories').'&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(); - } - - protected function postImage($id) - { - $ret = parent::postImage($id); - if (($id_category = (int)(Tools::getValue('id_category'))) AND isset($_FILES) AND sizeof($_FILES) AND $_FILES['image']['name'] != NULL AND file_exists(_PS_CAT_IMG_DIR_.$id_category.'.jpg')) - { - $imagesTypes = ImageType::getImagesTypes('categories'); - foreach ($imagesTypes AS $k => $imageType) - imageResize(_PS_CAT_IMG_DIR_.$id_category.'.jpg', _PS_CAT_IMG_DIR_.$id_category.'-'.stripslashes($imageType['name']).'.jpg', (int)($imageType['width']), (int)($imageType['height'])); - } - return $ret; - } - - public function displayForm($token = NULL) - { - parent::displayForm(); - - if (!($obj = $this->loadObject(true))) - return; - $active = $this->getFieldValue($obj, 'active'); - $customer_groups = $obj->getGroups(); - if ($this->context->shop->getContextType() == Shop::CONTEXT_SHOP) - $id_category = $this->context->shop->getCategory(); - else - $id_category = (int)Tools::getValue('id_parent'); - - echo ' -
- '.($obj->id ? '' : '').' -
'.$this->l('Category').' - -
'; - foreach ($this->_languages AS $language) - echo ' -
- id) ? ' onkeyup="copy2friendlyURL();"' : '').' /> * - '.$this->l('Invalid characters:').' <>;=#{}  -
'; - echo '

-
- -
- - - - -
- -
'; - // Translations are not automatic for the moment ;) - $trads = array( - 'Home' => $this->l('Home'), - 'selected' => $this->l('selected'), - 'Collapse All' => $this->l('Collapse All'), - 'Expand All' => $this->l('Expand All') - ); - echo Helper::renderAdminCategorieTree($trads, array(isset($obj->id_parent) ? $obj->id_parent : Tools::getValue('id_parent', 1)), 'id_parent', true); - echo '
- -
'; - foreach ($this->_languages AS $language) - echo ' -
- -
'; - echo '

-
- -
'; - echo $this->displayImage($obj->id, _PS_IMG_DIR_.'c/'.$obj->id.'.jpg', 350, NULL, Tools::getAdminToken('AdminCategories'.(int)(Tab::getIdFromClassName('AdminCategories')).$this->context->employee->id), true); - echo '
-

'.$this->l('Upload category logo from your computer').'

-
-

- -
'; - foreach ($this->_languages AS $language) - echo ' -
- - '.$this->l('Forbidden characters:').' <>;=#{}  -
'; - echo '

-
- -
'; - foreach ($this->_languages AS $language) - echo '
- - '.$this->l('Forbidden characters:').' <>;=#{}  -
'; - echo '

-
- -
'; - foreach ($this->_languages AS $language) - echo ' -
- - '.$this->l('Forbidden characters:').' <>;=#{}  -
'; - echo '

-
- -
'; - foreach ($this->_languages AS $language) - echo '
- * - '.$this->l('Only letters and the minus (-) character are allowed').'  -
'; - echo '

-
- -
'; - $groups = Group::getGroups((int)($this->context->language->id)); - if (sizeof($groups)) - { - echo ' - - - - - - '; - $irow = 0; - foreach ($groups AS $group) - echo ' - - - - - '; - echo ' -
id) ? 'checked="checked" ' : '').' />'.$this->l('ID').''.$this->l('Group name').'
id))) ? 'checked="checked" ' : '').'/>'.$group['id_group'].'
-

'.$this->l('Mark all groups you want to give access to this category').'

- '; - } else - echo '

'.$this->l('No group created').'

'; - echo ' -
-
- -   -
-
* '.$this->l('Required field').'
-
-
-

'; - // TinyMCE - $iso = $this->context->language->iso_code; - $isoTinyMCE = (file_exists(_PS_ROOT_DIR_.'/js/tiny_mce/langs/'.$iso.'.js') ? $iso : 'en'); - $ad = dirname($_SERVER["PHP_SELF"]); - echo ' - - '; - } -} diff --git a/admin-dev/themes/template/categories/form.tpl b/admin-dev/themes/template/categories/form.tpl new file mode 100644 index 000000000..37f3bc2ec --- /dev/null +++ b/admin-dev/themes/template/categories/form.tpl @@ -0,0 +1,300 @@ +{* +* 2007-2011 PrestaShop +* +* NOTICE OF LICENSE +* +* This source file is subject to the Academic Free License (AFL 3.0) +* that is bundled with this package in the file LICENSE.txt. +* It is also available through the world-wide-web at this URL: +* http://opensource.org/licenses/afl-3.0.php +* If you did not receive a copy of the license and are unable to +* obtain it through the world-wide-web, please send an email +* to license@prestashop.com so we can send you a copy immediately. +* +* DISCLAIMER +* +* Do not edit or add to this file if you wish to upgrade PrestaShop to newer +* versions in the future. If you wish to customize PrestaShop for your +* needs please refer to http://www.prestashop.com for more information. +* +* @author PrestaShop SA +* @copyright 2007-2011 PrestaShop SA +* @version Release: $Revision: 8971 $ +* @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0) +* International Registered Trademark & Property of PrestaShop SA +*} + +{if $firstCall} + + +{/if} +{if isset($fields.title)}

{$fields.title}

{/if} +
+ {if $form_id} + + {/if} +
+ {foreach $fields as $key => $field} + {if $key == 'legend'} + + {if isset($field.image)}{$field.title}{/if} + {$field.title} + + {elseif $key == 'input'} + {foreach $field as $input} + {if $input.name == 'id_state'} +
+ {/if} + {if isset($input.label)} + + {/if} + {if $input.type == 'hidden'} + + {else} +
+ {if $input.type == 'text'} + {if isset($input.lang) && isset($input.attributeLang)} + {foreach $languages as $language} +
+ + {if isset($input.hint)}{$input.hint} {/if} +
+ {/foreach} + {if count($languages) > 1} +
+ +
+
+ {l s='Choose language:'}

+ {foreach $languages as $language} + {$language.name} + {/foreach} +
+ {/if} + {else} + + {if isset($input.hint)}{$input.hint} {/if} + {/if} + {elseif $input.type == 'select'} + {if isset($input.options.query) && !$input.options.query && isset($input.empty_message)} + {$input.empty_message} + {$input.required = false} + {$input.p = null} + {else} + + {if isset($input.hint)}{$input.hint} {/if} + {/if} + {elseif $input.type == 'radio'} + {foreach $input.values as $value} + + + {if isset($input.br) && $input.br}
{/if} + {/foreach} + {elseif $input.type == 'textarea'} + {if isset($input.lang) && isset($input.attributeLang)} + {foreach $languages as $language} +
+ +
+ {/foreach} + {if count($languages) > 1} +
+ +
+
+ {l s='Choose language:'}

+ {foreach $languages as $language} + {$language.name} + {/foreach} +
+ {/if} + {else} + + {/if} + {elseif $input.type == 'checkbox'} + {foreach $input.values.query as $value} + {assign var=id_checkbox value=$input.name|cat:'_'|cat:$value[$input.values.id]} + +
+ {/foreach} + {elseif $input.type == 'file'} + {if $input.display_image} + {if isset($fields_value.image) && $fields_value.image} +
+ {$fields_value.image} +

{l s='File size'} {$fields_value.size}kb

+ + {l s='Delete'} {l s='Delete'} + +

+ {/if} + {/if} + + {elseif $input.type == 'password'} + + {elseif $input.type == 'group'} + {assign var=groups value=$input.values} + {include file='helper/form/form_group.tpl'} + {elseif $input.type == 'shop' OR $input.type == 'group_shop'} + {include file='helper/form/form_shop.tpl'} + {elseif $input.type == 'categories'} + {assign var=categories value=$input.values} + {include file='helper/form/form_category.tpl'} + {elseif $input.type == 'asso_shop' && isset($asso_shop) && $asso_shop} + +
+ {$asso_shop} +
+ {/if} + {if isset($input.required) && $input.required} *{/if} + {if isset($input.p)} +

+ {if is_array($input.p)} + {foreach $input.p as $p} + {if is_array($p)} + {$p.text}
+ {else} + {$p}
+ {/if} + {/foreach} + {else} + {$input.p} + {/if} +

+ {/if} + {if isset($languages)}
{/if} +
+ {/if} + {if $input.name == 'id_state'} +
+ {/if} + {/foreach} + {elseif $key == 'submit'} +
+ +
+ {/if} + {/foreach} + {if $required_fields} +
* {l s ='Required field'}
+ {/if} +
+
+ + + + + +

+{if $firstCall && !$no_back} + {if $back} + {l s='Back'} + {else} + {l s='Back to list'} + {/if} +
+{/if} diff --git a/admin-dev/themes/template/categories/list_header.tpl b/admin-dev/themes/template/categories/list_header.tpl new file mode 100644 index 000000000..d4d6394ae --- /dev/null +++ b/admin-dev/themes/template/categories/list_header.tpl @@ -0,0 +1,223 @@ +{* +* 2007-2011 PrestaShop +* +* NOTICE OF LICENSE +* +* This source file is subject to the Academic Free License (AFL 3.0) +* that is bundled with this package in the file LICENSE.txt. +* It is also available through the world-wide-web at this URL: +* http://opensource.org/licenses/afl-3.0.php +* If you did not receive a copy of the license and are unable to +* obtain it through the world-wide-web, please send an email +* to license@prestashop.com so we can send you a copy immediately. +* +* DISCLAIMER +* +* Do not edit or add to this file if you wish to upgrade PrestaShop to newer +* versions in the future. If you wish to customize PrestaShop for your +* needs please refer to http://www.prestashop.com for more information. +* +* @author PrestaShop SA +* @copyright 2007-2011 PrestaShop SA +* @version Release: $Revision: 9604 $ +* @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0) +* International Registered Trademark & Property of PrestaShop SA +*} +{if !$simple_header} + + + + {* Display column names and arrows for ordering (ASC, DESC) *} + {if $is_order_position} + + + + {/if} + + + +
+ {l s='Current Category:'} + {if count($categories_tree) == 0} +   {l s='Home'} + {else} + +   {l s='Home'} >  + + {foreach $categories_tree as $key => $category} + {if $key != 0} + + {$category.name} >  + + {else} + {$category.name} + {/if} + {/foreach} + {/if} +
+ +

{l s='Categories'}

+ +

+ {if $list_total == 0} + {l s='There are no subcategories in '} "{$categories_name}" + {else} + {$list_total}  + {if $list_total < 1} + {l s='subcategories'} + {else} + {l s='subcategory'} {l s='in category'} "{$categories_name}" + {/if} + {/if} +

+ + {if $add_button} +
{l s='Add new'}

+ {/if} +   + +
+{/if}{* End if simple_header *} + + + {if !$simple_header} + + + + {/if} + + +
+ + {if $page > 1} +   + + {/if} + {l s='Page '}{$page} / {$total_pages} + {if $page < $total_pages} +   + + {/if} + | {l s='Display'} + + / {$list_total} {l s='result(s)'} + + + + + + +
+ + + + {foreach $fields_display AS $key => $params} + + {/foreach} + + {if $shop_link_type} + + {/if} + {if $has_actions} + + {/if} + + {if !$simple_header} + + + + {* Filters (input, select, date or bool) *} + {foreach $fields_display AS $key => $params} + + {/foreach} + + {if $shop_link_type} + + {/if} + {if $has_actions} + + {/if} + + {/if} + diff --git a/classes/Category.php b/classes/Category.php index c8b3f2fe0..122ae1006 100644 --- a/classes/Category.php +++ b/classes/Category.php @@ -27,76 +27,89 @@ class CategoryCore extends ObjectModel { - public $id; + public $id; /** @var integer category ID */ - public $id_category; + public $id_category; /** @var string Name */ - public $name; + public $name; /** @var boolean Status for display */ - public $active = 1; + public $active = 1; /** @var integer category position */ - public $position; + public $position; /** @var string Description */ - public $description; + public $description; /** @var integer Parent category ID */ - public $id_parent; + public $id_parent; /** @var integer Parents number */ - public $level_depth; + public $level_depth; /** @var integer Nested tree model "left" value */ - public $nleft; + public $nleft; /** @var integer Nested tree model "right" value */ - public $nright; + public $nright; /** @var string string used in rewrited URL */ - public $link_rewrite; + public $link_rewrite; /** @var string Meta title */ - public $meta_title; + public $meta_title; /** @var string Meta keywords */ - public $meta_keywords; + public $meta_keywords; /** @var string Meta description */ - public $meta_description; + public $meta_description; /** @var string Object creation date */ - public $date_add; + public $date_add; /** @var string Object last modification date */ - public $date_upd; + public $date_upd; - protected $langMultiShop = true; + protected $langMultiShop = true; - public $groupBox; + public $groupBox; protected static $_links = array(); protected $tables = array ('category', 'category_lang'); - protected $fieldsRequired = array('active'); - protected $fieldsSize = array('active' => 1); - protected $fieldsValidate = array('nleft' => 'isUnsignedInt', 'nright' => 'isUnsignedInt', 'level_depth' => 'isUnsignedInt', 'active' => 'isBool', 'id_parent' => 'isUnsignedInt', 'groupBox' => 'isArrayWithIds'); - protected $fieldsRequiredLang = array('name', 'link_rewrite'); - protected $fieldsSizeLang = array('name' => 64, 'link_rewrite' => 64, 'meta_title' => 128, 'meta_description' => 255, 'meta_keywords' => 255); - protected $fieldsValidateLang = array('name' => 'isCatalogName', 'link_rewrite' => 'isLinkRewrite', 'description' => 'isString', - 'meta_title' => 'isGenericName', 'meta_description' => 'isGenericName', 'meta_keywords' => 'isGenericName'); + protected $fieldsRequired = array('active'); + protected $fieldsSize = array('active' => 1); + protected $fieldsValidate = array( + 'nleft' => 'isUnsignedInt', + 'nright' => 'isUnsignedInt', + 'level_depth' => 'isUnsignedInt', + 'active' => 'isBool', + 'id_parent' => 'isUnsignedInt', + 'groupBox' => 'isArrayWithIds' + ); + protected $fieldsRequiredLang = array('name', 'link_rewrite'); + protected $fieldsSizeLang = array('name' => 64, 'link_rewrite' => 64, 'meta_title' => 128, 'meta_description' => 255, 'meta_keywords' => 255); + protected $fieldsValidateLang = array( + 'name' => 'isCatalogName', + 'link_rewrite' => 'isLinkRewrite', + 'description' => 'isString', + 'meta_title' => 'isGenericName', + 'meta_description' => 'isGenericName', + 'meta_keywords' => 'isGenericName' + ); - protected $table = 'category'; - protected $identifier = 'id_category'; + protected $table = 'category'; + protected $identifier = 'id_category'; /** @var string id_image is the category ID when an image exists and 'default' otherwise */ - public $id_image = 'default'; + public $id_image = 'default'; - protected $webserviceParameters = array( + protected $webserviceParameters = array( 'objectsNodeName' => 'categories', 'hidden_fields' => array('nleft', 'nright', 'groupBox'), 'fields' => array( @@ -105,15 +118,15 @@ class CategoryCore extends ObjectModel 'nb_products_recursive' => array('getter' => 'getWsNbProductsRecursive', 'setter' => false), ), 'associations' => array( - 'categories' => array('getter' => 'getChildrenWs', 'resource' => 'category', ), - 'products' => array('getter' => 'getProductsWs', 'resource' => 'product', ), + 'categories' => array('getter' => 'getChildrenWs', 'resource' => 'category', ), + 'products' => array('getter' => 'getProductsWs', 'resource' => 'product', ), ), ); - public function __construct($id_category = NULL, $id_lang = NULL, $id_shop = NULL) + public function __construct($id_category = null, $id_lang = null, $id_shop = null) { parent::__construct($id_category, $id_lang, $id_shop); - $this->id_image = ($this->id AND file_exists(_PS_CAT_IMG_DIR_.(int)($this->id).'.jpg')) ? (int)($this->id) : false; + $this->id_image = ($this->id && file_exists(_PS_CAT_IMG_DIR_.(int)$this->id.'.jpg')) ? (int)$this->id : false; $this->image_dir = _PS_CAT_IMG_DIR_; } @@ -121,13 +134,13 @@ class CategoryCore extends ObjectModel { $this->validateFields(); if (isset($this->id)) - $fields['id_category'] = (int)($this->id); - $fields['active'] = (int)($this->active); - $fields['id_parent'] = (int)($this->id_parent); - $fields['position'] = (int)($this->position); - $fields['level_depth'] = (int)($this->level_depth); - $fields['nleft'] = (int)($this->nleft); - $fields['nright'] = (int)($this->nright); + $fields['id_category'] = (int)$this->id; + $fields['active'] = (int)$this->active; + $fields['id_parent'] = (int)$this->id_parent; + $fields['position'] = (int)$this->position; + $fields['level_depth'] = (int)$this->level_depth; + $fields['nleft'] = (int)$this->nleft; + $fields['nright'] = (int)$this->nright; $fields['date_add'] = pSQL($this->date_add); $fields['date_upd'] = pSQL($this->date_upd); return $fields; @@ -164,10 +177,10 @@ class CategoryCore extends ObjectModel public function add($autodate = true, $nullValues = false) { $this->position = self::getLastPosition((int)$this->id_parent); - if (!isset($this->level_depth) OR $this->level_depth != 0) + if (!isset($this->level_depth) || $this->level_depth != 0) $this->level_depth = $this->calcLevelDepth(); $ret = parent::add($autodate); - if (!isset($this->doNotRegenerateNTree) OR !$this->doNotRegenerateNTree) + if (!isset($this->doNotRegenerateNTree) || !$this->doNotRegenerateNTree) self::regenerateEntireNtree(); $this->updateGroup($this->groupBox); Module::hookExec('categoryAddition', array('category' => $this)); @@ -190,7 +203,7 @@ class CategoryCore extends ObjectModel if ($this->getDuplicatePosition()) $this->position = self::getLastPosition((int)$this->id_parent); $ret = parent::update($nullValues); - if (!isset($this->doNotRegenerateNTree) OR !$this->doNotRegenerateNTree) + if (!isset($this->doNotRegenerateNTree) || !$this->doNotRegenerateNTree) { self::regenerateEntireNtree(); $this->recalculateLevelDepth($this->id_category); @@ -212,14 +225,14 @@ class CategoryCore extends ObjectModel /** * Recursive scan of subcategories * - * @param integer $maxDepth Maximum depth of the tree (i.e. 2 => 3 levels depth) - * @param integer $currentDepth specify the current depth in the tree (don't use it, only for rucursivity!) + * @param integer $max_depth Maximum depth of the tree (i.e. 2 => 3 levels depth) + * @param integer $current_depth specify the current depth in the tree (don't use it, only for rucursivity!) * @param integer $id_lang Specify the id of the language used - * @param array $excludedIdsArray specify a list of ids to exclude of results + * @param array $excluded_ids_array specify a list of ids to exclude of results * * @return array Subcategories lite tree */ - public function recurseLiteCategTree($maxDepth = 3, $currentDepth = 0, $id_lang = NULL, $excludedIdsArray = NULL) + public function recurseLiteCategTree($max_depth = 3, $current_depth = 0, $id_lang = null, $excluded_ids_array = null) { $id_lang = is_null($id_lang) ? Context::getContext()->language->id : (int)$id_lang; @@ -227,15 +240,15 @@ class CategoryCore extends ObjectModel $id_lang = _USER_ID_LANG_; $children = array(); - if (($maxDepth == 0 OR $currentDepth < $maxDepth) AND $subcats = $this->getSubCategories($id_lang, true) AND sizeof($subcats)) - foreach ($subcats AS &$subcat) + if (($max_depth == 0 || $current_depth < $max_depth) && $subcats = $this->getSubCategories($id_lang, true) && count($subcats)) + foreach ($subcats as &$subcat) { if (!$subcat['id_category']) break; - elseif (!is_array($excludedIdsArray) || !in_array($subcat['id_category'], $excludedIdsArray)) + else if (!is_array($excluded_ids_array) || !in_array($subcat['id_category'], $excluded_ids_array)) { $categ = new Category($subcat['id_category'], $id_lang); - $children[] = $categ->recurseLiteCategTree($maxDepth, $currentDepth + 1, $id_lang, $excludedIdsArray); + $children[] = $categ->recurseLiteCategTree($max_depth, $current_depth + 1, $id_lang, $excluded_ids_array); } } @@ -253,46 +266,47 @@ class CategoryCore extends ObjectModel echo ''; if (isset($categories[$id_category])) - foreach (array_keys($categories[$id_category]) AS $key) + foreach (array_keys($categories[$id_category]) as $key) self::recurseCategory($categories, $categories[$id_category][$key], $key, $id_selected); } /** - * Recursively add specified category childs to $toDelete array + * Recursively add specified category childs to $to_delete array * - * @param array &$toDelete Array reference where categories ID will be saved + * @param array &$to_delete Array reference where categories ID will be saved * @param array $id_category Parent category ID */ - protected function recursiveDelete(&$toDelete, $id_category) + protected function recursiveDelete(&$to_delete, $id_category) { - if (!is_array($toDelete) OR !$id_category) + if (!is_array($to_delete) || !$id_category) die(Tools::displayError()); $result = Db::getInstance()->executeS(' SELECT `id_category` FROM `'._DB_PREFIX_.'category` - WHERE `id_parent` = '.(int)($id_category)); - foreach ($result AS $row) + WHERE `id_parent` = '.(int)$id_category); + foreach ($result as $row) { - $toDelete[] = (int)($row['id_category']); - $this->recursiveDelete($toDelete, (int)($row['id_category'])); + $to_delete[] = (int)$row['id_category']; + $this->recursiveDelete($to_delete, (int)$row['id_category']); } } public function delete() { - if ((int)($this->id) === 0 OR (int)($this->id) === 1) return false; + if ((int)$this->id === 0 || (int)$this->id === 1) + return false; $this->clearCache(); /* Get childs categories */ - $toDelete = array((int)($this->id)); - $this->recursiveDelete($toDelete, (int)($this->id)); - $toDelete = array_unique($toDelete); + $to_delete = array((int)$this->id); + $this->recursiveDelete($to_delete, (int)$this->id); + $to_delete = array_unique($to_delete); /* Delete category and its child from database */ - $list = sizeof($toDelete) > 1 ? implode(',', array_map('intval',$toDelete)) : (int)($this->id); + $list = count($to_delete) > 1 ? implode(',', array_map('intval', $to_delete)) : (int)$this->id; Db::getInstance()->execute('DELETE FROM `'._DB_PREFIX_.'category` WHERE `id_category` IN ('.$list.')'); Db::getInstance()->execute('DELETE FROM `'._DB_PREFIX_.'category_lang` WHERE `id_category` IN ('.$list.')'); Db::getInstance()->execute('DELETE FROM `'._DB_PREFIX_.'category_product` WHERE `id_category` IN ('.$list.')'); @@ -301,18 +315,19 @@ class CategoryCore extends ObjectModel self::cleanPositions($this->id_parent); /* Delete category images and its children images */ - $tmpCategory= new Category(); - foreach ($toDelete AS $id_category) + $tmp_category = new Category(); + foreach ($to_delete as $id_category) { - $tmpCategory->id = (int)$id_category; - $tmpCategory->deleteImage(); + $tmp_category->id = (int)$id_category; + $tmp_category->deleteImage(); } /* Delete products which were not in others categories */ $result = Db::getInstance()->executeS(' - SELECT `id_product` - FROM `'._DB_PREFIX_.'product` - WHERE `id_product` NOT IN (SELECT `id_product` FROM `'._DB_PREFIX_.'category_product`)'); + SELECT `id_product` + FROM `'._DB_PREFIX_.'product` + WHERE `id_product` NOT IN (SELECT `id_product` FROM `'._DB_PREFIX_.'category_product`) + '); foreach ($result as $p) { $product = new Product((int)$p['id_product']); @@ -322,19 +337,20 @@ class CategoryCore extends ObjectModel /* Set category default to 1 where categorie no more exists */ $result = Db::getInstance()->execute(' - UPDATE `'._DB_PREFIX_.'product` - SET `id_category_default` = 1 - WHERE `id_category_default` - NOT IN (SELECT `id_category` FROM `'._DB_PREFIX_.'category`)'); + UPDATE `'._DB_PREFIX_.'product` + SET `id_category_default` = 1 + WHERE `id_category_default` + NOT IN (SELECT `id_category` FROM `'._DB_PREFIX_.'category`) + '); /* Rebuild the nested tree */ - if (!isset($this->doNotRegenerateNTree) OR !$this->doNotRegenerateNTree) + if (!isset($this->doNotRegenerateNTree) || !$this->doNotRegenerateNTree) self::regenerateEntireNtree(); Module::hookExec('categoryDeletion', array('category' => $this)); /* Delete Categories in GroupReduction */ - foreach ($toDelete AS $category) + foreach ($to_delete as $category) if (GroupReduction::getGroupReductionByCategoryId((int)$category)) GroupReduction::deleteCategory($category); @@ -349,7 +365,7 @@ class CategoryCore extends ObjectModel public function deleteSelection($categories) { $return = 1; - foreach ($categories AS $id_category) + foreach ($categories as $id_category) { $category = new Category($id_category); $return &= $category->delete(); @@ -368,10 +384,10 @@ class CategoryCore extends ObjectModel if (!$this->id_parent) return 0; - $parentCategory = new Category($this->id_parent); - if (!Validate::isLoadedObject($parentCategory)) + $parent_category = new Category($this->id_parent); + if (!Validate::isLoadedObject($parent_category)) die('parent category does not exist'); - return $parentCategory->level_depth + 1; + return $parent_category->level_depth + 1; } /** @@ -380,22 +396,26 @@ class CategoryCore extends ObjectModel public static function regenerateEntireNtree() { $categories = Db::getInstance()->executeS('SELECT id_category, id_parent FROM '._DB_PREFIX_.'category ORDER BY id_category ASC'); - $categoriesArray = array(); - foreach ($categories AS $category) - $categoriesArray[(int)$category['id_parent']]['subcategories'][(int)$category['id_category']] = 1; + $categories_array = array(); + foreach ($categories as $category) + $categories_array[(int)$category['id_parent']]['subcategories'][(int)$category['id_category']] = 1; $n = 1; - self::_subTree($categoriesArray, 1, $n); + self::_subTree($categories_array, 1, $n); } protected static function _subTree(&$categories, $id_category, &$n) { $left = (int)$n++; if (isset($categories[(int)$id_category]['subcategories'])) - foreach (array_keys($categories[(int)$id_category]['subcategories']) AS $id_subcategory) + foreach (array_keys($categories[(int)$id_category]['subcategories']) as $id_subcategory) self::_subTree($categories, (int)$id_subcategory, $n); $right = (int)$n++; - Db::getInstance()->execute('UPDATE '._DB_PREFIX_.'category SET nleft = '.(int)$left.', nright = '.(int)$right.' WHERE id_category = '.(int)$id_category.' LIMIT 1'); + Db::getInstance()->execute(' + UPDATE '._DB_PREFIX_.'category + SET nleft = '.(int)$left.', nright = '.(int)$right.' + WHERE id_category = '.(int)$id_category.' LIMIT 1 + '); } /** @@ -439,21 +459,21 @@ class CategoryCore extends ObjectModel if (!Validate::isBool($active)) die(Tools::displayError()); $result = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS(' - SELECT * - FROM `'._DB_PREFIX_.'category` c - LEFT JOIN `'._DB_PREFIX_.'category_lang` cl ON c.`id_category` = cl.`id_category`'.Context::getContext()->shop->addSqlRestrictionOnLang('cl').' - WHERE 1 '.$sql_filter.' '.($id_lang ? 'AND `id_lang` = '.(int)($id_lang) : '').' - '.($active ? 'AND `active` = 1' : '').' - '.(!$id_lang ? 'GROUP BY c.id_category' : '').' - '.($sql_sort != '' ? $sql_sort : 'ORDER BY c.`level_depth` ASC, c.`position` ASC').' - '.($sql_limit != '' ? $sql_limit : '') + SELECT * + FROM `'._DB_PREFIX_.'category` c + LEFT JOIN `'._DB_PREFIX_.'category_lang` cl ON c.`id_category` = cl.`id_category`'.Context::getContext()->shop->addSqlRestrictionOnLang('cl').' + WHERE 1 '.$sql_filter.' '.($id_lang ? 'AND `id_lang` = '.(int)$id_lang : '').' + '.($active ? 'AND `active` = 1' : '').' + '.(!$id_lang ? 'GROUP BY c.id_category' : '').' + '.($sql_sort != '' ? $sql_sort : 'ORDER BY c.`level_depth` ASC, c.`position` ASC').' + '.($sql_limit != '' ? $sql_limit : '') ); if (!$order) return $result; $categories = array(); - foreach ($result AS $row) + foreach ($result as $row) $categories[$row['id_parent']][$row['id_category']]['infos'] = $row; return $categories; @@ -483,22 +503,26 @@ class CategoryCore extends ObjectModel die(Tools::displayError()); $groups = FrontController::getCurrentCustomerGroups(); - $sqlGroups = (count($groups) ? 'IN ('.implode(',', $groups).')' : '= 1'); + $sql_groups = (count($groups) ? 'IN ('.implode(',', $groups).')' : '= 1'); $result = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS(' - SELECT c.*, cl.id_lang, cl.name, cl.description, cl.link_rewrite, cl.meta_title, cl.meta_keywords, cl.meta_description - FROM `'._DB_PREFIX_.'category` c - LEFT JOIN `'._DB_PREFIX_.'category_lang` cl ON (c.`id_category` = cl.`id_category` AND `id_lang` = '.(int)$id_lang.Context::getContext()->shop->addSqlRestrictionOnLang('cl').') - LEFT JOIN `'._DB_PREFIX_.'category_group` cg ON (cg.`id_category` = c.`id_category`) - WHERE `id_parent` = '.(int)($this->id).' - '.($active ? 'AND `active` = 1' : '').' - AND cg.`id_group` '.$sqlGroups.' - GROUP BY c.`id_category` - ORDER BY `level_depth` ASC, c.`position` ASC'); + SELECT c.*, cl.id_lang, cl.name, cl.description, cl.link_rewrite, cl.meta_title, cl.meta_keywords, cl.meta_description + FROM `'._DB_PREFIX_.'category` c + LEFT JOIN `'._DB_PREFIX_.'category_lang` cl + ON (c.`id_category` = cl.`id_category` + AND `id_lang` = '.(int)$id_lang.Context::getContext()->shop->addSqlRestrictionOnLang('cl').') + LEFT JOIN `'._DB_PREFIX_.'category_group` cg + ON (cg.`id_category` = c.`id_category`) + WHERE `id_parent` = '.(int)$this->id.' + '.($active ? 'AND `active` = 1' : '').' + AND cg.`id_group` '.$sql_groups.' + GROUP BY c.`id_category` + ORDER BY `level_depth` ASC, c.`position` ASC + '); - foreach ($result AS &$row) + foreach ($result as &$row) { - $row['id_image'] = (file_exists(_PS_CAT_IMG_DIR_.$row['id_category'].'.jpg')) ? (int)($row['id_category']) : Language::getIsoById($id_lang).'-default'; + $row['id_image'] = file_exists(_PS_CAT_IMG_DIR_.$row['id_category'].'.jpg') ? (int)$row['id_category'] : Language::getIsoById($id_lang).'-default'; $row['legend'] = 'no picture'; } return $result; @@ -510,97 +534,119 @@ class CategoryCore extends ObjectModel * @param integer $id_lang Language ID * @param integer $p Page number * @param integer $n Number of products per page - * @param boolean $getTotal return the number of results instead of the results themself + * @param boolean $get_total return the number of results instead of the results themself * @param boolean $active return only active products * @param boolean $random active a random filter for returned products - * @param int $randomNumberProducts number of products to return if random is activated - * @param boolean $checkAccess set to false to return all products (even if customer hasn't access) + * @param int $random_number_products number of products to return if random is activated + * @param boolean $check_access set to false to return all products (even if customer hasn't access) * @return mixed Products or number of products */ - public function getProducts($id_lang, $p, $n, $orderBy = NULL, $orderWay = NULL, $getTotal = false, $active = true, $random = false, $randomNumberProducts = 1, $checkAccess = true, Context $context = null) + public function getProducts($id_lang, $p, $n, $order_by = null, $order_way = null, $get_total = false, $active = true, $random = false, $random_number_products = 1, $check_access = true, Context $context = null) { if (!$context) $context = Context::getContext(); - if (!$checkAccess OR !$this->checkAccess($context->customer->id)) + if (!$check_access || !$this->checkAccess($context->customer->id)) return false; if ($p < 1) $p = 1; - if (empty($orderBy)) - $orderBy = 'position'; + if (empty($order_by)) + $order_by = 'position'; else /* Fix for all modules which are now using lowercase values for 'orderBy' parameter */ - $orderBy = strtolower($orderBy); + $order_by = strtolower($order_by); - if (empty($orderWay)) - $orderWay = 'ASC'; - if ($orderBy == 'id_product' OR $orderBy == 'date_add') - $orderByPrefix = 'p'; - elseif ($orderBy == 'name') - $orderByPrefix = 'pl'; - elseif ($orderBy == 'manufacturer') + if (empty($order_way)) + $order_way = 'ASC'; + if ($order_by == 'id_product' || $order_by == 'date_add') + $order_by_prefix = 'p'; + else if ($order_by == 'name') + $order_by_prefix = 'pl'; + else if ($order_by == 'manufacturer') { - $orderByPrefix = 'm'; - $orderBy = 'name'; + $order_by_prefix = 'm'; + $order_by = 'name'; } - elseif ($orderBy == 'position') - $orderByPrefix = 'cp'; + else if ($order_by == 'position') + $order_by_prefix = 'cp'; - if ($orderBy == 'price') - $orderBy = 'orderprice'; + if ($order_by == 'price') + $order_by = 'orderprice'; - if (!Validate::isBool($active) OR !Validate::isOrderBy($orderBy) OR !Validate::isOrderWay($orderWay)) + if (!Validate::isBool($active) || !Validate::isOrderBy($order_by) || !Validate::isOrderWay($order_way)) die (Tools::displayError()); - $id_supplier = (int)(Tools::getValue('id_supplier')); + $id_supplier = (int)Tools::getValue('id_supplier'); /* Return only the number of products */ - if ($getTotal) + if ($get_total) { $sql = 'SELECT COUNT(cp.`id_product`) AS total FROM `'._DB_PREFIX_.'product` p '.$context->shop->addSqlAssociation('product', 'p').' LEFT JOIN `'._DB_PREFIX_.'category_product` cp ON p.`id_product` = cp.`id_product` - WHERE cp.`id_category` = '.(int)($this->id). + WHERE cp.`id_category` = '.(int)$this->id. ($active ? ' AND p.`active` = 1' : ''). - ($id_supplier ? 'AND p.id_supplier = '.(int)($id_supplier) : ''); + ($id_supplier ? 'AND p.id_supplier = '.(int)$id_supplier : ''); return (int)Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue($sql); } - $sql = 'SELECT p.*, sa.out_of_stock, stock.quantity, pa.`id_product_attribute`, pl.`description`, pl.`description_short`, pl.`available_now`, pl.`available_later`, pl.`link_rewrite`, pl.`meta_description`, pl.`meta_keywords`, pl.`meta_title`, pl.`name`, i.`id_image`, il.`legend`, m.`name` AS manufacturer_name, tl.`name` AS tax_name, t.`rate`, cl.`name` AS category_default, DATEDIFF(p.`date_add`, DATE_SUB(NOW(), INTERVAL '.(Validate::isUnsignedInt(Configuration::get('PS_NB_DAYS_NEW_PRODUCT')) ? Configuration::get('PS_NB_DAYS_NEW_PRODUCT') : 20).' DAY)) > 0 AS new, + $sql = 'SELECT p.*, sa.out_of_stock, stock.quantity, pa.`id_product_attribute`, pl.`description`, pl.`description_short`, pl.`available_now`, + pl.`available_later`, pl.`link_rewrite`, pl.`meta_description`, pl.`meta_keywords`, pl.`meta_title`, pl.`name`, i.`id_image`, + il.`legend`, m.`name` AS manufacturer_name, tl.`name` AS tax_name, t.`rate`, cl.`name` AS category_default, + DATEDIFF(p.`date_add`, DATE_SUB(NOW(), + INTERVAL '.(Validate::isUnsignedInt(Configuration::get('PS_NB_DAYS_NEW_PRODUCT')) ? Configuration::get('PS_NB_DAYS_NEW_PRODUCT') : 20).' + DAY)) > 0 AS new, (p.`price` * IF(t.`rate`,((100 + (t.`rate`))/100),1)) AS orderprice FROM `'._DB_PREFIX_.'category_product` cp - LEFT JOIN `'._DB_PREFIX_.'product` p ON p.`id_product` = cp.`id_product` - LEFT JOIN `'._DB_PREFIX_.'product_attribute` pa ON (p.`id_product` = pa.`id_product` AND default_on = 1) + LEFT JOIN `'._DB_PREFIX_.'product` p + ON p.`id_product` = cp.`id_product` + LEFT JOIN `'._DB_PREFIX_.'product_attribute` pa + ON (p.`id_product` = pa.`id_product` AND default_on = 1) '.$context->shop->addSqlAssociation('product', 'p').' '.Product::sqlStock('p', 'pa', false, $context->shop).' - LEFT JOIN `'._DB_PREFIX_.'category_lang` cl ON (p.`id_category_default` = cl.`id_category` AND cl.`id_lang` = '.(int)$id_lang.$context->shop->addSqlRestrictionOnLang('cl').') - LEFT JOIN `'._DB_PREFIX_.'product_lang` pl ON (p.`id_product` = pl.`id_product` AND pl.`id_lang` = '.(int)$id_lang.$context->shop->addSqlRestrictionOnLang('pl').') - LEFT JOIN `'._DB_PREFIX_.'image` i ON (i.`id_product` = p.`id_product` AND i.`cover` = 1) - LEFT JOIN `'._DB_PREFIX_.'image_lang` il ON (i.`id_image` = il.`id_image` AND il.`id_lang` = '.(int)$id_lang.') - LEFT JOIN `'._DB_PREFIX_.'tax_rule` tr ON (p.`id_tax_rules_group` = tr.`id_tax_rules_group` + LEFT JOIN `'._DB_PREFIX_.'category_lang` cl + ON (p.`id_category_default` = cl.`id_category` + AND cl.`id_lang` = '.(int)$id_lang.$context->shop->addSqlRestrictionOnLang('cl').') + LEFT JOIN `'._DB_PREFIX_.'product_lang` pl + ON (p.`id_product` = pl.`id_product` + AND pl.`id_lang` = '.(int)$id_lang.$context->shop->addSqlRestrictionOnLang('pl').') + LEFT JOIN `'._DB_PREFIX_.'image` i + ON (i.`id_product` = p.`id_product` + AND i.`cover` = 1) + LEFT JOIN `'._DB_PREFIX_.'image_lang` il + ON (i.`id_image` = il.`id_image` + AND il.`id_lang` = '.(int)$id_lang.') + LEFT JOIN `'._DB_PREFIX_.'tax_rule` tr + ON (p.`id_tax_rules_group` = tr.`id_tax_rules_group` AND tr.`id_country` = '.(int)$context->country->id.' AND tr.`id_state` = 0 AND tr.`zipcode_from` = 0) - LEFT JOIN `'._DB_PREFIX_.'tax` t ON (t.`id_tax` = tr.`id_tax`) - LEFT JOIN `'._DB_PREFIX_.'tax_lang` tl ON (t.`id_tax` = tl.`id_tax` AND tl.`id_lang` = '.(int)$id_lang.') - LEFT JOIN `'._DB_PREFIX_.'manufacturer` m ON m.`id_manufacturer` = p.`id_manufacturer` - LEFT JOIN `'._DB_PREFIX_.'stock_available` sa ON sa.`id_product` = p.`id_product` AND sa.id_product_attribute = 0 - WHERE cp.`id_category` = '.(int)($this->id) + LEFT JOIN `'._DB_PREFIX_.'tax` t + ON (t.`id_tax` = tr.`id_tax`) + LEFT JOIN `'._DB_PREFIX_.'tax_lang` tl + ON (t.`id_tax` = tl.`id_tax` + AND tl.`id_lang` = '.(int)$id_lang.') + LEFT JOIN `'._DB_PREFIX_.'manufacturer` m + ON m.`id_manufacturer` = p.`id_manufacturer` + LEFT JOIN `'._DB_PREFIX_.'stock_available` sa + ON sa.`id_product` = p.`id_product` + AND sa.id_product_attribute = 0 + WHERE cp.`id_category` = '.(int)$this->id .($active ? ' AND p.`active` = 1' : '') .($id_supplier ? ' AND p.id_supplier = '.(int)$id_supplier : ''); if ($random === true) { $sql .= ' ORDER BY RAND()'; - $sql .= ' LIMIT 0, '.(int)($randomNumberProducts); + $sql .= ' LIMIT 0, '.(int)$random_number_products; } else - $sql .= ' ORDER BY '.(isset($orderByPrefix) ? $orderByPrefix.'.' : '').'`'.pSQL($orderBy).'` '.pSQL($orderWay).' - LIMIT '.(((int)($p) - 1) * (int)($n)).','.(int)($n); + $sql .= ' ORDER BY '.(isset($order_by_prefix) ? $order_by_prefix.'.' : '').'`'.pSQL($order_by).'` '.pSQL($order_way).' + LIMIT '.(((int)$p - 1) * (int)$n).','.(int)$n; $result = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($sql); - if ($orderBy == 'orderprice') - Tools::orderbyPrice($result, $orderWay); + if ($order_by == 'orderprice') + Tools::orderbyPrice($result, $order_way); if (!$result) return false; @@ -621,7 +667,7 @@ class CategoryCore extends ObjectModel return self::getChildren(1, $id_lang, $active); } - static public function getRootCategory($id_lang = NULL, Shop $shop = null) + public static function getRootCategory($id_lang = null, Shop $shop = null) { if (is_null($id_lang)) $id_lang = Context::getContext()->language->id; @@ -647,8 +693,8 @@ class CategoryCore extends ObjectModel SELECT c.`id_category`, cl.`name`, cl.`link_rewrite` FROM `'._DB_PREFIX_.'category` c LEFT JOIN `'._DB_PREFIX_.'category_lang` cl ON c.`id_category` = cl.`id_category`'.Context::getContext()->shop->addSqlRestrictionOnLang('cl').' - WHERE `id_lang` = '.(int)($id_lang).' - AND c.`id_parent` = '.(int)($id_parent).' + WHERE `id_lang` = '.(int)$id_lang.' + AND c.`id_parent` = '.(int)$id_parent.' '.($active ? 'AND `active` = 1' : '').' ORDER BY `position` ASC'); } @@ -661,9 +707,10 @@ class CategoryCore extends ObjectModel public function getAllChildren() { return Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS(' - SELECT * - FROM `'._DB_PREFIX_.'category` - WHERE '. $this->nleft . ' < nleft AND nright < '. $this->nright); + SELECT * + FROM `'._DB_PREFIX_.'category` + WHERE '.$this->nleft.' < nleft AND nright < '.$this->nright + ); } /** @@ -674,27 +721,27 @@ class CategoryCore extends ObjectModel * @param int $id_lang * @return array */ - public static function getChildrenWithNbSelectedSubCat($id_parent, $selectedCat, $id_lang, Shop $shop = null) + public static function getChildrenWithNbSelectedSubCat($id_parent, $selected_cat, $id_lang, Shop $shop = null) { if (!$shop) $shop = Context::getContext()->shop; - $selectedCat = explode(',', str_replace(' ', '', $selectedCat)); + $selected_cat = explode(',', str_replace(' ', '', $selected_cat)); $sql = 'SELECT c.`id_category`, c.`level_depth`, cl.`name`, IF(( SELECT COUNT(*) FROM `'._DB_PREFIX_.'category` c2 WHERE c2.`id_parent` = c.`id_category` - ) > 0, 1, 0) AS has_children, '.($selectedCat ? '( + ) > 0, 1, 0) AS has_children, '.($selected_cat ? '( SELECT count(c3.`id_category`) FROM `'._DB_PREFIX_.'category` c3 WHERE c3.`nleft` > c.`nleft` AND c3.`nright` < c.`nright` - AND c3.`id_category` IN ('.implode(',', array_map('intval', $selectedCat)).') + AND c3.`id_category` IN ('.implode(',', array_map('intval', $selected_cat)).') )' : '0').' AS nbSelectedSubCat FROM `'._DB_PREFIX_.'category` c LEFT JOIN `'._DB_PREFIX_.'category_lang` cl ON c.`id_category` = cl.`id_category`'.$shop->addSqlRestrictionOnLang('cl').' - WHERE `id_lang` = '.(int)($id_lang).' - AND c.`id_parent` = '.(int)($id_parent).' + WHERE `id_lang` = '.(int)$id_lang.' + AND c.`id_parent` = '.(int)$id_parent.' ORDER BY `position` ASC'; return Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($sql); } @@ -715,10 +762,17 @@ class CategoryCore extends ObjectModel $row = array(); if ($result) - foreach ($result AS $i) - $row[] = '('.implode(', ', array((int)($id_new), $i['id_category'], '(SELECT tmp.max + 1 FROM (SELECT MAX(cp.`position`) AS max FROM `'._DB_PREFIX_.'category_product` cp WHERE cp.`id_category`='.(int)($i['id_category']).') AS tmp)')).')'; + foreach ($result as $i) + $row[] = '('.implode(', ', array((int)$id_new, $i['id_category'], '(SELECT tmp.max + 1 FROM ( + SELECT MAX(cp.`position`) AS max + FROM `'._DB_PREFIX_.'category_product` cp + WHERE cp.`id_category`='.(int)$i['id_category'].') AS tmp)' + )).')'; - $flag = Db::getInstance()->execute('INSERT INTO `'._DB_PREFIX_.'category_product` (`id_product`, `id_category`, `position`) VALUES '.implode(',', $row)); + $flag = Db::getInstance()->execute(' + INSERT INTO `'._DB_PREFIX_.'category_product` (`id_product`, `id_category`, `position`) + VALUES '.implode(',', $row) + ); return $flag; } @@ -734,11 +788,11 @@ class CategoryCore extends ObjectModel { if ($id_category == $id_parent) return false; if ($id_parent == 1) return true; - $i = (int)($id_parent); + $i = (int)$id_parent; while (42) { - $result = Db::getInstance()->getRow('SELECT `id_parent` FROM `'._DB_PREFIX_.'category` WHERE `id_category` = '.(int)($i)); + $result = Db::getInstance()->getRow('SELECT `id_parent` FROM `'._DB_PREFIX_.'category` WHERE `id_category` = '.(int)$i); if (!isset($result['id_parent'])) return false; if ($result['id_parent'] == $id_category) return false; if ($result['id_parent'] == 1) return true; @@ -748,7 +802,7 @@ class CategoryCore extends ObjectModel public static function getLinkRewrite($id_category, $id_lang) { - if (!Validate::isUnsignedId($id_category) OR !Validate::isUnsignedId($id_lang)) + if (!Validate::isUnsignedId($id_category) || !Validate::isUnsignedId($id_lang)) return false; if (isset(self::$_links[$id_category.'-'.$id_lang])) @@ -758,8 +812,8 @@ class CategoryCore extends ObjectModel SELECT cl.`link_rewrite` FROM `'._DB_PREFIX_.'category` c LEFT JOIN `'._DB_PREFIX_.'category_lang` cl ON c.`id_category` = cl.`id_category`'.Context::getContext()->shop->addSqlRestrictionOnLang('cl').' - WHERE `id_lang` = '.(int)($id_lang).' - AND c.`id_category` = '.(int)($id_category)); + WHERE `id_lang` = '.(int)$id_lang.' + AND c.`id_category` = '.(int)$id_category); self::$_links[$id_category.'-'.$id_lang] = $result['link_rewrite']; return $result['link_rewrite']; } @@ -771,14 +825,14 @@ class CategoryCore extends ObjectModel return $link->getCategoryLink($this->id, $this->link_rewrite); } - public function getName($id_lang = NULL) + public function getName($id_lang = null) { if (!$id_lang) { if (isset($this->name[Context::getContext()->language->id])) $id_lang = Context::getContext()->language->id; else - $id_lang = (int)(Configuration::get('PS_LANG_DEFAULT')); + $id_lang = (int)Configuration::get('PS_LANG_DEFAULT'); } return isset($this->name[$id_lang]) ? $this->name[$id_lang] : ''; } @@ -795,16 +849,22 @@ class CategoryCore extends ObjectModel { if ($unrestricted === true) return Db::getInstance()->getRow(' - SELECT c.*, cl.* - FROM `'._DB_PREFIX_.'category` c - LEFT JOIN `'._DB_PREFIX_.'category_lang` cl ON (c.`id_category` = cl.`id_category`'.Context::getContext()->shop->addSqlRestrictionOnLang('cl').') - WHERE `name` LIKE \''.pSQL($query).'\''); + SELECT c.*, cl.* + FROM `'._DB_PREFIX_.'category` c + LEFT JOIN `'._DB_PREFIX_.'category_lang` cl + ON (c.`id_category` = cl.`id_category`'.Context::getContext()->shop->addSqlRestrictionOnLang('cl').') + WHERE `name` LIKE \''.pSQL($query).'\' + '); else return Db::getInstance()->executeS(' - SELECT c.*, cl.* - FROM `'._DB_PREFIX_.'category` c - LEFT JOIN `'._DB_PREFIX_.'category_lang` cl ON (c.`id_category` = cl.`id_category` AND `id_lang` = '.(int)$id_lang.Context::getContext()->shop->addSqlRestrictionOnLang('cl').') - WHERE `name` LIKE \'%'.pSQL($query).'%\' AND c.`id_category` != 1'); + SELECT c.*, cl.* + FROM `'._DB_PREFIX_.'category` c + LEFT JOIN `'._DB_PREFIX_.'category_lang` cl + ON (c.`id_category` = cl.`id_category` + AND `id_lang` = '.(int)$id_lang.Context::getContext()->shop->addSqlRestrictionOnLang('cl').') + WHERE `name` LIKE \'%'.pSQL($query).'%\' + AND c.`id_category` != 1 + '); } /** @@ -818,12 +878,15 @@ class CategoryCore extends ObjectModel public static function searchByNameAndParentCategoryId($id_lang, $category_name, $id_parent_category) { return Db::getInstance()->getRow(' - SELECT c.*, cl.* - FROM `'._DB_PREFIX_.'category` c - LEFT JOIN `'._DB_PREFIX_.'category_lang` cl ON (c.`id_category` = cl.`id_category` AND `id_lang` = '.(int)$id_lang.Context::getContext()->shop->addSqlRestrictionOnLang('cl').') - WHERE `name` LIKE \''.pSQL($category_name).'\' - AND c.`id_category` != 1 - AND c.`id_parent` = '.(int)($id_parent_category)); + SELECT c.*, cl.* + FROM `'._DB_PREFIX_.'category` c + LEFT JOIN `'._DB_PREFIX_.'category_lang` cl + ON (c.`id_category` = cl.`id_category` + AND `id_lang` = '.(int)$id_lang.Context::getContext()->shop->addSqlRestrictionOnLang('cl').') + WHERE `name` LIKE \''.pSQL($category_name).'\' + AND c.`id_category` != 1 + AND c.`id_parent` = '.(int)$id_parent_category + ); } /** @@ -838,20 +901,23 @@ class CategoryCore extends ObjectModel $id_lang = $context->language->id; $categories = null; - $idCurrent = $this->id; + $id_current = $this->id; while (true) { $result = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS(' SELECT c.*, cl.* FROM `'._DB_PREFIX_.'category` c - LEFT JOIN `'._DB_PREFIX_.'category_lang` cl ON (c.`id_category` = cl.`id_category` AND `id_lang` = '.(int)$id_lang.Context::getContext()->shop->addSqlRestrictionOnLang('cl').') - WHERE c.`id_category` = '.(int)$idCurrent.' AND c.`id_parent` != 0 + LEFT JOIN `'._DB_PREFIX_.'category_lang` cl + ON (c.`id_category` = cl.`id_category` + AND `id_lang` = '.(int)$id_lang.Context::getContext()->shop->addSqlRestrictionOnLang('cl').') + WHERE c.`id_category` = '.(int)$id_current.' + AND c.`id_parent` != 0 '); - $categories[] = $result[0]; - if(!$result OR $result[0]['id_parent'] == 1) + isset($result[0]) ? $categories[] = $result[0] : $categories = array(); + if (!$result || $result[0]['id_parent'] == 1) return $categories; - $idCurrent = $result[0]['id_parent']; + $id_current = $result[0]['id_parent']; } } /** @@ -865,7 +931,7 @@ class CategoryCore extends ObjectModel $row = Db::getInstance()->getRow(' SELECT `id_category` FROM '._DB_PREFIX_.'category c - WHERE c.`id_category` = '.(int)($id_category)); + WHERE c.`id_category` = '.(int)$id_category); return isset($row['id_category']); } @@ -873,14 +939,14 @@ class CategoryCore extends ObjectModel public function cleanGroups() { - Db::getInstance()->execute('DELETE FROM `'._DB_PREFIX_.'category_group` WHERE `id_category` = '.(int)($this->id)); + Db::getInstance()->execute('DELETE FROM `'._DB_PREFIX_.'category_group` WHERE `id_category` = '.(int)$this->id); } public function addGroups($groups) { foreach ($groups as $group) { - $row = array('id_category' => (int)($this->id), 'id_group' => (int)($group)); + $row = array('id_category' => (int)$this->id, 'id_group' => (int)$group); Db::getInstance()->AutoExecute(_DB_PREFIX_.'category_group', $row, 'INSERT'); } } @@ -889,9 +955,10 @@ class CategoryCore extends ObjectModel { $groups = array(); $result = Db::getInstance()->executeS(' - SELECT cg.`id_group` - FROM '._DB_PREFIX_.'category_group cg - WHERE cg.`id_category` = '.(int)($this->id)); + SELECT cg.`id_group` + FROM '._DB_PREFIX_.'category_group cg + WHERE cg.`id_category` = '.(int)$this->id + ); foreach ($result as $group) $groups[] = $group['id_group']; return $groups; @@ -905,7 +972,7 @@ class CategoryCore extends ObjectModel if ($group == $id_group) return false; else - return $this->addGroups(array((int)($id_group))); + return $this->addGroups(array((int)$id_group)); } } @@ -921,17 +988,19 @@ class CategoryCore extends ObjectModel if (!$id_customer) { $result = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow(' - SELECT ctg.`id_group` - FROM '._DB_PREFIX_.'category_group ctg - WHERE ctg.`id_category` = '.(int)($this->id).' AND ctg.`id_group` = 1'); + SELECT ctg.`id_group` + FROM '._DB_PREFIX_.'category_group ctg + WHERE ctg.`id_category` = '.(int)$this->id.' AND ctg.`id_group` = 1 + '); } else { $result = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow(' - SELECT ctg.`id_group` - FROM '._DB_PREFIX_.'category_group ctg - INNER JOIN '._DB_PREFIX_.'customer_group cg on (cg.`id_group` = ctg.`id_group` AND cg.`id_customer` = '.(int)($id_customer).') - WHERE ctg.`id_category` = '.(int)($this->id)); + SELECT ctg.`id_group` + FROM '._DB_PREFIX_.'category_group ctg + INNER JOIN '._DB_PREFIX_.'customer_group cg on (cg.`id_group` = ctg.`id_group` AND cg.`id_customer` = '.(int)$id_customer.') + WHERE ctg.`id_category` = '.(int)$this->id + ); } - if ($result AND isset($result['id_group']) AND $result['id_group']) + if ($result && isset($result['id_group']) && $result['id_group']) return true; return false; } @@ -939,7 +1008,7 @@ class CategoryCore extends ObjectModel public function updateGroup($list) { $this->cleanGroups(); - if ($list AND sizeof($list)) + if ($list && count($list)) $this->addGroups($list); else $this->addGroups(array(1)); @@ -947,11 +1016,11 @@ class CategoryCore extends ObjectModel public static function setNewGroupForHome($id_group) { - if (!(int)($id_group)) + if (!(int)$id_group) return false; return Db::getInstance()->execute(' - INSERT INTO `'._DB_PREFIX_.'category_group` - VALUES (1, '.(int)($id_group).') + INSERT INTO `'._DB_PREFIX_.'category_group` + VALUES (1, '.(int)$id_group.') '); } @@ -965,11 +1034,11 @@ class CategoryCore extends ObjectModel )) return false; - foreach ($res AS $category) - if ((int)($category['id_category']) == (int)($this->id)) - $movedCategory = $category; + foreach ($res as $category) + if ((int)$category['id_category'] == (int)$this->id) + $moved_category = $category; - if (!isset($movedCategory) || !isset($position)) + if (!isset($moved_category) || !isset($position)) return false; // < and > statements rather than BETWEEN operator // since BETWEEN is treated differently according to databases @@ -978,14 +1047,14 @@ class CategoryCore extends ObjectModel SET `position`= `position` '.($way ? '- 1' : '+ 1').' WHERE `position` '.($way - ? '> '.(int)($movedCategory['position']).' AND `position` <= '.(int)($position) - : '< '.(int)($movedCategory['position']).' AND `position` >= '.(int)($position)).' - AND `id_parent`='.(int)($movedCategory['id_parent'])) - AND Db::getInstance()->execute(' + ? '> '.(int)$moved_category['position'].' AND `position` <= '.(int)$position + : '< '.(int)$moved_category['position'].' AND `position` >= '.(int)$position).' + AND `id_parent`='.(int)$moved_category['id_parent']) + && Db::getInstance()->execute(' UPDATE `'._DB_PREFIX_.'category` - SET `position` = '.(int)($position).' - WHERE `id_parent` = '.(int)($movedCategory['id_parent']).' - AND `id_category`='.(int)($movedCategory['id_category']))); + SET `position` = '.(int)$position.' + WHERE `id_parent` = '.(int)$moved_category['id_parent'].' + AND `id_category`='.(int)$moved_category['id_category'])); Module::hookExec('categoryUpdate'); return $result; } @@ -1003,19 +1072,21 @@ class CategoryCore extends ObjectModel $return = true; $result = Db::getInstance()->executeS(' - SELECT `id_category` - FROM `'._DB_PREFIX_.'category` - WHERE `id_parent` = '.(int)($id_category_parent).' - ORDER BY `position`'); - $sizeof = sizeof($result); - for ($i = 0; $i < $sizeof; $i++){ - $sql = ' + SELECT `id_category` + FROM `'._DB_PREFIX_.'category` + WHERE `id_parent` = '.(int)$id_category_parent.' + ORDER BY `position` + '); + $count = count($result); + for ($i = 0; $i < $count; $i++) + { + $sql = ' UPDATE `'._DB_PREFIX_.'category` - SET `position` = '.(int)($i).' - WHERE `id_parent` = '.(int)($id_category_parent).' - AND `id_category` = '.(int)($result[$i]['id_category']); - $return &= Db::getInstance()->execute($sql); - } + SET `position` = '.(int)$i.' + WHERE `id_parent` = '.(int)$id_category_parent.' + AND `id_category` = '.(int)$result[$i]['id_category']; + $return &= Db::getInstance()->execute($sql); + } return $return; } @@ -1027,19 +1098,19 @@ class CategoryCore extends ObjectModel */ public static function getLastPosition($id_category_parent) { - return (Db::getInstance()->getValue('SELECT MAX(position)+1 FROM `'._DB_PREFIX_.'category` WHERE `id_parent` = '.(int)($id_category_parent))); + return (Db::getInstance()->getValue('SELECT MAX(position)+1 FROM `'._DB_PREFIX_.'category` WHERE `id_parent` = '.(int)$id_category_parent)); } public static function getUrlRewriteInformations($id_category) - { + { return Db::getInstance()->executeS(' - SELECT l.`id_lang`, c.`link_rewrite` - FROM `'._DB_PREFIX_.'category_lang` AS c - LEFT JOIN `'._DB_PREFIX_.'lang` AS l ON c.`id_lang` = l.`id_lang` - WHERE c.`id_category` = '.(int)$id_category.' - AND l.`active` = 1' + SELECT l.`id_lang`, c.`link_rewrite` + FROM `'._DB_PREFIX_.'category_lang` AS c + LEFT JOIN `'._DB_PREFIX_.'lang` AS l ON c.`id_lang` = l.`id_lang` + WHERE c.`id_category` = '.(int)$id_category.' + AND l.`active` = 1' ); - } + } /** * Return nleft and nright fields for a given category @@ -1080,7 +1151,7 @@ class CategoryCore extends ObjectModel $result = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS(' SELECT c.`id_category` as id FROM `'._DB_PREFIX_.'category` c - WHERE c.`id_parent` = '.(int)($this->id).' + WHERE c.`id_parent` = '.(int)$this->id.' AND `active` = 1 ORDER BY `position` ASC'); return $result; @@ -1091,7 +1162,7 @@ class CategoryCore extends ObjectModel $result = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS(' SELECT cp.`id_product` as id FROM `'._DB_PREFIX_.'category_product` cp - WHERE cp.`id_category` = '.(int)($this->id).' + WHERE cp.`id_category` = '.(int)$this->id.' ORDER BY `position` ASC'); return $result; } @@ -1106,9 +1177,9 @@ class CategoryCore extends ObjectModel return Db::getInstance()->getRow(' SELECT c.`id_category` as id FROM `'._DB_PREFIX_.'category` c - WHERE c.`id_parent` = '.(int)($this->id_parent).' - AND `position` = '.(int)($this->position).' - AND c.`id_category` != '.(int)($this->id)); + WHERE c.`id_parent` = '.(int)$this->id_parent.' + AND `position` = '.(int)$this->position.' + AND c.`id_category` != '.(int)$this->id); } public function getWsNbProductsRecursive() @@ -1135,7 +1206,7 @@ class CategoryCore extends ObjectModel if ($id_lang === null) $id_lang = Context::getContext()->language->id; - if (!is_array($ids_category) || !sizeof($ids_category)) + if (!is_array($ids_category) || !count($ids_category)) return; $categories = array(); @@ -1147,7 +1218,7 @@ class CategoryCore extends ObjectModel AND c.`id_category` IN ('.implode(',', array_map('intval', $ids_category)).') '); - foreach($results as $category) + foreach ($results as $category) $categories[$category['id_category']] = $category; return $categories; diff --git a/controllers/admin/AdminCategoriesController.php b/controllers/admin/AdminCategoriesController.php new file mode 100644 index 000000000..190fd3d5d --- /dev/null +++ b/controllers/admin/AdminCategoriesController.php @@ -0,0 +1,398 @@ + +* @copyright 2007-2011 PrestaShop SA +* @version Release: $Revision: 8971 $ +* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) +* International Registered Trademark & Property of PrestaShop SA +*/ + +class AdminCategoriesControllerCore extends AdminController +{ + /** + * @var object Category() instance for navigation + */ + private $_category = null; + + public function __construct() + { + $this->table = 'category'; + $this->className = 'Category'; + $this->lang = true; + $this->deleted = false; + + $this->requiredDatabase = true; + + $this->context = Context::getContext(); + + $this->fieldImageSettings = array( + 'name' => 'image', + 'dir' => 'c' + ); + + $this->fieldsDisplay = array( + 'id_category' => array( + 'title' => $this->l('ID'), + 'align' => 'center', + 'width' => 30 + ), + 'name' => array( + 'title' => $this->l('Name'), + 'width' => 100 + ), + 'description' => array( + 'title' => $this->l('Description'), + 'width' => 500, + 'maxlength' => 90, + 'callback' => 'getDescriptionClean', + 'orderby' => false + ), + 'position' => array( + 'title' => $this->l('Position'), + 'width' => 40, + 'filter_key' => 'position', + 'align' => 'center', + 'position' => 'position' + ), + 'active' => array( + 'title' => $this->l('Displayed'), + 'active' => 'status', + 'align' => 'center', + 'type' => 'bool', + 'orderby' => false + ) + ); + + if ($id_category = Tools::getvalue('id_category')) + $this->_category = new Category($id_category); + else + $this->_category = new Category(1); + + parent::__construct(); + } + + public function initList() + { + $this->addRowAction('edit'); + $this->addRowAction('delete'); + $this->addRowAction('add'); + $this->addRowAction('view'); + + $this->bulk_actions = array('delete' => array('text' => $this->l('Delete selected'), 'confirm' => $this->l('Delete selected items?'))); + + $this->_filter .= 'AND `id_parent` = '.(int)$this->_category->id; + $this->_select = 'position '; + + $categories_tree = $this->_category->getParentsCategories($this->context->language->id); + asort($categories_tree); + $this->context->smarty->assign('categories_name', stripslashes($this->_category->getName())); + $this->context->smarty->assign('categories_tree', $categories_tree); + + return parent::initList(); + } + + public function getList($id_lang, $order_by = null, $order_way = null, $start = 0, $limit = null, $id_lang_shop = false) + { + parent::getList($id_lang, 'position', $order_way, $start, $limit, Context::getContext()->shop->getID(true)); + } + + public function initContent() + { + if ($this->display == 'view') + $this->initView(); + parent::initContent(); + } + + public function initView() + { + $this->content .= $this->initList(); + } + + public function initForm() + { + $selected_cat = array(isset($obj->id_parent) ? $obj->id_parent : Tools::getValue('id_parent', 1)); + if (sizeof($selected_cat) > 0) + { + if (isset($selected_cat[0])) + $selected_cat = implode(',', $selected_cat); + else + $selected_cat = implode(',', array_keys($selected_cat)); + } + else + $selected_cat = ''; + + $this->fields_form = array( + 'legend' => array( + 'title' => $this->l('Category'), + 'image' => '../img/admin/tab-categories.gif' + ), + 'input' => array( + array( + 'type' => 'text', + 'label' => $this->l('Name:'), + 'name' => 'name', + 'lang' => true, + 'attributeLang' => 'name¤description¤meta_title¤meta_description¤meta_keywords¤link_rewrite', + 'size' => 48, + 'required' => true, + 'hint' => $this->l('Invalid characters:').' <>;=#{}' + ), + array( + 'type' => 'radio', + 'label' => $this->l('Displayed:'), + 'name' => 'active', + 'required' => false, + 'class' => 't', + 'is_bool' => true, + 'values' => array( + array( + 'id' => 'active_on', + 'value' => 1, + 'label' => $this->l('Enabled') + ), + array( + 'id' => 'active_off', + 'value' => 0, + 'label' => $this->l('Disabled') + ) + ) + ), + array( + 'type' => 'categories', + 'label' => $this->l('Parent category:'), + 'name' => 'id_parent', + 'values' => array( + 'trads' => array( + 'Home' => $this->l('Home'), + 'selected' => $this->l('selected'), + 'Collapse All' => $this->l('Collapse All'), + 'Expand All' => $this->l('Expand All') + ), + 'selected_cat' => $selected_cat, + 'input_name' => 'id_parent', + 'use_radio' => true, + 'use_search' => false + ) + ), + array( + 'type' => 'textarea', + 'label' => $this->l('Description:'), + 'name' => 'description', + 'lang' => true, + 'attributeLang' => 'name¤description¤meta_title¤meta_description¤meta_keywords¤link_rewrite', + 'rows' => 10, + 'cols' => 100, + 'hint' => $this->l('Invalid characters:').' <>;=#{}' + ), + array( + 'type' => 'file', + 'label' => $this->l('Image:'), + 'name' => 'image', + 'display_image' => true, + 'p' => $this->l('Upload category logo from your computer') + ), + array( + 'type' => 'text', + 'label' => $this->l('Meta title:'), + 'name' => 'meta_title', + 'lang' => true, + 'attributeLang' => 'name¤description¤meta_title¤meta_description¤meta_keywords¤link_rewrite', + 'hint' => $this->l('Forbidden characters:').' <>;=#{}' + ), + array( + 'type' => 'text', + 'label' => $this->l('Meta description:'), + 'name' => 'meta_description', + 'lang' => true, + 'attributeLang' => 'name¤description¤meta_title¤meta_description¤meta_keywords¤link_rewrite', + 'hint' => $this->l('Forbidden characters:').' <>;=#{}' + ), + array( + 'type' => 'text', + 'label' => $this->l('Meta keywords:'), + 'name' => 'meta_keywords', + 'lang' => true, + 'attributeLang' => 'name¤description¤meta_title¤meta_description¤meta_keywords¤link_rewrite', + 'hint' => $this->l('Forbidden characters:').' <>;=#{}' + ), + array( + 'type' => 'text', + 'label' => $this->l('Friendly URL:'), + 'name' => 'link_rewrite', + 'lang' => true, + 'attributeLang' => 'name¤description¤meta_title¤meta_description¤meta_keywords¤link_rewrite', + 'required' => true, + 'hint' => $this->l('Forbidden characters:').' <>;=#{}' + ), + array( + 'type' => 'group', + 'label' => $this->l('Group access:'), + 'name' => 'groupBox', + 'values' => Group::getGroups(Context::getContext()->language->id), + 'p' => $this->l('Mark all groups you want to give access to this category') + ) + ), + 'submit' => array( + 'title' => $this->l(' Save '), + 'class' => 'button' + ) + ); + + if (!($obj = $this->loadObject(true))) + return; + + $image = cacheImage(_PS_CAT_IMG_DIR_.'/'.$obj->id.'.jpg', $this->table.'_'.(int)$obj->id.'.'.$this->imageType, 350, $this->imageType, true); + + $this->fields_value = array( + 'image' => $image ? $image : false, + 'size' => $image ? filesize(_PS_CAT_IMG_DIR_.'/'.$obj->id.'.jpg') / 1000 : false + ); + + $iso = $this->context->language->iso_code; + $this->context->smarty->assign(array( + 'iso' => file_exists(_PS_ROOT_DIR_.'/js/tiny_mce/langs/'.$iso.'.js') ? $iso : 'en', + 'theme_path_css' => _THEME_CSS_DIR_, + 'ad' => dirname($_SERVER["PHP_SELF"]) + )); + + // Added values of object Group + $carrier_groups = $obj->getGroups(); + $carrier_groups_ids = array(); + if (is_array($carrier_groups)) + foreach ($carrier_groups as $carrier_group) + $carrier_groups_ids[] = $carrier_group['id_group']; + + $groups = Group::getGroups($this->context->language->id); + foreach ($groups as $group) + $this->fields_value['groupBox_'.$group['id_group']] = Tools::getValue('groupBox_'.$group['id_group'], (in_array($group['id_group'], $carrier_groups_ids))); + + + return parent::initForm(); + } + + public function postProcess() + { + $this->tabAccess = Profile::getProfileAccess($this->context->employee->id_profile, $this->id); + + if (Tools::isSubmit('submitAdd'.$this->table)) + { + if ($id_category = (int)Tools::getValue('id_category')) + { + if (!Category::checkBeforeMove($id_category, $this->_category->id_parent)) + { + $this->_errors[] = Tools::displayError('Category cannot be moved here'); + return false; + } + } + } + /* Delete object */ + else if (isset($_GET['delete'.$this->table])) + { + if ($this->tabAccess['delete'] === '1') + { + if (Validate::isLoadedObject($object = $this->loadObject()) && isset($this->fieldImageSettings)) + { + // check if request at least one object with noZeroObject + if (isset($object->noZeroObject) && count($taxes = call_user_func(array($this->className, $object->noZeroObject))) <= 1) + $this->_errors[] = Tools::displayError('You need at least one object.').' '.$this->table.'
'.Tools::displayError('You cannot delete all of the items.'); + else + { + if ($this->deleted) + { + $object->deleteImage(); + $object->deleted = 1; + if ($object->update()) + Tools::redirectAdmin(self::$currentIndex.'&conf=1&token='.Tools::getValue('token').'&id_category='.(int)$object->id_parent); + } + else if ($object->delete()) + Tools::redirectAdmin(self::$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.').' '.$this->table.' '.Tools::displayError('(cannot load object)'); + } + else + $this->_errors[] = Tools::displayError('You do not have permission to delete here.'); + } + else if (isset($_GET['position'])) + { + 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.').' '.$this->table.' '.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 + 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')); + } + /* Delete multiple objects */ + else if (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(self::$currentIndex.'&conf=2&token='.Tools::getAdminTokenLite('AdminCategories').'&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(); + } + + protected function postImage($id) + { + $ret = parent::postImage($id); + if (($id_category = (int)Tools::getValue('id_category')) && isset($_FILES) && count($_FILES) && $_FILES['image']['name'] != null && file_exists(_PS_CAT_IMG_DIR_.$id_category.'.jpg')) + { + $images_types = ImageType::getImagesTypes('categories'); + foreach ($images_types as $k => $image_type) + imageResize(_PS_CAT_IMG_DIR_.$id_category.'.jpg', _PS_CAT_IMG_DIR_.$id_category.'-'.stripslashes($image_type['name']).'.jpg', (int)$image_type['width'], (int)$image_type['height']); + } + return $ret; + } + + /** + * Allows to display the category description without HTML tags and slashes + * + * @return string + */ + public static function getDescriptionClean($description) + { + return strip_tags(stripslashes($description)); + } +} + +
+ {if $delete} + + {/if} + {$params.title} + {if (!isset($params.orderby) || $params.orderby) && !$simple_header} +
+ + + + + + + {/if} +
+ {if $shop_link_type == 'shop'} + {l s='shop'} + {else} + {l s='Group shop'} + {/if} + {l s='Actions'}
+ {if $delete} + -- + {/if} + + {if isset($params.search) && !$params.search} + -- + {else} + {if $params.type == 'bool'} + + {elseif $params.type == 'date' || $params.type == 'datetime'} + {l s='From'}
+ {l s='To'} + {elseif $params.type == 'select'} + {if isset($params.filter_key)} + + {/if} + {else} + + {/if} + {/if} +
----