diff --git a/admin-dev/themes/template/addresses/form.tpl b/admin-dev/themes/template/addresses/form.tpl index cb4c99104..76c1f2c93 100644 --- a/admin-dev/themes/template/addresses/form.tpl +++ b/admin-dev/themes/template/addresses/form.tpl @@ -78,7 +78,7 @@ {else}
- * + *
{/if} {else} @@ -99,7 +99,7 @@ @@ -110,14 +110,14 @@ {foreach $optiongroup[$input.options.options.query] as $option} + {if $fields_value[$input.name] == $option[$input.options.options.id]}selected="selected"{/if}>{$option[$input.options.options.name]|escape:'htmlall':'UTF-8'} {/foreach} {/foreach} {else} {foreach $input.options.query AS $option} + {if $fields_value[$input.name] == $option[$input.options.id]}selected="selected"{/if}>{$option[$input.options.name]|escape:'htmlall':'UTF-8'} {/foreach} {/if} @@ -126,12 +126,12 @@ {/foreach} {elseif $input.type == 'textarea'} - + {elseif $input.type == 'checkbox'} {/if} diff --git a/admin-dev/themes/template/form.tpl b/admin-dev/themes/template/form.tpl index 5cf14e14c..3d6b09e2b 100644 --- a/admin-dev/themes/template/form.tpl +++ b/admin-dev/themes/template/form.tpl @@ -121,7 +121,7 @@ {foreach $optiongroup[$input.options.options.query] as $option} + {if $fields_value[$input.name] == $option[$input.options.options.id]}selected="selected"{/if}>{$option[$input.options.options.name]|escape:'htmlall':'UTF-8'} {/foreach} {/foreach} @@ -129,7 +129,7 @@ {foreach $input.options.query AS $option} {$fields_value[$input.name]|@p} + {if $fields_value[$input.name] == $option[$input.options.id]}selected="selected"{/if}>{$option[$input.options.name]|escape:'htmlall':'UTF-8'} {/foreach} {/if} @@ -138,7 +138,7 @@ {/foreach} diff --git a/admin-dev/themes/template/layout.tpl b/admin-dev/themes/template/layout.tpl index 82fbd84e7..4f8f6d6a9 100644 --- a/admin-dev/themes/template/layout.tpl +++ b/admin-dev/themes/template/layout.tpl @@ -53,7 +53,7 @@ {$errors|count} {l s='errors'}
    - {foreach $errors as $error} + {foreach $errors AS $error}
  1. {$error}
  2. {/foreach}
