[*] BO #PSFV-94 : Added AdminCategoriesController

This commit is contained in:
lLefevre
2011-10-27 10:22:31 +00:00
parent 1fb2e29347
commit abfb0cda7d
5 changed files with 1244 additions and 595 deletions
-343
View File
@@ -1,343 +0,0 @@
<?php
/*
* 2007-2011 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 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/osl-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 <contact@prestashop.com>
* @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 '<tr><td class="center" colspan="'.(sizeof($this->fieldsDisplay) + 2).'">'.$this->l('No items found').'</td></tr>';
/* 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 '<br /><br /><a href="'.self::$currentIndex.'&token='.$this->token.'"><img src="../img/admin/arrow2.gif" /> '.$this->l('Back to list').'</a><br />';
}
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 '<h3>'.(!$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()).'"</h3>';
if ($this->tabAccess['add'] === '1')
echo '<a href="'.__PS_BASE_URI__.substr($_SERVER['PHP_SELF'], strlen(__PS_BASE_URI__)).'?controller=AdminCategories&add'.$this->table.'&id_parent='.$this->_category->id.'&token='.($token!=NULL ? $token : $this->token).'"><img src="../img/admin/add.gif" border="0" /> '.$this->l('Add a new subcategory').'</a>';
echo '<a href="'.$this->context->link->getAdminLink('AdminProducts').'&amp;addproduct&amp;id_parent='.$this->_category->id.'">
<img src="../img/admin/add.gif" border="0" /> '.$this->l('Add a new product').'</a>';
echo '<div style="margin:10px;">';
$this->displayList($token);
echo '</div>';
}
}
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.').' <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(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.').' <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
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 '
<form action="'.self::$currentIndex.'&submitAdd'.$this->table.'=1&token='.($token!=NULL ? $token : $this->token).'" method="post" enctype="multipart/form-data">
'.($obj->id ? '<input type="hidden" name="id_'.$this->table.'" value="'.$obj->id.'" />' : '').'
<fieldset><legend><img src="../img/admin/tab-categories.gif" />'.$this->l('Category').'</legend>
<label>'.$this->l('Name:').' </label>
<div class="margin-form translatable">';
foreach ($this->_languages AS $language)
echo '
<div class="lang_'.$language['id_lang'].'" style="display: '.($language['id_lang'] == $this->_defaultFormLanguage ? 'block' : 'none').'; float: left;">
<input type="text" style="width: 260px" name="name_'.$language['id_lang'].'" id="name_'.$language['id_lang'].'" value="'.htmlentities($this->getFieldValue($obj, 'name', (int)($language['id_lang'])), ENT_COMPAT, 'UTF-8').'" '.((!$obj->id) ? ' onkeyup="copy2friendlyURL();"' : '').' /><sup> *</sup>
<span class="hint" name="help_box">'.$this->l('Invalid characters:').' <>;=#{}<span class="hint-pointer">&nbsp;</span></span>
</div>';
echo ' <p class="clear"></p>
</div>
<label>'.$this->l('Displayed:').' </label>
<div class="margin-form">
<input type="radio" name="active" id="active_on" value="1" '.($active ? 'checked="checked" ' : '').'/>
<label class="t" for="active_on"><img src="../img/admin/enabled.gif" alt="'.$this->l('Enabled').'" title="'.$this->l('Enabled').'" /></label>
<input type="radio" name="active" id="active_off" value="0" '.(!$active ? 'checked="checked" ' : '').'/>
<label class="t" for="active_off"><img src="../img/admin/disabled.gif" alt="'.$this->l('Disabled').'" title="'.$this->l('Disabled').'" /></label>
</div>
<label>'.$this->l('Parent category:').' </label>
<div class="margin-form">';
// 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 '</div>
<label>'.$this->l('Description:').' </label>
<div class="margin-form translatable">';
foreach ($this->_languages AS $language)
echo '
<div class="lang_'.$language['id_lang'].'" style="display: '.($language['id_lang'] == $this->_defaultFormLanguage ? 'block' : 'none').'; float: left;">
<textarea name="description_'.$language['id_lang'].'" rows="10" cols="100">'.htmlentities($this->getFieldValue($obj, 'description', (int)($language['id_lang'])), ENT_COMPAT, 'UTF-8').'</textarea>
</div>';
echo ' <p class="clear"></p>
</div>
<label>'.$this->l('Image:').' </label>
<div class="margin-form">';
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 ' <br /><input type="file" name="image" />
<p>'.$this->l('Upload category logo from your computer').'</p>
</div>
<div class="clear"><br /></div>
<label>'.$this->l('Meta title:').' </label>
<div class="margin-form translatable">';
foreach ($this->_languages AS $language)
echo '
<div class="lang_'.$language['id_lang'].'" style="display: '.($language['id_lang'] == $this->_defaultFormLanguage ? 'block' : 'none').'; float: left;">
<input type="text" name="meta_title_'.$language['id_lang'].'" id="meta_title_'.$language['id_lang'].'" value="'.htmlentities($this->getFieldValue($obj, 'meta_title', (int)($language['id_lang'])), ENT_COMPAT, 'UTF-8').'" />
<span class="hint" name="help_box">'.$this->l('Forbidden characters:').' <>;=#{}<span class="hint-pointer">&nbsp;</span></span>
</div>';
echo ' <p class="clear"></p>
</div>
<label>'.$this->l('Meta description:').' </label>
<div class="margin-form translatable">';
foreach ($this->_languages AS $language)
echo '<div class="lang_'.$language['id_lang'].'" style="display: '.($language['id_lang'] == $this->_defaultFormLanguage ? 'block' : 'none').'; float: left;">
<input type="text" name="meta_description_'.$language['id_lang'].'" id="meta_description_'.$language['id_lang'].'" value="'.htmlentities($this->getFieldValue($obj, 'meta_description', (int)($language['id_lang'])), ENT_COMPAT, 'UTF-8').'" />
<span class="hint" name="help_box">'.$this->l('Forbidden characters:').' <>;=#{}<span class="hint-pointer">&nbsp;</span></span>
</div>';
echo ' <p class="clear"></p>
</div>
<label>'.$this->l('Meta keywords:').' </label>
<div class="margin-form translatable">';
foreach ($this->_languages AS $language)
echo '
<div class="lang_'.$language['id_lang'].'" style="display: '.($language['id_lang'] == $this->_defaultFormLanguage ? 'block' : 'none').'; float: left;">
<input type="text" name="meta_keywords_'.$language['id_lang'].'" id="meta_keywords_'.$language['id_lang'].'" value="'.htmlentities($this->getFieldValue($obj, 'meta_keywords', (int)($language['id_lang'])), ENT_COMPAT, 'UTF-8').'" />
<span class="hint" name="help_box">'.$this->l('Forbidden characters:').' <>;=#{}<span class="hint-pointer">&nbsp;</span></span>
</div>';
echo ' <p class="clear"></p>
</div>
<label>'.$this->l('Friendly URL:').' </label>
<div class="margin-form translatable">';
foreach ($this->_languages AS $language)
echo '<div class="lang_'.$language['id_lang'].'" style="display: '.($language['id_lang'] == $this->_defaultFormLanguage ? 'block' : 'none').'; float: left;">
<input type="text" name="link_rewrite_'.$language['id_lang'].'" id="link_rewrite_'.$language['id_lang'].'" value="'.htmlentities($this->getFieldValue($obj, 'link_rewrite', (int)($language['id_lang'])), ENT_COMPAT, 'UTF-8').'" onchange="this.value = str2url(this.value);" /><sup> *</sup>
<span class="hint" name="help_box">'.$this->l('Only letters and the minus (-) character are allowed').'<span class="hint-pointer">&nbsp;</span></span>
</div>';
echo ' <p class="clear"></p>
</div>
<label>'.$this->l('Groups access:').' </label>
<div class="margin-form">';
$groups = Group::getGroups((int)($this->context->language->id));
if (sizeof($groups))
{
echo '
<table cellspacing="0" cellpadding="0" class="table" style="width: 28em;">
<tr>
<th><input type="checkbox" name="checkme" class="noborder" onclick="checkDelBoxes(this.form, \'groupBox[]\', this.checked)"'.(!isset($obj->id) ? 'checked="checked" ' : '').' /></th>
<th>'.$this->l('ID').'</th>
<th>'.$this->l('Group name').'</th>
</tr>';
$irow = 0;
foreach ($groups AS $group)
echo '
<tr class="'.($irow++ % 2 ? 'alt_row' : '').'">
<td><input type="checkbox" name="groupBox[]" class="groupBox" id="groupBox_'.$group['id_group'].'" value="'.$group['id_group'].'" '.((in_array($group['id_group'], $customer_groups) OR (!isset($obj->id))) ? 'checked="checked" ' : '').'/></td>
<td>'.$group['id_group'].'</td>
<td><label for="groupBox_'.$group['id_group'].'" class="t">'.$group['name'].'</label></td>
</tr>';
echo '
</table>
<p style="padding:0px; margin:10px 0px 10px 0px;">'.$this->l('Mark all groups you want to give access to this category').'</p>
';
} else
echo '<p>'.$this->l('No group created').'</p>';
echo '
</div>
<div class="margin-form">
<input type="submit" value="'.$this->l('Save and back to parent category').'" name="submitAdd'.$this->table.'AndBackToParent" class="button" />
&nbsp;<input type="submit" class="button" name="submitAdd'.$this->table.'" value="'.$this->l('Save').'"/>
</div>
<div class="small"><sup>*</sup> '.$this->l('Required field').'</div>
</fieldset>
</form>
<p class="clear"></p>';
// 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 '<script type="text/javascript">
var iso = \''.$isoTinyMCE.'\' ;
var pathCSS = \''._THEME_CSS_DIR_.'\' ;
var ad = \''.$ad.'\' ;
</script>
<script type="text/javascript" src="'.__PS_BASE_URI__.'js/tiny_mce/tiny_mce.js"></script>
<script type="text/javascript" src="'.__PS_BASE_URI__.'js/tinymce.inc.js"></script>';
}
}
@@ -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 <contact@prestashop.com>
* @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}
<script type="text/javascript">
var vat_number = {$vat_number};
var module_dir = '{$module_dir}';
var id_language = {$defaultFormLanguage};
var languages = new Array();
$(document).ready(function() {
{foreach $languages as $k => $language}
languages[{$k}] = {
id_lang: {$language.id_lang},
iso_code: '{$language.iso_code}',
name: '{$language.name}'
};
{/foreach}
displayFlags(languages, id_language, {$allowEmployeeFormLang});
$('input[name=name_'+id_language+']').keyup(function() {
$('input[name=link_rewrite_'+id_language+']').val(str2url($(this).val()));
});
});
</script>
<script type="text/javascript" src="../js/form.js"></script>
{/if}
{if isset($fields.title)}<h2>{$fields.title}</h2>{/if}
<form action="{$current}&{$submit_action}=1&token={$token}" method="post" enctype="multipart/form-data">
{if $form_id}
<input type="hidden" name="id_{$table}" value="{$form_id}" />
{/if}
<fieldset>
{foreach $fields as $key => $field}
{if $key == 'legend'}
<legend>
{if isset($field.image)}<img src="{$field.image}" alt="{$field.title}" />{/if}
{$field.title}
</legend>
{elseif $key == 'input'}
{foreach $field as $input}
{if $input.name == 'id_state'}
<div id="contains_states" {if $contains_states}style="display:none;"{/if}>
{/if}
{if isset($input.label)}
<label>{$input.label} </label>
{/if}
{if $input.type == 'hidden'}
<input type="hidden" name="{$input.name}" value="{$fields_value[$input.name]}" />
{else}
<div class="margin-form">
{if $input.type == 'text'}
{if isset($input.lang) && isset($input.attributeLang)}
{foreach $languages as $language}
<div id="{$input.name}_{$language.id_lang}" style="display:{if $language.id_lang == $defaultFormLanguage}block{else}none{/if}; float: left;">
<input type="text"
name="{$input.name}_{$language.id_lang}"
value="{$fields_value[$input.name][$language.id_lang]}"
{if isset($input.size)}size="{$input.size}"{/if}
{if isset($input.maxlength)}maxlength="{$input.maxlength}"{/if}
{if isset($input.class)}class="{$input.class}"{/if}
{if isset($input.readonly) && $input.readonly}readonly="readonly"{/if}
{if isset($input.disabled) && $input.disabled}disabled="disabled"{/if} />
{if isset($input.hint)}<span class="hint" name="help_box">{$input.hint}<span class="hint-pointer">&nbsp;</span></span>{/if}
</div>
{/foreach}
{if count($languages) > 1}
<div class="displayed_flag">
<img src="../img/l/{$defaultFormLanguage}.jpg"
class="pointer"
id="language_current_{$input.name}"
onclick="toggleLanguageFlags(this);" />
</div>
<div id="languages_{$input.name}" class="language_flags">
{l s='Choose language:'}<br /><br />
{foreach $languages as $language}
<img src="../img/l/{$language.id_lang}.jpg"
class="pointer"
alt="{$language.name}"
title="{$language.name}"
onclick="changeLanguage('{$input.name}', '{$input.attributeLang}', {$language.id_lang}, '{$language.iso_code}');" />
{/foreach}
</div>
{/if}
{else}
<input type="text"
name="{$input.name}"
id="{$input.name}"
value="{$fields_value[$input.name]}"
{if isset($input.size)}size="{$input.size}"{/if}
{if isset($input.maxlength)}maxlength="{$input.maxlength}"{/if}
{if isset($input.class)}class="{$input.class}"{/if}
{if isset($input.readonly) && $input.readonly}readonly="readonly"{/if}
{if isset($input.disabled) && $input.disabled}disabled="disabled"{/if} />
{if isset($input.hint)}<span class="hint" name="help_box">{$input.hint}<span class="hint-pointer">&nbsp;</span></span>{/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}
<select name="{$input.name}" id="{$input.name}" {if isset($input.multiple)}multiple="multiple" {/if}{if isset($input.onchange)}onchange="{$input.onchange}"{/if}>
{if isset($input.options.default)}
<option value="{$input.options.default.value}">{$input.options.default.label}</option>
{/if}
{if isset($input.options.optiongroup)}
{foreach $input.options.optiongroup.query AS $optiongroup}
<optgroup label="{$optiongroup[$input.options.optiongroup.label]}">
{foreach $optiongroup[$input.options.options.query] as $option}
<option value="{$option[$input.options.options.id]}"
{if isset($input.multiple)}
{foreach $fields_value[$input.name] as $field_value}
{if $field_value == $option[$input.options.options.id]}selected="selected"{/if}
{/foreach}
{else}
{if $fields_value[$input.name] == $option[$input.options.options.id]}selected="selected"{/if}
{/if}
>{$option[$input.options.options.name]|escape:'htmlall':'UTF-8'}</option>
{/foreach}
</optgroup>
{/foreach}
{else}
{foreach $input.options.query AS $option}
<option value="{$option[$input.options.id]}"
{if isset($input.multiple)}
{foreach $fields_value[$input.name] as $field_value}
{$field_value}
{if $field_value == $option[$input.options.id]}selected="selected"{/if}
{/foreach}
{else}
{if $fields_value[$input.name] == $option[$input.options.id]}selected="selected"{/if}
{/if}
>{$option[$input.options.name]|escape:'htmlall':'UTF-8'}</option>
{/foreach}
{/if}
</select>
{if isset($input.hint)}<span class="hint" name="help_box">{$input.hint}<span class="hint-pointer">&nbsp;</span></span>{/if}
{/if}
{elseif $input.type == 'radio'}
{foreach $input.values as $value}
<input type="radio"
name="{$input.name}"
id="{$value.id}"
value="{$value.value|escape:'htmlall':'UTF-8'}"
{if $fields_value[$input.name] == $value.value}checked="checked"{/if} />
<label {if isset($input.class)}class="{$input.class}"{/if} for="{$value.id}">
{if isset($input.is_bool) && $input.is_bool == true}
{if $value.value == 1}
<img src="../img/admin/enabled.gif" alt="{$value.label}" title="{$value.label}" />
{else}
<img src="../img/admin/disabled.gif" alt="{$value.label}" title="{$value.label}" />
{/if}
{else}
{$value.label}
{/if}
</label>
{if isset($input.br) && $input.br}<br />{/if}
{/foreach}
{elseif $input.type == 'textarea'}
{if isset($input.lang) && isset($input.attributeLang)}
{foreach $languages as $language}
<div id="{$input.name}_{$language.id_lang}" style="display:{if $language.id_lang == $defaultFormLanguage}block{else}none{/if}; float: left;">
<textarea cols="{$input.cols}" rows="{$input.rows}" name="{$input.name}_{$language.id_lang}">{$fields_value[$input.name][$language.id_lang]}</textarea>
</div>
{/foreach}
{if count($languages) > 1}
<div class="displayed_flag">
<img src="../img/l/{$defaultFormLanguage}.jpg"
class="pointer"
id="language_current_{$input.name}"
onclick="toggleLanguageFlags(this);" />
</div>
<div id="languages_{$input.name}" class="language_flags">
{l s='Choose language:'}<br /><br />
{foreach $languages as $language}
<img src="../img/l/{$language.id_lang}.jpg"
class="pointer"
alt="{$language.name}"
title="{$language.name}"
onclick="changeLanguage('{$input.name}', '{$input.attributeLang}', {$language.id_lang}, '{$language.iso_code}');" />
{/foreach}
</div>
{/if}
{else}
<textarea name="{$input.name}" id="{$input.name}" cols="{$input.cols}" rows="{$input.rows}">{$fields_value[$input.name]}</textarea>
{/if}
{elseif $input.type == 'checkbox'}
{foreach $input.values.query as $value}
{assign var=id_checkbox value=$input.name|cat:'_'|cat:$value[$input.values.id]}
<input type="checkbox" name="{$id_checkbox}" id="{$id_checkbox}" {if $fields_value[$id_checkbox]}checked="checked"{/if} />
<label for="{$id_checkbox}" class="t"><strong>{$value[$input.values.name]}</strong></label><br />
{/foreach}
{elseif $input.type == 'file'}
{if $input.display_image}
{if isset($fields_value.image) && $fields_value.image}
<div id="image">
{$fields_value.image}
<p align="center">{l s='File size'} {$fields_value.size}kb</p>
<a href="{$current}&id_category={$form_id}&token={$token}&deleteImage=1">
<img src="../img/admin/delete.gif" alt="{l s='Delete'}" /> {l s='Delete'}
</a>
</div><br />
{/if}
{/if}
<input type="file" name="{$input.name}" />
{elseif $input.type == 'password'}
<input type="password"
name="{$input.name}"
size="{$input.size}"
value="" />
{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}
<label>{l s='Shop association:'}</label>
<div class="margin-form">
{$asso_shop}
</div>
{/if}
{if isset($input.required) && $input.required} <sup>*</sup>{/if}
{if isset($input.p)}
<p class="clear">
{if is_array($input.p)}
{foreach $input.p as $p}
{if is_array($p)}
<span id="{$p.id}">{$p.text}</span><br />
{else}
{$p}<br />
{/if}
{/foreach}
{else}
{$input.p}
{/if}
</p>
{/if}
{if isset($languages)}<div class="clear"></div>{/if}
</div>
{/if}
{if $input.name == 'id_state'}
</div>
{/if}
{/foreach}
{elseif $key == 'submit'}
<div class="margin-form">
<input type="submit" value="{$field.title}" name="{$submit_action}" {if isset($field.class)}class="{$field.class}"{/if} />
</div>
{/if}
{/foreach}
{if $required_fields}
<div class="small"><sup>*</sup> {l s ='Required field'}</div>
{/if}
</fieldset>
</form>
<script type="text/javascript">
var iso = '{$iso}';
var pathCSS = '{$theme_path_css}';
var ad = '{$ad}';
</script>
<script type="text/javascript" src="../js/tiny_mce/tiny_mce.js"></script>
<script type="text/javascript" src="../js/tinymce.inc.js"></script>
<br /><br />
{if $firstCall && !$no_back}
{if $back}
<a href="{$back}"><img src="../img/admin/arrow2.gif" />{l s='Back'}</a>
{else}
<a href="{$current}&token={$token}"><img src="../img/admin/arrow2.gif" />{l s='Back to list'}</a>
{/if}
<br />
{/if}
@@ -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 <contact@prestashop.com>
* @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}
<link href="../css/admin.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
$(document).ready(function() {
$('table.{$table} .filter').keypress(function(event){
formSubmit(event, 'submitFilterButton{$table}')
})
});
</script>
{* Display column names and arrows for ordering (ASC, DESC) *}
{if $is_order_position}
<script type="text/javascript" src="../js/jquery/jquery.tablednd_0_5.js"></script>
<script type="text/javascript">
var token = '{$token}';
var come_from = '{$table}';
var alternate = {if $order_way == 'DESC'}'1'{else}'0'{/if};
</script>
<script type="text/javascript" src="../js/admin-dnd.js"></script>
{/if}
<script type="text/javascript">
$(function() {
if ($("table.{$table} .datepicker").length > 0)
$("table.{$table} .datepicker").datepicker({
prevText: '',
nextText: '',
dateFormat: 'yy-mm-dd'
});
});
</script>
<div class="cat_bar">
<span style="color: #3C8534;">{l s='Current Category:'}</span>
{if count($categories_tree) == 0}
&nbsp;<img src="../img/admin/home.gif" alt="" /> {l s='Home'}
{else}
<a href="{$currentIndex}&id_category=1&viewcategory&token={$token}">
&nbsp;<img src="../img/admin/home.gif" alt="" /> {l s='Home'}&nbsp;>&nbsp;
</a>
{foreach $categories_tree as $key => $category}
{if $key != 0}
<a href="{$currentIndex}&id_category={$category.id_category}&viewcategory&token={$token}">
<img src="../img/admin/edit.gif" alt="" /> {$category.name}&nbsp;>&nbsp;
</a>
{else}
<img src="../img/admin/edit.gif" alt="" /> {$category.name}
{/if}
{/foreach}
{/if}
</div>
<h2>{l s='Categories'}</h2>
<h3>
{if $list_total == 0}
{l s='There are no subcategories in '} "{$categories_name}"
{else}
{$list_total}&nbsp;
{if $list_total < 1}
{l s='subcategories'}
{else}
{l s='subcategory'} {l s='in category'} "{$categories_name}"
{/if}
{/if}
</h3>
{if $add_button}
<br /><a href="{$currentIndex}&add{$table}&token={$token}"><img src="../img/admin/add.gif" border="0" /> {l s='Add new'}</a><br /><br />
{/if}
<a name="{$table}">&nbsp;</a>
<form method="post" action="{$action}" class="form">
{/if}{* End if simple_header *}
<input type="hidden" id="submitFilter{$table}" name="submitFilter{$table}" value="0"/>
<table style="table-layout: fixed; width: 100%;">
{if !$simple_header}
<tr>
<td style="vertical-align: bottom;">
<span style="float: left;">
{if $page > 1}
<input type="image" src="../img/admin/list-prev2.gif" onclick="getE('submitFilter{$table}').value=1"/>&nbsp;
<input type="image" src="../img/admin/list-prev.gif" onclick="getE('submitFilter{$table}').value={$page - 1}"/>
{/if}
{l s='Page '}<b>{$page}</b> / {$total_pages}
{if $page < $total_pages}
<input type="image" src="../img/admin/list-next.gif" onclick="getE('submitFilter{$table}').value={$page + 1}"/>&nbsp;
<input type="image" src="../img/admin/list-next2.gif" onclick="getE('submitFilter{$table}'').value={$total_pages}"/>
{/if}
| {l s='Display'}
<select name="pagination">
{* Choose number of results per page *}
{foreach $pagination AS $value}
<option value="{$value|intval}"{if $selected_pagination == $value} selected="selected" {elseif $selected_pagination == NULL && $value == $pagination[1]} selected="selected2"{/if}>{$value|intval}</option>
{/foreach}
</select>
/ {$list_total} {l s='result(s)'}
</span>
<span style="float: right;">
<input type="submit" name="submitReset{$table}" value="{l s='Reset'}" class="button" />
<input type="submit" id="submitFilterButton{$table}" name="submitFilter" value="{l s='Filter'}" class="button" />
</span>
<span class="clear"></span>
</td>
</tr>
{/if}
<tr>
<td{if $simple_header} style="border:none;"{/if}>
<table
{if $table_id} id={$table_id}{/if}
class="table {if $table_dnd}tableDnd{/if} {$table}"
cellpadding="0" cellspacing="0"
style="width: 100%; margin-bottom:10px;"
>
<thead>
<tr class="nodrag nodrop">
<th style="width:10px;">
{if $delete}
<input type="checkbox" name="checkme" class="noborder" onclick="checkDelBoxes(this.form, '{$table}Box[]', this.checked)" />
{/if}
</th>
{foreach $fields_display AS $key => $params}
<th {if isset($params.widthColumn)} style="width: {if $params.widthColumn == 'auto'}auto{else}{$params.widthColumn}px{/if}"{/if}>{$params.title}
{if (!isset($params.orderby) || $params.orderby) && !$simple_header}
<br />
<a href="{$currentIndex}&{$identifier}={$id_cat}&{$table}Orderby={$key|urlencode}&{$table}Orderway=desc&token={$token}">
<img border="0" src="../img/admin/down{if isset($order_by) && ($key == $order_by) && ($order_way == 'DESC')}_d{/if}.gif" />
</a>
<a href="{$currentIndex}&{$identifier}={$id_cat}&{$table}Orderby={$key|urlencode}&{$table}Orderway=asc&token={$token}">
<img border="0" src="../img/admin/up{if isset($order_by) && ($key == $order_by) && ($order_way == 'ASC')}_d{/if}.gif" />
</a>
{/if}
</th>
{/foreach}
{if $shop_link_type}
<th style="width: 80px">
{if $shop_link_type == 'shop'}
{l s='shop'}
{else}
{l s='Group shop'}
{/if}
</th>
{/if}
{if $has_actions}
<th style="width: 52px">{l s='Actions'}</th>
{/if}
</tr>
{if !$simple_header}
<tr class="nodrag nodrop" style="height: 35px;">
<td class="center">
{if $delete}
--
{/if}
</td>
{* Filters (input, select, date or bool) *}
{foreach $fields_display AS $key => $params}
<td {if isset($params.align)} class="{$params.align}" {/if}>
{if isset($params.search) && !$params.search}
--
{else}
{if $params.type == 'bool'}
<select onchange="$('#submitFilterButton{$table}').focus();$('#submitFilterButton{$table}').click();" name="{$table}Filter_{$key}">
<option value="">--</option>
<option value="1" {if $params.value == 1} selected="selected" {/if}>{l s='Yes'}</option>
<option value="0" {if $params.value == 0 && $params.value != ''} selected="selected" {/if}>{l s='No'}</option>
</select>
{elseif $params.type == 'date' || $params.type == 'datetime'}
{l s='From'} <input type="text" class="filter datepicker" id="{$name_id}_0" name="{$name}[0]" value="{if isset($value.0)}$value.0{/if}"{if isset($params.width)} style="width:{$params.width}px"{/if}/><br />
{l s='To'} <input type="text" class="filter datepicker" id="{$name_id}_1" name="{$name}[1]" value="{if isset($value.1)}$value.1{/if}"{if isset($params.width)} style="width:{$params.width}px"{/if}/>
{elseif $params.type == 'select'}
{if isset($params.filter_key)}
<select onchange="$('#submitFilterButton{$table}').focus();$('#submitFilterButton{$table}').click();" name="{$table}Filter_{$params.filter_key}" {if isset($params.width)} style="width:{$params.width}px"{/if}>
<option value="" {if $params.value == 0 && $params.value != ''} selected="selected" {/if}>--</option>
{if isset($params.select) && is_array($params.select)}
{foreach $params.select AS $option_value => $option_display}
<option value="{$option_value}" {if $option_display.selected == 'selected'} selected="selected"{/if}>{$option_display}</option>
{/foreach}
{/if}
</select>
{/if}
{else}
<input type="text" class="filter" name="{$table}Filter_{if isset($params.filter_key)}{$params.filter_key}{else}{$key}{/if}" value="{$params.value|escape:'htmlall':'UTF-8'}" {if isset($params.width)} style="width:{$params.width}px"{/if} />
{/if}
{/if}
</td>
{/foreach}
{if $shop_link_type}
<td>--</td>
{/if}
{if $has_actions}
<td class="center">--</td>
{/if}
</tr>
{/if}
</thead>
+249 -178
View File
@@ -84,11 +84,24 @@ class CategoryCore extends ObjectModel
protected $fieldsRequired = array('active'); protected $fieldsRequired = array('active');
protected $fieldsSize = array('active' => 1); protected $fieldsSize = array('active' => 1);
protected $fieldsValidate = array('nleft' => 'isUnsignedInt', 'nright' => 'isUnsignedInt', 'level_depth' => 'isUnsignedInt', 'active' => 'isBool', 'id_parent' => 'isUnsignedInt', 'groupBox' => 'isArrayWithIds'); protected $fieldsValidate = array(
'nleft' => 'isUnsignedInt',
'nright' => 'isUnsignedInt',
'level_depth' => 'isUnsignedInt',
'active' => 'isBool',
'id_parent' => 'isUnsignedInt',
'groupBox' => 'isArrayWithIds'
);
protected $fieldsRequiredLang = array('name', 'link_rewrite'); protected $fieldsRequiredLang = array('name', 'link_rewrite');
protected $fieldsSizeLang = array('name' => 64, 'link_rewrite' => 64, 'meta_title' => 128, 'meta_description' => 255, 'meta_keywords' => 255); 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', protected $fieldsValidateLang = array(
'meta_title' => 'isGenericName', 'meta_description' => 'isGenericName', 'meta_keywords' => 'isGenericName'); 'name' => 'isCatalogName',
'link_rewrite' => 'isLinkRewrite',
'description' => 'isString',
'meta_title' => 'isGenericName',
'meta_description' => 'isGenericName',
'meta_keywords' => 'isGenericName'
);
protected $table = 'category'; protected $table = 'category';
protected $identifier = 'id_category'; protected $identifier = 'id_category';
@@ -110,10 +123,10 @@ class CategoryCore extends ObjectModel
), ),
); );
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); 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_; $this->image_dir = _PS_CAT_IMG_DIR_;
} }
@@ -121,13 +134,13 @@ class CategoryCore extends ObjectModel
{ {
$this->validateFields(); $this->validateFields();
if (isset($this->id)) if (isset($this->id))
$fields['id_category'] = (int)($this->id); $fields['id_category'] = (int)$this->id;
$fields['active'] = (int)($this->active); $fields['active'] = (int)$this->active;
$fields['id_parent'] = (int)($this->id_parent); $fields['id_parent'] = (int)$this->id_parent;
$fields['position'] = (int)($this->position); $fields['position'] = (int)$this->position;
$fields['level_depth'] = (int)($this->level_depth); $fields['level_depth'] = (int)$this->level_depth;
$fields['nleft'] = (int)($this->nleft); $fields['nleft'] = (int)$this->nleft;
$fields['nright'] = (int)($this->nright); $fields['nright'] = (int)$this->nright;
$fields['date_add'] = pSQL($this->date_add); $fields['date_add'] = pSQL($this->date_add);
$fields['date_upd'] = pSQL($this->date_upd); $fields['date_upd'] = pSQL($this->date_upd);
return $fields; return $fields;
@@ -164,10 +177,10 @@ class CategoryCore extends ObjectModel
public function add($autodate = true, $nullValues = false) public function add($autodate = true, $nullValues = false)
{ {
$this->position = self::getLastPosition((int)$this->id_parent); $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(); $this->level_depth = $this->calcLevelDepth();
$ret = parent::add($autodate); $ret = parent::add($autodate);
if (!isset($this->doNotRegenerateNTree) OR !$this->doNotRegenerateNTree) if (!isset($this->doNotRegenerateNTree) || !$this->doNotRegenerateNTree)
self::regenerateEntireNtree(); self::regenerateEntireNtree();
$this->updateGroup($this->groupBox); $this->updateGroup($this->groupBox);
Module::hookExec('categoryAddition', array('category' => $this)); Module::hookExec('categoryAddition', array('category' => $this));
@@ -190,7 +203,7 @@ class CategoryCore extends ObjectModel
if ($this->getDuplicatePosition()) if ($this->getDuplicatePosition())
$this->position = self::getLastPosition((int)$this->id_parent); $this->position = self::getLastPosition((int)$this->id_parent);
$ret = parent::update($nullValues); $ret = parent::update($nullValues);
if (!isset($this->doNotRegenerateNTree) OR !$this->doNotRegenerateNTree) if (!isset($this->doNotRegenerateNTree) || !$this->doNotRegenerateNTree)
{ {
self::regenerateEntireNtree(); self::regenerateEntireNtree();
$this->recalculateLevelDepth($this->id_category); $this->recalculateLevelDepth($this->id_category);
@@ -212,14 +225,14 @@ class CategoryCore extends ObjectModel
/** /**
* Recursive scan of subcategories * Recursive scan of subcategories
* *
* @param integer $maxDepth Maximum depth of the tree (i.e. 2 => 3 levels depth) * @param integer $max_depth 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 $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 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 * @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; $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_; $id_lang = _USER_ID_LANG_;
$children = array(); $children = array();
if (($maxDepth == 0 OR $currentDepth < $maxDepth) AND $subcats = $this->getSubCategories($id_lang, true) AND sizeof($subcats)) if (($max_depth == 0 || $current_depth < $max_depth) && $subcats = $this->getSubCategories($id_lang, true) && count($subcats))
foreach ($subcats AS &$subcat) foreach ($subcats as &$subcat)
{ {
if (!$subcat['id_category']) if (!$subcat['id_category'])
break; 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); $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 '<option value="'.$id_category.'"'.(($id_selected == $id_category) ? ' selected="selected"' : '').'>'. echo '<option value="'.$id_category.'"'.(($id_selected == $id_category) ? ' selected="selected"' : '').'>'.
str_repeat('&nbsp;', $current['infos']['level_depth'] * 5).stripslashes($current['infos']['name']).'</option>'; str_repeat('&nbsp;', $current['infos']['level_depth'] * 5).stripslashes($current['infos']['name']).'</option>';
if (isset($categories[$id_category])) 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); 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 * @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()); die(Tools::displayError());
$result = Db::getInstance()->executeS(' $result = Db::getInstance()->executeS('
SELECT `id_category` SELECT `id_category`
FROM `'._DB_PREFIX_.'category` FROM `'._DB_PREFIX_.'category`
WHERE `id_parent` = '.(int)($id_category)); WHERE `id_parent` = '.(int)$id_category);
foreach ($result AS $row) foreach ($result as $row)
{ {
$toDelete[] = (int)($row['id_category']); $to_delete[] = (int)$row['id_category'];
$this->recursiveDelete($toDelete, (int)($row['id_category'])); $this->recursiveDelete($to_delete, (int)$row['id_category']);
} }
} }
public function delete() 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(); $this->clearCache();
/* Get childs categories */ /* Get childs categories */
$toDelete = array((int)($this->id)); $to_delete = array((int)$this->id);
$this->recursiveDelete($toDelete, (int)($this->id)); $this->recursiveDelete($to_delete, (int)$this->id);
$toDelete = array_unique($toDelete); $to_delete = array_unique($to_delete);
/* Delete category and its child from database */ /* 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` 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_lang` WHERE `id_category` IN ('.$list.')');
Db::getInstance()->execute('DELETE FROM `'._DB_PREFIX_.'category_product` 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); self::cleanPositions($this->id_parent);
/* Delete category images and its children images */ /* Delete category images and its children images */
$tmpCategory= new Category(); $tmp_category = new Category();
foreach ($toDelete AS $id_category) foreach ($to_delete as $id_category)
{ {
$tmpCategory->id = (int)$id_category; $tmp_category->id = (int)$id_category;
$tmpCategory->deleteImage(); $tmp_category->deleteImage();
} }
/* Delete products which were not in others categories */ /* Delete products which were not in others categories */
$result = Db::getInstance()->executeS(' $result = Db::getInstance()->executeS('
SELECT `id_product` SELECT `id_product`
FROM `'._DB_PREFIX_.'product` FROM `'._DB_PREFIX_.'product`
WHERE `id_product` NOT IN (SELECT `id_product` FROM `'._DB_PREFIX_.'category_product`)'); WHERE `id_product` NOT IN (SELECT `id_product` FROM `'._DB_PREFIX_.'category_product`)
');
foreach ($result as $p) foreach ($result as $p)
{ {
$product = new Product((int)$p['id_product']); $product = new Product((int)$p['id_product']);
@@ -325,16 +340,17 @@ class CategoryCore extends ObjectModel
UPDATE `'._DB_PREFIX_.'product` UPDATE `'._DB_PREFIX_.'product`
SET `id_category_default` = 1 SET `id_category_default` = 1
WHERE `id_category_default` WHERE `id_category_default`
NOT IN (SELECT `id_category` FROM `'._DB_PREFIX_.'category`)'); NOT IN (SELECT `id_category` FROM `'._DB_PREFIX_.'category`)
');
/* Rebuild the nested tree */ /* Rebuild the nested tree */
if (!isset($this->doNotRegenerateNTree) OR !$this->doNotRegenerateNTree) if (!isset($this->doNotRegenerateNTree) || !$this->doNotRegenerateNTree)
self::regenerateEntireNtree(); self::regenerateEntireNtree();
Module::hookExec('categoryDeletion', array('category' => $this)); Module::hookExec('categoryDeletion', array('category' => $this));
/* Delete Categories in GroupReduction */ /* Delete Categories in GroupReduction */
foreach ($toDelete AS $category) foreach ($to_delete as $category)
if (GroupReduction::getGroupReductionByCategoryId((int)$category)) if (GroupReduction::getGroupReductionByCategoryId((int)$category))
GroupReduction::deleteCategory($category); GroupReduction::deleteCategory($category);
@@ -349,7 +365,7 @@ class CategoryCore extends ObjectModel
public function deleteSelection($categories) public function deleteSelection($categories)
{ {
$return = 1; $return = 1;
foreach ($categories AS $id_category) foreach ($categories as $id_category)
{ {
$category = new Category($id_category); $category = new Category($id_category);
$return &= $category->delete(); $return &= $category->delete();
@@ -368,10 +384,10 @@ class CategoryCore extends ObjectModel
if (!$this->id_parent) if (!$this->id_parent)
return 0; return 0;
$parentCategory = new Category($this->id_parent); $parent_category = new Category($this->id_parent);
if (!Validate::isLoadedObject($parentCategory)) if (!Validate::isLoadedObject($parent_category))
die('parent category does not exist'); 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() public static function regenerateEntireNtree()
{ {
$categories = Db::getInstance()->executeS('SELECT id_category, id_parent FROM '._DB_PREFIX_.'category ORDER BY id_category ASC'); $categories = Db::getInstance()->executeS('SELECT id_category, id_parent FROM '._DB_PREFIX_.'category ORDER BY id_category ASC');
$categoriesArray = array(); $categories_array = array();
foreach ($categories AS $category) foreach ($categories as $category)
$categoriesArray[(int)$category['id_parent']]['subcategories'][(int)$category['id_category']] = 1; $categories_array[(int)$category['id_parent']]['subcategories'][(int)$category['id_category']] = 1;
$n = 1; $n = 1;
self::_subTree($categoriesArray, 1, $n); self::_subTree($categories_array, 1, $n);
} }
protected static function _subTree(&$categories, $id_category, &$n) protected static function _subTree(&$categories, $id_category, &$n)
{ {
$left = (int)$n++; $left = (int)$n++;
if (isset($categories[(int)$id_category]['subcategories'])) 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); self::_subTree($categories, (int)$id_subcategory, $n);
$right = (int)$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
');
} }
/** /**
@@ -442,7 +462,7 @@ class CategoryCore extends ObjectModel
SELECT * SELECT *
FROM `'._DB_PREFIX_.'category` c FROM `'._DB_PREFIX_.'category` c
LEFT JOIN `'._DB_PREFIX_.'category_lang` cl ON c.`id_category` = cl.`id_category`'.Context::getContext()->shop->addSqlRestrictionOnLang('cl').' 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) : '').' WHERE 1 '.$sql_filter.' '.($id_lang ? 'AND `id_lang` = '.(int)$id_lang : '').'
'.($active ? 'AND `active` = 1' : '').' '.($active ? 'AND `active` = 1' : '').'
'.(!$id_lang ? 'GROUP BY c.id_category' : '').' '.(!$id_lang ? 'GROUP BY c.id_category' : '').'
'.($sql_sort != '' ? $sql_sort : 'ORDER BY c.`level_depth` ASC, c.`position` ASC').' '.($sql_sort != '' ? $sql_sort : 'ORDER BY c.`level_depth` ASC, c.`position` ASC').'
@@ -453,7 +473,7 @@ class CategoryCore extends ObjectModel
return $result; return $result;
$categories = array(); $categories = array();
foreach ($result AS $row) foreach ($result as $row)
$categories[$row['id_parent']][$row['id_category']]['infos'] = $row; $categories[$row['id_parent']][$row['id_category']]['infos'] = $row;
return $categories; return $categories;
@@ -483,22 +503,26 @@ class CategoryCore extends ObjectModel
die(Tools::displayError()); die(Tools::displayError());
$groups = FrontController::getCurrentCustomerGroups(); $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(' $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 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 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_lang` cl
LEFT JOIN `'._DB_PREFIX_.'category_group` cg ON (cg.`id_category` = c.`id_category`) ON (c.`id_category` = cl.`id_category`
WHERE `id_parent` = '.(int)($this->id).' 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' : '').' '.($active ? 'AND `active` = 1' : '').'
AND cg.`id_group` '.$sqlGroups.' AND cg.`id_group` '.$sql_groups.'
GROUP BY c.`id_category` GROUP BY c.`id_category`
ORDER BY `level_depth` ASC, c.`position` ASC'); 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'; $row['legend'] = 'no picture';
} }
return $result; return $result;
@@ -510,97 +534,119 @@ class CategoryCore extends ObjectModel
* @param integer $id_lang Language ID * @param integer $id_lang Language ID
* @param integer $p Page number * @param integer $p Page number
* @param integer $n Number of products per page * @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 $active return only active products
* @param boolean $random active a random filter for returned products * @param boolean $random active a random filter for returned products
* @param int $randomNumberProducts number of products to return if random is activated * @param int $random_number_products 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 boolean $check_access set to false to return all products (even if customer hasn't access)
* @return mixed Products or number of products * @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) if (!$context)
$context = Context::getContext(); $context = Context::getContext();
if (!$checkAccess OR !$this->checkAccess($context->customer->id)) if (!$check_access || !$this->checkAccess($context->customer->id))
return false; return false;
if ($p < 1) $p = 1; if ($p < 1) $p = 1;
if (empty($orderBy)) if (empty($order_by))
$orderBy = 'position'; $order_by = 'position';
else else
/* Fix for all modules which are now using lowercase values for 'orderBy' parameter */ /* Fix for all modules which are now using lowercase values for 'orderBy' parameter */
$orderBy = strtolower($orderBy); $order_by = strtolower($order_by);
if (empty($orderWay)) if (empty($order_way))
$orderWay = 'ASC'; $order_way = 'ASC';
if ($orderBy == 'id_product' OR $orderBy == 'date_add') if ($order_by == 'id_product' || $order_by == 'date_add')
$orderByPrefix = 'p'; $order_by_prefix = 'p';
elseif ($orderBy == 'name') else if ($order_by == 'name')
$orderByPrefix = 'pl'; $order_by_prefix = 'pl';
elseif ($orderBy == 'manufacturer') else if ($order_by == 'manufacturer')
{ {
$orderByPrefix = 'm'; $order_by_prefix = 'm';
$orderBy = 'name'; $order_by = 'name';
} }
elseif ($orderBy == 'position') else if ($order_by == 'position')
$orderByPrefix = 'cp'; $order_by_prefix = 'cp';
if ($orderBy == 'price') if ($order_by == 'price')
$orderBy = 'orderprice'; $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()); die (Tools::displayError());
$id_supplier = (int)(Tools::getValue('id_supplier')); $id_supplier = (int)Tools::getValue('id_supplier');
/* Return only the number of products */ /* Return only the number of products */
if ($getTotal) if ($get_total)
{ {
$sql = 'SELECT COUNT(cp.`id_product`) AS total $sql = 'SELECT COUNT(cp.`id_product`) AS total
FROM `'._DB_PREFIX_.'product` p FROM `'._DB_PREFIX_.'product` p
'.$context->shop->addSqlAssociation('product', 'p').' '.$context->shop->addSqlAssociation('product', 'p').'
LEFT JOIN `'._DB_PREFIX_.'category_product` cp ON p.`id_product` = cp.`id_product` 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' : ''). ($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); 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 (p.`price` * IF(t.`rate`,((100 + (t.`rate`))/100),1)) AS orderprice
FROM `'._DB_PREFIX_.'category_product` cp FROM `'._DB_PREFIX_.'category_product` cp
LEFT JOIN `'._DB_PREFIX_.'product` p ON p.`id_product` = cp.`id_product` LEFT JOIN `'._DB_PREFIX_.'product` p
LEFT JOIN `'._DB_PREFIX_.'product_attribute` pa ON (p.`id_product` = pa.`id_product` AND default_on = 1) 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').' '.$context->shop->addSqlAssociation('product', 'p').'
'.Product::sqlStock('p', 'pa', false, $context->shop).' '.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_.'category_lang` 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').') ON (p.`id_category_default` = cl.`id_category`
LEFT JOIN `'._DB_PREFIX_.'image` i ON (i.`id_product` = p.`id_product` AND i.`cover` = 1) AND cl.`id_lang` = '.(int)$id_lang.$context->shop->addSqlRestrictionOnLang('cl').')
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_.'product_lang` pl
LEFT JOIN `'._DB_PREFIX_.'tax_rule` tr ON (p.`id_tax_rules_group` = tr.`id_tax_rules_group` 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_country` = '.(int)$context->country->id.'
AND tr.`id_state` = 0 AND tr.`id_state` = 0
AND tr.`zipcode_from` = 0) AND tr.`zipcode_from` = 0)
LEFT JOIN `'._DB_PREFIX_.'tax` t ON (t.`id_tax` = tr.`id_tax`) LEFT JOIN `'._DB_PREFIX_.'tax` t
LEFT JOIN `'._DB_PREFIX_.'tax_lang` tl ON (t.`id_tax` = tl.`id_tax` AND tl.`id_lang` = '.(int)$id_lang.') ON (t.`id_tax` = tr.`id_tax`)
LEFT JOIN `'._DB_PREFIX_.'manufacturer` m ON m.`id_manufacturer` = p.`id_manufacturer` LEFT JOIN `'._DB_PREFIX_.'tax_lang` tl
LEFT JOIN `'._DB_PREFIX_.'stock_available` sa ON sa.`id_product` = p.`id_product` AND sa.id_product_attribute = 0 ON (t.`id_tax` = tl.`id_tax`
WHERE cp.`id_category` = '.(int)($this->id) 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' : '') .($active ? ' AND p.`active` = 1' : '')
.($id_supplier ? ' AND p.id_supplier = '.(int)$id_supplier : ''); .($id_supplier ? ' AND p.id_supplier = '.(int)$id_supplier : '');
if ($random === true) if ($random === true)
{ {
$sql .= ' ORDER BY RAND()'; $sql .= ' ORDER BY RAND()';
$sql .= ' LIMIT 0, '.(int)($randomNumberProducts); $sql .= ' LIMIT 0, '.(int)$random_number_products;
} }
else else
$sql .= ' ORDER BY '.(isset($orderByPrefix) ? $orderByPrefix.'.' : '').'`'.pSQL($orderBy).'` '.pSQL($orderWay).' $sql .= ' ORDER BY '.(isset($order_by_prefix) ? $order_by_prefix.'.' : '').'`'.pSQL($order_by).'` '.pSQL($order_way).'
LIMIT '.(((int)($p) - 1) * (int)($n)).','.(int)($n); LIMIT '.(((int)$p - 1) * (int)$n).','.(int)$n;
$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($sql); $result = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($sql);
if ($orderBy == 'orderprice') if ($order_by == 'orderprice')
Tools::orderbyPrice($result, $orderWay); Tools::orderbyPrice($result, $order_way);
if (!$result) if (!$result)
return false; return false;
@@ -621,7 +667,7 @@ class CategoryCore extends ObjectModel
return self::getChildren(1, $id_lang, $active); 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)) if (is_null($id_lang))
$id_lang = Context::getContext()->language->id; $id_lang = Context::getContext()->language->id;
@@ -647,8 +693,8 @@ class CategoryCore extends ObjectModel
SELECT c.`id_category`, cl.`name`, cl.`link_rewrite` SELECT c.`id_category`, cl.`name`, cl.`link_rewrite`
FROM `'._DB_PREFIX_.'category` c FROM `'._DB_PREFIX_.'category` c
LEFT JOIN `'._DB_PREFIX_.'category_lang` cl ON c.`id_category` = cl.`id_category`'.Context::getContext()->shop->addSqlRestrictionOnLang('cl').' 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).' WHERE `id_lang` = '.(int)$id_lang.'
AND c.`id_parent` = '.(int)($id_parent).' AND c.`id_parent` = '.(int)$id_parent.'
'.($active ? 'AND `active` = 1' : '').' '.($active ? 'AND `active` = 1' : '').'
ORDER BY `position` ASC'); ORDER BY `position` ASC');
} }
@@ -663,7 +709,8 @@ class CategoryCore extends ObjectModel
return Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS(' return Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS('
SELECT * SELECT *
FROM `'._DB_PREFIX_.'category` FROM `'._DB_PREFIX_.'category`
WHERE '. $this->nleft . ' < nleft AND nright < '. $this->nright); WHERE '.$this->nleft.' < nleft AND nright < '.$this->nright
);
} }
/** /**
@@ -674,27 +721,27 @@ class CategoryCore extends ObjectModel
* @param int $id_lang * @param int $id_lang
* @return array * @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) if (!$shop)
$shop = Context::getContext()->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(( $sql = 'SELECT c.`id_category`, c.`level_depth`, cl.`name`, IF((
SELECT COUNT(*) SELECT COUNT(*)
FROM `'._DB_PREFIX_.'category` c2 FROM `'._DB_PREFIX_.'category` c2
WHERE c2.`id_parent` = c.`id_category` 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`) SELECT count(c3.`id_category`)
FROM `'._DB_PREFIX_.'category` c3 FROM `'._DB_PREFIX_.'category` c3
WHERE c3.`nleft` > c.`nleft` WHERE c3.`nleft` > c.`nleft`
AND c3.`nright` < c.`nright` 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 )' : '0').' AS nbSelectedSubCat
FROM `'._DB_PREFIX_.'category` c FROM `'._DB_PREFIX_.'category` c
LEFT JOIN `'._DB_PREFIX_.'category_lang` cl ON c.`id_category` = cl.`id_category`'.$shop->addSqlRestrictionOnLang('cl').' LEFT JOIN `'._DB_PREFIX_.'category_lang` cl ON c.`id_category` = cl.`id_category`'.$shop->addSqlRestrictionOnLang('cl').'
WHERE `id_lang` = '.(int)($id_lang).' WHERE `id_lang` = '.(int)$id_lang.'
AND c.`id_parent` = '.(int)($id_parent).' AND c.`id_parent` = '.(int)$id_parent.'
ORDER BY `position` ASC'; ORDER BY `position` ASC';
return Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($sql); return Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($sql);
} }
@@ -715,10 +762,17 @@ class CategoryCore extends ObjectModel
$row = array(); $row = array();
if ($result) if ($result)
foreach ($result AS $i) 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)')).')'; $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; return $flag;
} }
@@ -734,11 +788,11 @@ class CategoryCore extends ObjectModel
{ {
if ($id_category == $id_parent) return false; if ($id_category == $id_parent) return false;
if ($id_parent == 1) return true; if ($id_parent == 1) return true;
$i = (int)($id_parent); $i = (int)$id_parent;
while (42) 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 (!isset($result['id_parent'])) return false;
if ($result['id_parent'] == $id_category) return false; if ($result['id_parent'] == $id_category) return false;
if ($result['id_parent'] == 1) return true; if ($result['id_parent'] == 1) return true;
@@ -748,7 +802,7 @@ class CategoryCore extends ObjectModel
public static function getLinkRewrite($id_category, $id_lang) 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; return false;
if (isset(self::$_links[$id_category.'-'.$id_lang])) if (isset(self::$_links[$id_category.'-'.$id_lang]))
@@ -758,8 +812,8 @@ class CategoryCore extends ObjectModel
SELECT cl.`link_rewrite` SELECT cl.`link_rewrite`
FROM `'._DB_PREFIX_.'category` c FROM `'._DB_PREFIX_.'category` c
LEFT JOIN `'._DB_PREFIX_.'category_lang` cl ON c.`id_category` = cl.`id_category`'.Context::getContext()->shop->addSqlRestrictionOnLang('cl').' 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).' WHERE `id_lang` = '.(int)$id_lang.'
AND c.`id_category` = '.(int)($id_category)); AND c.`id_category` = '.(int)$id_category);
self::$_links[$id_category.'-'.$id_lang] = $result['link_rewrite']; self::$_links[$id_category.'-'.$id_lang] = $result['link_rewrite'];
return $result['link_rewrite']; return $result['link_rewrite'];
} }
@@ -771,14 +825,14 @@ class CategoryCore extends ObjectModel
return $link->getCategoryLink($this->id, $this->link_rewrite); return $link->getCategoryLink($this->id, $this->link_rewrite);
} }
public function getName($id_lang = NULL) public function getName($id_lang = null)
{ {
if (!$id_lang) if (!$id_lang)
{ {
if (isset($this->name[Context::getContext()->language->id])) if (isset($this->name[Context::getContext()->language->id]))
$id_lang = Context::getContext()->language->id; $id_lang = Context::getContext()->language->id;
else 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] : ''; return isset($this->name[$id_lang]) ? $this->name[$id_lang] : '';
} }
@@ -797,14 +851,20 @@ class CategoryCore extends ObjectModel
return Db::getInstance()->getRow(' return Db::getInstance()->getRow('
SELECT c.*, cl.* SELECT c.*, cl.*
FROM `'._DB_PREFIX_.'category` c FROM `'._DB_PREFIX_.'category` c
LEFT JOIN `'._DB_PREFIX_.'category_lang` cl ON (c.`id_category` = cl.`id_category`'.Context::getContext()->shop->addSqlRestrictionOnLang('cl').') LEFT JOIN `'._DB_PREFIX_.'category_lang` cl
WHERE `name` LIKE \''.pSQL($query).'\''); ON (c.`id_category` = cl.`id_category`'.Context::getContext()->shop->addSqlRestrictionOnLang('cl').')
WHERE `name` LIKE \''.pSQL($query).'\'
');
else else
return Db::getInstance()->executeS(' return Db::getInstance()->executeS('
SELECT c.*, cl.* SELECT c.*, cl.*
FROM `'._DB_PREFIX_.'category` c 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_lang` cl
WHERE `name` LIKE \'%'.pSQL($query).'%\' AND c.`id_category` != 1'); 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
');
} }
/** /**
@@ -820,10 +880,13 @@ class CategoryCore extends ObjectModel
return Db::getInstance()->getRow(' return Db::getInstance()->getRow('
SELECT c.*, cl.* SELECT c.*, cl.*
FROM `'._DB_PREFIX_.'category` c 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_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).'\' WHERE `name` LIKE \''.pSQL($category_name).'\'
AND c.`id_category` != 1 AND c.`id_category` != 1
AND c.`id_parent` = '.(int)($id_parent_category)); AND c.`id_parent` = '.(int)$id_parent_category
);
} }
/** /**
@@ -838,20 +901,23 @@ class CategoryCore extends ObjectModel
$id_lang = $context->language->id; $id_lang = $context->language->id;
$categories = null; $categories = null;
$idCurrent = $this->id; $id_current = $this->id;
while (true) while (true)
{ {
$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS(' $result = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS('
SELECT c.*, cl.* SELECT c.*, cl.*
FROM `'._DB_PREFIX_.'category` c 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_lang` cl
WHERE c.`id_category` = '.(int)$idCurrent.' AND c.`id_parent` != 0 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]; isset($result[0]) ? $categories[] = $result[0] : $categories = array();
if(!$result OR $result[0]['id_parent'] == 1) if (!$result || $result[0]['id_parent'] == 1)
return $categories; 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(' $row = Db::getInstance()->getRow('
SELECT `id_category` SELECT `id_category`
FROM '._DB_PREFIX_.'category c FROM '._DB_PREFIX_.'category c
WHERE c.`id_category` = '.(int)($id_category)); WHERE c.`id_category` = '.(int)$id_category);
return isset($row['id_category']); return isset($row['id_category']);
} }
@@ -873,14 +939,14 @@ class CategoryCore extends ObjectModel
public function cleanGroups() 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) public function addGroups($groups)
{ {
foreach ($groups as $group) 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'); Db::getInstance()->AutoExecute(_DB_PREFIX_.'category_group', $row, 'INSERT');
} }
} }
@@ -891,7 +957,8 @@ class CategoryCore extends ObjectModel
$result = Db::getInstance()->executeS(' $result = Db::getInstance()->executeS('
SELECT cg.`id_group` SELECT cg.`id_group`
FROM '._DB_PREFIX_.'category_group cg FROM '._DB_PREFIX_.'category_group cg
WHERE cg.`id_category` = '.(int)($this->id)); WHERE cg.`id_category` = '.(int)$this->id
);
foreach ($result as $group) foreach ($result as $group)
$groups[] = $group['id_group']; $groups[] = $group['id_group'];
return $groups; return $groups;
@@ -905,7 +972,7 @@ class CategoryCore extends ObjectModel
if ($group == $id_group) if ($group == $id_group)
return false; return false;
else else
return $this->addGroups(array((int)($id_group))); return $this->addGroups(array((int)$id_group));
} }
} }
@@ -923,15 +990,17 @@ class CategoryCore extends ObjectModel
$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow(' $result = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow('
SELECT ctg.`id_group` SELECT ctg.`id_group`
FROM '._DB_PREFIX_.'category_group ctg FROM '._DB_PREFIX_.'category_group ctg
WHERE ctg.`id_category` = '.(int)($this->id).' AND ctg.`id_group` = 1'); WHERE ctg.`id_category` = '.(int)$this->id.' AND ctg.`id_group` = 1
');
} else { } else {
$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow(' $result = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow('
SELECT ctg.`id_group` SELECT ctg.`id_group`
FROM '._DB_PREFIX_.'category_group ctg 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).') 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)); 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 true;
return false; return false;
} }
@@ -939,7 +1008,7 @@ class CategoryCore extends ObjectModel
public function updateGroup($list) public function updateGroup($list)
{ {
$this->cleanGroups(); $this->cleanGroups();
if ($list AND sizeof($list)) if ($list && count($list))
$this->addGroups($list); $this->addGroups($list);
else else
$this->addGroups(array(1)); $this->addGroups(array(1));
@@ -947,11 +1016,11 @@ class CategoryCore extends ObjectModel
public static function setNewGroupForHome($id_group) public static function setNewGroupForHome($id_group)
{ {
if (!(int)($id_group)) if (!(int)$id_group)
return false; return false;
return Db::getInstance()->execute(' return Db::getInstance()->execute('
INSERT INTO `'._DB_PREFIX_.'category_group` INSERT INTO `'._DB_PREFIX_.'category_group`
VALUES (1, '.(int)($id_group).') VALUES (1, '.(int)$id_group.')
'); ');
} }
@@ -965,11 +1034,11 @@ class CategoryCore extends ObjectModel
)) ))
return false; return false;
foreach ($res AS $category) foreach ($res as $category)
if ((int)($category['id_category']) == (int)($this->id)) if ((int)$category['id_category'] == (int)$this->id)
$movedCategory = $category; $moved_category = $category;
if (!isset($movedCategory) || !isset($position)) if (!isset($moved_category) || !isset($position))
return false; return false;
// < and > statements rather than BETWEEN operator // < and > statements rather than BETWEEN operator
// since BETWEEN is treated differently according to databases // since BETWEEN is treated differently according to databases
@@ -978,14 +1047,14 @@ class CategoryCore extends ObjectModel
SET `position`= `position` '.($way ? '- 1' : '+ 1').' SET `position`= `position` '.($way ? '- 1' : '+ 1').'
WHERE `position` WHERE `position`
'.($way '.($way
? '> '.(int)($movedCategory['position']).' AND `position` <= '.(int)($position) ? '> '.(int)$moved_category['position'].' AND `position` <= '.(int)$position
: '< '.(int)($movedCategory['position']).' AND `position` >= '.(int)($position)).' : '< '.(int)$moved_category['position'].' AND `position` >= '.(int)$position).'
AND `id_parent`='.(int)($movedCategory['id_parent'])) AND `id_parent`='.(int)$moved_category['id_parent'])
AND Db::getInstance()->execute(' && Db::getInstance()->execute('
UPDATE `'._DB_PREFIX_.'category` UPDATE `'._DB_PREFIX_.'category`
SET `position` = '.(int)($position).' SET `position` = '.(int)$position.'
WHERE `id_parent` = '.(int)($movedCategory['id_parent']).' WHERE `id_parent` = '.(int)$moved_category['id_parent'].'
AND `id_category`='.(int)($movedCategory['id_category']))); AND `id_category`='.(int)$moved_category['id_category']));
Module::hookExec('categoryUpdate'); Module::hookExec('categoryUpdate');
return $result; return $result;
} }
@@ -1005,15 +1074,17 @@ class CategoryCore extends ObjectModel
$result = Db::getInstance()->executeS(' $result = Db::getInstance()->executeS('
SELECT `id_category` SELECT `id_category`
FROM `'._DB_PREFIX_.'category` FROM `'._DB_PREFIX_.'category`
WHERE `id_parent` = '.(int)($id_category_parent).' WHERE `id_parent` = '.(int)$id_category_parent.'
ORDER BY `position`'); ORDER BY `position`
$sizeof = sizeof($result); ');
for ($i = 0; $i < $sizeof; $i++){ $count = count($result);
for ($i = 0; $i < $count; $i++)
{
$sql = ' $sql = '
UPDATE `'._DB_PREFIX_.'category` UPDATE `'._DB_PREFIX_.'category`
SET `position` = '.(int)($i).' SET `position` = '.(int)$i.'
WHERE `id_parent` = '.(int)($id_category_parent).' WHERE `id_parent` = '.(int)$id_category_parent.'
AND `id_category` = '.(int)($result[$i]['id_category']); AND `id_category` = '.(int)$result[$i]['id_category'];
$return &= Db::getInstance()->execute($sql); $return &= Db::getInstance()->execute($sql);
} }
return $return; return $return;
@@ -1027,7 +1098,7 @@ class CategoryCore extends ObjectModel
*/ */
public static function getLastPosition($id_category_parent) 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) public static function getUrlRewriteInformations($id_category)
@@ -1080,7 +1151,7 @@ class CategoryCore extends ObjectModel
$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS(' $result = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS('
SELECT c.`id_category` as id SELECT c.`id_category` as id
FROM `'._DB_PREFIX_.'category` c FROM `'._DB_PREFIX_.'category` c
WHERE c.`id_parent` = '.(int)($this->id).' WHERE c.`id_parent` = '.(int)$this->id.'
AND `active` = 1 AND `active` = 1
ORDER BY `position` ASC'); ORDER BY `position` ASC');
return $result; return $result;
@@ -1091,7 +1162,7 @@ class CategoryCore extends ObjectModel
$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS(' $result = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS('
SELECT cp.`id_product` as id SELECT cp.`id_product` as id
FROM `'._DB_PREFIX_.'category_product` cp FROM `'._DB_PREFIX_.'category_product` cp
WHERE cp.`id_category` = '.(int)($this->id).' WHERE cp.`id_category` = '.(int)$this->id.'
ORDER BY `position` ASC'); ORDER BY `position` ASC');
return $result; return $result;
} }
@@ -1106,9 +1177,9 @@ class CategoryCore extends ObjectModel
return Db::getInstance()->getRow(' return Db::getInstance()->getRow('
SELECT c.`id_category` as id SELECT c.`id_category` as id
FROM `'._DB_PREFIX_.'category` c FROM `'._DB_PREFIX_.'category` c
WHERE c.`id_parent` = '.(int)($this->id_parent).' WHERE c.`id_parent` = '.(int)$this->id_parent.'
AND `position` = '.(int)($this->position).' AND `position` = '.(int)$this->position.'
AND c.`id_category` != '.(int)($this->id)); AND c.`id_category` != '.(int)$this->id);
} }
public function getWsNbProductsRecursive() public function getWsNbProductsRecursive()
@@ -1135,7 +1206,7 @@ class CategoryCore extends ObjectModel
if ($id_lang === null) if ($id_lang === null)
$id_lang = Context::getContext()->language->id; $id_lang = Context::getContext()->language->id;
if (!is_array($ids_category) || !sizeof($ids_category)) if (!is_array($ids_category) || !count($ids_category))
return; return;
$categories = array(); $categories = array();
@@ -0,0 +1,398 @@
<?php
/*
* 2007-2011 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 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/osl-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 <contact@prestashop.com>
* @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.').' <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(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.').' <b>'.$this->table.'</b> '.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.').' <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
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));
}
}