[*] classes : new module architecture

This commit is contained in:
rMalie
2012-01-31 16:57:19 +00:00
parent 62f105ae6e
commit 4f7b3d4550
71 changed files with 815 additions and 622 deletions
+2 -2
View File
@@ -154,11 +154,11 @@ class Autoload
if (!$integrity_is_ok)
{
file_put_contents($filename, '<?php return array(); ?>');
throw new PrestashopException('Your file '.$filename.' is corrupted. Please remove this file, a new one will be regenerated automatically');
throw new PrestaShopException('Your file '.$filename.' is corrupted. Please remove this file, a new one will be regenerated automatically');
}
}
else
throw new PrestashopException($filename.' is not writable!');
throw new PrestaShopException($filename.' is not writable!');
$this->index = $classes;
}
+81 -34
View File
@@ -105,7 +105,7 @@ class CollectionCore implements Iterator, ArrayAccess, Countable
/**
* Join current entity to an associated entity
*
* @param $association Association name
* @param string $association Association name
* @param string $on
* @param int $type
* @return Collection
@@ -304,10 +304,6 @@ class CollectionCore implements Iterator, ArrayAccess, Countable
return $this;
$this->is_hydrated = true;
$alias = $this->generateAlias();
//$this->query->select($alias.'.*');
$this->query->from($this->definition['table'], $alias);
// If multilang, create association to lang table
if (!empty($this->definition['multilang']))
{
@@ -316,6 +312,39 @@ class CollectionCore implements Iterator, ArrayAccess, Countable
$this->where(self::LANG_ALIAS.'.id_lang', '=', $this->id_lang);
}
// Build query
$this->query->from($this->definition['table'], $this->generateAlias());
// Add list of fields to select
$association_list = array('');
$association_list = array_merge($association_list, array_keys($this->join_list));
$fields_tree = array();
$fields = array();
$fields_alias = array();
foreach ($association_list as $association)
{
$def = $this->getDefinition($association);
$is_lang = !empty($def['is_lang']);
foreach ($def['fields'] as $field => $info)
if ((!$is_lang && empty($info['lang'])) || ($is_lang && !empty($info['lang'])))
{
$fields_tree[$association][] = $field;
if (!isset($fields[$field]))
$fields[$field] = $association;
else
{
if (!isset($fields_alias[$field]))
$fields_alias[$field] = array($fields[$field]);
$fields_alias[$field][] = $association;
}
}
}
$this->query->select('*');
foreach ($fields_alias as $field => $associations)
foreach ($associations as $association)
$this->query->select($this->generateAlias($association).'.'.$field.' as \''.$association.'.'.$field.'\'');
// Add join clause
foreach ($this->join_list as $data)
{
@@ -340,8 +369,31 @@ class CollectionCore implements Iterator, ArrayAccess, Countable
if ($display_query)
echo $this->query.'<br />';
$this->results = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($this->query);
$this->results = ObjectModel::hydrateCollection($this->classname, $this->results, $this->id_lang);
// Get results and organize them
/*$results = array();
$query_ressource = Db::getInstance(_PS_USE_SQL_SLAVE_)->query($this->query);
while ($row = Db::getInstance(_PS_USE_SQL_SLAVE_)->nextRow($query_ressource))
{
$result = array();
foreach ($fields_tree as $association => $fields)
{
if ($association)
{
$ref = &$result;
foreach (explode('.', $association) as $asso)
{
if (!isset($ref['@associations'][$asso]))
$ref['@associations'][$asso] = array();
$ref = &$ref['@associations'][$asso];
$ref = &$ref[count($ref) - 1];
}
}
}
$results[] = $result;
}
d($results);*/
$this->results = ObjectModel::hydrateCollection($this->classname, Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($this->query), $this->id_lang);
return $this;
}
@@ -497,25 +549,23 @@ class CollectionCore implements Iterator, ArrayAccess, Countable
if (!isset($this->association_definition[$association]))
{
$definition = $this->definition;
// Get previous association definition
$split = explode('.', $association);
$is_lang = false;
for ($i = 0, $total_association = count($split); $i < $total_association; $i++)
$asso = array_pop($split);
$previous_association = implode('.', $split);
$definition = $this->getDefinition($previous_association);
// Check if association exists
if (!isset($definition['associations'][$asso]))
throw new PrestaShopException('Association '.$asso.' not found for class '.$definition['classname']);
$current_def = $definition['associations'][$asso];
// Special case for lang alias
if ($asso == self::LANG_ALIAS)
$is_lang = true;
else
{
$asso = $split[$i];
// Check is current association exists in current definition
if (!isset($definition['associations'][$asso]))
throw new PrestaShopException('Association '.$asso.' not found for class '.$this->definition['classname']);
$current_def = $definition['associations'][$asso];
// Special case for lang alias
if ($asso == self::LANG_ALIAS)
{
$is_lang = true;
break;
}
$is_lang = false;
$classname = (isset($current_def['object'])) ? $current_def['object'] : Tools::toCamelCase($asso, true);
$definition = ObjectModel::getDefinition($classname);
}
@@ -524,22 +574,22 @@ class CollectionCore implements Iterator, ArrayAccess, Countable
$current_def['name'] = $asso;
if (!isset($current_def['object']))
$current_def['object'] = Tools::toCamelCase($asso, true);
if (!isset($current_def['field']))
$current_def['field'] = 'id_'.$asso;
if (!isset($current_def['foreign_field']))
$current_def['foreign_field'] = 'id_'.$asso;
if ($total_association > 1)
{
unset($split[$total_association - 1]);
$current_def['complete_field'] = implode('.', $split).'.'.$current_def['field'];
}
else
$current_def['complete_field'] = $current_def['field'];
$current_def['complete_field'] = (($previous_association) ? '.' : '').$current_def['field'];
$current_def['complete_foreign_field'] = $association.'.'.$current_def['field'];
$definition['is_lang'] = $is_lang;
$definition['asso'] = $current_def;
$this->association_definition[$association] = $definition;
// Create join clause for this association
$this->join($association);
}
else
$definition = $this->association_definition[$association];
@@ -618,9 +668,6 @@ class CollectionCore implements Iterator, ArrayAccess, Countable
}
$definition = $this->getDefinition($association);
if ($association && !isset($this->join_list[$association]))
$this->join($association);
if ($fieldname == $definition['primary'] || (!empty($definition['is_lang']) && $fieldname == 'id_lang'))
$type = ObjectModel::TYPE_INT;
else
+137 -117
View File
@@ -30,6 +30,13 @@
*/
class DispatcherCore
{
/**
* List of available front controllers types
*/
const FC_FRONT = 1;
const FC_ADMIN = 2;
const FC_MODULE = 3;
/**
* @var Dispatcher
*/
@@ -108,11 +115,14 @@ class DispatcherCore
),
),
'module' => array(
'controller' => 'module',
'rule' => 'module/{module}{/:process}',
'controller' => null,
'rule' => 'module/{module}{/:controller}',
'keywords' => array(
'module' => array('regexp' => '[a-zA-Z0-9_-]+', 'param' => 'module'),
'process' => array('regexp' => '[a-zA-Z0-9_-]*', 'param' => 'process'),
'controller' => array('regexp' => '[a-zA-Z0-9_-]+', 'param' => 'controller'),
),
'params' => array(
'fc' => 'module',
),
),
);
@@ -152,6 +162,11 @@ class DispatcherCore
*/
protected $controller_not_found = 'pagenotfound';
/**
* @var string Front controller to use
*/
protected $front_controller = self::FC_FRONT;
/**
* @var array List of controllers where are stored controllers
*/
@@ -174,6 +189,14 @@ class DispatcherCore
*/
protected function __construct()
{
// Select right front controller
if (defined('_PS_ADMIN_DIR_'))
$this->setFrontController(self::FC_ADMIN);
else if (Tools::getValue('fc') == 'module')
$this->setFrontController(self::FC_MODULE);
else
$this->setFrontController(self::FC_FRONT);
$this->setDefaultController('index');
$this->setControllerDirectories(_PS_FRONT_CONTROLLER_DIR_);
$this->use_routes = (bool)Configuration::get('PS_REWRITING_SETTINGS');
@@ -207,6 +230,13 @@ class DispatcherCore
$this->controller_not_found = $controller;
}
public function setFrontController($fc)
{
if (!in_array($fc, array(self::FC_FRONT, self::FC_ADMIN, self::FC_MODULE)))
throw new PrestaShopException('Bad front controller chosen');
$this->front_controller = $fc;
}
/**
* Set list of controllers where are stored controllers
*
@@ -219,48 +249,6 @@ class DispatcherCore
$this->controller_directories = $dir;
}
/**
* Get the controller row in db
*
* @param string $name
*/
public static function getAdminController($name)
{
if (!Validate::isTabName($name))
return false;
$row = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow('
SELECT id_tab, class_name, module
FROM `'._DB_PREFIX_.'tab`
WHERE LOWER(class_name) = \''.pSQL($name).'\'');
return $row;
}
/**
* Include the file containing a controller or tab from a mdodule
*
* @param string $module
* @param string $name controller name
* @return string|bool controller type or false if file not found
*/
public static function includeModuleClass($module, $name)
{
$file = _PS_MODULE_DIR_.$module.'/controllers/admin/'.$name.'Controller.php';
if (file_exists($file))
{
include($file);
return 'controller';
}
$file = _PS_MODULE_DIR_.$module.'/'.$name.'.php';
if (file_exists($file))
{
include($file);
return 'tab';
}
return false;
}
/**
* Find the controller and instantiate it
*/
@@ -276,79 +264,97 @@ class DispatcherCore
$this->request_uri = substr($this->request_uri, 3);
}
// Get current controller and list of controllers
// Get current controller
$this->getController();
if (!$this->controller)
$this->controller = $this->default_controller;
// FO dispatch
if (!defined('_PS_ADMIN_DIR_'))
// Dispatch with right front controller
switch ($this->front_controller)
{
$controllers = Dispatcher::getControllers($this->controller_directories);
if (!isset($controllers[$this->controller]))
$this->controller = strtolower($this->controller_not_found);
$controller_class = $controllers[$this->controller];
// Dispatch front office controller
case self::FC_FRONT :
$controllers = Dispatcher::getControllers(_PS_FRONT_CONTROLLER_DIR_);
// If module controller is called, we have to call the right module controller
if ($controller_class == 'ModuleController')
{
$controllers['index'] = 'IndexController';
if (isset($controllers['auth']))
$controllers['authentication'] = $controllers['auth'];
if (isset($controllers['compare']))
$controllers['productscomparison'] = $controllers['compare'];
if (!isset($controllers[$this->controller]))
$this->controller = 'pagenotfound';
$controller_class = $controllers[$this->controller];
break;
// Dispatch module controller for front office
case self::FC_MODULE :
$module_name = Tools::getValue('module');
$module = Module::getInstanceByName($module_name);
if (Validate::isLoadedObject($module) && $module->active && file_exists(_PS_MODULE_DIR_.$module_name.'/'.$module_name.'Controller.php'))
$controller_class = 'PageNotFoundController';
if (Validate::isLoadedObject($module) && $module->active)
{
include_once(_PS_MODULE_DIR_.$module_name.'/'.$module_name.'Controller.php');
$controller_class = 'Module'.$module_name.'Controller';
$controllers = Dispatcher::getControllers(_PS_MODULE_DIR_.$module_name.'/controllers/front/');
if (isset($controllers[$this->controller]))
{
include_once(_PS_MODULE_DIR_.$module_name.'/controllers/front/'.$this->controller.'.php');
$controller_class = $module_name.$this->controller.'ModuleFrontController';
}
}
break;
// Dispatch back office controller + module back office controller
case self::FC_ADMIN :
$tab = Tab::getInstanceFromClassName($this->controller);
$retrocompatibility_admin_tab = null;
if ($tab->module)
{
if (file_exists(_PS_MODULE_DIR_.$tab->module.'/'.$tab->class_name.'.php'))
$retrocompatibility_admin_tab = _PS_MODULE_DIR_.$tab->module.'/'.$tab->class_name.'.php';
else
{
$controllers = Dispatcher::getControllers(_PS_MODULE_DIR_.$tab->module.'/controllers/admin/');
if (!isset($controllers[$this->controller]))
{
$this->controller = 'adminnotfound';
$controller_class = 'AdminNotFoundController';
}
else
{
include_once(_PS_MODULE_DIR_.$tab->module.'/controllers/admin/'.$this->controller.'.php');
$controller_class = $controllers[$this->controller].'Controller';
}
}
}
else
$controller_class = $controllers[$this->controller_not_found];
}
}
// BO dispatch
else
{
// Get controller class name
$controller_row = Dispatcher::getAdminController($this->controller);
if (empty($controller_row))
{
// We need controller_not_found to be the camelcase controller name
$this->controller = strtolower($this->controller_not_found);
$controller_class = $this->controller_not_found;
}
else
$controller_class = $controller_row['class_name'];
{
$controllers = Dispatcher::getControllers(array(_PS_ADMIN_DIR_.'/tabs/', _PS_ADMIN_CONTROLLER_DIR_));
if (!isset($controllers[$this->controller]))
$this->controller = 'adminnotfound';
$controller_class = $controllers[$this->controller];
// If Tab/Controller is in module, include it
if (!empty($controller_row['module']))
$controller_type = Dispatcher::includeModuleClass($controller_row['module'], $controller_class);
// If it is an AdminTab, include it
else if (file_exists(_PS_ADMIN_DIR_.'/tabs/'.$controller_class.'.php'))
{
include(_PS_ADMIN_DIR_.'/tabs/'.$controller_class.'.php');
$controller_type = 'tab';
}
// For retrocompatibility with admin/tabs/ old system
if (isset($controller_type) && $controller_type == 'tab')
{
require_once(_PS_ADMIN_DIR_.'/functions.php');
$ajax_mode = !empty($_REQUEST['ajaxMode']);
runAdminTab($controller_class, $ajax_mode);
return;
}
if (file_exists(_PS_ADMIN_DIR_.'/tabs/'.$controller_class.'.php'))
$retrocompatibility_admin_tab = _PS_ADMIN_DIR_.'/tabs/'.$controller_class.'.php';
}
$controller_class = $controller_class.'Controller';
// @retrocompatibility with admin/tabs/ old system
if ($retrocompatibility_admin_tab)
{
include_once($retrocompatibility_admin_tab);
include_once(_PS_ADMIN_DIR_.'/functions.php');
runAdminTab($this->controller, !empty($_REQUEST['ajaxMode']));
return;
}
break;
default :
throw new PrestaShopException('Bad front controller chosen');
}
// Instantiate controller
try
{
$controller = Controller::getController($controller_class);
// Controller comes from a module set "module name"
if (!empty($controller_row['module']) && $controller_type == 'controller')
$controller->module = $controller_row['module'];
$controller->run();
Controller::getController($controller_class)->run();
}
catch (PrestaShopException $e)
{
@@ -363,7 +369,13 @@ class DispatcherCore
{
$context = Context::getContext();
foreach ($this->default_routes as $id => $route)
$this->addRoute($id, $route['rule'], $route['controller'], $route['keywords']);
$this->addRoute(
$id,
$route['rule'],
$route['controller'],
$route['keywords'],
isset($route['params']) ? $route['params'] : array()
);
if ($this->use_routes)
{
@@ -389,7 +401,13 @@ class DispatcherCore
// Load custom routes
foreach ($this->default_routes as $route_id => $route_data)
if ($custom_route = Configuration::get('PS_ROUTE_'.$route_id))
$this->addRoute($route_id, $custom_route, $route_data['controller'], $route_data['keywords']);
$this->addRoute(
$route_id,
$custom_route,
$route_data['controller'],
$route_data['keywords'],
isset($route_data['params']) ? $route_data['params'] : array()
);
}
}
@@ -399,7 +417,7 @@ class DispatcherCore
* @param string $rule Url rule
* @param string $controller Controller to call if request uri match the rule
*/
public function addRoute($route_id, $rule, $controller, $keywords = array())
public function addRoute($route_id, $rule, $controller, array $keywords = array(), array $params = array())
{
$regexp = preg_quote($rule, '#');
if ($keywords)
@@ -432,6 +450,7 @@ class DispatcherCore
'regexp' => $regexp,
'controller' => $controller,
'keywords' => $keywords,
'params' => $params,
);
}
@@ -478,11 +497,8 @@ class DispatcherCore
* @param bool $use_routes If false, don't use to create this url
* @param string $anchor Optional anchor to add at the end of this url
*/
public function createUrl($route_id, $params = array(), $use_routes = true, $anchor = '')
public function createUrl($route_id, array $params = array(), $use_routes = true, $anchor = '')
{
if (!is_array($params))
die('Dispatcher::createUrl() $params must be an array');
if (!isset($this->routes[$route_id]))
{
$query = http_build_query($params);
@@ -491,7 +507,7 @@ class DispatcherCore
$route = $this->routes[$route_id];
// Check required fields
$query_params = array();
$query_params = isset($route['params']) ? $route['params'] : array();
foreach ($route['keywords'] as $key => $data)
{
if (!$data['required'])
@@ -529,7 +545,16 @@ class DispatcherCore
}
// Build a classic url index.php?controller=foo&...
else
$url = 'index.php?controller='.$route['controller'].(($query_params) ? '&'.http_build_query($query_params) : '');
{
$add_params = array();
foreach ($params as $key => $value)
if (!isset($route['keywords'][$key]) && !isset($this->default_routes[$route_id]['keywords'][$key]))
$add_params[$key] = $value;
if (!empty($route['controller']))
$query_params['controller'] = $route['controller'];
$url = 'index.php?'.http_build_query(array_merge($add_params, $query_params));
}
return $url.$anchor;
}
@@ -604,14 +629,6 @@ class DispatcherCore
$controllers = array();
foreach ($dirs as $dir)
$controllers = array_merge($controllers, Dispatcher::getControllersInDirectory($dir));
// Add default controllers
$controllers['index'] = 'IndexController';
if (isset($controllers['auth']))
$controllers['authentication'] = $controllers['auth'];
if (isset($controllers['compare']))
$controllers['productscomparison'] = $controllers['compare'];
return $controllers;
}
@@ -623,6 +640,9 @@ class DispatcherCore
*/
public static function getControllersInDirectory($dir)
{
if (!is_dir($dir))
return array();
$controllers = array();
$controller_files = scandir($dir);
foreach ($controller_files as $controller_filename)
+2 -3
View File
@@ -278,7 +278,7 @@ class LinkCore
* @param int $id_lang
* @return string
*/
public function getModuleLink($module, $process = '', $ssl = false, $id_lang = null)
public function getModuleLink($module, $controller = 'default', array $params = array(), $ssl = false, $id_lang = null)
{
$base = (($ssl && Configuration::get('PS_SSL_ENABLED')) ? _PS_BASE_URL_SSL_ : _PS_BASE_URL_);
@@ -287,9 +287,8 @@ class LinkCore
$url = $base.__PS_BASE_URI__.$this->getLangLink($id_lang);
// Set available keywords
$params = array();
$params['module'] = $module;
$params['process'] = $process;
$params['controller'] = $controller ? $controller : 'default';
return $url.Dispatcher::getInstance()->createUrl('module', $params, $this->allow);
}
+26 -6
View File
@@ -1236,16 +1236,18 @@ abstract class ModuleCore
global $_MODULES, $_MODULE;
if ($id_lang == null)
$id_lang = Context::getContext()->language->id;
$file = _PS_MODULE_DIR_.$this->name.'/'.Context::getContext()->language->iso_code.'.php';
// @retrocompatibility with translations files in module root
if (Tools::file_exists_cache($this->local_path.'/translations/'.Context::getContext()->language->iso_code.'.php'))
$file = $this->local_path.'/translations/'.Context::getContext()->language->iso_code.'.php';
else
$file = $this->local_path.'/'.Context::getContext()->language->iso_code.'.php';
if (Tools::file_exists_cache($file) && include_once($file))
$_MODULES = !empty($_MODULES) ? array_merge($_MODULES, $_MODULE) : $_MODULE;
$source = $specific ? $specific : $this->name;
$string = str_replace('\'', '\\\'', $string);
$ret = $this->findTranslation($this->name, $string, $source);
$ret = Module::findTranslation($this->name, $string, $source);
return $ret;
}
@@ -1421,6 +1423,8 @@ abstract class ModuleCore
{
if (Tools::file_exists_cache(_PS_THEME_DIR_.'modules/'.$module_name.'/'.$template))
return true;
elseif (Tools::file_exists_cache(_PS_MODULE_DIR_.$module_name.'/views/templates/hook/'.$template))
return false;
elseif (Tools::file_exists_cache(_PS_MODULE_DIR_.$module_name.'/'.$template))
return false;
return null;
@@ -1443,7 +1447,7 @@ abstract class ModuleCore
));
$smarty_subtemplate = $this->context->smarty->createTemplate(
($overloaded ? _PS_THEME_DIR_.'modules/'.basename($file, '.php') : _PS_MODULE_DIR_.basename($file, '.php')).'/'.$template,
$this->getTemplatePath($template),
$cacheId,
$compileId,
$this->smarty
@@ -1466,7 +1470,12 @@ abstract class ModuleCore
$overloaded = $this->_isTemplateOverloaded($template);
if (is_null($overloaded))
return null;
return ($overloaded ? _PS_THEME_DIR_.'modules/'.$this->name : _PS_MODULE_DIR_.$this->name).'/'.$template;
if ($overloaded)
return _PS_THEME_DIR_.'modules/'.$this->name.'/'.$template;
else if (file_exists(_PS_MODULE_DIR_.$this->name.'/views/templates/hook/'.$template))
return _PS_MODULE_DIR_.$this->name.'/views/templates/hook/'.$template;
else
return _PS_MODULE_DIR_.$this->name.'/'.$template;
}
protected function _getApplicableTemplateDir($template)
@@ -1599,6 +1608,17 @@ abstract class ModuleCore
return $this->_confirmations;
}
/**
* Get local path for module
*
* @since 1.5.0
* @return string
*/
public function getLocalPath()
{
return $this->local_path;
}
/**
* Get uri path for module
*
+88 -90
View File
@@ -110,7 +110,7 @@ class ToolsCore
if (isset($_SERVER['HTTP_REFERER']) && $url == $_SERVER['HTTP_REFERER'])
header('Location: '.$_SERVER['HTTP_REFERER']);
else
header('Location: '.$base_uri.$url);
header('Location: '.$url);
exit;
}
@@ -123,9 +123,9 @@ class ToolsCore
{
if (!preg_match('@^https?://@i', $url))
{
if (strpos($url, __PS_BASE_URI__) !== FALSE && strpos($url, __PS_BASE_URI__) == 0)
if (strpos($url, __PS_BASE_URI__) !== false && strpos($url, __PS_BASE_URI__) == 0)
$url = substr($url, strlen(__PS_BASE_URI__));
if (strpos($url, 'index.php?controller=') !== FALSE && strpos($url, 'index.php/') == 0)
if (strpos($url, 'index.php?controller=') !== false && strpos($url, 'index.php/') == 0)
$url = substr($url, strlen('index.php?controller='));
$explode = explode('?', $url);
$url = Context::getContext()->link->getPageLink($explode[0]);
@@ -230,9 +230,9 @@ class ToolsCore
*
* @return string server name
*/
static function getServerName()
public static function getServerName()
{
if (isset($_SERVER['HTTP_X_FORWARDED_SERVER']) AND $_SERVER['HTTP_X_FORWARDED_SERVER'])
if (isset($_SERVER['HTTP_X_FORWARDED_SERVER']) && $_SERVER['HTTP_X_FORWARDED_SERVER'])
return $_SERVER['HTTP_X_FORWARDED_SERVER'];
return $_SERVER['SERVER_NAME'];
}
@@ -242,10 +242,10 @@ class ToolsCore
*
* @return string $remote_addr ip of client
*/
static function getRemoteAddr()
public static function getRemoteAddr()
{
// This condition is necessary when using CDN, don't remove it.
if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) AND $_SERVER['HTTP_X_FORWARDED_FOR'] AND (!isset($_SERVER['REMOTE_ADDR']) OR preg_match('/^127\..*/i', trim($_SERVER['REMOTE_ADDR'])) OR preg_match('/^172\.16.*/i', trim($_SERVER['REMOTE_ADDR'])) OR preg_match('/^192\.168\.*/i', trim($_SERVER['REMOTE_ADDR'])) OR preg_match('/^10\..*/i', trim($_SERVER['REMOTE_ADDR']))))
if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && $_SERVER['HTTP_X_FORWARDED_FOR'] && (!isset($_SERVER['REMOTE_ADDR']) || preg_match('/^127\..*/i', trim($_SERVER['REMOTE_ADDR'])) || preg_match('/^172\.16.*/i', trim($_SERVER['REMOTE_ADDR'])) || preg_match('/^192\.168\.*/i', trim($_SERVER['REMOTE_ADDR'])) || preg_match('/^10\..*/i', trim($_SERVER['REMOTE_ADDR']))))
{
if (strpos($_SERVER['HTTP_X_FORWARDED_FOR'], ','))
{
@@ -310,7 +310,7 @@ class ToolsCore
*/
public static function getValue($key, $defaultValue = false)
{
if (!isset($key) OR empty($key) OR !is_string($key))
if (!isset($key) || empty($key) || !is_string($key))
return false;
$ret = (isset($_POST[$key]) ? $_POST[$key] : (isset($_GET[$key]) ? $_GET[$key] : $defaultValue));
@@ -321,7 +321,7 @@ class ToolsCore
public static function getIsset($key)
{
if (!isset($key) OR empty($key) OR !is_string($key))
if (!isset($key) || empty($key) || !is_string($key))
return false;
return isset($_POST[$key]) ? true : (isset($_GET[$key]) ? true : false);
}
@@ -339,12 +339,12 @@ class ToolsCore
if ($cookie->id_lang)
{
$lang = new Language((int)$cookie->id_lang);
if (!Validate::isLoadedObject($lang) OR !$lang->active OR !$lang->isAssociatedToShop())
$cookie->id_lang = NULL;
if (!Validate::isLoadedObject($lang) || !$lang->active || !$lang->isAssociatedToShop())
$cookie->id_lang = null;
}
/* Automatically detect language if not already defined */
if (!$cookie->id_lang AND isset($_SERVER['HTTP_ACCEPT_LANGUAGE']))
if (!$cookie->id_lang && isset($_SERVER['HTTP_ACCEPT_LANGUAGE']))
{
$array = explode(',', Tools::strtolower($_SERVER['HTTP_ACCEPT_LANGUAGE']));
if (Tools::strlen($array[0]) > 2)
@@ -357,13 +357,13 @@ class ToolsCore
if (Validate::isLanguageIsoCode($string))
{
$lang = new Language((int)(Language::getIdByIso($string)));
if (Validate::isLoadedObject($lang) AND $lang->active)
if (Validate::isLoadedObject($lang) && $lang->active)
$cookie->id_lang = (int)($lang->id);
}
}
/* If language file not present, you must use default language file */
if (!$cookie->id_lang OR !Validate::isUnsignedId($cookie->id_lang))
if (!$cookie->id_lang || !Validate::isUnsignedId($cookie->id_lang))
$cookie->id_lang = (int)(Configuration::get('PS_LANG_DEFAULT'));
$iso = Language::getIsoById((int)$cookie->id_lang);
@@ -395,21 +395,21 @@ class ToolsCore
public static function setCurrency($cookie)
{
if (Tools::isSubmit('SubmitCurrency'))
if (isset($_POST['id_currency']) AND is_numeric($_POST['id_currency']))
if (isset($_POST['id_currency']) && is_numeric($_POST['id_currency']))
{
$currency = Currency::getCurrencyInstance((int)($_POST['id_currency']));
if (is_object($currency) AND $currency->id AND !$currency->deleted AND $currency->isAssociatedToShop())
if (is_object($currency) && $currency->id && !$currency->deleted && $currency->isAssociatedToShop())
$cookie->id_currency = (int)($currency->id);
}
if ((int)$cookie->id_currency)
{
$currency = Currency::getCurrencyInstance((int)$cookie->id_currency);
if (is_object($currency) AND (int)$currency->id AND (int)$currency->deleted != 1 AND $currency->active AND $currency->isAssociatedToShop())
if (is_object($currency) && (int)$currency->id && (int)$currency->deleted != 1 && $currency->active && $currency->isAssociatedToShop())
return $currency;
}
$currency = Currency::getCurrencyInstance((int)(Configuration::get('PS_CURRENCY_DEFAULT')));
if (is_object($currency) AND $currency->id)
if (is_object($currency) && $currency->id)
$cookie->id_currency = (int)($currency->id);
return $currency;
}
@@ -421,13 +421,13 @@ class ToolsCore
* @param object $currency Current currency (object, id_currency, NULL => context currency)
* @return string Price correctly formated (sign, decimal separator...)
*/
public static function displayPrice($price, $currency = NULL, $no_utf8 = false, Context $context = null)
public static function displayPrice($price, $currency = null, $no_utf8 = false, Context $context = null)
{
if (!is_numeric($price))
return $price;
if (!$context)
$context = Context::getContext();
if ($currency === NULL)
if ($currency === null)
$currency = $context->currency;
// if you modified this function, don't forget to modify the Javascript function formatCurrency (in tools.js)
elseif (is_int($currency))
@@ -499,11 +499,11 @@ class ToolsCore
* @param object $currency Current currency object
* @param boolean $to_currency convert to currency or from currency to default currency
*/
public static function convertPrice($price, $currency = NULL, $to_currency = true, Context $context = null)
public static function convertPrice($price, $currency = null, $to_currency = true, Context $context = null)
{
if (!$context)
$context = Context::getContext();
if ($currency === NULL)
if ($currency === null)
$currency = $context->currency;
elseif (is_numeric($currency))
$currency = Currency::getCurrencyInstance($currency);
@@ -641,14 +641,14 @@ class ToolsCore
$dirname = rtrim($dirname, '/').'/';
$files = scandir($dirname);
foreach ($files as $file)
if ($file != '.' AND $file != '..')
if ($file != '.' && $file != '..')
{
if (is_dir($dirname.$file))
Tools::deleteDirectory($dirname.$file, true);
elseif (file_exists($dirname.$file))
unlink($dirname.$file);
}
if($delete_self)
if ($delete_self)
rmdir($dirname);
}
@@ -667,12 +667,12 @@ class ToolsCore
@include_once(_PS_TRANSLATIONS_DIR_.$context->language->iso_code.'/errors.php');
if (defined('_PS_MODE_DEV_') AND _PS_MODE_DEV_ AND $string == 'Fatal error')
if (defined('_PS_MODE_DEV_') && _PS_MODE_DEV_ && $string == 'Fatal error')
return ('<pre>'.print_r(debug_backtrace(), true).'</pre>');
if (!is_array($_ERRORS))
return str_replace('"', '&quot;', $string);
$key = md5(str_replace('\'', '\\\'', $string));
$str = (isset($_ERRORS) AND is_array($_ERRORS) AND key_exists($key, $_ERRORS)) ? ($htmlentities ? htmlentities($_ERRORS[$key], ENT_COMPAT, 'UTF-8') : $_ERRORS[$key]) : $string;
$str = (isset($_ERRORS) && is_array($_ERRORS) && array_key_exists($key, $_ERRORS)) ? ($htmlentities ? htmlentities($_ERRORS[$key], ENT_COMPAT, 'UTF-8') : $_ERRORS[$key]) : $string;
return str_replace('"', '&quot;', stripslashes($str));
}
@@ -735,8 +735,8 @@ class ToolsCore
public static function isSubmit($submit)
{
return (
isset($_POST[$submit]) OR isset($_POST[$submit.'_x']) OR isset($_POST[$submit.'_y'])
OR isset($_GET[$submit]) OR isset($_GET[$submit.'_x']) OR isset($_GET[$submit.'_y'])
isset($_POST[$submit]) || isset($_POST[$submit.'_x']) || isset($_POST[$submit.'_y'])
|| isset($_GET[$submit]) || isset($_GET[$submit.'_x']) || isset($_GET[$submit.'_y'])
);
}
@@ -811,7 +811,7 @@ class ToolsCore
{
if (empty($row['meta_description']))
$row['meta_description'] = strip_tags($row['meta_description']);
$row['meta_title'] .= $row['name'] . (!empty($page_number) ? ' ('.$page_number.')' : '');
$row['meta_title'] .= $row['name'].(!empty($page_number) ? ' ('.$page_number.')' : '');
$row['meta_title'] .= ' - '.Configuration::get('PS_SHOP_NAME');
return Tools::completeMetaTags($row, $row['meta_title']);
}
@@ -879,9 +879,9 @@ class ToolsCore
{
/* Metas-tags */
$metas = Meta::getMetaByPage($page_name, $id_lang);
$ret['meta_title'] = (isset($metas['title']) AND $metas['title']) ? $metas['title'].' - '.Configuration::get('PS_SHOP_NAME') : Configuration::get('PS_SHOP_NAME');
$ret['meta_description'] = (isset($metas['description']) AND $metas['description']) ? $metas['description'] : '';
$ret['meta_keywords'] = (isset($metas['keywords']) AND $metas['keywords']) ? $metas['keywords'] : '';
$ret['meta_title'] = (isset($metas['title']) && $metas['title']) ? $metas['title'].' - '.Configuration::get('PS_SHOP_NAME') : Configuration::get('PS_SHOP_NAME');
$ret['meta_description'] = (isset($metas['description']) && $metas['description']) ? $metas['description'] : '';
$ret['meta_keywords'] = (isset($metas['keywords']) && $metas['keywords']) ? $metas['keywords'] : '';
return $ret;
}
@@ -991,8 +991,8 @@ class ToolsCore
$categories = Db::getInstance()->executeS($sql);
$n = 1;
$nCategories = (int)sizeof($categories);
foreach ($categories AS $category)
$nCategories = count($categories);
foreach ($categories as $category)
{
$fullPath .=
(($n < $nCategories || $linkOntheLastItem) ? '<a href="'.Tools::safeOutput($context->link->getCategoryLink((int)$category['id_category'], $category['link_rewrite'])).'" title="'.htmlentities($category['name'], ENT_NOQUOTES, 'UTF-8').'">' : '').
@@ -1076,10 +1076,10 @@ class ToolsCore
$str = Tools::replaceAccentedChars($str);
// Remove all non-whitelist chars.
$str = preg_replace('/[^a-zA-Z0-9\s\'\:\/\[\]-\pL]/u','', $str);
$str = preg_replace('/[\s\'\:\/\[\]-]+/',' ', $str);
$str = preg_replace('/[ ]/','-', $str);
$str = preg_replace('/[\/]/','-', $str);
$str = preg_replace('/[^a-zA-Z0-9\s\'\:\/\[\]-\pL]/u', '', $str);
$str = preg_replace('/[\s\'\:\/\[\]-]+/', ' ', $str);
$str = preg_replace('/[ ]/', '-', $str);
$str = preg_replace('/[\/]/', '-', $str);
// If it was not possible to lowercase the string with mb_strtolower, we do it after the transformations.
// This way we lose fewer special chars.
@@ -1096,23 +1096,23 @@ class ToolsCore
*/
public static function replaceAccentedChars($str)
{
$str = preg_replace('/[\x{0105}\x{0104}\x{00E0}\x{00E1}\x{00E2}\x{00E3}\x{00E4}\x{00E5}]/u','a', $str);
$str = preg_replace('/[\x{00E7}\x{010D}\x{0107}\x{0106}]/u','c', $str);
$str = preg_replace('/[\x{010F}]/u','d', $str);
$str = preg_replace('/[\x{00E8}\x{00E9}\x{00EA}\x{00EB}\x{011B}\x{0119}\x{0118}]/u','e', $str);
$str = preg_replace('/[\x{00EC}\x{00ED}\x{00EE}\x{00EF}]/u','i', $str);
$str = preg_replace('/[\x{0142}\x{0141}\x{013E}\x{013A}]/u','l', $str);
$str = preg_replace('/[\x{00F1}\x{0148}]/u','n', $str);
$str = preg_replace('/[\x{00F2}\x{00F3}\x{00F4}\x{00F5}\x{00F6}\x{00F8}\x{00D3}]/u','o', $str);
$str = preg_replace('/[\x{0159}\x{0155}]/u','r', $str);
$str = preg_replace('/[\x{015B}\x{015A}\x{0161}]/u','s', $str);
$str = preg_replace('/[\x{00DF}]/u','ss', $str);
$str = preg_replace('/[\x{0165}]/u','t', $str);
$str = preg_replace('/[\x{00F9}\x{00FA}\x{00FB}\x{00FC}\x{016F}]/u','u', $str);
$str = preg_replace('/[\x{00FD}\x{00FF}]/u','y', $str);
$str = preg_replace('/[\x{017C}\x{017A}\x{017B}\x{0179}\x{017E}]/u','z', $str);
$str = preg_replace('/[\x{00E6}]/u','ae', $str);
$str = preg_replace('/[\x{0153}]/u','oe', $str);
$str = preg_replace('/[\x{0105}\x{0104}\x{00E0}\x{00E1}\x{00E2}\x{00E3}\x{00E4}\x{00E5}]/u', 'a', $str);
$str = preg_replace('/[\x{00E7}\x{010D}\x{0107}\x{0106}]/u', 'c', $str);
$str = preg_replace('/[\x{010F}]/u', 'd', $str);
$str = preg_replace('/[\x{00E8}\x{00E9}\x{00EA}\x{00EB}\x{011B}\x{0119}\x{0118}]/u', 'e', $str);
$str = preg_replace('/[\x{00EC}\x{00ED}\x{00EE}\x{00EF}]/u', 'i', $str);
$str = preg_replace('/[\x{0142}\x{0141}\x{013E}\x{013A}]/u', 'l', $str);
$str = preg_replace('/[\x{00F1}\x{0148}]/u', 'n', $str);
$str = preg_replace('/[\x{00F2}\x{00F3}\x{00F4}\x{00F5}\x{00F6}\x{00F8}\x{00D3}]/u', 'o', $str);
$str = preg_replace('/[\x{0159}\x{0155}]/u', 'r', $str);
$str = preg_replace('/[\x{015B}\x{015A}\x{0161}]/u', 's', $str);
$str = preg_replace('/[\x{00DF}]/u', 'ss', $str);
$str = preg_replace('/[\x{0165}]/u', 't', $str);
$str = preg_replace('/[\x{00F9}\x{00FA}\x{00FB}\x{00FC}\x{016F}]/u', 'u', $str);
$str = preg_replace('/[\x{00FD}\x{00FF}]/u', 'y', $str);
$str = preg_replace('/[\x{017C}\x{017A}\x{017B}\x{0179}\x{017E}]/u', 'z', $str);
$str = preg_replace('/[\x{00E6}]/u', 'ae', $str);
$str = preg_replace('/[\x{0153}]/u', 'oe', $str);
return $str;
}
@@ -1185,7 +1185,7 @@ class ToolsCore
return $date;
}
static function strtolower($str)
public static function strtolower($str)
{
if (is_array($str))
return false;
@@ -1194,7 +1194,7 @@ class ToolsCore
return strtolower($str);
}
static function strlen($str, $encoding = 'UTF-8')
public static function strlen($str, $encoding = 'UTF-8')
{
if (is_array($str))
return false;
@@ -1204,14 +1204,14 @@ class ToolsCore
return strlen($str);
}
static function stripslashes($string)
public static function stripslashes($string)
{
if (_PS_MAGIC_QUOTES_GPC_)
$string = stripslashes($string);
return $string;
}
static function strtoupper($str)
public static function strtoupper($str)
{
if (is_array($str))
return false;
@@ -1220,7 +1220,7 @@ class ToolsCore
return strtoupper($str);
}
static function substr($str, $start, $length = false, $encoding = 'utf-8')
public static function substr($str, $start, $length = false, $encoding = 'utf-8')
{
if (is_array($str))
return false;
@@ -1229,20 +1229,20 @@ class ToolsCore
return substr($str, $start, ($length === false ? Tools::strlen($str) : (int)($length)));
}
static function ucfirst($str)
public static function ucfirst($str)
{
return Tools::strtoupper(Tools::substr($str, 0, 1)).Tools::substr($str, 1);
}
public static function orderbyPrice(&$array, $orderWay)
{
foreach($array as &$row)
$row['price_tmp'] = Product::getPriceStatic($row['id_product'], true, ((isset($row['id_product_attribute']) AND !empty($row['id_product_attribute'])) ? (int)($row['id_product_attribute']) : NULL), 2);
if(strtolower($orderWay) == 'desc')
foreach ($array as &$row)
$row['price_tmp'] = Product::getPriceStatic($row['id_product'], true, ((isset($row['id_product_attribute']) && !empty($row['id_product_attribute'])) ? (int)($row['id_product_attribute']) : null), 2);
if (strtolower($orderWay) == 'desc')
uasort($array, 'cmpPriceDesc');
else
uasort($array, 'cmpPriceAsc');
foreach($array as &$row)
foreach ($array as &$row)
unset($row['price_tmp']);
}
@@ -1255,7 +1255,7 @@ class ToolsCore
public static function isEmpty($field)
{
return ($field === '' OR $field === NULL);
return ($field === '' || $field === null);
}
/**
@@ -1330,9 +1330,9 @@ class ToolsCore
return self::$file_exists_cache[$filename];
}
public static function file_get_contents($url, $useIncludePath = false, $streamContext = NULL, $curlTimeOut = 5)
{
if ($streamContext == NULL)
public static function file_get_contents($url, $useIncludePath = false, $streamContext = null, $curlTimeOut = 5)
{
if ($streamContext == null)
$streamContext = @stream_context_create(array('http' => array('timeout' => 5)));
if (in_array(ini_get('allow_url_fopen'), array('On', 'on', '1')))
@@ -1379,7 +1379,7 @@ class ToolsCore
public static function toCamelCase($str, $capitaliseFirstChar = false)
{
$str = strtolower($str);
if($capitaliseFirstChar)
if ($capitaliseFirstChar)
$str = ucfirst($str);
return preg_replace_callback('/_([a-z])/', create_function('$c', 'return strtoupper($c[1]);'), $str);
}
@@ -1460,7 +1460,7 @@ class ToolsCore
public static function minifyCSS($css_content, $fileuri = false)
{
Tools::displayAsDeprecated();
return Media::minifyCSS($css_content, $fileuri);
return Media::minifyCSS($css_content, $fileuri);
}
public static function replaceByAbsoluteURL($matches)
@@ -1541,7 +1541,7 @@ class ToolsCore
self::$_cache_nb_media_servers = 3;
}
if (self::$_cache_nb_media_servers AND ($id_media_server = (abs(crc32($filename)) % self::$_cache_nb_media_servers + 1)))
if (self::$_cache_nb_media_servers && ($id_media_server = (abs(crc32($filename)) % self::$_cache_nb_media_servers + 1)))
return constant('_MEDIA_SERVER_'.$id_media_server.'_');
return Tools::getHttpHost();
}
@@ -1647,7 +1647,7 @@ class ToolsCore
$img_name .= '$'.$j;
}
$img_name .= '$'.$j;
fwrite($write_fd, 'RewriteRule ^'.str_repeat('([0-9])', $i).'(\-[_a-zA-Z0-9-]*)?(-[0-9]+)?/[_a-zA-Z0-9-\pL]*\.jpg$ '._PS_PROD_IMG_.$img_path.$img_name.'$'.($j+1).".jpg [L]\n");
fwrite($write_fd, 'RewriteRule ^'.str_repeat('([0-9])', $i).'(\-[_a-zA-Z0-9-]*)?(-[0-9]+)?/[_a-zA-Z0-9-\pL]*\.jpg$ '._PS_PROD_IMG_.$img_path.$img_name.'$'.($j + 1).".jpg [L]\n");
}
fwrite($write_fd, 'RewriteRule ^c/([0-9]+)(\-[_a-zA-Z0-9-\pL]*)(-[0-9]+)?/[_a-zA-Z0-9-]*\.jpg$ img/c/$1$2$3.jpg [L]'."\n");
fwrite($write_fd, 'RewriteRule ^c/([a-zA-Z-]+)(-[0-9]+)?/[a-zA-Z0-9-\pL]+\.jpg$ img/c/$1$2.jpg [L]'."\n");
@@ -1693,8 +1693,8 @@ FileETag INode MTime Size
}
// In case the user hasn't rewrite mod enabled
fwrite($write_fd, "#If rewrite mod isn't enabled\n");
fwrite($write_fd, "ErrorDocument 404 " . $uri['physical'] . "index.php?controller=404\n\n");
fwrite($write_fd, '#If rewrite mod isn\'t enabled\n');
fwrite($write_fd, 'ErrorDocument 404 '.$uri['physical']."index.php?controller=404\n\n");
fwrite($write_fd, "# ~~end~~ Do not remove this comment, Prestashop will keep automatically the code outside this comment when .htaccess will be generated again\n");
fwrite($write_fd, "\n\n".trim($specific_after));
@@ -1805,8 +1805,8 @@ FileETag INode MTime Size
$smarty = $context->smarty;
if (!Configuration::get('PS_SMARTY_CACHE'))
return;
if ($smarty->force_compile == 0 AND $smarty->caching == $level)
return ;
if ($smarty->force_compile == 0 && $smarty->caching == $level)
return;
self::$_forceCompile = (int)($smarty->force_compile);
self::$_caching = (int)($smarty->caching);
$smarty->force_compile = 0;
@@ -1827,7 +1827,7 @@ FileETag INode MTime Size
public static function isCallable($function)
{
$disabled = explode(',', ini_get('disable_functions'));
return (!in_array($function, $disabled) AND is_callable($function));
return (!in_array($function, $disabled) && is_callable($function));
}
public static function pRegexp($s, $delim)
@@ -1838,7 +1838,7 @@ FileETag INode MTime Size
return $s;
}
public static function str_replace_once($needle , $replace, $haystack)
public static function str_replace_once($needle, $replace, $haystack)
{
$pos = strpos($haystack, $needle);
if ($pos === false)
@@ -1878,13 +1878,13 @@ FileETag INode MTime Size
{
$version = null;
if(defined('PHP_VERSION'))
if (defined('PHP_VERSION'))
$version = PHP_VERSION;
else
$version = phpversion('');
//Case management system of ubuntu, php version return 5.2.4-2ubuntu5.2
if(strpos($version, '-') !== false )
if (strpos($version, '-') !== false)
$version = substr($version, 0, strpos($version, '-'));
return $version;
@@ -1920,7 +1920,7 @@ FileETag INode MTime Size
if (class_exists('ZipArchive', false))
{
$zip = new ZipArchive();
if ($zip->open($fromFile) === true AND $zip->extractTo($toDir) AND $zip->close())
if ($zip->open($fromFile) === true && $zip->extractTo($toDir) && $zip->close())
return true;
return false;
}
@@ -1988,9 +1988,7 @@ FileETag INode MTime Size
public static function convertBytes($value)
{
if (is_numeric($value))
{
return $value;
}
else
{
$value_length = strlen($value);
@@ -2147,7 +2145,7 @@ FileETag INode MTime Size
// we need strpos (example, evasive can be evasive20)
foreach ($apacheModuleList as $module)
{
if (strpos($module, $name)!==false)
if (strpos($module, $name) !== false)
return true;
}
}
@@ -2185,15 +2183,15 @@ FileETag INode MTime Size
$filtered_files = array();
$real_ext = '';
$real_ext = '';
if (!empty($ext))
$real_ext = '.' . $ext;
$real_ext = '.'.$ext;
$real_ext_length = strlen($real_ext);
foreach ($files as $file)
if (strpos($file, $real_ext) && strpos($file, $real_ext) == (strlen($file) - $real_ext_length))
$filtered_files[] = $dir . '/' . $file;
$filtered_files[] = $dir.'/'.$file;
return $filtered_files;
}
}
@@ -2206,7 +2204,7 @@ FileETag INode MTime Size
* @return integer
*/
/* Externalized because of a bug in PHP 5.1.6 when inside an object */
function cmpPriceAsc($a,$b)
function cmpPriceAsc($a, $b)
{
if ((float)($a['price_tmp']) < (float)($b['price_tmp']))
return (-1);
@@ -2215,7 +2213,7 @@ function cmpPriceAsc($a,$b)
return (0);
}
function cmpPriceDesc($a,$b)
function cmpPriceDesc($a, $b)
{
if ((float)($a['price_tmp']) < (float)($b['price_tmp']))
return (1);
@@ -172,9 +172,6 @@ class AdminControllerCore extends Controller
/** @var array required_fields to display in the Required Fields form */
public $required_fields = array();
/** @var module contain the controller */
public $module;
/**
* @var array actions to execute on multiple selections
* Usage:
@@ -1956,23 +1953,9 @@ class AdminControllerCore extends Controller
throw new PrestaShopException(sprintf('Table name %s is invalid:', $this->table));
if (empty($order_by))
{
if ($this->context->cookie->{$this->table.'Orderby'})
$order_by = $this->context->cookie->{$this->table.'Orderby'};
elseif ($this->_orderBy)
$order_by = $this->_orderBy;
else
$order_by = $this->_defaultOrderBy;
}
$order_by = $this->context->cookie->__get($this->table.'Orderby') ? $this->context->cookie->__get($this->table.'Orderby') : $this->_defaultOrderBy;
if (empty($order_way))
{
if ($this->context->cookie->{$this->table.'Orderway'})
$order_way = $this->context->cookie->{$this->table.'Orderway'};
elseif ($this->_orderWay)
$order_way = $this->_orderWay;
else
$order_way = $this->_defaultOrderWay;
}
$order_way = $this->context->cookie->__get($this->table.'Orderway') ? $this->context->cookie->__get($this->table.'Orderway') : $this->_defaultOrderWay;
$limit = (int)Tools::getValue('pagination', $limit);
$this->context->cookie->{$this->table.'_pagination'} = $limit;
@@ -1993,7 +1976,7 @@ class AdminControllerCore extends Controller
/* Cache */
$this->_lang = (int)$id_lang;
$this->_orderBy = substr($order_by, strpos($order_by, '.') + 1);
$this->_orderBy = $order_by;
$this->_orderWay = Tools::strtoupper($order_way);
/* SQL table : orders, but class name is Order */
@@ -2061,11 +2044,7 @@ class AdminControllerCore extends Controller
if (isset($this->_having))
$having_clause .= $this->_having.' ';
}
if (strpos($order_by, '.') > 0)
{
$order_by = explode('.', $order_by);
$order_by = pSQL($order_by[0]).'.`'.pSQL($order_by[1]).'`';
}
$sql = 'SELECT SQL_CALC_FOUND_ROWS
'.($this->_tmpTableFilter ? ' * FROM (SELECT ' : '').'
'.($this->lang ? 'b.*, ' : '').'a.*'.(isset($this->_select) ? ', '.$this->_select.' ' : '').$select_shop.'
@@ -2078,7 +2057,7 @@ class AdminControllerCore extends Controller
(isset($this->_filter) ? $this->_filter : '').$where_shop.'
'.(isset($this->_group) ? $this->_group.' ' : '').'
'.$having_clause.'
ORDER BY '.(($order_by == $this->identifier) ? 'a.' : '').pSQL($order_by).' '.pSQL($order_way).
ORDER BY '.(($order_by == $this->identifier) ? 'a.' : '').'`'.pSQL($order_by).'` '.pSQL($order_way).
($this->_tmpTableFilter ? ') tmpTable WHERE 1'.$this->_tmpTableFilter : '').
(($use_limit === true) ? ' LIMIT '.(int)$start.','.(int)$limit : '');
@@ -2454,25 +2433,23 @@ class AdminControllerCore extends Controller
$max_size = isset($this->max_image_size) ? $this->max_image_size : 0;
if ($error = ImageManager::validateUpload($_FILES[$name], Tools::getMaxUploadSize($max_size)))
$this->errors[] = $error;
$tmp_name = tempnam(_PS_TMP_IMG_DIR_, 'PS');
if (!$tmp_name)
else if (!($tmp_name = tempnam(_PS_TMP_IMG_DIR_, 'PS')) || !move_uploaded_file($_FILES[$name]['tmp_name'], $tmp_name))
return false;
if (!move_uploaded_file($_FILES[$name]['tmp_name'], $tmp_name))
return false;
// Copy new image
if (!ImageManager::resize($tmp_name, _PS_IMG_DIR_.$dir.$id.'.'.$this->imageType, (int)$width, (int)$height, ($ext ? $ext : $this->imageType)))
$this->errors[] = Tools::displayError('An error occurred while uploading image.');
if (count($this->errors))
return false;
if ($this->afterImageUpload())
else
{
unlink($tmp_name);
return true;
$tmp_name = $_FILES[$name]['tmp_name'];
// Copy new image
if (!ImageManager::resize($tmp_name, _PS_IMG_DIR_.$dir.$id.'.'.$this->imageType, (int)$width, (int)$height, ($ext ? $ext : $this->imageType)))
$this->errors[] = Tools::displayError('An error occurred while uploading image.');
if (count($this->errors))
return false;
if ($this->afterImageUpload())
{
unlink($tmp_name);
return true;
}
return false;
}
return false;
}
return true;
}
@@ -2613,15 +2590,6 @@ class AdminControllerCore extends Controller
*/
public function createTemplate($tpl_name)
{
// Use for module
if (!is_null($this->module))
{
$moduleTemplate = _PS_MODULE_DIR_.$this->module.'/templates/admin/'.$this->override_folder.$tpl_name;
if ($this->viewAccess() && file_exists($moduleTemplate))
return $this->context->smarty->createTemplate($moduleTemplate, $this->context->smarty);
}
// Use override tpl if it exists
// If view access is denied, we want to use the default template that will be used to display an error
if ($this->viewAccess()
@@ -255,9 +255,9 @@ class FrontControllerCore extends Controller
$page_name = $this->page_name;
else if (!empty($this->php_self))
$page_name = $this->php_self;
else if (Tools::getValue('controller') == 'module' && $module_name != '' && new $module_name() instanceof PaymentModule)
else if (0&&Tools::getValue('fc') == 'module' && $module_name != '' && new $module_name() instanceof PaymentModule)
$page_name = 'module-payment-submit';
// Are we in a module
// @retrocompatibility Are we in a module ?
else if (preg_match('#^'.preg_quote($this->context->shop->getPhysicalURI(), '#').'modules/([a-zA-Z0-9_-]+?)/(.*)$#', $_SERVER['REQUEST_URI'], $m))
$page_name = 'module-'.$m[1].'-'.str_replace(array('.php', '/'), array('', '-'), $m[2]);
else
@@ -562,7 +562,7 @@ class FrontControllerCore extends Controller
if (!preg_match('/^'.Tools::pRegexp($canonicalURL, '/').'([&?].*)?$/', $matchUrl))
{
$params = array();
$excludedKey = array('isolang', 'id_lang', 'controller');
$excludedKey = array('isolang', 'id_lang', 'controller', 'fc');
foreach ($_GET as $key => $value)
if (!in_array($key, $excludedKey))
$params[] = $key.'='.$value;
@@ -0,0 +1,68 @@
<?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$
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
/**
* @since 1.5.0
*/
abstract class ModuleAdminControllerCore extends AdminController
{
/**
* @var Module
*/
public $module;
public function __construct()
{
parent::__construct();
$tab = new Tab($this->id);
if (!$tab->module)
throw new PrestaShopException('Admin tab '.get_class($this).' is not a module tab');
$this->module = Module::getInstanceByName($tab->module);
if (!$this->module->id)
throw new PrestaShopException("Module {$tab->module} not found");
}
public function createTemplate($tpl_name)
{
if (file_exists($this->getTemplatePath().$this->override_folder.$tpl_name) && $this->viewAccess())
return $this->context->smarty->createTemplate($this->getTemplatePath().$this->override_folder.$tpl_name, $this->context->smarty);
return parent::createTemplate($tpl_name);
}
/**
* Get path to back office templates for the module
*
* @return string
*/
public function getTemplatePath()
{
return _PS_MODULE_DIR_.$this->module->name.'/views/templates/admin/';
}
}
@@ -0,0 +1,72 @@
<?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$
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
/**
* @since 1.5.0
*/
class ModuleFrontControllerCore extends FrontController
{
/**
* @var Module
*/
public $module;
public function __construct()
{
$this->module = Module::getInstanceByName(Tools::getValue('module'));
if (!$this->module->active)
Tools::redirect('index');
$this->page_name = 'module-'.$this->module->name.'-'.Dispatcher::getInstance()->getController();
parent::__construct();
}
/**
* Assign module template
*
* @param string $template
*/
public function setTemplate($template)
{
if (Tools::file_exists_cache(_PS_THEME_DIR_.'modules/'.$this->module->name.'/'.$template))
$this->template = _PS_THEME_DIR_.'modules/'.$this->module->name.'/'.$template;
elseif (Tools::file_exists_cache($this->getTemplatePath().$template))
$this->template = $this->getTemplatePath().$template;
else
throw new PrestaShopException("Template '$template'' not found");
}
/**
* Get path to front office templates for the module
*
* @return string
*/
public function getTemplatePath()
{
return _PS_MODULE_DIR_.$this->module->name.'/views/templates/front/';
}
}
+6 -2
View File
@@ -79,8 +79,12 @@ class HelperCore
*/
public function createTemplate($tpl_name)
{
// Overrides exists?
if ($this->override_folder && file_exists($this->context->smarty->getTemplateDir(0).'controllers/'.$this->override_folder.$tpl_name))
if ($this->context->controller instanceof ModuleAdminController)
{
if ($this->override_folder && file_exists($this->context->controller->getTemplatePath().$this->override_folder.$tpl_name))
return $this->context->smarty->createTemplate($this->context->controller->getTemplatePath().$this->override_folder.$tpl_name);
}
else if ($this->override_folder && file_exists($this->context->smarty->getTemplateDir(0).'controllers/'.$this->override_folder.$tpl_name))
return $this->context->smarty->createTemplate('controllers/'.$this->override_folder.$tpl_name);
return $this->context->smarty->createTemplate($this->base_folder.$tpl_name);