diff --git a/admin-dev/themes/template/list_content.tpl b/admin-dev/themes/template/list_content.tpl index 66220c189..a1c13c5b3 100644 --- a/admin-dev/themes/template/list_content.tpl +++ b/admin-dev/themes/template/list_content.tpl @@ -79,7 +79,7 @@ {elseif isset($params.type) && $params.type == 'datetime'} {$tr.$key} {elseif isset($tr.$key)} - {$tr.$key} + {$tr.$key|escape:'htmlall':'UTF-8'} {else} -- {/if} @@ -88,7 +88,7 @@ {/foreach} {if $shop_link_type} - $tr.shop_short_name + {$tr.shop_short_name} {/if} {if $has_actions} diff --git a/admin-dev/themes/template/options.tpl b/admin-dev/themes/template/options.tpl new file mode 100644 index 000000000..87c52ec4c --- /dev/null +++ b/admin-dev/themes/template/options.tpl @@ -0,0 +1,158 @@ +{* +* 2007-2011 PrestaShop +* +* NOTICE OF LICENSE +* +* This source file is subject to the Academic Free License (AFL 3.0) +* that is bundled with this package in the file LICENSE.txt. +* It is also available through the world-wide-web at this URL: +* http://opensource.org/licenses/afl-3.0.php +* If you did not receive a copy of the license and are unable to +* obtain it through the world-wide-web, please send an email +* to license@prestashop.com so we can send you a copy immediately. +* +* DISCLAIMER +* +* Do not edit or add to this file if you wish to upgrade PrestaShop to newer +* versions in the future. If you wish to customize PrestaShop for your +* needs please refer to http://www.prestashop.com for more information. +* +* @author PrestaShop SA +* @copyright 2007-2011 PrestaShop SA +* @version Release: $Revision$ +* @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0) +* International Registered Trademark & Property of PrestaShop SA +*} +
+ + +
+{foreach $optionsList AS $category => $categoryData} + {if isset($categoryData['top'])}{$categoryData['top']}{/if} +
+ {* Options category title *} + + + {if isset($categoryData['title'])}{$categoryData['title']}{else}{l s='Options'}{/if} + + + {* Category description *} + {if (isset($categoryData['description']) && $categoryData['description'])} +

{$categoryData['description']}

+ {/if} + + {foreach $categoryData['fields'] AS $key => $field} +
+ {if $field['title']} + + {/if} +
+ + {if $field['type'] == 'select'} + + {elseif $field['type'] == 'bool'} + + + + + + + {elseif $field['type'] == 'radio'} + {foreach $field['choices'] AS $k => $v} + +
+ {/foreach} +
+ {*{elseif $field['type'] == 'checkbox'} + {foreach $field['choices'] AS $k => $v} + +
+ {/foreach} +
+ *} + {elseif $field['type'] == 'text'} + + {if isset($field['next'])} {$field['next']|strval}{/if} + {elseif $field['type'] == 'password'} + + {if isset($field['next'])} {$field['next']|strval}{/if} + {elseif $field['type'] == 'textarea'} + + {elseif $field['type'] == 'file'} + {if isset($field['thumb']) && $field['thumb'] && $field['thumb']['pos'] == 'before'} + {$field['title']}
+ {/if} + + {* {elseif $field['type'] == 'image'} + + + $i = 0; + foreach ($field['list'] as $theme) + { + '; + if (isset($field['max']) && ($i +1 ) % $field['max'] == 0) + echo ''; + $i++; + } + echo ''; + echo '
+ '; + echo ''; + echo '
'; + echo ''; + echo '
'; + *} + {elseif $field['type'] == 'textLang'} + {foreach $field['languages'] AS $id_lang => $value} +
+ +
+ {/foreach} + {$field['flags']} + {elseif $field['type'] == 'textareaLang'} + {foreach $field['languages'] AS $id_lang => $value} +
'; + +
+ {/foreach} + {$field['flags']} +
+ + + {/if} + {if isset($field['method'])}$field['method']{/if} + + {if ($field['multishop_default'])} +
+ +
+ {/if} + {if isset($field['desc'])}

{$field['desc']}

{/if} + {if $field['is_invisible']}

{l s='You can\'t change the value of this configuration field in this shop context'}

{/if} +
+ {/foreach} + +
+ +
+ {if $field['required']} +
* {l s='Required field'}
+ {/if} +

+ {if isset($categoryData['bottom'])}{$categoryData['bottom']}{/if} +{/foreach} +
diff --git a/classes/AdminController.php b/classes/AdminController.php index 30e3de046..34c7353d7 100644 --- a/classes/AdminController.php +++ b/classes/AdminController.php @@ -76,6 +76,8 @@ class AdminControllerCore extends Controller protected $list_display; + protected $form_list; + protected $_listSkipDelete = array(); protected $shopLink; @@ -160,6 +162,7 @@ class AdminControllerCore extends Controller protected $edit; protected $delete; protected $duplicate; + protected $deleted; /** * @var bool is a list filter set */ @@ -943,7 +946,7 @@ class AdminControllerCore extends Controller // Check if form template has been overriden if (file_exists($this->context->smarty->template_dir.'/'.$this->tpl_folder.'form.tpl')) $helper->tpl = $this->tpl_folder.'form.tpl'; - HelperForm::$currentIndex = self::$currentIndex; + $helper->currentIndex = self::$currentIndex; $helper->token = $this->token; $helper->table = $this->table; $helper->id = $obj->id; @@ -993,7 +996,7 @@ class AdminControllerCore extends Controller $helper->duplicate = $this->duplicate;*/ $helper->bulk_actions = $this->bulk_actions; - HelperList::$currentIndex = self::$currentIndex; + $helper->currentIndex = self::$currentIndex; $helper->className = $this->className; $helper->table = $this->table; $helper->shopLink = $this->shopLink; @@ -1006,6 +1009,11 @@ class AdminControllerCore extends Controller $this->content .= $helper->generateList($this->_list, $this->fieldsDisplay); } + else if ($this->display == 'options') + { + $helper = new HelperOptions(); + $this->content .= $helper->generateOptions(); + } } /** @@ -1124,6 +1132,8 @@ class AdminControllerCore extends Controller //define('_PS_BASE_URL_', Tools::getShopDomain(true)); //define('_PS_BASE_URL_SSL_', Tools::getShopDomainSsl(true)); + $this->context->currency = new Currency(Configuration::get('PS_CURRENCY_DEFAULT')); + // Change shop context ? if (Shop::isMultiShopActivated() && Tools::getValue('setShopContext') !== false) { @@ -1613,6 +1623,135 @@ class AdminControllerCore extends Controller VALUES('.(int)$asso['id_object'].', '.(int)$asso['id_'.$type].')'); } + protected function validateField($value, $field) + { + if (isset($field['validation'])) + { + if ((!isset($field['empty']) || !$field['empty'] || (isset($field['empty']) && $field['empty'] && $value)) && method_exists('Validate', $field['validation'])) + { + if (!Validate::$field['validation']($value)) + { + $this->_errors[] = Tools::displayError($field['title'].' : Incorrect value'); + return false; + } + } + } + + return true; + } + + /** + * Can be overriden + */ + public function beforeUpdateOptions() + { + } + + /** + * Update options and preferences + * + * @param string $token + */ + protected function updateOptions($token) + { + if ($this->tabAccess['edit'] === '1') + { + $this->beforeUpdateOptions(); + + $languages = Language::getLanguages(false); + + foreach ($this->form_list as $option_list) + { + foreach ($option_list as $category => $categoryData) + { + $fields = $categoryData['fields']; + + /* Check required fields */ + foreach ($fields as $field => $values) + if (isset($values['required']) && $values['required'] && !isset($_POST['configUseDefault'][$field])) + if (isset($values['type']) && $values['type'] == 'textLang') + { + foreach ($languages as $language) + if (($value = Tools::getValue($field.'_'.$language['id_lang'])) == false && (string)$value != '0') + $this->_errors[] = Tools::displayError('field').' '.$values['title'].' '.Tools::displayError('is required.'); + } + elseif (($value = Tools::getValue($field)) == false && (string)$value != '0') + $this->_errors[] = Tools::displayError('field').' '.$values['title'].' '.Tools::displayError('is required.'); + + /* Check fields validity */ + foreach ($fields as $field => $values) + if (isset($values['type']) && $values['type'] == 'textLang') + { + foreach ($languages as $language) + if (Tools::getValue($field.'_'.$language['id_lang']) && isset($values['validation'])) + if (!Validate::$values['validation'](Tools::getValue($field.'_'.$language['id_lang']))) + $this->_errors[] = Tools::displayError('field').' '.$values['title'].' '.Tools::displayError('is invalid.'); + } + elseif (Tools::getValue($field) && isset($values['validation'])) + if (!Validate::$values['validation'](Tools::getValue($field))) + $this->_errors[] = Tools::displayError('field').' '.$values['title'].' '.Tools::displayError('is invalid.'); + + /* Default value if null */ + foreach ($fields as $field => $values) + if (!Tools::getValue($field) && isset($values['default'])) + $_POST[$field] = $values['default']; + + if (1||!count($this->_errors)) + { + foreach ($fields as $key => $options) + { + if (isset($options['visibility']) && $options['visibility'] > Context::getContext()->shop->getContextType()) + continue; + + if (Shop::isMultiShopActivated() && isset($_POST['configUseDefault'][$key])) + { + Configuration::deleteFromContext($key); + continue; + } + + // check if a method updateOptionFieldName is available + $method_name = 'updateOption'.Tools::toCamelCase($key, true); + if (method_exists($this, $method_name)) + $this->$method_name(Tools::getValue($key)); + else if (isset($options['type']) && in_array($options['type'], array('textLang', 'textareaLang'))) + { + $list = array(); + foreach ($languages as $language) + { + $val = (isset($options['cast']) ? $options['cast'](Tools::getValue($key.'_'.$language['id_lang'])) : Tools::getValue($key.'_'.$language['id_lang'])); + if ($this->validateField($val, $options)) + { + if (Validate::isCleanHtml($val)) + $list[$language['id_lang']] = $val; + else + $this->_errors[] = Tools::displayError('Can not add configuration '.$key.' for lang '.Language::getIsoById((int)$language['id_lang'])); + } + } + Configuration::updateValue($key, $list); + } + else + { + $val = (isset($options['cast']) ? $options['cast'](Tools::getValue($key)) : Tools::getValue($key)); + if ($this->validateField($val, $options)) + { + if (Validate::isCleanHtml($val)) + Configuration::updateValue($key, $val); + else + $this->_errors[] = Tools::displayError('Can not add configuration '.$key); + } + } + } + } + } + } + + if (count($this->_errors) <= 0) + Tools::redirectAdmin(self::$currentIndex.'&conf=6&token='.$token); + } + else + $this->_errors[] = Tools::displayError('You do not have permission to edit here.'); + } + /** * Overload this method for custom checking * diff --git a/classes/Helper.php b/classes/Helper.php index 943292544..e2d90deb5 100755 --- a/classes/Helper.php +++ b/classes/Helper.php @@ -32,6 +32,10 @@ class HelperCore { + public $currentIndex; + public $table; + public $token; + public $context; public function __construct() { @@ -202,5 +206,34 @@ class HelperCore return rtrim($html, ' '); } + /** + * use translations files to replace english expression. + * + * @param mixed $string term or expression in english + * @param string $class + * @param boolan $addslashes if set to true, the return value will pass through addslashes(). Otherwise, stripslashes(). + * @param boolean $htmlentities if set to true(default), the return value will pass through htmlentities($string, ENT_QUOTES, 'utf-8') + * @return string the translation if available, or the english default text. + */ + protected function l($string, $class = 'AdminTab', $addslashes = FALSE, $htmlentities = TRUE) + { + // if the class is extended by a module, use modules/[module_name]/xx.php lang file + $currentClass = get_class($this); + if(Module::getModuleNameFromClass($currentClass)) + { + $string = str_replace('\'', '\\\'', $string); + return Module::findTranslation(Module::$classInModule[$currentClass], $string, $currentClass); + } + global $_LANGADM; + + if ($class == __CLASS__) + $class = 'AdminTab'; + + $key = md5(str_replace('\'', '\\\'', $string)); + $str = (key_exists(get_class($this).$key, $_LANGADM)) ? $_LANGADM[get_class($this).$key] : ((key_exists($class.$key, $_LANGADM)) ? $_LANGADM[$class.$key] : $string); + $str = $htmlentities ? htmlentities($str, ENT_QUOTES, 'utf-8') : $str; + return str_replace('"', '"', ($addslashes ? addslashes($str) : stripslashes($str))); + } + } diff --git a/classes/HelperForm.php b/classes/HelperForm.php index 1fc21d019..d7e8c9438 100644 --- a/classes/HelperForm.php +++ b/classes/HelperForm.php @@ -49,8 +49,6 @@ class HelperFormCore extends Helper public $default_form_language = null; public $allow_employee_form_lang = null; - public static $currentIndex; - public $tpl = 'form.tpl'; public function generateForm($fields_form) @@ -64,7 +62,7 @@ class HelperFormCore extends Helper { $this->context->smarty->assign(array( 'firstCall' => $this->first_call, - 'current' => self::$currentIndex, + 'current' => $this->currentIndex, 'token' => $this->token, 'table' => $this->table, 'languages' => $this->languages, @@ -85,10 +83,9 @@ class HelperFormCore extends Helper public function getFieldsRequired() { - if (isset($this->fields_form['input'])) - foreach ($this->fields_form['input'] as $input) - if (array_key_exists('required', $input) && $input['required']) - return true; + foreach ($this->fields_form['input'] as $input) + if (array_key_exists('required', $input) && $input['required']) + return true; return false; } diff --git a/classes/HelperList.php b/classes/HelperList.php index 0851ac15f..af6a8a7cb 100644 --- a/classes/HelperList.php +++ b/classes/HelperList.php @@ -51,16 +51,10 @@ class HelperListCore extends Helper /** @var string Order way (ASC, DESC) determined by arrows in list header */ protected $_orderWay; - protected $context; - public $identifier; protected $deleted = 0; - public static $currentIndex; - - public $token; - public static $cache_lang = array(); protected $is_cms = false; @@ -145,7 +139,7 @@ class HelperListCore extends Helper */ protected function _displayEnableLink($token, $id, $value, $active, $id_category = null, $id_product = null) { - return 'currentIndex.'&'.$this->identifier.'='.$id.'&'.$active.$this->table. ((int)$id_category && (int)$id_product ? '&id_category='.$id_category : '').'&token='.($token != null ? $token : $this->token).'"> '.($value ? $this->l('Enabled') : $this->l('Disabled')).''; @@ -216,10 +210,10 @@ class HelperListCore extends Helper { $this->_list[$index][$key] = array( 'position' => $tr[$key], - 'position_url_down' => self::$currentIndex. + 'position_url_down' => $this->currentIndex. '&'.$key_to_get.'='.(int)$id_category.'&'.$this->identifiersDnd[$this->identifier].'='.$id. '&way=1&position='.(int)($tr['position'] + 1).'&token='.$this->token, - 'position_url_up' => self::$currentIndex. + 'position_url_up' => $this->currentIndex. '&'.$key_to_get.'='.(int)$id_category.'&'.$this->identifiersDnd[$this->identifier].'='.$id. '&way=0&position='.(int)($tr['position'] - 1).'&token='.$this->token ); @@ -289,7 +283,7 @@ class HelperListCore extends Helper 'list' => $this->_list, 'actions' => $this->actions, 'no_link' => $this->noLink, - 'current_index' => self::$currentIndex, + 'current_index' => $this->currentIndex, 'view' => in_array('view', $this->actions), 'edit' => in_array('edit', $this->actions), 'has_actions' => (bool)count($this->actions), @@ -305,10 +299,10 @@ class HelperListCore extends Helper if (!array_key_exists('Copy images too?', self::$cache_lang)) self::$cache_lang['Copy images too?'] = $this->l('Copy images too?', __CLASS__, true, false); - $duplicate = self::$currentIndex.'&'.$this->identifier.'='.$id.'&duplicate'.$this->table; + $duplicate = $this->currentIndex.'&'.$this->identifier.'='.$id.'&duplicate'.$this->table; $this->context->smarty->assign(array( - 'href' => self::$currentIndex.'&'.$this->identifier.'='.$id.'&view'.$this->table.'&token='.($token != null ? $token : $this->token), + 'href' => $this->currentIndex.'&'.$this->identifier.'='.$id.'&view'.$this->table.'&token='.($token != null ? $token : $this->token), 'action' => self::$cache_lang['Duplicate'], 'confirm' => self::$cache_lang['Copy images too?'], 'location_ok' => $duplicate.'&token='.($token != null ? $token : $this->token), @@ -325,7 +319,7 @@ class HelperListCore extends Helper self::$cache_lang['View'] = $this->l('View'); $this->context->smarty->assign(array( - 'href' => self::$currentIndex.'&'.$this->identifier.'='.$id.'&view'.$this->table.'&token='.($token != null ? $token : $this->token), + 'href' => $this->currentIndex.'&'.$this->identifier.'='.$id.'&view'.$this->table.'&token='.($token != null ? $token : $this->token), 'action' => self::$cache_lang['View'], )); @@ -339,7 +333,7 @@ class HelperListCore extends Helper self::$cache_lang['Edit'] = $this->l('Edit'); $this->context->smarty->assign(array( - 'href' => self::$currentIndex.'&'.$this->identifier.'='.$id.'&update'.$this->table.'&token='.($token != null ? $token : $this->token), + 'href' => $this->currentIndex.'&'.$this->identifier.'='.$id.'&update'.$this->table.'&token='.($token != null ? $token : $this->token), 'action' => self::$cache_lang['Edit'], )); @@ -356,7 +350,7 @@ class HelperListCore extends Helper self::$cache_lang['DeleteItem'] = $this->l('Delete item #', __CLASS__, true, false); $this->context->smarty->assign(array( - 'href' => self::$currentIndex.'&'.$this->identifier.'='.$id.'&delete'.$this->table.'&token='.($token != null ? $token : $this->token), + 'href' => $this->currentIndex.'&'.$this->identifier.'='.$id.'&delete'.$this->table.'&token='.($token != null ? $token : $this->token), 'confirm' => self::$cache_lang['DeleteItem'].$id.' ?'.(!is_null($this->specificConfirmDelete) ? '\r'.$this->specificConfirmDelete : ''), 'action' => self::$cache_lang['Delete'], )); @@ -384,7 +378,7 @@ class HelperListCore extends Helper if (!$total_pages) $total_pages = 1; - $action = self::$currentIndex + $action = $this->currentIndex .(Tools::getIsset($this->identifier) ? '&'.$this->identifier.'='.(int)Tools::getValue($this->identifier) : '') @@ -419,7 +413,7 @@ class HelperListCore extends Helper // Cleaning links if (Tools::getValue($this->table.'Orderby') && Tools::getValue($this->table.'Orderway')) - self::$currentIndex = preg_replace('/&'.$this->table.'Orderby=([a-z _]*)&'.$this->table.'Orderway=([a-z]*)/i', '', self::$currentIndex); + $this->currentIndex = preg_replace('/&'.$this->table.'Orderby=([a-z _]*)&'.$this->table.'Orderway=([a-z]*)/i', '', $this->currentIndex); if (array_key_exists($this->identifier, $this->identifiersDnd) && (int)Tools::getValue($this->identifiersDnd[$this->identifier], 1)) $table_id = substr($this->identifier, 3, strlen($this->identifier)); @@ -468,7 +462,7 @@ class HelperListCore extends Helper $this->context->smarty->assign(array( 'table' => $this->table, - 'currentIndex' => self::$currentIndex, + 'currentIndex' => $this->currentIndex, 'action' => $action, 'page' => $page, 'total_pages' => $total_pages, @@ -505,35 +499,4 @@ class HelperListCore extends Helper )); return $this->context->smarty->fetch(_PS_ADMIN_DIR_.'/themes/template/list_footer.tpl'); } - - /** - * use translations files to replace english expression. - * - * @param mixed $string term or expression in english - * @param string $class - * @param boolan $addslashes if set to true, the return value will pass through addslashes(). Otherwise, stripslashes(). - * @param boolean $htmlentities if set to true(default), the return value will pass through htmlentities($string, ENT_QUOTES, 'utf-8') - * @return string the translation if available, or the english default text. - */ - protected function l($string, $class = 'AdminTab', $addslashes = false, $htmlentities = true) - { - // if the class is extended by a module, use modules/[module_name]/xx.php lang file - $current_class = get_class($this); - if (Module::getModuleNameFromClass($current_class)) - { - $string = str_replace('\'', '\\\'', $string); - return Module::findTranslation(Module::$classInModule[$current_class], $string, $current_class); - } - global $_LANGADM; - - if ($class == __CLASS__) - $class = 'AdminTab'; - - $key = md5(str_replace('\'', '\\\'', $string)); - $str = key_exists(get_class($this).$key, $_LANGADM) - ? $_LANGADM[get_class($this).$key] - : ((key_exists($class.$key, $_LANGADM)) ? $_LANGADM[$class.$key] : $string); - $str = $htmlentities ? htmlentities($str, ENT_QUOTES, 'utf-8') : $str; - return str_replace('"', '"', ($addslashes ? addslashes($str) : stripslashes($str))); - } } \ No newline at end of file diff --git a/classes/HelperOptions.php b/classes/HelperOptions.php new file mode 100644 index 000000000..8a87e2b35 --- /dev/null +++ b/classes/HelperOptions.php @@ -0,0 +1,193 @@ + +* @copyright 2007-2011 PrestaShop SA +* @version Release: $Revision$ +* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) +* International Registered Trademark & Property of PrestaShop SA +*/ + +/** + * Use this helper to generate preferences forms, with values stored in the configuration table + */ +class HelperOptionsCore extends Helper +{ + public $first_call = true; + + /** + * @var array of forms fields + * Usage : + * + */ + protected $fields_form = array(); + + public $fields_value = array(); + + public $tpl = 'options.tpl'; + + /** + * Generate a form for options + * @param array options + * @return string html + */ + public function generateOptions($option_list) + { + $tab = Tab::getTab($this->context->language->id, $this->id); + + foreach ($option_list as $category => $category_data) + { + $required = false; + foreach ($category_data['fields'] as $key => $field) + { + // Field value + $option_list[$category]['fields'][$key]['value'] = $this->getOptionValue($key, $field); + + // Check if var is invisible (can't edit it in current shop context), or disable (use default value for multishop) + $isDisabled = $isInvisible = false; + if (Shop::isMultiShopActivated()) + { + if (isset($field['visibility']) && $field['visibility'] > $this->context->shop->getContextType()) + { + $isDisabled = true; + $isInvisible = true; + } + else if (Context::shop() != Shop::CONTEXT_ALL && !Configuration::isOverridenByCurrentContext($key)) + $isDisabled = true; + } + $option_list[$category]['fields'][$key]['is_disabled'] = $isDisabled; + $option_list[$category]['fields'][$key]['is_invisible'] = $isInvisible; + + // Cast options values if specified + if ($field['type'] == 'select' && isset($field['cast'])) + foreach ($field['list'] as $option_key => $option) + $option_list[$category]['fields'][$key]['list'][$option_key][$field['identifier']] = $field['cast']($option[$field['identifier']]); + + // Fill values for all languages for all lang fields + if (substr($field['type'], -4) == 'Lang') + { + if (!isset($languages)) + $languages = Language::getLanguages(false); + + foreach ($languages as $language) + { + if ($field['type'] == 'textLang') + $value = Tools::safeOutput(Tools::getValue($key.'_'.$language['id_lang'], Configuration::get($key, $language['id_lang']))); + elseif ($field['type'] == 'textareaLang') + $value = Configuration::get($key, $language['id_lang']); + $option_list[$category]['fields'][$key]['languages'][$language['id_lang']] = $value; + } + $option_list[$category]['fields'][$key]['flags'] = $this->displayFlags($languages, $this->context->language->id, $key, $key, true); + } + + // Multishop default value + $option_list[$category]['fields'][$key]['multishop_default'] = (Shop::isMultiShopActivated() && Context::shop() != Shop::CONTEXT_ALL && !$isInvisible); + } + } + $this->context->smarty->assign(array( + 'img_legend' => (!empty($tab['module']) && file_exists($_SERVER['DOCUMENT_ROOT']._MODULE_DIR_.$tab['module'].'/'.$tab['class_name'].'.gif') ? _MODULE_DIR_.$tab['module'].'/' : '../img/t/').$tab['class_name'].'.gif', + 'current' => $this->currentIndex, + 'optionsList' => $option_list, + 'current_id_lang' => $this->context->language->id, + )); + return $this->context->smarty->fetch(_PS_ADMIN_DIR_.'/themes/template/'.$this->tpl); + } + + /** + * Type = image + * @ TODO + */ + public function displayOptionTypeImage($key, $field, $value) + { + echo ''; + echo ''; + + $i = 0; + foreach ($field['list'] as $theme) + { + echo ''; + if (isset($field['max']) && ($i +1 ) % $field['max'] == 0) + echo ''; + $i++; + } + echo ''; + echo '
'; + echo ''; + echo ''; + echo '
'; + echo ''; + echo '
'; + } + + + /** + * Type = selectLang + * @ TODO + */ + public function displayOptionTypeSelectLang($key, $field, $value) + { + $languages = Language::getLanguages(false); + foreach ($languages as $language) + { + echo '
'; + echo ''; + echo '
'; + } + $this->displayFlags($languages, $this->context->language->id, $key, $key); + } + + /** + * Type = price + * @ TODO + */ + public function displayOptionTypePrice($key, $field, $value) + { + echo $this->context->currency->getSign('left'); + $this->displayOptionTypeText($key, $field, $value); + echo $this->context->currency->getSign('right').' '.$this->l('(tax excl.)'); + } + + /** + * Type = disabled + * + * @ TODO + */ + public function displayOptionTypeDisabled($key, $field, $value) + { + echo $field['disabled']; + } + + public function getOptionValue($key, $field) + { + $value = Tools::getValue($key, Configuration::get($key)); + if (!Validate::isCleanHtml($value)) + $value = Configuration::get($key); + + if (isset($field['defaultValue']) && !$value) + $value = $field['defaultValue']; + return $value; + } + +} \ No newline at end of file diff --git a/controllers/admin/AdminImagesController.php b/controllers/admin/AdminImagesController.php new file mode 100644 index 000000000..c5719bbca --- /dev/null +++ b/controllers/admin/AdminImagesController.php @@ -0,0 +1,567 @@ + +* @copyright 2007-2011 PrestaShop SA +* @version Release: $Revision$ +* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) +* International Registered Trademark & Property of PrestaShop SA +*/ + +class AdminImagesController extends AdminController +{ + private $start_time = 0; + private $max_execution_time = 7200; + + public function __construct() + { + $this->table = 'image_type'; + $this->className = 'ImageType'; + $this->lang = false; + $this->edit = true; + $this->delete = true; + + $this->fieldsDisplay = array( + 'id_image_type' => array('title' => $this->l('ID'), 'align' => 'center', 'width' => 25), + 'name' => array('title' => $this->l('Name'), 'width' => 140, 'size' => 16), + 'width' => array('title' => $this->l('Width'), 'align' => 'right', 'suffix' => ' px', 'width' => 50, 'size' => 5), + 'height' => array('title' => $this->l('Height'), 'align' => 'right', 'suffix' => ' px', 'width' => 50, 'size' => 5) + ); + + $this->form_list = array( + 'options_image_pref' => array( + 'images' => array( + 'title' => $this->l('Images'), + 'icon' => 'tab-orders', + 'class' => 'width4', + 'top' => '', + 'bottom' => '', + 'description' => $this->l('JPEG images have a small file size and standard quality. PNG images have a bigger file size, a higher quality and support transparency. Note that in all cases the image files will have the .jpg extension.').' +

'.$this->l('WARNING: This feature may not be compatible with your theme or with some modules. In particular, PNG mode is not compatible with the Watermark module. If you encounter any issue, turn it off by selecting "Use JPEG".'), + 'fields' => array( + 'PS_IMAGE_QUALITY' => array('title' => $this->l('Image quality'), 'show' => true, 'required' => true, 'type' => 'radio', 'choices' => array('jpg' => $this->l('Use JPEG'), 'png' => $this->l('Use PNG only if the base image is in PNG format'), 'png_all' => $this->l('Use PNG for all images'))), + 'PS_JPEG_QUALITY' => array('title' => $this->l('JPEG quality'), 'desc' => $this->l('Ranges from 0 (worst quality, smallest file) to 100 (best quality, biggest file)'), 'validation' => 'isUnsignedId', 'required' => true, 'cast' => 'intval', 'type' => 'text'), + 'PS_PNG_QUALITY' => array('title' => $this->l('PNG quality'), 'desc' => $this->l('Ranges from 9 (worst quality, smallest file) to 0 (best quality, biggest file)'), 'validation' => 'isUnsignedId', 'required' => true, 'cast' => 'intval', 'type' => 'text'), + ), + ), + ) + ); + + parent::__construct(); + } + + public function postProcess() + { + if (Tools::getValue('submitRegenerate'.$this->table)) + { + if ($this->tabAccess['edit'] === '1') + { + if ($this->_regenerateThumbnails(Tools::getValue('type'), Tools::getValue('erase'))) + Tools::redirectAdmin(self::$currentIndex.'&conf=9'.'&token='.$this->token); + } + else + $this->_errors[] = Tools::displayError('You do not have permission to edit here.'); + }elseif (Tools::getValue('submitMoveImages'.$this->table)) + { + if ($this->tabAccess['edit'] === '1') + { + if($this->_moveImagesToNewFileSystem()) + Tools::redirectAdmin(self::$currentIndex.'&conf=25'.'&token='.$this->token); + } + else + $this->_errors[] = Tools::displayError('You do not have permission to edit here.'); + }elseif (Tools::getValue('submitImagePreferences')) + { + if ($this->tabAccess['edit'] === '1') + { + if ((int)Tools::getValue('PS_JPEG_QUALITY') < 0 + || (int)Tools::getValue('PS_JPEG_QUALITY') > 100) + $this->_errors[] = Tools::displayError('Incorrect value for JPEG image quality.'); + elseif ((int)Tools::getValue('PS_PNG_QUALITY') < 0 + || (int)Tools::getValue('PS_PNG_QUALITY') > 9) + $this->_errors[] = Tools::displayError('Incorrect value for PNG image quality.'); + elseif (!Configuration::updateValue('PS_IMAGE_QUALITY', Tools::getValue('PS_IMAGE_QUALITY')) + || !Configuration::updateValue('PS_JPEG_QUALITY', Tools::getValue('PS_JPEG_QUALITY')) + || !Configuration::updateValue('PS_PNG_QUALITY', Tools::getValue('PS_PNG_QUALITY'))) + $this->_errors[] = Tools::displayError('Unknown error.'); + else + Tools::redirectAdmin(self::$currentIndex.'&token='.Tools::getValue('token').'&conf=4'); + } + else + $this->_errors[] = Tools::displayError('You do not have permission to edit here.'); + } + else + parent::postProcess(); + } + + protected function _childValidation() + { + if (!Tools::getValue('id_image_type') AND Validate::isImageTypeName($typeName = Tools::getValue('name')) AND ImageType::typeAlreadyExists($typeName)) + $this->_errors[] = Tools::displayError('This name already exists.'); + } + + public function displayForm($isMainTab = true) + { + parent::displayForm(); + + if (!($obj = $this->loadObject(true))) + return; + + echo $obj->id ? $this->displayWarning($this->l('After modification, do not forget to regenerate thumbnails')) : ''; + + echo ' +
+ '.($obj->id ? '' : '').' +
+ '.$this->l('Images').'
+ +
+ * +

'.$this->l('Letters only (e.g., small, medium, large, extra-large)').'

+
+ +
+ * +

'.$this->l('Maximum image width in pixels').'

+
+ +
+ * +

'.$this->l('Maximum image height in pixels').'

+
+ +
+ getFieldValue($obj, 'products') ? 'checked="checked" ' : '').'/> + + getFieldValue($obj, 'products') ? 'checked="checked" ' : '').'/> + +

'.$this->l('This type will be applied to product images').'

+
+ +
+ getFieldValue($obj, 'categories') ? 'checked="checked" ' : '').'/> + + getFieldValue($obj, 'categories') ? 'checked="checked" ' : '').'/> + +

'.$this->l('This type will be applied to category images').'

+
+ +
+ getFieldValue($obj, 'manufacturers') ? 'checked="checked" ' : '').'/> + + getFieldValue($obj, 'manufacturers') ? 'checked="checked" ' : '').'/> + +

