// Improve flexibility of dispatcher + fix controllers access in BO (only admin controllers are loaded by the dispatcher)

git-svn-id: http://dev.prestashop.com/svn/v1/branches/1.5.x@8764 b9a71923-0436-4b27-9f14-aed3839534dd
This commit is contained in:
rMalie committed 2011-09-26 09:57:00 +00:00
1 parent e98c1cdf5c
commit 6a39d24f05
6 files changed
+104 -63

No files matched your search

+9 -4
View File
@@ -233,6 +233,11 @@ function translate($string)
*/ */
function checkingTab($tab) function checkingTab($tab)
{ {
static $controllers;
if (is_null($controllers))
$controllers = Dispatcher::getControllers(_PS_ADMIN_DIR_.'/tabs/');
$tab = trim($tab); $tab = trim($tab);
if (!Validate::isTabName($tab)) if (!Validate::isTabName($tab))
return false; return false;
@@ -244,10 +249,10 @@ function checkingTab($tab)
echo sprintf(Tools::displayError('Tab %s cannot be found.'),$tab); echo sprintf(Tools::displayError('Tab %s cannot be found.'),$tab);
return false; return false;
} }
if ($row['module'] AND file_exists(_PS_MODULE_DIR_.'/'.$row['module'].'/'.Dispatcher::$controllers[$tab].'.php')) if ($row['module'] AND file_exists(_PS_MODULE_DIR_.'/'.$row['module'].'/'.$controllers[$tab].'.php'))
include_once(_PS_MODULE_DIR_.'/'.$row['module'].'/'.Dispatcher::$controllers[$tab].'.php'); include_once(_PS_MODULE_DIR_.'/'.$row['module'].'/'.$controllers[$tab].'.php');
elseif (file_exists(_PS_ADMIN_DIR_.'/tabs/'.Dispatcher::$controllers[$tab].'.php')) elseif (file_exists(_PS_ADMIN_DIR_.'/tabs/'.$controllers[$tab].'.php'))
include_once(_PS_ADMIN_DIR_.'/tabs/'.Dispatcher::$controllers[$tab].'.php'); include_once(_PS_ADMIN_DIR_.'/tabs/'.$controllers[$tab].'.php');
if (!class_exists($tab, false) OR !$row['id_tab']) if (!class_exists($tab, false) OR !$row['id_tab'])
{ {
echo sprintf(Tools::displayError('Tab file %s cannot be found.'),$tab); echo sprintf(Tools::displayError('Tab file %s cannot be found.'),$tab);
+2 -1
View File
@@ -278,7 +278,8 @@ echo ' </select>
if (empty($tab)) if (empty($tab))
echo '<div class="mainsubtablist" style="display:none"></div>'; echo '<div class="mainsubtablist" style="display:none"></div>';
// This is made to display the subtab list // This is made to display the subtab list
$id_current_tab = (int)(Tab::getIdFromClassName(Dispatcher::$controllers[$tab])); $controllers = Dispatcher::getControllers(_PS_ADMIN_DIR_.'/tabs/');
$id_current_tab = (int)Tab::getIdFromClassName($controllers[$tab]);
$myCurrentTab = new Tab($id_current_tab); $myCurrentTab = new Tab($id_current_tab);
$tabs = Tab::getTabs(Context::getContext()->language->id, 0); $tabs = Tab::getTabs(Context::getContext()->language->id, 0);
$echoLis = ''; $echoLis = '';
+4 -1
View File
@@ -28,5 +28,8 @@
define('_PS_ADMIN_DIR_', getcwd()); define('_PS_ADMIN_DIR_', getcwd());
require(dirname(__FILE__).'/../config/config.inc.php'); require(dirname(__FILE__).'/../config/config.inc.php');
require(dirname(__FILE__).'/functions.php'); require(dirname(__FILE__).'/functions.php');
Dispatcher::getInstance()->dispatch();
Dispatcher::getInstance()->setDefaultController('adminhome');
Dispatcher::getInstance()->setControllerNotFound('adminhome');
Dispatcher::getInstance()->setControllerDirectories(array(_PS_ADMIN_DIR_.'/tabs/', _PS_ADMIN_CONTROLLER_DIR_));
Dispatcher::getInstance()->dispatch();
+18 -18
View File
@@ -1,6 +1,6 @@
<?php <?php
/* /*
* 2007-2011 PrestaShop * 2007-2011 PrestaShop
* *
* NOTICE OF LICENSE * NOTICE OF LICENSE
* *
@@ -92,7 +92,7 @@ class AdminModulesPositions extends AdminTab
if (!$this->_errors && !$module->registerExceptions($id_hook, $exceptions, Context::getContext()->shop->getListOfID())) if (!$this->_errors && !$module->registerExceptions($id_hook, $exceptions, Context::getContext()->shop->getListOfID()))
$this->_errors[] = Tools::displayError('An error occurred while transplanting module to hook.'); $this->_errors[] = Tools::displayError('An error occurred while transplanting module to hook.');
} }
if (!$this->_errors) if (!$this->_errors)
Tools::redirectAdmin(self::$currentIndex.'&conf=16'.($this->displayKey ? '&show_modules='.$this->displayKey : '').'&token='.$this->token); Tools::redirectAdmin(self::$currentIndex.'&conf=16'.($this->displayKey ? '&show_modules='.$this->displayKey : '').'&token='.$this->token);
} }
@@ -100,7 +100,7 @@ class AdminModulesPositions extends AdminTab
else else
$this->_errors[] = Tools::displayError('You do not have permission to add here.'); $this->_errors[] = Tools::displayError('You do not have permission to add here.');
} }
// Edit module from hook // Edit module from hook
elseif (Tools::isSubmit('submitEditGraft')) elseif (Tools::isSubmit('submitEditGraft'))
{ {
@@ -111,7 +111,7 @@ class AdminModulesPositions extends AdminTab
$module = Module::getInstanceById($id_module); $module = Module::getInstanceById($id_module);
$id_hook = (int)(Tools::getValue('id_hook')); $id_hook = (int)(Tools::getValue('id_hook'));
$hook = new Hook($id_hook); $hook = new Hook($id_hook);
if (!$id_module OR !Validate::isLoadedObject($module)) if (!$id_module OR !Validate::isLoadedObject($module))
$this->_errors[] = Tools::displayError('module cannot be loaded'); $this->_errors[] = Tools::displayError('module cannot be loaded');
elseif (!$id_hook OR !Validate::isLoadedObject($hook)) elseif (!$id_hook OR !Validate::isLoadedObject($hook))
@@ -124,19 +124,19 @@ class AdminModulesPositions extends AdminTab
foreach ($exceptions as $id => $exception) foreach ($exceptions as $id => $exception)
{ {
$exception = explode(',', str_replace(' ', '', $exception)); $exception = explode(',', str_replace(' ', '', $exception));
// Check files name // Check files name
foreach ($exception AS $except) foreach ($exception AS $except)
if (!Validate::isFileName($except)) if (!Validate::isFileName($except))
$this->_errors[] = Tools::displayError('No valid value for field exceptions'); $this->_errors[] = Tools::displayError('No valid value for field exceptions');
$exceptions[$id] = $exception; $exceptions[$id] = $exception;
} }
// Add files exceptions // Add files exceptions
if (!$module->editExceptions($id_hook, $exceptions)) if (!$module->editExceptions($id_hook, $exceptions))
$this->_errors[] = Tools::displayError('An error occurred while transplanting module to hook.'); $this->_errors[] = Tools::displayError('An error occurred while transplanting module to hook.');
if (!$this->_errors) if (!$this->_errors)
Tools::redirectAdmin(self::$currentIndex.'&conf=16'.($this->displayKey ? '&show_modules='.$this->displayKey : '').'&token='.$this->token); Tools::redirectAdmin(self::$currentIndex.'&conf=16'.($this->displayKey ? '&show_modules='.$this->displayKey : '').'&token='.$this->token);
} }
@@ -226,7 +226,7 @@ class AdminModulesPositions extends AdminTab
{ {
$admin_dir = dirname($_SERVER['PHP_SELF']); $admin_dir = dirname($_SERVER['PHP_SELF']);
$admin_dir = substr($admin_dir, strrpos($admin_dir,'/') + 1); $admin_dir = substr($admin_dir, strrpos($admin_dir,'/') + 1);
echo ' echo '
<script type="text/javascript" src="../js/jquery/jquery.tablednd_0_5.js"></script> <script type="text/javascript" src="../js/jquery/jquery.tablednd_0_5.js"></script>
<script type="text/javascript"> <script type="text/javascript">
@@ -259,7 +259,7 @@ class AdminModulesPositions extends AdminTab
<br /><br /> <br /><br />
<input type="checkbox" id="hook_position" onclick="autoUrlNoList(\'hook_position\', \''.self::$currentIndex.'&token='.$this->token.'&show_modules='.(int)(Tools::getValue('show_modules')).'&hook_position=\')" '.(Tools::getValue('hook_position') ? 'checked="checked" ' : '').' />&nbsp;<label class="t" for="hook_position">'.$this->l('Display non-positionable hook').'</label> <input type="checkbox" id="hook_position" onclick="autoUrlNoList(\'hook_position\', \''.self::$currentIndex.'&token='.$this->token.'&show_modules='.(int)(Tools::getValue('show_modules')).'&hook_position=\')" '.(Tools::getValue('hook_position') ? 'checked="checked" ' : '').' />&nbsp;<label class="t" for="hook_position">'.$this->l('Display non-positionable hook').'</label>
</form> </form>
<fieldset style="width:250px;float:right"><legend>'.$this->l('Live edit').'</legend>'; <fieldset style="width:250px;float:right"><legend>'.$this->l('Live edit').'</legend>';
if (Shop::isMultiShopActivated() && $this->context->shop->getContextType() != Shop::CONTEXT_SHOP) if (Shop::isMultiShopActivated() && $this->context->shop->getContextType() != Shop::CONTEXT_SHOP)
echo '<p>'.$this->l('You have to select a shop to use live edit').'</p>'; echo '<p>'.$this->l('You have to select a shop to use live edit').'</p>';
@@ -350,7 +350,7 @@ class AdminModulesPositions extends AdminTab
// Check auth for this page // Check auth for this page
if (!$id_module || !$id_hook) if (!$id_module || !$id_hook)
Tools::redirectAdmin(self::$currentIndex . '&token='.$this->token); Tools::redirectAdmin(self::$currentIndex . '&token='.$this->token);
$sql = 'SELECT id_module $sql = 'SELECT id_module
FROM '._DB_PREFIX_.'hook_module FROM '._DB_PREFIX_.'hook_module
WHERE id_module = '.$id_module.' WHERE id_module = '.$id_module.'
@@ -369,7 +369,7 @@ class AdminModulesPositions extends AdminTab
foreach ($exceptsList as $k => $v) foreach ($exceptsList as $k => $v)
if (array_diff($v, $first) || array_diff($first, $v)) if (array_diff($v, $first) || array_diff($first, $v))
$exceptsDiff = true; $exceptsDiff = true;
if (!$exceptsDiff) if (!$exceptsDiff)
$excepts = implode(', ', $first); $excepts = implode(', ', $first);
} }
@@ -411,7 +411,7 @@ class AdminModulesPositions extends AdminTab
echo ' echo '
</select><sup> *</sup> </select><sup> *</sup>
</div>'; </div>';
echo <<<EOF echo <<<EOF
<script type="text/javascript"> <script type="text/javascript">
//<![CDATA //<![CDATA
@@ -423,7 +423,7 @@ class AdminModulesPositions extends AdminTab
if (!r.test(inputValue)) if (!r.test(inputValue))
$('#em_text_'+shopID).val(inputValue + ((inputValue.trim()) ? ', ' : '') + listValue); $('#em_text_'+shopID).val(inputValue + ((inputValue.trim()) ? ', ' : '') + listValue);
} }
function position_exception_remove(shopID) function position_exception_remove(shopID)
{ {
var listValue = $('#em_list_'+shopID).val(); var listValue = $('#em_list_'+shopID).val();
@@ -467,7 +467,7 @@ EOF;
<br /><br /> <br /><br />
</div>'; </div>';
} }
echo '<div class="margin-form"> echo '<div class="margin-form">
'; ';
@@ -484,7 +484,7 @@ EOF;
</fieldset> </fieldset>
</form>'; </form>';
} }
public function displayModuleExceptionList($fileList, $shopID) public function displayModuleExceptionList($fileList, $shopID)
{ {
if (!is_array($fileList)) if (!is_array($fileList))
@@ -494,15 +494,15 @@ EOF;
if ($shopID) if ($shopID)
echo ' ('.Shop::getInstance($shopID)->name.')'; echo ' ('.Shop::getInstance($shopID)->name.')';
echo '<br /><select id="em_list_'.$shopID.'">'; echo '<br /><select id="em_list_'.$shopID.'">';
// @todo do something better with controllers // @todo do something better with controllers
$controllers = Dispatcher::getControllers(); $controllers = Dispatcher::getControllers(_PS_FRONT_CONTROLLER_DIR_);
ksort($controllers); ksort($controllers);
foreach ($controllers as $k => $v) foreach ($controllers as $k => $v)
{ {
echo '<option value="'.$k.'">'.$k.'</option>'; echo '<option value="'.$k.'">'.$k.'</option>';
} }
echo '</select> <input type="button" class="button" value="'.$this->l('Add').'" onclick="position_exception_add('.$shopID.')" /> echo '</select> <input type="button" class="button" value="'.$this->l('Add').'" onclick="position_exception_add('.$shopID.')" />
<input type="button" class="button" value="'.$this->l('Remove').'" onclick="position_exception_remove('.$shopID.')" /><br /><br />'; <input type="button" class="button" value="'.$this->l('Remove').'" onclick="position_exception_remove('.$shopID.')" /><br /><br />';
} }
} }
+69 -39
View File
@@ -36,14 +36,7 @@ class DispatcherCore
public static $instance = null; public static $instance = null;
/** /**
* @var array list of available controllers * @var array List of default routes
*/
public static $controllers;
/**
* List of default routes
*
* @var array
*/ */
public $default_routes = array( public $default_routes = array(
'product_rule' => array( 'product_rule' => array(
@@ -124,40 +117,45 @@ class DispatcherCore
); );
/** /**
* If true, use routes to build URL (mod rewrite must be activated) * @var bool If true, use routes to build URL (mod rewrite must be activated)
*
* @var bool
*/ */
protected $use_routes = false; protected $use_routes = false;
/** /**
* List of loaded routes * @var array List of loaded routes
*
* @var array
*/ */
protected $routes = array(); protected $routes = array();
/** /**
* Current controller name * @var string Current controller name
*
* @var string
*/ */
protected $controller; protected $controller;
/** /**
* Current request uri * @var string Current request uri
*
* @var string
*/ */
protected $request_uri; protected $request_uri;
/** /**
* Store empty route (a route with an empty rule) * @var array Store empty route (a route with an empty rule)
*
* @var array
*/ */
protected $empty_route; protected $empty_route;
/**
* @var string Set default controller, which will be used if http parameter 'controller' is empty
*/
protected $default_controller = 'index';
/**
* @var string Controller to use if found controller doesn't exist
*/
protected $controller_not_found = 'pagenotfound';
/**
* @var array List of controllers where are stored controllers
*/
protected $controller_directories = array();
/** /**
* Get current instance of dispatcher (singleton) * Get current instance of dispatcher (singleton)
* *
@@ -175,6 +173,8 @@ class DispatcherCore
*/ */
protected function __construct() protected function __construct()
{ {
$this->setDefaultController('index');
$this->setControllerDirectories(_PS_FRONT_CONTROLLER_DIR_);
$this->use_routes = (bool)Configuration::get('PS_REWRITING_SETTINGS'); $this->use_routes = (bool)Configuration::get('PS_REWRITING_SETTINGS');
$this->loadRoutes(); $this->loadRoutes();
@@ -185,6 +185,38 @@ class DispatcherCore
$this->request_uri = $_SERVER['HTTP_X_REWRITE_URL']; $this->request_uri = $_SERVER['HTTP_X_REWRITE_URL'];
} }
/**
* Set default controller, which will be used if http parameter 'controller' is empty
*
* @param string $controller
*/
public function setDefaultController($controller)
{
$this->default_controller = $controller;
}
/**
* Controller to use if found controller doesn't exist
*
* @var string $controller
*/
public function setControllerNotFound($controller)
{
$this->controller_not_found = $controller;
}
/**
* Set list of controllers where are stored controllers
*
* @param mixed A directory, or an array of directory
*/
public function setControllerDirectories($dir)
{
if (!is_array($dir))
$dir = array($dir);
$this->controller_directories = $dir;
}
/** /**
* Find the controller and instantiate it * Find the controller and instantiate it
*/ */
@@ -202,20 +234,20 @@ class DispatcherCore
// Get current controller and list of controllers // Get current controller and list of controllers
$this->getController(); $this->getController();
$controllers = Dispatcher::getControllers(); $controllers = Dispatcher::getControllers($this->controller_directories);
if (!$this->controller) if (!$this->controller)
$this->controller = (defined('_PS_ADMIN_DIR_')) ? 'adminhome' : 'index'; $this->controller = (defined('_PS_ADMIN_DIR_')) ? 'adminhome' : 'index';
// For retrocompatibility with admin/tabs/ old system // For retrocompatibility with admin/tabs/ old system
if (defined('_PS_ADMIN_DIR_') && file_exists(_PS_ADMIN_DIR_.'/tabs/'.$controllers[$this->controller].'.php')) if (isset($controllers[$this->controller]) && defined('_PS_ADMIN_DIR_') && file_exists(_PS_ADMIN_DIR_.'/tabs/'.$controllers[$this->controller].'.php'))
{ {
require_once(_PS_ADMIN_DIR_.'/functions.php'); require_once(_PS_ADMIN_DIR_.'/functions.php');
runAdminTab(); runAdminTab();
return; return;
} }
else if (!isset($controllers[$this->controller])) else if (!isset($controllers[$this->controller]))
$this->controller = 'pagenotfound'; $this->controller = $this->controller_not_found;
// Instantiate controller // Instantiate controller
Controller::getController($controllers[$this->controller])->run(); Controller::getController($controllers[$this->controller])->run();
@@ -446,17 +478,17 @@ class DispatcherCore
/** /**
* Get list of all available controllers * Get list of all available controllers
* *
* @var mixed $dirs
* @return array * @return array
*/ */
public static function getControllers() public static function getControllers($dirs)
{ {
if (self::$controllers) if (!is_array($dirs))
return self::$controllers; $dirs = array($dirs);
$controllers = array(); $controllers = array();
if (defined('_PS_ADMIN_DIR_')) foreach ($dirs as $dir)
$controllers = array_merge($controllers, Dispatcher::getControllersInDirectory(_PS_ADMIN_DIR_.'/tabs/', '')); $controllers = array_merge($controllers, Dispatcher::getControllersInDirectory($dir));
$controllers = array_merge($controllers, Dispatcher::getControllersInDirectory(_PS_CONTROLLER_DIR_));
// Add default controllers // Add default controllers
$controllers['index'] = 'IndexController'; $controllers['index'] = 'IndexController';
@@ -465,18 +497,16 @@ class DispatcherCore
if (isset($controllers['compare'])) if (isset($controllers['compare']))
$controllers['productscomparison'] = $controllers['compare']; $controllers['productscomparison'] = $controllers['compare'];
self::$controllers = $controllers; return $controllers;
return self::$controllers;
} }
/** /**
* Get list of available controllers from the specified dir * Get list of available controllers from the specified dir
* *
* @param string dir directory to scan (recursively) * @param string dir directory to scan (recursively)
* @param filename suffix (without .php extension). Others files will be ignored.
* @return array * @return array
*/ */
public static function getControllersInDirectory($dir, $suffix = 'Controller') public static function getControllersInDirectory($dir)
{ {
$controllers = array(); $controllers = array();
$controller_files = scandir($dir); $controller_files = scandir($dir);
@@ -486,10 +516,10 @@ class DispatcherCore
{ {
if (is_dir($dir.$controller_filename)) if (is_dir($dir.$controller_filename))
$controllers += Dispatcher::getControllersInDirectory($dir.$controller_filename.DIRECTORY_SEPARATOR); $controllers += Dispatcher::getControllersInDirectory($dir.$controller_filename.DIRECTORY_SEPARATOR);
else if (substr($controller_filename, - (strlen($suffix) + 4), - 4) == $suffix) else if ($controller_filename != 'index.php')
{ {
$subdir = str_replace(_PS_CONTROLLER_DIR_, '', $dir); $key = str_replace(array('controller.php', '.php'), array('', ''), strtolower($controller_filename));
$controllers[strtolower(substr($controller_filename, 0, - (strlen($suffix) + 4)))] = basename($controller_filename, '.php'); $controllers[$key] = basename($controller_filename, '.php');
} }
} }
} }
+2
View File
@@ -71,6 +71,8 @@ define('_MODULE_DIR_', __PS_BASE_URI__.'modules/');
define('_PS_ROOT_DIR_', realpath($currentDir.'/..')); define('_PS_ROOT_DIR_', realpath($currentDir.'/..'));
define('_PS_CLASS_DIR_', _PS_ROOT_DIR_.'/classes/'); define('_PS_CLASS_DIR_', _PS_ROOT_DIR_.'/classes/');
define('_PS_CONTROLLER_DIR_', _PS_ROOT_DIR_.'/controllers/'); define('_PS_CONTROLLER_DIR_', _PS_ROOT_DIR_.'/controllers/');
define('_PS_FRONT_CONTROLLER_DIR_', _PS_ROOT_DIR_.'/controllers/front/');
define('_PS_ADMIN_CONTROLLER_DIR_', _PS_ROOT_DIR_.'/controllers/admin/');
define('_PS_TRANSLATIONS_DIR_', _PS_ROOT_DIR_.'/translations/'); define('_PS_TRANSLATIONS_DIR_', _PS_ROOT_DIR_.'/translations/');
define('_PS_DOWNLOAD_DIR_', _PS_ROOT_DIR_.'/download/'); define('_PS_DOWNLOAD_DIR_', _PS_ROOT_DIR_.'/download/');
define('_PS_MAIL_DIR_', _PS_ROOT_DIR_.'/mails/'); define('_PS_MAIL_DIR_', _PS_ROOT_DIR_.'/mails/');