diff options
| author | 2017-02-15 14:14:03 +0100 | |
|---|---|---|
| committer | 2017-02-15 14:14:03 +0100 | |
| commit | 5a1bb1393b4496eb35a2ffb3cc63d41c9dc1e2e5 (patch) | |
| tree | 67028e45792c575c25c92616633f64cc7a4a13eb /lib/Minz | |
| parent | 7e949d50320317b5c3b5a2da2bdaf324e794b2f7 (diff) | |
| parent | 5f637bd816b7323885bfe1751a1724ee59a822f6 (diff) | |
Merge remote-tracking branch 'FreshRSS/master'
Diffstat (limited to 'lib/Minz')
| -rw-r--r-- | lib/Minz/ActionController.php | 6 | ||||
| -rw-r--r-- | lib/Minz/BadConfigurationException.php | 9 | ||||
| -rw-r--r-- | lib/Minz/Cache.php | 116 | ||||
| -rw-r--r-- | lib/Minz/Configuration.php | 474 | ||||
| -rw-r--r-- | lib/Minz/ConfigurationException.php | 8 | ||||
| -rw-r--r-- | lib/Minz/ConfigurationNamespaceException.php | 4 | ||||
| -rw-r--r-- | lib/Minz/ConfigurationParamException.php | 4 | ||||
| -rw-r--r-- | lib/Minz/Dispatcher.php | 159 | ||||
| -rw-r--r-- | lib/Minz/Error.php | 40 | ||||
| -rw-r--r-- | lib/Minz/Extension.php | 208 | ||||
| -rw-r--r-- | lib/Minz/ExtensionException.php | 15 | ||||
| -rw-r--r-- | lib/Minz/ExtensionManager.php | 301 | ||||
| -rw-r--r-- | lib/Minz/FrontController.php | 89 | ||||
| -rw-r--r-- | lib/Minz/Helper.php | 17 | ||||
| -rw-r--r-- | lib/Minz/Log.php | 38 | ||||
| -rw-r--r-- | lib/Minz/ModelPdo.php | 142 | ||||
| -rw-r--r-- | lib/Minz/Request.php | 191 | ||||
| -rw-r--r-- | lib/Minz/Response.php | 60 | ||||
| -rw-r--r-- | lib/Minz/RouteNotFoundException.php | 16 | ||||
| -rw-r--r-- | lib/Minz/Router.php | 209 | ||||
| -rw-r--r-- | lib/Minz/Session.php | 81 | ||||
| -rw-r--r-- | lib/Minz/Translate.php | 241 | ||||
| -rw-r--r-- | lib/Minz/Url.php | 72 | ||||
| -rw-r--r-- | lib/Minz/View.php | 102 |
24 files changed, 1486 insertions, 1116 deletions
diff --git a/lib/Minz/ActionController.php b/lib/Minz/ActionController.php index 409d9611f..b47c54554 100644 --- a/lib/Minz/ActionController.php +++ b/lib/Minz/ActionController.php @@ -8,16 +8,12 @@ * La classe ActionController représente le contrôleur de l'application */ class Minz_ActionController { - protected $router; protected $view; /** * Constructeur - * @param $controller nom du controller - * @param $action nom de l'action à lancer */ - public function __construct ($router) { - $this->router = $router; + public function __construct () { $this->view = new Minz_View (); $this->view->attributeParams (); } diff --git a/lib/Minz/BadConfigurationException.php b/lib/Minz/BadConfigurationException.php deleted file mode 100644 index a7b77d687..000000000 --- a/lib/Minz/BadConfigurationException.php +++ /dev/null @@ -1,9 +0,0 @@ -<?php -class Minz_BadConfigurationException extends Minz_Exception { - public function __construct ($part_missing, $code = self::ERROR) { - $message = '`' . $part_missing - . '` in the configuration file is missing or is misconfigured'; - - parent::__construct ($message, $code); - } -} diff --git a/lib/Minz/Cache.php b/lib/Minz/Cache.php deleted file mode 100644 index fcb627eb2..000000000 --- a/lib/Minz/Cache.php +++ /dev/null @@ -1,116 +0,0 @@ -<?php -/** - * MINZ - Copyright 2011 Marien Fressinaud - * Sous licence AGPL3 <http://www.gnu.org/licenses/> -*/ - -/** - * La classe Cache permet de gérer facilement les pages en cache - */ -class Minz_Cache { - /** - * $expire timestamp auquel expire le cache de $url - */ - private $expire = 0; - - /** - * $file est le nom du fichier de cache - */ - private $file = ''; - - /** - * $enabled permet de déterminer si le cache est activé - */ - private static $enabled = true; - - /** - * Constructeur - */ - public function __construct () { - $this->_fileName (); - $this->_expire (); - } - - /** - * Setteurs - */ - public function _fileName () { - $file = md5 (Minz_Request::getURI ()); - - $this->file = CACHE_PATH . '/'.$file; - } - - public function _expire () { - if ($this->exist ()) { - $this->expire = filemtime ($this->file) - + Minz_Configuration::delayCache (); - } - } - - /** - * Permet de savoir si le cache est activé - * @return true si activé, false sinon - */ - public static function isEnabled () { - return Minz_Configuration::cacheEnabled () && self::$enabled; - } - - /** - * Active / désactive le cache - */ - public static function switchOn () { - self::$enabled = true; - } - public static function switchOff () { - self::$enabled = false; - } - - /** - * Détermine si le cache de $url a expiré ou non - * @return true si il a expiré, false sinon - */ - public function expired () { - return time () > $this->expire; - } - - /** - * Affiche le contenu du cache - * @print le code html du cache - */ - public function render () { - if ($this->exist ()) { - include ($this->file); - } - } - - /** - * Enregistre $html en cache - * @param $html le html à mettre en cache - */ - public function cache ($html) { - file_put_contents ($this->file, $html); - } - - /** - * Permet de savoir si le cache existe - * @return true si il existe, false sinon - */ - public function exist () { - return file_exists ($this->file); - } - - /** - * Nettoie le cache en supprimant tous les fichiers - */ - public static function clean () { - $files = opendir (CACHE_PATH); - - while ($fic = readdir ($files)) { - if ($fic != '.' && $fic != '..') { - unlink (CACHE_PATH.'/'.$fic); - } - } - - closedir ($files); - } -} diff --git a/lib/Minz/Configuration.php b/lib/Minz/Configuration.php index b3de9e39e..d695d4a53 100644 --- a/lib/Minz/Configuration.php +++ b/lib/Minz/Configuration.php @@ -1,357 +1,215 @@ <?php -/** - * MINZ - Copyright 2011 Marien Fressinaud - * Sous licence AGPL3 <http://www.gnu.org/licenses/> -*/ /** - * La classe Configuration permet de gérer la configuration de l'application + * Manage configuration for the application. */ class Minz_Configuration { - const CONF_PATH_NAME = '/config.php'; - /** - * VERSION est la version actuelle de MINZ + * The list of configurations. */ - const VERSION = '1.3.1.freshrss'; // version spéciale FreshRSS + private static $config_list = array(); /** - * valeurs possibles pour l'"environment" - * SILENT rend l'application muette (pas de log) - * PRODUCTION est recommandée pour une appli en production - * (log les erreurs critiques) - * DEVELOPMENT log toutes les erreurs + * Add a new configuration to the list of configuration. + * + * @param $namespace the name of the current configuration + * @param $config_filename the filename of the configuration + * @param $default_filename a filename containing default values for the configuration + * @param $configuration_setter an optional helper to set values in configuration */ - const SILENT = 0; - const PRODUCTION = 1; - const DEVELOPMENT = 2; + public static function register($namespace, $config_filename, $default_filename = null, + $configuration_setter = null) { + self::$config_list[$namespace] = new Minz_Configuration( + $namespace, $config_filename, $default_filename, $configuration_setter + ); + } /** - * définition des variables de configuration - * $salt une chaîne de caractères aléatoires (obligatoire) - * $environment gère le niveau d'affichage pour log et erreurs - * $use_url_rewriting indique si on utilise l'url_rewriting - * $base_url le chemin de base pour accéder à l'application - * $title le nom de l'application - * $language la langue par défaut de l'application - * $cacheEnabled permet de savoir si le cache doit être activé - * $delayCache la limite de cache - * $db paramètres pour la base de données (tableau) - * - host le serveur de la base - * - user nom d'utilisateur - * - password mot de passe de l'utilisateur - * - base le nom de la base de données + * Parse a file and return its data. + * + * If the file does not contain a valid PHP code returning an array, an + * empty array is returned anyway. + * + * @param $filename the name of the file to parse. + * @return an array of values + * @throws Minz_FileNotExistException if the file does not exist. */ - private static $salt = ''; - private static $environment = Minz_Configuration::PRODUCTION; - private static $base_url = ''; - private static $use_url_rewriting = false; - private static $title = ''; - private static $language = 'en'; - private static $cache_enabled = false; - private static $delay_cache = 3600; - private static $default_user = ''; - private static $allow_anonymous = false; - private static $allow_anonymous_refresh = false; - private static $auth_type = 'none'; - - private static $db = array ( - 'type' => 'mysql', - 'host' => '', - 'user' => '', - 'password' => '', - 'base' => '', - 'prefix' => '', - ); + public static function load($filename) { + if (!file_exists($filename)) { + throw new Minz_FileNotExistException($filename); + } - /* - * Getteurs - */ - public static function salt () { - return self::$salt; + $data = include($filename); + if (is_array($data)) { + return $data; + } else { + return array(); + } } - public static function environment ($str = false) { - $env = self::$environment; - if ($str) { - switch (self::$environment) { - case self::SILENT: - $env = 'silent'; - break; - case self::DEVELOPMENT: - $env = 'development'; - break; - case self::PRODUCTION: - default: - $env = 'production'; - } + /** + * Return the configuration related to a given namespace. + * + * @param $namespace the name of the configuration to get. + * @return a Minz_Configuration object + * @throws Minz_ConfigurationNamespaceException if the namespace does not exist. + */ + public static function get($namespace) { + if (!isset(self::$config_list[$namespace])) { + throw new Minz_ConfigurationNamespaceException( + $namespace . ' namespace does not exist' + ); } - return $env; - } - public static function baseUrl () { - return self::$base_url; - } - public static function useUrlRewriting () { - return self::$use_url_rewriting; - } - public static function title () { - return self::$title; - } - public static function language () { - return self::$language; - } - public static function cacheEnabled () { - return self::$cache_enabled; - } - public static function delayCache () { - return self::$delay_cache; - } - public static function dataBase () { - return self::$db; - } - public static function defaultUser () { - return self::$default_user; - } - public static function isAdmin($currentUser) { - return $currentUser === self::$default_user; - } - public static function allowAnonymous() { - return self::$allow_anonymous; - } - public static function allowAnonymousRefresh() { - return self::$allow_anonymous_refresh; - } - public static function authType() { - return self::$auth_type; - } - public static function needsLogin() { - return self::$auth_type !== 'none'; - } - public static function canLogIn() { - return self::$auth_type === 'form' || self::$auth_type === 'persona'; + return self::$config_list[$namespace]; } - public static function _allowAnonymous($allow = false) { - self::$allow_anonymous = ((bool)$allow) && self::canLogIn(); - } - public static function _allowAnonymousRefresh($allow = false) { - self::$allow_anonymous_refresh = ((bool)$allow) && self::allowAnonymous(); + /** + * The namespace of the current configuration. + */ + private $namespace = ''; + + /** + * The filename for the current configuration. + */ + private $config_filename = ''; + + /** + * The filename for the current default values, null by default. + */ + private $default_filename = null; + + /** + * The configuration values, an empty array by default. + */ + private $data = array(); + + /** + * An object which help to set good values in configuration. + */ + private $configuration_setter = null; + + public function removeExtension($ext_name) { + self::$extensions_enabled = array_diff( + self::$extensions_enabled, + array($ext_name) + ); } - public static function _authType($value) { - $value = strtolower($value); - switch ($value) { - case 'form': - case 'http_auth': - case 'persona': - case 'none': - self::$auth_type = $value; - break; + public function addExtension($ext_name) { + $found = array_search($ext_name, self::$extensions_enabled) !== false; + if (!$found) { + self::$extensions_enabled[] = $ext_name; } - self::_allowAnonymous(self::$allow_anonymous); } /** - * Initialise les variables de configuration - * @exception Minz_FileNotExistException si le CONF_PATH_NAME n'existe pas - * @exception Minz_BadConfigurationException si CONF_PATH_NAME mal formaté + * Create a new Minz_Configuration object. + * + * @param $namespace the name of the current configuration. + * @param $config_filename the file containing configuration values. + * @param $default_filename the file containing default values, null by default. + * @param $configuration_setter an optional helper to set values in configuration */ - public static function init () { + private function __construct($namespace, $config_filename, $default_filename = null, + $configuration_setter = null) { + $this->namespace = $namespace; + $this->config_filename = $config_filename; + $this->default_filename = $default_filename; + $this->_configurationSetter($configuration_setter); + + if (!is_null($this->default_filename)) { + $this->data = self::load($this->default_filename); + } + try { - self::parseFile (); - self::setReporting (); + $this->data = array_replace_recursive( + $this->data, self::load($this->config_filename) + ); } catch (Minz_FileNotExistException $e) { - throw $e; - } catch (Minz_BadConfigurationException $e) { - throw $e; + if (is_null($this->default_filename)) { + throw $e; + } } } - public static function writeFile() { - $ini_array = array( - 'general' => array( - 'environment' => self::environment(true), - 'use_url_rewriting' => self::$use_url_rewriting, - 'salt' => self::$salt, - 'base_url' => self::$base_url, - 'title' => self::$title, - 'default_user' => self::$default_user, - 'allow_anonymous' => self::$allow_anonymous, - 'allow_anonymous_refresh' => self::$allow_anonymous_refresh, - 'auth_type' => self::$auth_type, - ), - 'db' => self::$db, - ); - @rename(DATA_PATH . self::CONF_PATH_NAME, DATA_PATH . self::CONF_PATH_NAME . '.bak.php'); - $result = file_put_contents(DATA_PATH . self::CONF_PATH_NAME, "<?php\n return " . var_export($ini_array, true) . ';'); - if (function_exists('opcache_invalidate')) { - opcache_invalidate(DATA_PATH . self::CONF_PATH_NAME); //Clear PHP 5.5+ cache for include + /** + * Set a configuration setter for the current configuration. + * @param $configuration_setter the setter to call when modifying data. It + * must implement an handle($key, $value) method. + */ + public function _configurationSetter($configuration_setter) { + if (is_callable(array($configuration_setter, 'handle'))) { + $this->configuration_setter = $configuration_setter; } - return (bool)$result; } /** - * Parse un fichier de configuration - * @exception Minz_PermissionDeniedException si le CONF_PATH_NAME n'est pas accessible - * @exception Minz_BadConfigurationException si CONF_PATH_NAME mal formaté + * Return the value of the given param. + * + * @param $key the name of the param. + * @param $default default value to return if key does not exist. + * @return the value corresponding to the key. + * @throws Minz_ConfigurationParamException if the param does not exist */ - private static function parseFile () { - $ini_array = include(DATA_PATH . self::CONF_PATH_NAME); - - if (!is_array($ini_array)) { - throw new Minz_PermissionDeniedException ( - DATA_PATH . self::CONF_PATH_NAME, - Minz_Exception::ERROR - ); + public function param($key, $default = null) { + if (isset($this->data[$key])) { + return $this->data[$key]; + } elseif (!is_null($default)) { + return $default; + } else { + Minz_Log::warning($key . ' does not exist in configuration'); + return null; } + } - // [general] est obligatoire - if (!isset ($ini_array['general'])) { - throw new Minz_BadConfigurationException ( - '[general]', - Minz_Exception::ERROR - ); - } - $general = $ini_array['general']; + /** + * A wrapper for param(). + */ + public function __get($key) { + return $this->param($key); + } - // salt est obligatoire - if (!isset ($general['salt'])) { - if (isset($general['sel_application'])) { //v0.6 - $general['salt'] = $general['sel_application']; - } else { - throw new Minz_BadConfigurationException ( - 'salt', - Minz_Exception::ERROR - ); - } + /** + * Set or remove a param. + * + * @param $key the param name to set. + * @param $value the value to set. If null, the key is removed from the configuration. + */ + public function _param($key, $value = null) { + if (!is_null($this->configuration_setter) && $this->configuration_setter->support($key)) { + $this->configuration_setter->handle($this->data, $key, $value); + } elseif (isset($this->data[$key]) && is_null($value)) { + unset($this->data[$key]); + } elseif (!is_null($value)) { + $this->data[$key] = $value; } - self::$salt = $general['salt']; + } - if (isset ($general['environment'])) { - switch ($general['environment']) { - case 'silent': - self::$environment = Minz_Configuration::SILENT; - break; - case 'development': - self::$environment = Minz_Configuration::DEVELOPMENT; - break; - case 'production': - self::$environment = Minz_Configuration::PRODUCTION; - break; - default: - if ($general['environment'] >= 0 && - $general['environment'] <= 2) { - // fallback 0.7-beta - self::$environment = $general['environment']; - } else { - throw new Minz_BadConfigurationException ( - 'environment', - Minz_Exception::ERROR - ); - } - } + /** + * A wrapper for _param(). + */ + public function __set($key, $value) { + $this->_param($key, $value); + } - } - if (isset ($general['base_url'])) { - self::$base_url = $general['base_url']; - } - if (isset ($general['use_url_rewriting'])) { - self::$use_url_rewriting = $general['use_url_rewriting']; - } + /** + * Save the current configuration in the configuration file. + */ + public function save() { + $back_filename = $this->config_filename . '.bak.php'; + @rename($this->config_filename, $back_filename); - if (isset ($general['title'])) { - self::$title = $general['title']; - } - if (isset ($general['language'])) { - self::$language = $general['language']; - } - if (isset ($general['cache_enabled'])) { - self::$cache_enabled = $general['cache_enabled']; - if (CACHE_PATH === false && self::$cache_enabled) { - throw new FileNotExistException ( - 'CACHE_PATH', - Minz_Exception::ERROR - ); - } + if (file_put_contents($this->config_filename, + "<?php\nreturn " . var_export($this->data, true) . ';', + LOCK_EX) === false) { + return false; } - if (isset ($general['delay_cache'])) { - self::$delay_cache = inval($general['delay_cache']); - } - if (isset ($general['default_user'])) { - self::$default_user = $general['default_user']; - } - if (isset ($general['auth_type'])) { - self::_authType($general['auth_type']); - } - if (isset ($general['allow_anonymous'])) { - self::$allow_anonymous = ( - ((bool)($general['allow_anonymous'])) && - ($general['allow_anonymous'] !== 'no') - ); - } - if (isset ($general['allow_anonymous_refresh'])) { - self::$allow_anonymous_refresh = ( - ((bool)($general['allow_anonymous_refresh'])) && - ($general['allow_anonymous_refresh'] !== 'no') - ); - } - - // Base de données - if (isset ($ini_array['db'])) { - $db = $ini_array['db']; - if (empty($db['host'])) { - throw new Minz_BadConfigurationException ( - 'host', - Minz_Exception::ERROR - ); - } - if (empty($db['user'])) { - throw new Minz_BadConfigurationException ( - 'user', - Minz_Exception::ERROR - ); - } - if (!isset ($db['password'])) { - throw new Minz_BadConfigurationException ( - 'password', - Minz_Exception::ERROR - ); - } - if (empty($db['base'])) { - throw new Minz_BadConfigurationException ( - 'base', - Minz_Exception::ERROR - ); - } - if (!empty($db['type'])) { - self::$db['type'] = $db['type']; - } - self::$db['host'] = $db['host']; - self::$db['user'] = $db['user']; - self::$db['password'] = $db['password']; - self::$db['base'] = $db['base']; - if (isset($db['prefix'])) { - self::$db['prefix'] = $db['prefix']; - } + // Clear PHP 5.5+ cache for include + if (function_exists('opcache_invalidate')) { + opcache_invalidate($this->config_filename); } - } - private static function setReporting() { - switch (self::$environment) { - case self::PRODUCTION: - error_reporting(E_ALL); - ini_set('display_errors','Off'); - ini_set('log_errors', 'On'); - break; - case self::DEVELOPMENT: - error_reporting(E_ALL); - ini_set('display_errors','On'); - ini_set('log_errors', 'On'); - break; - case self::SILENT: - error_reporting(0); - break; - } + return true; } } diff --git a/lib/Minz/ConfigurationException.php b/lib/Minz/ConfigurationException.php new file mode 100644 index 000000000..f294c3341 --- /dev/null +++ b/lib/Minz/ConfigurationException.php @@ -0,0 +1,8 @@ +<?php + +class Minz_ConfigurationException extends Minz_Exception { + public function __construct($error, $code = self::ERROR) { + $message = 'Configuration error: ' . $error; + parent::__construct($message, $code); + } +} diff --git a/lib/Minz/ConfigurationNamespaceException.php b/lib/Minz/ConfigurationNamespaceException.php new file mode 100644 index 000000000..f4278c5d6 --- /dev/null +++ b/lib/Minz/ConfigurationNamespaceException.php @@ -0,0 +1,4 @@ +<?php + +class Minz_ConfigurationNamespaceException extends Minz_ConfigurationException { +} diff --git a/lib/Minz/ConfigurationParamException.php b/lib/Minz/ConfigurationParamException.php new file mode 100644 index 000000000..eac977935 --- /dev/null +++ b/lib/Minz/ConfigurationParamException.php @@ -0,0 +1,4 @@ +<?php + +class Minz_ConfigurationParamException extends Minz_ConfigurationException { +} diff --git a/lib/Minz/Dispatcher.php b/lib/Minz/Dispatcher.php index 71dfe8ac6..125ce5757 100644 --- a/lib/Minz/Dispatcher.php +++ b/lib/Minz/Dispatcher.php @@ -14,97 +14,72 @@ class Minz_Dispatcher { /* singleton */ private static $instance = null; + private static $needsReset; + private static $registrations = array(); - private $router; private $controller; /** * Récupère l'instance du Dispatcher */ - public static function getInstance ($router) { + public static function getInstance () { if (self::$instance === null) { - self::$instance = new Minz_Dispatcher ($router); + self::$instance = new Minz_Dispatcher (); } return self::$instance; } /** - * Constructeur - */ - private function __construct ($router) { - $this->router = $router; - } - - /** * Lance le controller indiqué dans Request * Remplit le body de Response à partir de la Vue * @exception Minz_Exception */ - public function run ($ob = true) { - $cache = new Minz_Cache(); - // Le ob_start est dupliqué : sans ça il y a un bug sous Firefox - // ici on l'appelle avec 'ob_gzhandler', après sans. - // Vraisemblablement la compression fonctionne mais c'est sale - // J'ignore les effets de bord :( - if ($ob) { - ob_start ('ob_gzhandler'); - } + public function run () { + do { + self::$needsReset = false; - if (Minz_Cache::isEnabled () && !$cache->expired ()) { - if ($ob) { - ob_start (); - } - $cache->render (); - if ($ob) { - $text = ob_get_clean(); - } - } else { - $text = ''; //TODO: Clean this code - while (Minz_Request::$reseted) { - Minz_Request::$reseted = false; - - try { - $this->createController ('FreshRSS_' . Minz_Request::controllerName () . '_Controller'); - $this->controller->init (); - $this->controller->firstAction (); + try { + $this->createController (Minz_Request::controllerName ()); + $this->controller->init (); + $this->controller->firstAction (); + if (!self::$needsReset) { $this->launchAction ( Minz_Request::actionName () . 'Action' ); - $this->controller->lastAction (); - - if (!Minz_Request::$reseted) { - if ($ob) { - ob_start (); - } - $this->controller->view ()->build (); - if ($ob) { - $text = ob_get_clean(); - } - } - } catch (Minz_Exception $e) { - throw $e; } - } + $this->controller->lastAction (); - if (Minz_Cache::isEnabled ()) { - $cache->cache ($text); + if (!self::$needsReset) { + $this->controller->view ()->build (); + } + } catch (Minz_Exception $e) { + throw $e; } - } + } while (self::$needsReset); + } - Minz_Response::setBody ($text); + /** + * Informe le contrôleur qu'il doit recommancer car la requête a été modifiée + */ + public static function reset() { + self::$needsReset = true; } /** * Instancie le Controller - * @param $controller_name le nom du controller à instancier + * @param $base_name le nom du controller à instancier * @exception ControllerNotExistException le controller n'existe pas * @exception ControllerNotActionControllerException controller n'est * > pas une instance de ActionController */ - private function createController ($controller_name) { - $filename = APP_PATH . self::CONTROLLERS_PATH_NAME . '/' - . $controller_name . '.php'; + private function createController ($base_name) { + if (self::isRegistered($base_name)) { + self::loadController($base_name); + $controller_name = 'FreshExtension_' . $base_name . '_Controller'; + } else { + $controller_name = 'FreshRSS_' . $base_name . '_Controller'; + } if (!class_exists ($controller_name)) { throw new Minz_ControllerNotExistException ( @@ -112,7 +87,7 @@ class Minz_Dispatcher { Minz_Exception::ERROR ); } - $this->controller = new $controller_name ($this->router); + $this->controller = new $controller_name (); if (! ($this->controller instanceof Minz_ActionController)) { throw new Minz_ControllerNotActionControllerException ( @@ -129,21 +104,57 @@ class Minz_Dispatcher { * le controller */ private function launchAction ($action_name) { - if (!Minz_Request::$reseted) { - if (!is_callable (array ( - $this->controller, - $action_name - ))) { - throw new Minz_ActionException ( - get_class ($this->controller), - $action_name, - Minz_Exception::ERROR - ); - } - call_user_func (array ( - $this->controller, - $action_name - )); + if (!is_callable (array ( + $this->controller, + $action_name + ))) { + throw new Minz_ActionException ( + get_class ($this->controller), + $action_name, + Minz_Exception::ERROR + ); } + call_user_func (array ( + $this->controller, + $action_name + )); + } + + /** + * Register a controller file. + * + * @param $base_name the base name of the controller (i.e. ./?c=<base_name>) + * @param $base_path the base path where we should look into to find info. + */ + public static function registerController($base_name, $base_path) { + if (!self::isRegistered($base_name)) { + self::$registrations[$base_name] = $base_path; + } + } + + /** + * Return if a controller is registered. + * + * @param $base_name the base name of the controller. + * @return true if the controller has been registered, false else. + */ + public static function isRegistered($base_name) { + return isset(self::$registrations[$base_name]); + } + + /** + * Load a controller file (include). + * + * @param $base_name the base name of the controller. + */ + private static function loadController($base_name) { + $base_path = self::$registrations[$base_name]; + $controller_filename = $base_path . '/controllers/' . $base_name . 'Controller.php'; + include_once $controller_filename; + } + + private static function setViewPath($controller, $base_name) { + $base_path = self::$registrations[$base_name]; + $controller->view()->setBasePathname($base_path); } } diff --git a/lib/Minz/Error.php b/lib/Minz/Error.php index 337ab6c0a..3e4a3e8f3 100644 --- a/lib/Minz/Error.php +++ b/lib/Minz/Error.php @@ -19,41 +19,28 @@ class Minz_Error { * > $logs['notice'] * @param $redirect indique s'il faut forcer la redirection (les logs ne seront pas transmis) */ - public static function error ($code = 404, $logs = array (), $redirect = false) { + public static function error ($code = 404, $logs = array (), $redirect = true) { $logs = self::processLogs ($logs); $error_filename = APP_PATH . '/Controllers/errorController.php'; if (file_exists ($error_filename)) { - $params = array ( - 'code' => $code, - 'logs' => $logs - ); + Minz_Session::_param('error_code', $code); + Minz_Session::_param('error_logs', $logs); - Minz_Response::setHeader ($code); - if ($redirect) { - Minz_Request::forward (array ( - 'c' => 'error' - ), true); - } else { - Minz_Request::forward (array ( - 'c' => 'error', - 'params' => $params - ), false); - } + Minz_Request::forward (array ( + 'c' => 'error' + ), $redirect); } else { - $text = '<h1>An error occured</h1>'."\n"; + echo '<h1>An error occured</h1>' . "\n"; if (!empty ($logs)) { - $text .= '<ul>'."\n"; + echo '<ul>' . "\n"; foreach ($logs as $log) { - $text .= '<li>' . $log . '</li>'."\n"; + echo '<li>' . $log . '</li>' . "\n"; } - $text .= '</ul>'."\n"; + echo '</ul>' . "\n"; } - Minz_Response::setHeader ($code); - Minz_Response::setBody ($text); - Minz_Response::send (); exit (); } } @@ -66,7 +53,8 @@ class Minz_Error { * > en fonction de l'environment */ private static function processLogs ($logs) { - $env = Minz_Configuration::environment (); + $conf = Minz_Configuration::get('system'); + $env = $conf->environment; $logs_ok = array (); $error = array (); $warning = array (); @@ -82,10 +70,10 @@ class Minz_Error { $notice = $logs['notice']; } - if ($env == Minz_Configuration::PRODUCTION) { + if ($env == 'production') { $logs_ok = $error; } - if ($env == Minz_Configuration::DEVELOPMENT) { + if ($env == 'development') { $logs_ok = array_merge ($error, $warning, $notice); } diff --git a/lib/Minz/Extension.php b/lib/Minz/Extension.php new file mode 100644 index 000000000..78b8a2725 --- /dev/null +++ b/lib/Minz/Extension.php @@ -0,0 +1,208 @@ +<?php + +/** + * The extension base class. + */ +class Minz_Extension { + private $name; + private $entrypoint; + private $path; + private $author; + private $description; + private $version; + private $type; + + public static $authorized_types = array( + 'system', + 'user', + ); + + private $is_enabled; + + /** + * The constructor to assign specific information to the extension. + * + * Available fields are: + * - name: the name of the extension (required). + * - entrypoint: the extension class name (required). + * - path: the pathname to the extension files (required). + * - author: the name and / or email address of the extension author. + * - description: a short description to describe the extension role. + * - version: a version for the current extension. + * - type: "system" or "user" (default). + * + * It must not be redefined by child classes. + * + * @param $meta_info contains information about the extension. + */ + public function __construct($meta_info) { + $this->name = $meta_info['name']; + $this->entrypoint = $meta_info['entrypoint']; + $this->path = $meta_info['path']; + $this->author = isset($meta_info['author']) ? $meta_info['author'] : ''; + $this->description = isset($meta_info['description']) ? $meta_info['description'] : ''; + $this->version = isset($meta_info['version']) ? $meta_info['version'] : '0.1'; + $this->setType(isset($meta_info['type']) ? $meta_info['type'] : 'user'); + + $this->is_enabled = false; + } + + /** + * Used when installing an extension (e.g. update the database scheme). + * + * It must be redefined by child classes. + * + * @return true if the extension has been installed or a string explaining + * the problem. + */ + public function install() { + return true; + } + + /** + * Used when uninstalling an extension (e.g. revert the database scheme to + * cancel changes from install). + * + * It must be redefined by child classes. + * + * @return true if the extension has been uninstalled or a string explaining + * the problem. + */ + public function uninstall() { + return true; + } + + /** + * Call at the initialization of the extension (i.e. when the extension is + * enabled by the extension manager). + * + * It must be redefined by child classes. + */ + public function init() {} + + /** + * Set the current extension to enable. + */ + public function enable() { + $this->is_enabled = true; + } + + /** + * Return if the extension is currently enabled. + * + * @return true if extension is enabled, false else. + */ + public function isEnabled() { + return $this->is_enabled; + } + + /** + * Return the content of the configure view for the current extension. + * + * @return the html content from ext_dir/configure.phtml, false if it does + * not exist. + */ + public function getConfigureView() { + $filename = $this->path . '/configure.phtml'; + if (!file_exists($filename)) { + return false; + } + + ob_start(); + include($filename); + return ob_get_clean(); + } + + /** + * Handle the configure action. + * + * It must be redefined by child classes. + */ + public function handleConfigureAction() {} + + /** + * Getters and setters. + */ + public function getName() { + return $this->name; + } + public function getEntrypoint() { + return $this->entrypoint; + } + public function getPath() { + return $this->path; + } + public function getAuthor() { + return $this->author; + } + public function getDescription() { + return $this->description; + } + public function getVersion() { + return $this->version; + } + public function getType() { + return $this->type; + } + private function setType($type) { + if (!in_array($type, self::$authorized_types)) { + throw new Minz_ExtensionException('invalid `type` info', $this->name); + } + $this->type = $type; + } + + /** + * Return the url for a given file. + * + * @param $filename name of the file to serve. + * @param $type the type (js or css) of the file to serve. + * @return the url corresponding to the file. + */ + public function getFileUrl($filename, $type) { + $dir = substr(strrchr($this->path, '/'), 1); + $file_name_url = urlencode($dir . '/static/' . $filename); + + $absolute_path = $this->path . '/static/' . $filename; + $mtime = @filemtime($absolute_path); + + $url = '/ext.php?f=' . $file_name_url . + '&t=' . $type . + '&' . $mtime; + return Minz_Url::display($url, 'php'); + } + + /** + * Register a controller in the Dispatcher. + * + * @param @base_name the base name of the controller. Final name will be: + * FreshExtension_<base_name>_Controller. + */ + public function registerController($base_name) { + Minz_Dispatcher::registerController($base_name, $this->path); + } + + /** + * Register the views in order to be accessible by the application. + */ + public function registerViews() { + Minz_View::addBasePathname($this->path); + } + + /** + * Register i18n files from ext_dir/i18n/ + */ + public function registerTranslates() { + $i18n_dir = $this->path . '/i18n'; + Minz_Translate::registerPath($i18n_dir); + } + + /** + * Register a new hook. + * + * @param $hook_name the hook name (must exist). + * @param $hook_function the function name to call (must be callable). + */ + public function registerHook($hook_name, $hook_function) { + Minz_ExtensionManager::addHook($hook_name, $hook_function, $this); + } +} diff --git a/lib/Minz/ExtensionException.php b/lib/Minz/ExtensionException.php new file mode 100644 index 000000000..647f1a9b9 --- /dev/null +++ b/lib/Minz/ExtensionException.php @@ -0,0 +1,15 @@ +<?php + +class Minz_ExtensionException extends Minz_Exception { + public function __construct ($message, $extension_name = false, $code = self::ERROR) { + if ($extension_name) { + $message = 'An error occured in `' . $extension_name + . '` extension with the message: ' . $message; + } else { + $message = 'An error occured in an unnamed ' + . 'extension with the message: ' . $message; + } + + parent::__construct($message, $code); + } +} diff --git a/lib/Minz/ExtensionManager.php b/lib/Minz/ExtensionManager.php new file mode 100644 index 000000000..c5c68a8d4 --- /dev/null +++ b/lib/Minz/ExtensionManager.php @@ -0,0 +1,301 @@ +<?php + +/** + * An extension manager to load extensions present in EXTENSIONS_PATH. + * + * @todo see coding style for methods!! + */ +class Minz_ExtensionManager { + private static $ext_metaname = 'metadata.json'; + private static $ext_entry_point = 'extension.php'; + private static $ext_list = array(); + private static $ext_list_enabled = array(); + + private static $ext_auto_enabled = array(); + + // List of available hooks. Please keep this list sorted. + private static $hook_list = array( + 'entry_before_display' => array( // function($entry) -> Entry | null + 'list' => array(), + 'signature' => 'OneToOne', + ), + 'entry_before_insert' => array( // function($entry) -> Entry | null + 'list' => array(), + 'signature' => 'OneToOne', + ), + 'feed_before_insert' => array( // function($feed) -> Feed | null + 'list' => array(), + 'signature' => 'OneToOne', + ), + 'post_update' => array( // function(none) -> none + 'list' => array(), + 'signature' => 'NoneToNone', + ), + ); + private static $ext_to_hooks = array(); + + /** + * Initialize the extension manager by loading extensions in EXTENSIONS_PATH. + * + * A valid extension is a directory containing metadata.json and + * extension.php files. + * metadata.json is a JSON structure where the only required fields are + * `name` and `entry_point`. + * extension.php should contain at least a class named <name>Extension where + * <name> must match with the entry point in metadata.json. This class must + * inherit from Minz_Extension class. + */ + public static function init() { + $list_potential_extensions = array_values(array_diff( + scandir(EXTENSIONS_PATH), + array('..', '.') + )); + + $system_conf = Minz_Configuration::get('system'); + self::$ext_auto_enabled = $system_conf->extensions_enabled; + + foreach ($list_potential_extensions as $ext_dir) { + $ext_pathname = EXTENSIONS_PATH . '/' . $ext_dir; + if (!is_dir($ext_pathname)) { + continue; + } + $metadata_filename = $ext_pathname . '/' . self::$ext_metaname; + + // Try to load metadata file. + if (!file_exists($metadata_filename)) { + // No metadata file? Invalid! + continue; + } + $meta_raw_content = file_get_contents($metadata_filename); + $meta_json = json_decode($meta_raw_content, true); + if (!$meta_json || !self::isValidMetadata($meta_json)) { + // metadata.json is not a json file? Invalid! + // or metadata.json is invalid (no required information), invalid! + Minz_Log::warning('`' . $metadata_filename . '` is not a valid metadata file'); + continue; + } + + $meta_json['path'] = $ext_pathname; + + // Try to load extension itself + $extension = self::load($meta_json); + if (!is_null($extension)) { + self::register($extension); + } + } + } + + /** + * Indicates if the given parameter is a valid metadata array. + * + * Required fields are: + * - `name`: the name of the extension + * - `entry_point`: a class name to load the extension source code + * If the extension class name is `TestExtension`, entry point will be `Test`. + * `entry_point` must be composed of alphanumeric characters. + * + * @param $meta is an array of values. + * @return true if the array is valid, false else. + */ + public static function isValidMetadata($meta) { + $valid_chars = array('_'); + return !(empty($meta['name']) || + empty($meta['entrypoint']) || + !ctype_alnum(str_replace($valid_chars, '', $meta['entrypoint']))); + } + + /** + * Load the extension source code based on info metadata. + * + * @param $info an array containing information about extension. + * @return an extension inheriting from Minz_Extension. + */ + public static function load($info) { + $entry_point_filename = $info['path'] . '/' . self::$ext_entry_point; + $ext_class_name = $info['entrypoint'] . 'Extension'; + + include_once($entry_point_filename); + + // Test if the given extension class exists. + if (!class_exists($ext_class_name)) { + Minz_Log::warning('`' . $ext_class_name . + '` cannot be found in `' . $entry_point_filename . '`'); + return null; + } + + // Try to load the class. + $extension = null; + try { + $extension = new $ext_class_name($info); + } catch (Minz_ExtensionException $e) { + // We cannot load the extension? Invalid! + Minz_Log::warning('In `' . $metadata_filename . '`: ' . $e->getMessage()); + return null; + } + + // Test if class is correct. + if (!($extension instanceof Minz_Extension)) { + Minz_Log::warning('`' . $ext_class_name . + '` is not an instance of `Minz_Extension`'); + return null; + } + + return $extension; + } + + /** + * Add the extension to the list of the known extensions ($ext_list). + * + * If the extension is present in $ext_auto_enabled and if its type is "system", + * it will be enabled in the same time. + * + * @param $ext a valid extension. + */ + public static function register($ext) { + $name = $ext->getName(); + self::$ext_list[$name] = $ext; + + if ($ext->getType() === 'system' && + in_array($name, self::$ext_auto_enabled)) { + self::enable($ext->getName()); + } + + self::$ext_to_hooks[$name] = array(); + } + + /** + * Enable an extension so it will be called when necessary. + * + * The extension init() method will be called. + * + * @param $ext_name is the name of a valid extension present in $ext_list. + */ + public static function enable($ext_name) { + if (isset(self::$ext_list[$ext_name])) { + $ext = self::$ext_list[$ext_name]; + self::$ext_list_enabled[$ext_name] = $ext; + $ext->enable(); + $ext->init(); + } + } + + /** + * Enable a list of extensions. + * + * @param $ext_list the names of extensions we want to load. + */ + public static function enableByList($ext_list) { + foreach ($ext_list as $ext_name) { + self::enable($ext_name); + } + } + + /** + * Return a list of extensions. + * + * @param $only_enabled if true returns only the enabled extensions (false by default). + * @return an array of extensions. + */ + public static function listExtensions($only_enabled = false) { + if ($only_enabled) { + return self::$ext_list_enabled; + } else { + return self::$ext_list; + } + } + + /** + * Return an extension by its name. + * + * @param $ext_name the name of the extension. + * @return the corresponding extension or null if it doesn't exist. + */ + public static function findExtension($ext_name) { + if (!isset(self::$ext_list[$ext_name])) { + return null; + } + + return self::$ext_list[$ext_name]; + } + + /** + * Add a hook function to a given hook. + * + * The hook name must be a valid one. For the valid list, see self::$hook_list + * array keys. + * + * @param $hook_name the hook name (must exist). + * @param $hook_function the function name to call (must be callable). + * @param $ext the extension which register the hook. + */ + public static function addHook($hook_name, $hook_function, $ext) { + if (isset(self::$hook_list[$hook_name]) && is_callable($hook_function)) { + self::$hook_list[$hook_name]['list'][] = $hook_function; + self::$ext_to_hooks[$ext->getName()][] = $hook_name; + } + } + + /** + * Call functions related to a given hook. + * + * The hook name must be a valid one. For the valid list, see self::$hook_list + * array keys. + * + * @param $hook_name the hook to call. + * @param additionnal parameters (for signature, please see self::$hook_list). + * @return the final result of the called hook. + */ + public static function callHook($hook_name) { + if (!isset(self::$hook_list[$hook_name])) { + return; + } + + $signature = self::$hook_list[$hook_name]['signature']; + $signature = 'self::call' . $signature; + $args = func_get_args(); + + return call_user_func_array($signature, $args); + } + + /** + * Call a hook which takes one argument and return a result. + * + * The result is chained between the extension, for instance, first extension + * hook will receive the initial argument and return a result which will be + * passed as an argument to the next extension hook and so on. + * + * If a hook return a null value, the method is stopped and return null. + * + * @param $hook_name is the hook to call. + * @param $arg is the argument to pass to the first extension hook. + * @return the final chained result of the hooks. If nothing is changed, + * the initial argument is returned. + */ + private static function callOneToOne($hook_name, $arg) { + $result = $arg; + foreach (self::$hook_list[$hook_name]['list'] as $function) { + $result = call_user_func($function, $arg); + + if (is_null($result)) { + break; + } + + $arg = $result; + } + return $result; + } + + /** + * Call a hook which takes no argument and returns nothing. + * + * This case is simpler than callOneToOne because hooks are called one by + * one, without any consideration of argument nor result. + * + * @param $hook_name is the hook to call. + */ + private static function callNoneToNone($hook_name) { + foreach (self::$hook_list[$hook_name]['list'] as $function) { + call_user_func($function); + } + } +} diff --git a/lib/Minz/FrontController.php b/lib/Minz/FrontController.php index 80eda8877..f9eff3db6 100644 --- a/lib/Minz/FrontController.php +++ b/lib/Minz/FrontController.php @@ -24,50 +24,67 @@ */ class Minz_FrontController { protected $dispatcher; - protected $router; - - private $useOb = true; /** * Constructeur - * Initialise le router et le dispatcher + * Initialise le dispatcher, met à jour la Request */ public function __construct () { - if (LOG_PATH === false) { - $this->killApp ('Path not found: LOG_PATH'); - } - try { - Minz_Configuration::init (); + Minz_Configuration::register('system', + DATA_PATH . '/config.php', + DATA_PATH . '/config.default.php'); + $this->setReporting(); - Minz_Request::init (); + Minz_Request::init(); - $this->router = new Minz_Router (); - $this->router->init (); - } catch (Minz_RouteNotFoundException $e) { - Minz_Log::record ($e->getMessage (), Minz_Log::ERROR); - Minz_Error::error ( - 404, - array ('error' => array ($e->getMessage ())) + $url = $this->buildUrl(); + $url['params'] = array_merge ( + $url['params'], + Minz_Request::fetchPOST () ); + Minz_Request::forward ($url); } catch (Minz_Exception $e) { - Minz_Log::record ($e->getMessage (), Minz_Log::ERROR); + Minz_Log::error($e->getMessage()); $this->killApp ($e->getMessage ()); } - $this->dispatcher = Minz_Dispatcher::getInstance ($this->router); + $this->dispatcher = Minz_Dispatcher::getInstance(); } /** - * Démarre l'application (lance le dispatcher et renvoie la réponse + * Retourne un tableau représentant l'url passée par la barre d'adresses + * @return tableau représentant l'url + */ + private function buildUrl() { + $url = array (); + + $url['c'] = Minz_Request::fetchGET ( + 'c', + Minz_Request::defaultControllerName () + ); + $url['a'] = Minz_Request::fetchGET ( + 'a', + Minz_Request::defaultActionName () + ); + $url['params'] = Minz_Request::fetchGET (); + + // post-traitement + unset ($url['params']['c']); + unset ($url['params']['a']); + + return $url; + } + + /** + * Démarre l'application (lance le dispatcher et renvoie la réponse) */ public function run () { try { - $this->dispatcher->run ($this->useOb); - Minz_Response::send (); + $this->dispatcher->run(); } catch (Minz_Exception $e) { try { - Minz_Log::record ($e->getMessage (), Minz_Log::ERROR); + Minz_Log::error($e->getMessage()); } catch (Minz_PermissionDeniedException $e) { $this->killApp ($e->getMessage ()); } @@ -97,14 +114,22 @@ class Minz_FrontController { exit ('### Application problem ###<br />'."\n".$txt); } - public function useOb() { - return $this->useOb; - } - - /** - * Use ob_start('ob_gzhandler') or not. - */ - public function _useOb($ob) { - return $this->useOb = (bool)$ob; + private function setReporting() { + $conf = Minz_Configuration::get('system'); + switch($conf->environment) { + case 'production': + error_reporting(E_ALL); + ini_set('display_errors','Off'); + ini_set('log_errors', 'On'); + break; + case 'development': + error_reporting(E_ALL); + ini_set('display_errors','On'); + ini_set('log_errors', 'On'); + break; + case 'silent': + error_reporting(0); + break; + } } } diff --git a/lib/Minz/Helper.php b/lib/Minz/Helper.php index b058211d3..f4a547c4e 100644 --- a/lib/Minz/Helper.php +++ b/lib/Minz/Helper.php @@ -12,11 +12,22 @@ class Minz_Helper { * Annule les effets des magic_quotes pour une variable donnée * @param $var variable à traiter (tableau ou simple variable) */ - public static function stripslashes_r ($var) { - if (is_array ($var)){ - return array_map (array ('Helper', 'stripslashes_r'), $var); + public static function stripslashes_r($var) { + if (is_array($var)){ + return array_map(array('Minz_Helper', 'stripslashes_r'), $var); } else { return stripslashes($var); } } + + /** + * Wrapper for htmlspecialchars. + * Force UTf-8 value and can be used on array too. + */ + public static function htmlspecialchars_utf8($var) { + if (is_array($var)) { + return array_map(array('Minz_Helper', 'htmlspecialchars_utf8'), $var); + } + return htmlspecialchars($var, ENT_COMPAT, 'UTF-8'); + } } diff --git a/lib/Minz/Log.php b/lib/Minz/Log.php index e710aad4a..9559a0bd4 100644 --- a/lib/Minz/Log.php +++ b/lib/Minz/Log.php @@ -28,16 +28,25 @@ class Minz_Log { * - level = NOTICE et environment = PRODUCTION * @param $information message d'erreur / information à enregistrer * @param $level niveau d'erreur - * @param $file_name fichier de log, par défaut LOG_PATH/application.log + * @param $file_name fichier de log */ public static function record ($information, $level, $file_name = null) { - $env = Minz_Configuration::environment (); + try { + $conf = Minz_Configuration::get('system'); + $env = $conf->environment; + } catch (Minz_ConfigurationException $e) { + $env = 'production'; + } - if (! ($env === Minz_Configuration::SILENT - || ($env === Minz_Configuration::PRODUCTION + if (! ($env === 'silent' + || ($env === 'production' && ($level >= Minz_Log::NOTICE)))) { if ($file_name === null) { - $file_name = LOG_PATH . '/' . Minz_Session::param('currentUser', '_') . '.log'; + $username = Minz_Session::param('currentUser', ''); + if ($username == '') { + $username = '_'; + } + $file_name = join_path(USERS_PATH, $username, 'log.txt'); } switch ($level) { @@ -71,7 +80,7 @@ class Minz_Log { * Automatise le log des variables globales $_GET et $_POST * Fait appel à la fonction record(...) * Ne fonctionne qu'en environnement "development" - * @param $file_name fichier de log, par défaut LOG_PATH/application.log + * @param $file_name fichier de log */ public static function recordRequest($file_name = null) { $msg_get = str_replace("\n", '', '$_GET content : ' . print_r($_GET, true)); @@ -80,4 +89,21 @@ class Minz_Log { self::record($msg_get, Minz_Log::DEBUG, $file_name); self::record($msg_post, Minz_Log::DEBUG, $file_name); } + + /** + * Some helpers to Minz_Log::record() method + * Parameters are the same of those of the record() method. + */ + public static function debug($msg, $file_name = null) { + self::record($msg, Minz_Log::DEBUG, $file_name); + } + public static function notice($msg, $file_name = null) { + self::record($msg, Minz_Log::NOTICE, $file_name); + } + public static function warning($msg, $file_name = null) { + self::record($msg, Minz_Log::WARNING, $file_name); + } + public static function error($msg, $file_name = null) { + self::record($msg, Minz_Log::ERROR, $file_name); + } } diff --git a/lib/Minz/ModelPdo.php b/lib/Minz/ModelPdo.php index 831df13a2..caab1d114 100644 --- a/lib/Minz/ModelPdo.php +++ b/lib/Minz/ModelPdo.php @@ -16,54 +16,83 @@ class Minz_ModelPdo { public static $useSharedBd = true; private static $sharedBd = null; private static $sharedPrefix; + private static $sharedCurrentUser; + protected static $sharedDbType; /** * $bd variable représentant la base de données */ protected $bd; + protected $current_user; protected $prefix; + public function dbType() { + return self::$sharedDbType; + } + /** * Créé la connexion à la base de données à l'aide des variables * HOST, BASE, USER et PASS définies dans le fichier de configuration */ - public function __construct () { - if (self::$useSharedBd && self::$sharedBd != null) { + public function __construct($currentUser = null) { + if ($currentUser === null) { + $currentUser = Minz_Session::param('currentUser'); + } + if (self::$useSharedBd && self::$sharedBd != null && + ($currentUser == null || $currentUser === self::$sharedCurrentUser)) { $this->bd = self::$sharedBd; $this->prefix = self::$sharedPrefix; + $this->current_user = self::$sharedCurrentUser; return; } + $this->current_user = $currentUser; + self::$sharedCurrentUser = $currentUser; + + $conf = Minz_Configuration::get('system'); + $db = $conf->db; - $db = Minz_Configuration::dataBase (); - $driver_options = null; + $driver_options = isset($conf->db['pdo_options']) && is_array($conf->db['pdo_options']) ? $conf->db['pdo_options'] : array(); + $dbServer = parse_url('db://' . $db['host']); try { - $type = $db['type']; - if($type == 'mysql') { - $string = $type - . ':host=' . $db['host'] - . ';dbname=' . $db['base'] - . ';charset=utf8'; - $driver_options = array( - PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8' - ); - } elseif($type == 'sqlite') { - $string = $type . ':/' . DATA_PATH . $db['base'] . '.sqlite'; //TODO: DEBUG UTF-8 http://www.siteduzero.com/forum/sujet/sqlite-connexion-utf-8-18797 + switch ($db['type']) { + case 'mysql': + $string = 'mysql:host=' . $dbServer['host'] . ';dbname=' . $db['base'] . ';charset=utf8mb4'; + if (!empty($dbServer['port'])) { + $string .= ';port=' . $dbServer['port']; + } + $driver_options[PDO::MYSQL_ATTR_INIT_COMMAND] = 'SET NAMES utf8mb4'; + $this->prefix = $db['prefix'] . $currentUser . '_'; + $this->bd = new MinzPDOMySql($string, $db['user'], $db['password'], $driver_options); + break; + case 'sqlite': + $string = 'sqlite:' . join_path(DATA_PATH, 'users', $currentUser, 'db.sqlite'); + $this->prefix = ''; + $this->bd = new MinzPDOMSQLite($string, $db['user'], $db['password'], $driver_options); + $this->bd->exec('PRAGMA foreign_keys = ON;'); + break; + case 'pgsql': + $string = 'pgsql:host=' . $dbServer['host'] . ';dbname=' . $db['base']; + if (!empty($dbServer['port'])) { + $string .= ';port=' . $dbServer['port']; + } + $this->prefix = $db['prefix'] . $currentUser . '_'; + $this->bd = new MinzPDOPGSQL($string, $db['user'], $db['password'], $driver_options); + $this->bd->exec("SET NAMES 'UTF8';"); + break; + default: + throw new Minz_PDOConnectionException( + 'Invalid database type!', + $db['user'], Minz_Exception::ERROR + ); + break; } - - $this->bd = new FreshPDO ( - $string, - $db['user'], - $db['password'], - $driver_options - ); self::$sharedBd = $this->bd; - - $this->prefix = $db['prefix'] . Minz_Session::param('currentUser', '_') . '_'; + self::$sharedDbType = $db['type']; self::$sharedPrefix = $this->prefix; } catch (Exception $e) { - throw new Minz_PDOConnectionException ( + throw new Minz_PDOConnectionException( $string, $db['user'], Minz_Exception::ERROR ); @@ -73,6 +102,9 @@ class Minz_ModelPdo { public function beginTransaction() { $this->bd->beginTransaction(); } + public function inTransaction() { + return $this->bd->inTransaction(); //requires PHP >= 5.3.3 + } public function commit() { $this->bd->commit(); } @@ -80,40 +112,62 @@ class Minz_ModelPdo { $this->bd->rollBack(); } - public function size($all = false) { - $db = Minz_Configuration::dataBase (); - $sql = 'SELECT SUM(data_length + index_length) FROM information_schema.TABLES WHERE table_schema = ?'; - $values = array ($db['base']); - if (!$all) { - $sql .= ' AND table_name LIKE ?'; - $values[] = $this->prefix . '%'; - } - $stm = $this->bd->prepare ($sql); - $stm->execute ($values); - $res = $stm->fetchAll(PDO::FETCH_COLUMN, 0); - return $res[0]; - } - public static function clean() { self::$sharedBd = null; self::$sharedPrefix = ''; } + + public function disableBuffering() { + if ((self::$sharedDbType === 'mysql') && defined('PDO::MYSQL_ATTR_USE_BUFFERED_QUERY')) { + $this->bd->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false); + } + } } -class FreshPDO extends PDO { +class MinzPDO extends PDO { private static function check($statement) { if (preg_match('/^(?:UPDATE|INSERT|DELETE)/i', $statement)) { invalidateHttpCache(); } } - public function prepare ($statement, $driver_options = array()) { - FreshPDO::check($statement); + protected function compatibility($statement) { + return $statement; + } + + public function prepare($statement, $driver_options = array()) { + MinzPDO::check($statement); + $statement = $this->compatibility($statement); return parent::prepare($statement, $driver_options); } - public function exec ($statement) { - FreshPDO::check($statement); + public function exec($statement) { + MinzPDO::check($statement); + $statement = $this->compatibility($statement); return parent::exec($statement); } + + public function query($statement) { + MinzPDO::check($statement); + $statement = $this->compatibility($statement); + return parent::query($statement); + } +} + +class MinzPDOMySql extends MinzPDO { + public function lastInsertId($name = null) { + return parent::lastInsertId(); //We discard the name, only used by PostgreSQL + } +} + +class MinzPDOMSQLite extends MinzPDO { + public function lastInsertId($name = null) { + return parent::lastInsertId(); //We discard the name, only used by PostgreSQL + } +} + +class MinzPDOPGSQL extends MinzPDO { + protected function compatibility($statement) { + return str_replace(array('`', ' LIKE '), array('"', ' ILIKE '), $statement); + } } diff --git a/lib/Minz/Request.php b/lib/Minz/Request.php index 282d47a77..f80b707d6 100644 --- a/lib/Minz/Request.php +++ b/lib/Minz/Request.php @@ -10,68 +10,68 @@ class Minz_Request { private static $controller_name = ''; private static $action_name = ''; - private static $params = array (); + private static $params = array(); private static $default_controller_name = 'index'; private static $default_action_name = 'index'; - public static $reseted = true; - /** * Getteurs */ - public static function controllerName () { + public static function controllerName() { return self::$controller_name; } - public static function actionName () { + public static function actionName() { return self::$action_name; } - public static function params () { + public static function params() { return self::$params; } - static function htmlspecialchars_utf8 ($p) { - return htmlspecialchars($p, ENT_COMPAT, 'UTF-8'); - } - public static function param ($key, $default = false, $specialchars = false) { - if (isset (self::$params[$key])) { + public static function param($key, $default = false, $specialchars = false) { + if (isset(self::$params[$key])) { $p = self::$params[$key]; - if(is_object($p) || $specialchars) { + if (is_object($p) || $specialchars) { return $p; - } elseif(is_array($p)) { - return array_map('self::htmlspecialchars_utf8', $p); } else { - return self::htmlspecialchars_utf8($p); + return Minz_Helper::htmlspecialchars_utf8($p); } } else { return $default; } } - public static function defaultControllerName () { + public static function defaultControllerName() { return self::$default_controller_name; } - public static function defaultActionName () { + public static function defaultActionName() { return self::$default_action_name; } + public static function currentRequest() { + return array( + 'c' => self::$controller_name, + 'a' => self::$action_name, + 'params' => self::$params, + ); + } /** * Setteurs */ - public static function _controllerName ($controller_name) { + public static function _controllerName($controller_name) { self::$controller_name = $controller_name; } - public static function _actionName ($action_name) { + public static function _actionName($action_name) { self::$action_name = $action_name; } - public static function _params ($params) { + public static function _params($params) { if (!is_array($params)) { - $params = array ($params); + $params = array($params); } self::$params = $params; } - public static function _param ($key, $value = false) { + public static function _param($key, $value = false) { if ($value === false) { - unset (self::$params[$key]); + unset(self::$params[$key]); } else { self::$params[$key] = $value; } @@ -80,48 +80,69 @@ class Minz_Request { /** * Initialise la Request */ - public static function init () { - self::magicQuotesOff (); + public static function init() { + self::magicQuotesOff(); } /** - * Retourn le nom de domaine du site + * Return true if the request is over HTTPS, false otherwise (HTTP) */ - public static function getDomainName () { - return $_SERVER['HTTP_HOST']; + public static function isHttps() { + if (isset($_SERVER['HTTP_X_FORWARDED_PROTO'])) { + return strtolower($_SERVER['HTTP_X_FORWARDED_PROTO']) === 'https'; + } else { + return isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on'; + } } /** - * Détermine la base de l'url - * @return la base de l'url + * Try to guess the base URL from $_SERVER information + * + * @return the base url (e.g. http://example.com/) */ - public static function getBaseUrl () { - $defaultBaseUrl = Minz_Configuration::baseUrl(); - if (!empty($defaultBaseUrl)) { - return $defaultBaseUrl; - } elseif (isset($_SERVER['REQUEST_URI'])) { - return dirname($_SERVER['REQUEST_URI']) . '/'; + public static function guessBaseUrl() { + $url = 'http'; + + $https = self::isHttps(); + + if (!empty($_SERVER['HTTP_HOST'])) { + $host = $_SERVER['HTTP_HOST']; + } elseif (!empty($_SERVER['SERVER_NAME'])) { + $host = $_SERVER['SERVER_NAME']; } else { - return '/'; + $host = 'localhost'; } - } - /** - * Récupère l'URI de la requête - * @return l'URI - */ - public static function getURI () { - if (isset ($_SERVER['REQUEST_URI'])) { - $base_url = self::getBaseUrl (); - $uri = $_SERVER['REQUEST_URI']; + if (!empty($_SERVER['HTTP_X_FORWARDED_PORT'])) { + $port = intval($_SERVER['HTTP_X_FORWARDED_PORT']); + } elseif (!empty($_SERVER['SERVER_PORT'])) { + $port = intval($_SERVER['SERVER_PORT']); + } else { + $port = $https ? 443 : 80; + } - $len_base_url = strlen ($base_url); - $real_uri = substr ($uri, $len_base_url); + if ($https) { + $url .= 's://' . $host . ($port == 443 ? '' : ':' . $port); } else { - $real_uri = ''; + $url .= '://' . $host . ($port == 80 ? '' : ':' . $port); } + if (isset($_SERVER['REQUEST_URI'])) { + $path = $_SERVER['REQUEST_URI']; + $url .= substr($path, -1) === '/' ? substr($path, 0, -1) : dirname($path); + } + + return filter_var($url, FILTER_SANITIZE_URL); + } - return $real_uri; + /** + * Return the base_url from configuration and add a suffix if given. + * + * @return the base_url with a suffix. + */ + public static function getBaseUrl() { + $conf = Minz_Configuration::get('system'); + $url = rtrim($conf->base_url, '/\\'); + return filter_var($url, FILTER_SANITIZE_URL); } /** @@ -130,24 +151,53 @@ class Minz_Request { * @param $redirect si vrai, force la redirection http * > sinon, le dispatcher recharge en interne */ - public static function forward ($url = array (), $redirect = false) { - $url = Minz_Url::checkUrl ($url); + public static function forward($url = array(), $redirect = false) { + if (!is_array($url)) { + header('Location: ' . $url); + exit(); + } + + $url = Minz_Url::checkUrl($url); if ($redirect) { - header ('Location: ' . Minz_Url::display ($url, 'php')); - exit (); + header('Location: ' . Minz_Url::display($url, 'php')); + exit(); } else { - self::$reseted = true; - - self::_controllerName ($url['c']); - self::_actionName ($url['a']); - self::_params (array_merge ( + self::_controllerName($url['c']); + self::_actionName($url['a']); + self::_params(array_merge( self::$params, $url['params'] )); + Minz_Dispatcher::reset(); } } + + /** + * Wrappers good notifications + redirection + * @param $msg notification content + * @param $url url array to where we should be forwarded + */ + public static function good($msg, $url = array()) { + Minz_Session::_param('notification', array( + 'type' => 'good', + 'content' => $msg + )); + + Minz_Request::forward($url, true); + } + + public static function bad($msg, $url = array()) { + Minz_Session::_param('notification', array( + 'type' => 'bad', + 'content' => $msg + )); + + Minz_Request::forward($url, true); + } + + /** * Permet de récupérer une variable de type $_GET * @param $param nom de la variable @@ -156,10 +206,10 @@ class Minz_Request { * $_GET si $param = false * $default si $_GET[$param] n'existe pas */ - public static function fetchGET ($param = false, $default = false) { + public static function fetchGET($param = false, $default = false) { if ($param === false) { return $_GET; - } elseif (isset ($_GET[$param])) { + } elseif (isset($_GET[$param])) { return $_GET[$param]; } else { return $default; @@ -174,10 +224,10 @@ class Minz_Request { * $_POST si $param = false * $default si $_POST[$param] n'existe pas */ - public static function fetchPOST ($param = false, $default = false) { + public static function fetchPOST($param = false, $default = false) { if ($param === false) { return $_POST; - } elseif (isset ($_POST[$param])) { + } elseif (isset($_POST[$param])) { return $_POST[$param]; } else { return $default; @@ -190,15 +240,16 @@ class Minz_Request { * $_POST * $_COOKIE */ - private static function magicQuotesOff () { - if (get_magic_quotes_gpc ()) { - $_GET = Minz_Helper::stripslashes_r ($_GET); - $_POST = Minz_Helper::stripslashes_r ($_POST); - $_COOKIE = Minz_Helper::stripslashes_r ($_COOKIE); + private static function magicQuotesOff() { + if (get_magic_quotes_gpc()) { + $_GET = Minz_Helper::stripslashes_r($_GET); + $_POST = Minz_Helper::stripslashes_r($_POST); + $_COOKIE = Minz_Helper::stripslashes_r($_COOKIE); } } - public static function isPost () { - return $_SERVER['REQUEST_METHOD'] === 'POST'; + public static function isPost() { + return isset($_SERVER['REQUEST_METHOD']) && + $_SERVER['REQUEST_METHOD'] === 'POST'; } } diff --git a/lib/Minz/Response.php b/lib/Minz/Response.php deleted file mode 100644 index f8ea3d946..000000000 --- a/lib/Minz/Response.php +++ /dev/null @@ -1,60 +0,0 @@ -<?php -/** - * MINZ - Copyright 2011 Marien Fressinaud - * Sous licence AGPL3 <http://www.gnu.org/licenses/> -*/ - -/** - * Response représente la requête http renvoyée à l'utilisateur - */ -class Minz_Response { - private static $header = 'HTTP/1.0 200 OK'; - private static $body = ''; - - /** - * Mets à jour le body de la Response - * @param $text le texte à incorporer dans le body - */ - public static function setBody ($text) { - self::$body = $text; - } - - /** - * Mets à jour le header de la Response - * @param $code le code HTTP, valeurs possibles - * - 200 (OK) - * - 403 (Forbidden) - * - 404 (Forbidden) - * - 500 (Forbidden) -> par défaut si $code erroné - * - 503 (Forbidden) - */ - public static function setHeader ($code) { - switch ($code) { - case 200 : - self::$header = 'HTTP/1.0 200 OK'; - break; - case 403 : - self::$header = 'HTTP/1.0 403 Forbidden'; - break; - case 404 : - self::$header = 'HTTP/1.0 404 Not Found'; - break; - case 500 : - self::$header = 'HTTP/1.0 500 Internal Server Error'; - break; - case 503 : - self::$header = 'HTTP/1.0 503 Service Unavailable'; - break; - default : - self::$header = 'HTTP/1.0 500 Internal Server Error'; - } - } - - /** - * Envoie la Response à l'utilisateur - */ - public static function send () { - header (self::$header); - echo self::$body; - } -} diff --git a/lib/Minz/RouteNotFoundException.php b/lib/Minz/RouteNotFoundException.php deleted file mode 100644 index dc4f6fbad..000000000 --- a/lib/Minz/RouteNotFoundException.php +++ /dev/null @@ -1,16 +0,0 @@ -<?php -class Minz_RouteNotFoundException extends Minz_Exception { - private $route; - - public function __construct ($route, $code = self::ERROR) { - $this->route = $route; - - $message = 'Route `' . $route . '` not found'; - - parent::__construct ($message, $code); - } - - public function route () { - return $this->route; - } -} diff --git a/lib/Minz/Router.php b/lib/Minz/Router.php deleted file mode 100644 index 1ccd72597..000000000 --- a/lib/Minz/Router.php +++ /dev/null @@ -1,209 +0,0 @@ -<?php -/** - * MINZ - Copyright 2011 Marien Fressinaud - * Sous licence AGPL3 <http://www.gnu.org/licenses/> -*/ - -/** - * La classe Router gère le routage de l'application - * Les routes sont définies dans APP_PATH.'/configuration/routes.php' - */ -class Minz_Router { - const ROUTES_PATH_NAME = '/configuration/routes.php'; - - private $routes = array (); - - /** - * Constructeur - * @exception FileNotExistException si ROUTES_PATH_NAME n'existe pas - * et que l'on utilise l'url rewriting - */ - public function __construct () { - if (Minz_Configuration::useUrlRewriting ()) { - if (file_exists (APP_PATH . self::ROUTES_PATH_NAME)) { - $routes = include ( - APP_PATH . self::ROUTES_PATH_NAME - ); - - if (!is_array ($routes)) { - $routes = array (); - } - - $this->routes = array_map ( - array ('Url', 'checkUrl'), - $routes - ); - } else { - throw new Minz_FileNotExistException ( - self::ROUTES_PATH_NAME, - Minz_Exception::ERROR - ); - } - } - } - - /** - * Initialise le Router en déterminant le couple Controller / Action - * Mets à jour la Request - * @exception RouteNotFoundException si l'uri n'est pas présente dans - * > la table de routage - */ - public function init () { - $url = array (); - - if (Minz_Configuration::useUrlRewriting ()) { - try { - $url = $this->buildWithRewriting (); - } catch (Minz_RouteNotFoundException $e) { - throw $e; - } - } else { - $url = $this->buildWithoutRewriting (); - } - - $url['params'] = array_merge ( - $url['params'], - Minz_Request::fetchPOST () - ); - - Minz_Request::forward ($url); - } - - /** - * Retourne un tableau représentant l'url passée par la barre d'adresses - * Ne se base PAS sur la table de routage - * @return tableau représentant l'url - */ - public function buildWithoutRewriting () { - $url = array (); - - $url['c'] = Minz_Request::fetchGET ( - 'c', - Minz_Request::defaultControllerName () - ); - $url['a'] = Minz_Request::fetchGET ( - 'a', - Minz_Request::defaultActionName () - ); - $url['params'] = Minz_Request::fetchGET (); - - // post-traitement - unset ($url['params']['c']); - unset ($url['params']['a']); - - return $url; - } - - /** - * Retourne un tableau représentant l'url passée par la barre d'adresses - * Se base sur la table de routage - * @return tableau représentant l'url - * @exception RouteNotFoundException si l'uri n'est pas présente dans - * > la table de routage - */ - public function buildWithRewriting () { - $url = array (); - $uri = Minz_Request::getURI (); - $find = false; - - foreach ($this->routes as $route) { - $regex = '*^' . $route['route'] . '$*'; - if (preg_match ($regex, $uri, $matches)) { - $url['c'] = $route['controller']; - $url['a'] = $route['action']; - $url['params'] = $this->getParams ( - $route['params'], - $matches - ); - $find = true; - break; - } - } - - if (!$find && $uri != '/') { - throw new Minz_RouteNotFoundException ( - $uri, - Minz_Exception::ERROR - ); - } - - // post-traitement - $url = Minz_Url::checkUrl ($url); - - return $url; - } - - /** - * Retourne l'uri d'une url en se basant sur la table de routage - * @param l'url sous forme de tableau - * @return l'uri formatée (string) selon une route trouvée - */ - public function printUriRewrited ($url) { - $route = $this->searchRoute ($url); - - if ($route !== false) { - return $this->replaceParams ($route, $url['params']); - } - - return ''; - } - - /** - * Recherche la route correspondante à une url - * @param l'url sous forme de tableau - * @return la route telle que spécifiée dans la table de routage, - * false si pas trouvée - */ - public function searchRoute ($url) { - foreach ($this->routes as $route) { - if ($route['controller'] == $url['c'] - && $route['action'] == $url['a']) { - // calcule la différence des tableaux de params - $params = array_flip ($route['params']); - $difference_params = array_diff_key ( - $params, - $url['params'] - ); - - // vérifie que pas de différence - // et le cas où $params est vide et pas $url['params'] - if (empty ($difference_params) - && (!empty ($params) || empty ($url['params']))) { - return $route; - } - } - } - - return false; - } - - /** - * Récupère un tableau dont - * - les clés sont définies dans $params_route - * - les valeurs sont situées dans $matches - * Le tableau $matches est décalé de +1 par rapport à $params_route - */ - private function getParams($params_route, $matches) { - $params = array (); - - for ($i = 0; $i < count ($params_route); $i++) { - $param = $params_route[$i]; - $params[$param] = $matches[$i + 1]; - } - - return $params; - } - - /** - * Remplace les éléments de la route par les valeurs contenues dans $params - */ - private function replaceParams ($route, $params_replace) { - $uri = $route['route']; - $params = array(); - foreach($route['params'] as $param) { - $uri = preg_replace('#\((.+)\)#U', $params_replace[$param], $uri, 1); - } - - return stripslashes($uri); - } -} diff --git a/lib/Minz/Session.php b/lib/Minz/Session.php index ddabc4658..c94f2b646 100644 --- a/lib/Minz/Session.php +++ b/lib/Minz/Session.php @@ -2,28 +2,20 @@ /** * La classe Session gère la session utilisateur - * C'est un singleton */ class Minz_Session { /** - * $session stocke les variables de session - */ - private static $session = array (); //TODO: Try to avoid having another local copy - - /** * Initialise la session, avec un nom - * Le nom de session est utilisé comme nom pour les cookies et les URLs (i.e. PHPSESSID). + * Le nom de session est utilisé comme nom pour les cookies et les URLs(i.e. PHPSESSID). * Il ne doit contenir que des caractères alphanumériques ; il doit être court et descriptif */ - public static function init ($name) { - // démarre la session - session_name ($name); - session_set_cookie_params (0, dirname(empty($_SERVER['REQUEST_URI']) ? '/' : dirname($_SERVER['REQUEST_URI'])), null, false, true); - session_start (); + public static function init($name) { + $cookie = session_get_cookie_params(); + self::keepCookie($cookie['lifetime']); - if (isset ($_SESSION)) { - self::$session = $_SESSION; - } + // démarre la session + session_name($name); + session_start(); } @@ -32,8 +24,8 @@ class Minz_Session { * @param $p le paramètre à récupérer * @return la valeur de la variable de session, false si n'existe pas */ - public static function param ($p, $default = false) { - return isset(self::$session[$p]) ? self::$session[$p] : $default; + public static function param($p, $default = false) { + return isset($_SESSION[$p]) ? $_SESSION[$p] : $default; } @@ -42,13 +34,11 @@ class Minz_Session { * @param $p le paramètre à créer ou modifier * @param $v la valeur à attribuer, false pour supprimer */ - public static function _param ($p, $v = false) { + public static function _param($p, $v = false) { if ($v === false) { - unset ($_SESSION[$p]); - unset (self::$session[$p]); + unset($_SESSION[$p]); } else { $_SESSION[$p] = $v; - self::$session[$p] = $v; } } @@ -57,15 +47,54 @@ class Minz_Session { * Permet d'effacer une session * @param $force si à false, n'efface pas le paramètre de langue */ - public static function unset_session ($force = false) { - $language = self::param ('language'); + public static function unset_session($force = false) { + $language = self::param('language'); session_destroy(); - self::$session = array (); + $_SESSION = array(); if (!$force) { - self::_param ('language', $language); - Minz_Translate::reset (); + self::_param('language', $language); + Minz_Translate::reset($language); } } + + public static function getCookieDir() { + // Get the script_name (e.g. /p/i/index.php) and keep only the path. + $cookie_dir = empty($_SERVER['REQUEST_URI']) ? '/' : $_SERVER['REQUEST_URI']; + if (substr($cookie_dir, -1) !== '/') { + $cookie_dir = dirname($cookie_dir) . '/'; + } + return $cookie_dir; + } + + /** + * Spécifie la durée de vie des cookies + * @param $l la durée de vie + */ + public static function keepCookie($l) { + session_set_cookie_params($l, self::getCookieDir(), '', Minz_Request::isHttps(), true); + } + + + /** + * Régénère un id de session. + * Utile pour appeler session_set_cookie_params après session_start() + */ + public static function regenerateID() { + session_regenerate_id(true); + } + + public static function deleteLongTermCookie($name) { + setcookie($name, '', 1, '', '', Minz_Request::isHttps(), true); + } + + public static function setLongTermCookie($name, $value, $expire) { + setcookie($name, $value, $expire, '', '', Minz_Request::isHttps(), true); + } + + public static function getLongTermCookie($name) { + return isset($_COOKIE[$name]) ? $_COOKIE[$name] : null; + } + } diff --git a/lib/Minz/Translate.php b/lib/Minz/Translate.php index e14f783f7..baddcb424 100644 --- a/lib/Minz/Translate.php +++ b/lib/Minz/Translate.php @@ -5,67 +5,226 @@ */ /** - * La classe Translate se charge de la traduction - * Utilise les fichiers du répertoire /app/i18n/ + * This class is used for the internationalization. + * It uses files in `./app/i18n/` */ class Minz_Translate { /** - * $language est la langue à afficher + * $path_list is the list of registered base path to search translations. */ - private static $language; - + private static $path_list = array(); + + /** + * $lang_name is the name of the current language to use. + */ + private static $lang_name; + + /** + * $lang_files is a list of registered i18n files. + */ + private static $lang_files = array(); + + /** + * $translates is a cache for i18n translation. + */ + private static $translates = array(); + + /** + * Init the translation object. + * @param $lang_name the lang to show. + */ + public static function init($lang_name = null) { + self::$lang_name = $lang_name; + self::$lang_files = array(); + self::$translates = array(); + self::registerPath(APP_PATH . '/i18n'); + foreach (self::$path_list as $path) { + self::loadLang($path); + } + } + /** - * $translates est le tableau de correspondance - * $key => $traduction + * Reset the translation object with a new language. + * @param $lang_name the new language to use */ - private static $translates = array (); - + public static function reset($lang_name) { + self::$lang_name = $lang_name; + self::$lang_files = array(); + self::$translates = array(); + foreach (self::$path_list as $path) { + self::loadLang($path); + } + } + /** - * Inclus le fichier de langue qui va bien - * l'enregistre dans $translates + * Return the list of available languages. + * @return an array containing langs found in different registered paths. */ - public static function init () { - $l = Minz_Configuration::language (); - self::$language = Minz_Session::param ('language', $l); - - $l_path = APP_PATH . '/i18n/' . self::$language . '.php'; - - if (file_exists ($l_path)) { - self::$translates = include ($l_path); + public static function availableLanguages() { + $list_langs = array(); + + foreach (self::$path_list as $path) { + $path_langs = array_values(array_diff( + scandir($path), + array('..', '.') + )); + + $list_langs = array_merge($list_langs, $path_langs); } + + return array_unique($list_langs); } - + /** - * Alias de init + * Register a new path. + * @param $path a path containing i18n directories (e.g. ./en/, ./fr/). */ - public static function reset () { - self::init (); + public static function registerPath($path) { + if (in_array($path, self::$path_list)) { + return; + } + + self::$path_list[] = $path; + self::loadLang($path); } - + /** - * Traduit une clé en sa valeur du tableau $translates - * @param $key la clé à traduire - * @return la valeur correspondante à la clé - * > si non présente dans le tableau, on retourne la clé elle-même + * Load translations of the current language from the given path. + * @param $path the path containing i18n directories. + */ + private static function loadLang($path) { + $lang_path = $path . '/' . self::$lang_name; + if (!file_exists($lang_path) || is_null(self::$lang_name)) { + // The lang path does not exist, nothing more to do. + return; + } + + $list_i18n_files = array_values(array_diff( + scandir($lang_path), + array('..', '.') + )); + + // Each file basename correspond to a top-level i18n key. For each of + // these keys we store the file pathname and mark translations must be + // reloaded (by setting $translates[$i18n_key] to null). + foreach ($list_i18n_files as $i18n_filename) { + $i18n_key = basename($i18n_filename, '.php'); + if (!isset(self::$lang_files[$i18n_key])) { + self::$lang_files[$i18n_key] = array(); + } + self::$lang_files[$i18n_key][] = $lang_path . '/' . $i18n_filename; + self::$translates[$i18n_key] = null; + } + } + + /** + * Load the files associated to $key into $translates. + * @param $key the top level i18n key we want to load. + */ + private static function loadKey($key) { + // The top level key is not in $lang_files, it means it does not exist! + if (!isset(self::$lang_files[$key])) { + Minz_Log::debug($key . ' is not a valid top level key'); + return false; + } + + self::$translates[$key] = array(); + + foreach (self::$lang_files[$key] as $lang_pathname) { + $i18n_array = include($lang_pathname); + if (!is_array($i18n_array)) { + Minz_Log::warning('`' . $lang_pathname . '` does not contain a PHP array'); + continue; + } + + // We must avoid to erase previous data so we just override them if + // needed. + self::$translates[$key] = array_replace_recursive( + self::$translates[$key], $i18n_array + ); + } + + return true; + } + + /** + * Translate a key into its corresponding value based on selected language. + * @param $key the key to translate. + * @param additional parameters for variable keys. + * @return the value corresponding to the key. + * If no value is found, return the key itself. */ - public static function t ($key) { - $translate = $key; - - if (isset (self::$translates[$key])) { - $translate = self::$translates[$key]; + public static function t($key) { + $group = explode('.', $key); + + if (count($group) < 2) { + Minz_Log::debug($key . ' is not in a valid format'); + $top_level = 'gen'; + } else { + $top_level = array_shift($group); } - $args = func_get_args (); + // If $translates[$top_level] is null it means we have to load the + // corresponding files. + if (!isset(self::$translates[$top_level]) || + is_null(self::$translates[$top_level])) { + $res = self::loadKey($top_level); + if (!$res) { + return $key; + } + } + + // Go through the i18n keys to get the correct translation value. + $translates = self::$translates[$top_level]; + $size_group = count($group); + $level_processed = 0; + $translation_value = $key; + foreach ($group as $i18n_level) { + $level_processed++; + if (!isset($translates[$i18n_level])) { + Minz_Log::debug($key . ' is not a valid key'); + return $key; + } + + if ($level_processed < $size_group) { + $translates = $translates[$i18n_level]; + } else { + $translation_value = $translates[$i18n_level]; + } + } + + if (is_array($translation_value)) { + if (isset($translation_value['_'])) { + $translation_value = $translation_value['_']; + } else { + Minz_Log::debug($key . ' is not a valid key'); + return $key; + } + } + + // Get the facultative arguments to replace i18n variables. + $args = func_get_args(); unset($args[0]); - - return vsprintf ($translate, $args); + + return vsprintf($translation_value, $args); } - + /** - * Retourne la langue utilisée actuellement - * @return la langue + * Return the current language. */ - public static function language () { - return self::$language; + public static function language() { + return self::$lang_name; } } + + +/** + * Alias for Minz_Translate::t() + */ +function _t($key) { + $args = func_get_args(); + unset($args[0]); + array_unshift($args, $key); + + return call_user_func_array('Minz_Translate::t', $args); +} diff --git a/lib/Minz/Url.php b/lib/Minz/Url.php index 17f1ddece..99c0443c1 100644 --- a/lib/Minz/Url.php +++ b/lib/Minz/Url.php @@ -5,13 +5,11 @@ */ class Minz_Url { /** - * Affiche une Url formatée selon que l'on utilise l'url_rewriting ou non - * si oui, on cherche dans la table de routage la correspondance pour formater + * Affiche une Url formatée * @param $url l'url à formater définie comme un tableau : * $url['c'] = controller * $url['a'] = action * $url['params'] = tableau des paramètres supplémentaires - * $url['protocol'] = protocole à utiliser (http par défaut) * ou comme une chaîne de caractère * @param $encodage pour indiquer comment encoder les & (& ou & pour html) * @return l'url formatée @@ -20,77 +18,77 @@ class Minz_Url { $isArray = is_array($url); if ($isArray) { - $url = self::checkUrl ($url); + $url = self::checkUrl($url); } $url_string = ''; if ($absolute) { - if ($isArray && isset ($url['protocol'])) { - $protocol = $url['protocol']; - } elseif (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') { - $protocol = 'https:'; - } else { - $protocol = 'http:'; + $url_string = Minz_Request::getBaseUrl(); + if ($url_string == '') { + $url_string = Minz_Request::guessBaseUrl(); + } + if ($isArray) { + $url_string .= PUBLIC_TO_INDEX_PATH; + } + if ($absolute === 'root') { + $url_string = parse_url($url_string, PHP_URL_PATH); } - $url_string = $protocol . '//' . Minz_Request::getDomainName () . Minz_Request::getBaseUrl (); } else { $url_string = $isArray ? '.' : PUBLIC_RELATIVE; } if ($isArray) { - $router = new Minz_Router (); - - if (Minz_Configuration::useUrlRewriting ()) { - $url_string .= $router->printUriRewrited ($url); - } else { - $url_string .= self::printUri ($url, $encodage); - } + $url_string .= self::printUri($url, $encodage); + } elseif ($encodage === 'html') { + $url_string = Minz_Helper::htmlspecialchars_utf8($url_string . $url); } else { $url_string .= $url; } return $url_string; } - + /** - * Construit l'URI d'une URL sans url rewriting + * Construit l'URI d'une URL * @param l'url sous forme de tableau * @param $encodage pour indiquer comment encoder les & (& ou & pour html) * @return l'uri sous la forme ?key=value&key2=value2 */ - private static function printUri ($url, $encodage) { + private static function printUri($url, $encodage) { $uri = ''; - $separator = '/?'; - - if($encodage == 'html') { + $separator = '?'; + + if ($encodage === 'html') { $and = '&'; } else { $and = '&'; } - - if (isset ($url['c']) - && $url['c'] != Minz_Request::defaultControllerName ()) { + + if (isset($url['c']) + && $url['c'] != Minz_Request::defaultControllerName()) { $uri .= $separator . 'c=' . $url['c']; $separator = $and; } - - if (isset ($url['a']) - && $url['a'] != Minz_Request::defaultActionName ()) { + + if (isset($url['a']) + && $url['a'] != Minz_Request::defaultActionName()) { $uri .= $separator . 'a=' . $url['a']; $separator = $and; } - - if (isset ($url['params'])) { + + if (isset($url['params'])) { + unset($url['params']['c']); + unset($url['params']['a']); foreach ($url['params'] as $key => $param) { - $uri .= $separator . $key . '=' . $param; + $uri .= $separator . urlencode($key) . '=' . urlencode($param); $separator = $and; } } - + return $uri; } - + /** * Vérifie que les éléments du tableau représentant une url soit ok * @param l'url sous forme de tableau (sinon renverra directement $url) @@ -98,7 +96,7 @@ class Minz_Url { */ public static function checkUrl ($url) { $url_checked = $url; - + if (is_array ($url)) { if (!isset ($url['c'])) { $url_checked['c'] = Minz_Request::defaultControllerName (); @@ -110,7 +108,7 @@ class Minz_Url { $url_checked['params'] = array (); } } - + return $url_checked; } } diff --git a/lib/Minz/View.php b/lib/Minz/View.php index e170bd406..8c5230ab6 100644 --- a/lib/Minz/View.php +++ b/lib/Minz/View.php @@ -13,8 +13,9 @@ class Minz_View { const LAYOUT_FILENAME = '/layout.phtml'; private $view_filename = ''; - private $use_layout = null; + private $use_layout = true; + private static $base_pathnames = array(APP_PATH); private static $title = ''; private static $styles = array (); private static $scripts = array (); @@ -26,21 +27,37 @@ class Minz_View { * Détermine si on utilise un layout ou non */ public function __construct () { - $this->view_filename = APP_PATH - . self::VIEWS_PATH_NAME . '/' - . Minz_Request::controllerName () . '/' - . Minz_Request::actionName () . '.phtml'; + $this->change_view(Minz_Request::controllerName(), + Minz_Request::actionName()); - self::$title = Minz_Configuration::title (); + $conf = Minz_Configuration::get('system'); + self::$title = $conf->title; + } + + /** + * Change le fichier de vue en fonction d'un controller / action + */ + public function change_view($controller_name, $action_name) { + $this->view_filename = self::VIEWS_PATH_NAME . '/' + . $controller_name . '/' + . $action_name . '.phtml'; + } + + /** + * Add a base pathname to search views. + * + * New pathnames will be added at the beginning of the list. + * + * @param $base_pathname the new base pathname. + */ + public static function addBasePathname($base_pathname) { + array_unshift(self::$base_pathnames, $base_pathname); } /** * Construit la vue */ public function build () { - if ($this->use_layout === null) { //TODO: avoid file_exists and require views to be explicit - $this->use_layout = file_exists (APP_PATH . self::LAYOUT_PATH_NAME . self::LAYOUT_FILENAME); - } if ($this->use_layout) { $this->buildLayout (); } else { @@ -49,24 +66,41 @@ class Minz_View { } /** + * Include a view file. + * + * The file is searched inside list of $base_pathnames. + * + * @param $filename the name of the file to include. + * @return true if the file has been included, false else. + */ + private function includeFile($filename) { + // We search the filename in the list of base pathnames. Only the first view + // found is considered. + foreach (self::$base_pathnames as $base) { + $absolute_filename = $base . $filename; + if (file_exists($absolute_filename)) { + include $absolute_filename; + return true; + } + } + + return false; + } + + /** * Construit le layout */ public function buildLayout () { - include ( - APP_PATH - . self::LAYOUT_PATH_NAME - . self::LAYOUT_FILENAME - ); + header('Content-Type: text/html; charset=UTF-8'); + $this->includeFile(self::LAYOUT_PATH_NAME . self::LAYOUT_FILENAME); } /** * Affiche la Vue en elle-même */ public function render () { - if ((include($this->view_filename)) === false) { - Minz_Log::record ('File not found: `' - . $this->view_filename . '`', - Minz_Log::NOTICE); + if (!$this->includeFile($this->view_filename)) { + Minz_Log::notice('File not found: `' . $this->view_filename . '`'); } } @@ -75,14 +109,9 @@ class Minz_View { * @param $part l'élément partial à ajouter */ public function partial ($part) { - $fic_partial = APP_PATH - . self::LAYOUT_PATH_NAME . '/' - . $part . '.phtml'; - - if ((include($fic_partial)) === false) { - Minz_Log::record ('File not found: `' - . $fic_partial . '`', - Minz_Log::WARNING); + $fic_partial = self::LAYOUT_PATH_NAME . '/' . $part . '.phtml'; + if (!$this->includeFile($fic_partial)) { + Minz_Log::warning('File not found: `' . $fic_partial . '`'); } } @@ -91,18 +120,23 @@ class Minz_View { * @param $helper l'élément à afficher */ public function renderHelper ($helper) { - $fic_helper = APP_PATH - . '/views/helpers/' - . $helper . '.phtml'; - - if ((include($fic_helper)) === false) {; - Minz_Log::record ('File not found: `' - . $fic_helper . '`', - Minz_Log::WARNING); + $fic_helper = '/views/helpers/' . $helper . '.phtml'; + if (!$this->includeFile($fic_helper)) { + Minz_Log::warning('File not found: `' . $fic_helper . '`'); } } /** + * Retourne renderHelper() dans une chaîne + * @param $helper l'élément à traîter + */ + public function helperToString($helper) { + ob_start(); + $this->renderHelper($helper); + return ob_get_clean(); + } + + /** * Permet de choisir si on souhaite utiliser le layout * @param $use true si on souhaite utiliser le layout, false sinon */ |