'.$this->l('This type will be applied to manufacturer images').'

+
+ +
+ getFieldValue($obj, 'suppliers') ? 'checked="checked" ' : '').'/> + + getFieldValue($obj, 'suppliers') ? 'checked="checked" ' : '').'/> + +

'.$this->l('This type will be applied to suppliers images').'

+
+ +
+ getFieldValue($obj, 'scenes') ? 'checked="checked" ' : '').'/> + + getFieldValue($obj, 'scenes') ? 'checked="checked" ' : '').'/> + +

'.$this->l('This type will be applied to scenes images').'

+
+ +
+ getFieldValue($obj, 'stores') ? 'checked="checked" ' : '').'/> + + getFieldValue($obj, 'stores') ? 'checked="checked" ' : '').'/> + +

'.$this->l('This type will be applied to stores images').'

+
+
+ +
+
* '.$this->l('Required field').'
+
+
'; + } + + /** + * Display form for thumbnails regeneration + */ + public function displayRegenerate() + { + $types = array( + 'categories' => $this->l('Categories'), + 'manufacturers' => $this->l('Manufacturers'), + 'suppliers' => $this->l('Suppliers'), + 'scenes' => $this->l('Scenes'), + 'products' => $this->l('Products'), + 'stores' => $this->l('Stores') + ); + $this->content .= ' +

'.$this->l('Regenerate thumbnails').'

+ '.$this->l('Regenerates thumbnails for all existing product images').'.

'; + $this->displayWarning($this->l('Please be patient, as this can take several minutes').'
'.$this->l('Be careful! Manually generated thumbnails will be erased by automatically generated thumbnails.')); + $this->content .= '
+ +
+ +
+ '.$this->l('Regenerate thumbnails').'
+ +
+ +
'; + + foreach ($types AS $k => $type) + { + $formats = ImageType::getImagesTypes($k); + $this->content .= ' + + '; + } + $this->content .= ' + + +
+ +

'.$this->l('Uncheck this checkbox only if your server timed out and you need to resume the regeneration.').'

+
+
+
+
+
'; + } + + /** + * Delete resized image then regenerate new one with updated settings + */ + private function _deleteOldImages($dir, $type, $product = false) + { + if (!is_dir($dir)) + return false; + $toDel = scandir($dir); + foreach ($toDel AS $d) + foreach ($type AS $imageType) + if (preg_match('/^[0-9]+\-'.($product ? '[0-9]+\-' : '').$imageType['name'].'\.jpg$/', $d) OR preg_match('/^([[:lower:]]{2})\-default\-(.*)\.jpg$/', $d)) + if (file_exists($dir.$d)) + unlink($dir.$d); + + // delete product images using new filesystem. + if ($product) + { + $productsImages = Image::getAllImages(); + foreach ($productsImages AS $k => $image) + { + $imageObj = new Image($image['id_image']); + $imageObj->id_product = $image['id_product']; + if (file_exists($dir.$imageObj->getImgFolder())) + { + $toDel = scandir($dir.$imageObj->getImgFolder()); + foreach ($toDel AS $d) + foreach ($type AS $imageType) + if (preg_match('/^[0-9]+\-'.$imageType['name'].'\.jpg$/', $d)) + if (file_exists($dir.$imageObj->getImgFolder().$d)) + unlink($dir.$imageObj->getImgFolder().$d); + } + } + } + } + + // Regenerate images + private function _regenerateNewImages($dir, $type, $productsImages = false) + { + if (!is_dir($dir)) + return false; + $errors = false; + $toRegen = scandir($dir); + if (!$productsImages) + { + foreach ($toRegen AS $image) + if (preg_match('/^[0-9]*\.jpg$/', $image)) + foreach ($type AS $k => $imageType) + { + // Customizable writing dir + $newDir = $dir; + if ($imageType['name'] == 'thumb_scene') + $newDir .= 'thumbs/'; + if (!file_exists($newDir)) + continue; + if (!file_exists($newDir.substr($image, 0, -4).'-'.stripslashes($imageType['name']).'.jpg')) + if (!imageResize($dir.$image, $newDir.substr($image, 0, -4).'-'.stripslashes($imageType['name']).'.jpg', (int)($imageType['width']), (int)($imageType['height']))) + $errors = true; + if (time() - $this->start_time > $this->max_execution_time - 4) // stop 4 seconds before the tiemout, just enough time to process the end of the page on a slow server + return 'timeout'; + } + } + else + { + $productsImages = Image::getAllImages(); + foreach ($productsImages AS $k => $image) + { + $imageObj = new Image($image['id_image']); + if (file_exists($dir.$imageObj->getExistingImgPath().'.jpg')) + foreach ($type AS $k => $imageType) + { + if (!file_exists($dir.$imageObj->getExistingImgPath().'-'.stripslashes($imageType['name']).'.jpg')) + if (!imageResize($dir.$imageObj->getExistingImgPath().'.jpg', $dir.$imageObj->getExistingImgPath().'-'.stripslashes($imageType['name']).'.jpg', (int)($imageType['width']), (int)($imageType['height']))) + $errors = true; + if (time() - $this->start_time > $this->max_execution_time - 4) // stop 4 seconds before the tiemout, just enough time to process the end of the page on a slow server + return 'timeout'; + } + } + } + return $errors; + } + + // Regenerate no-pictures images + private function _regenerateNoPictureImages($dir, $type, $languages) + { + $errors = false; + foreach ($type AS $k => $imageType) + foreach ($languages AS $language) + { + $file = $dir.$language['iso_code'].'.jpg'; + if (!file_exists($file)) + $file = _PS_PROD_IMG_DIR_.Language::getIsoById((int)(Configuration::get('PS_LANG_DEFAULT'))).'.jpg'; + if (!file_exists($dir.$language['iso_code'].'-default-'.stripslashes($imageType['name']).'.jpg')) + if (!imageResize($file, $dir.$language['iso_code'].'-default-'.stripslashes($imageType['name']).'.jpg', (int)($imageType['width']), (int)($imageType['height']))) + $errors = true; + } + return $errors; + } + + // Hook watermark optimization + private function _regenerateWatermark($dir) + { + $result = Db::getInstance()->executeS(' + SELECT m.`name` FROM `'._DB_PREFIX_.'module` m + LEFT JOIN `'._DB_PREFIX_.'hook_module` hm ON hm.`id_module` = m.`id_module` + LEFT JOIN `'._DB_PREFIX_.'hook` h ON hm.`id_hook` = h.`id_hook` + WHERE h.`name` = \'watermark\' AND m.`active` = 1'); + + if ($result AND sizeof($result)) + { + $productsImages = Image::getAllImages(); + foreach ($productsImages AS $k => $image) + { + $imageObj = new Image($image['id_image']); + if (file_exists($dir.$imageObj->getExistingImgPath().'.jpg')) + foreach ($result AS $k => $module) + { + if ($moduleInstance = Module::getInstanceByName($module['name']) AND is_callable(array($moduleInstance, 'hookwatermark'))) + call_user_func(array($moduleInstance, 'hookwatermark'), array('id_image' => $imageObj->id, 'id_product' => $imageObj->id_product)); + if (time() - $this->start_time > $this->max_execution_time - 4) // stop 4 seconds before the tiemout, just enough time to process the end of the page on a slow server + return 'timeout'; + } + } + } + } + + private function _regenerateThumbnails($type = 'all', $deleteOldImages = false) + { + $this->start_time = time(); + ini_set('max_execution_time', $this->max_execution_time); // ini_set may be disabled, we need the real value + $this->max_execution_time = (int)ini_get('max_execution_time'); + $languages = Language::getLanguages(false); + + $process = + array( + array('type' => 'categories', 'dir' => _PS_CAT_IMG_DIR_), + array('type' => 'manufacturers', 'dir' => _PS_MANU_IMG_DIR_), + array('type' => 'suppliers', 'dir' => _PS_SUPP_IMG_DIR_), + array('type' => 'scenes', 'dir' => _PS_SCENE_IMG_DIR_), + array('type' => 'products', 'dir' => _PS_PROD_IMG_DIR_), + array('type' => 'stores', 'dir' => _PS_STORE_IMG_DIR_) + ); + + // Launching generation process + foreach ($process AS $k => $proc) + { + if ($type != 'all' && $type != $proc['type']) + continue ; + + // Getting format generation + $formats = ImageType::getImagesTypes($proc['type']); + if ($type != 'all') + { + $format = strval(Tools::getValue('format_'.$type)); + if ($format != 'all') + foreach ($formats AS $k => $form) + if ($form['id_image_type'] != $format) + unset($formats[$k]); + } + + if ($deleteOldImages) + $this->_deleteOldImages($proc['dir'], $formats, ($proc['type'] == 'products' ? true : false)); + if (($return = $this->_regenerateNewImages($proc['dir'], $formats, ($proc['type'] == 'products' ? true : false))) === true) + $this->_errors[] = Tools::displayError('Cannot write ').$proc['type'].Tools::displayError(' images. Please check the folder\'s writing permissions.'); + elseif ($return == 'timeout') + $this->_errors[] = Tools::displayError('Only part of the images have been regenerated, server timed out before finishing.'); + else + { + if ($proc['type'] == 'products') + if ($this->_regenerateWatermark($proc['dir']) == 'timeout') + $this->_errors[] = Tools::displayError('Server timed out, the watermark may not have been applied on all your images.'); + if (!count($this->_errors)) + if ($this->_regenerateNoPictureImages($proc['dir'], $formats, $languages)) + $this->_errors[] = Tools::displayError('Cannot write no-picture image to').' ('.$proc['type'].') '.Tools::displayError('images folder. Please check the folder\'s writing permissions.'); + } + } + return (sizeof($this->_errors) > 0 ? false : true); + } + + /** + * Display the block for moving images + */ + public function displayMoveImages() + { + $safe_mode = ini_get('safe_mode'); + + $this->content .= ' +

'.$this->l('Move images').'

'. + $this->l('A new storage system for product images is now used by PrestaShop. It offers better performance if your shop has a very large number of products.').'
'. + '
'; + if (file_exists(_PS_PROD_IMG_DIR_.'duplicates/')) + { + $this->content .= '
'; + $this->displayWarning($this->l('Duplicate images were found when moving the product images. It is probably caused by unused demonstration images. Please make sure that the folder '). + _PS_PROD_IMG_DIR_.'duplicates/'. + $this->l(' only contains demonstration images then delete this folder.')); + $this->content .= '
'; + } + if($safe_mode) + $this->displayWarning($this->l('PrestaShop has detected that your server configuration is not compatible with the new storage system (directive "safe_mode" is activated). You should continue to use the actual system.')); + else + $this->content .= ' +
+
+ '.$this->l('Move images').'
'. + $this->l('You can choose to keep your images stored in the previous system - nothing wrong with that.').'
'. + $this->l('You can also decide to move your images to the new storage system: in this case, click on the "Move images" button below. Please be patient, as this can take several minutes.'). + '

 '. + $this->l('After moving all of your product images, for best performance go to the '). + ''.$this->l('product preferences tab').''. + $this->l(' and set "Use the legacy image filesystem" to NO.').' +
+
+
+
'; +} + + /** + * Move product images to the new filesystem + */ + private function _moveImagesToNewFileSystem() + { + if (!Image::testFileSystem()) + $this->_errors[] = Tools::displayError('Error: your server configuration is not compatible with the new image system. No images were moved'); + else + { + ini_set('max_execution_time', $this->max_execution_time); // ini_set may be disabled, we need the real value + $this->max_execution_time = (int)ini_get('max_execution_time'); + $result = Image::moveToNewFileSystem($this->max_execution_time); + if ($result === 'timeout') + $this->_errors[] = Tools::displayError('Not all images have been moved, server timed out before finishing. Click on \"Move images\" again to resume moving images'); + else if ($result === false) + $this->_errors[] = Tools::displayError('Error: some or all images could not be moved.'); + } + return (sizeof($this->_errors) > 0 ? false : true); + } + + /** + * Display the block for moving images + */ + public function displayImagePreferences() + { + $this->content .= '
+
+
+ '.$this->l('Images').''.' +

'.$this->l('JPEG images have a small file size and standard quality. PNG images have a bigger file size, a higher quality and support transparency. Note that in all cases the image files will have the .jpg extension.').' +

'.$this->l('WARNING: This feature may not be compatible with your theme or with some modules. In particular, PNG mode is not compatible with the Watermark module. If you encounter any issue, turn it off by selecting "Use JPEG".').'

+
+ +
+ + +
+ + +
+ + +
+
+ +
+ +

'.$this->l('Ranges from 0 (worst quality, smallest file) to 100 (best quality, biggest file)').'

+
+ +
+ +

'.$this->l('Ranges from 9 (worst quality, smallest file) to 0 (best quality, biggest file)').'

+
+
+ +
+
+
'; + } + + public function initContent() + { + if ($this->display != 'edit' && $this->display != 'add') + $this->display = 'list'; + + parent::initContent(); + + if ($this->display = 'list') + { + $this->context->smarty->assign('list', true); + + $helper = new HelperOptions(); + $helper->id = $this->id; + $helper->currentIndex = self::$currentIndex; + $this->content .= $helper->generateOptions($this->form_list['options_image_pref']); + + //$this->displayImagePreferences(); + $this->displayRegenerate(); + $this->displayMoveImages(); + } + } +}