diff options
| author | 2015-01-08 14:18:32 +0100 | |
|---|---|---|
| committer | 2015-01-08 14:18:32 +0100 | |
| commit | 73023bc12b81a27045703e1f733faeb2b4e02cec (patch) | |
| tree | 14aca1a1953d0a813c06794e48a63738abccdcea /lib | |
| parent | 26da4aa448906f857a252507b34d369a386043c6 (diff) | |
| parent | 0e4e16ac55097aa173c7c439367294ebd7645562 (diff) | |
Merge branch 'dev' into 252-extensions
Conflicts:
app/FreshRSS.php
app/Models/Configuration.php
app/views/index/index.phtml
app/views/index/normal.phtml
lib/Minz/Configuration.php
lib/Minz/Translate.php
lib/lib_rss.php
Diffstat (limited to 'lib')
| -rw-r--r-- | lib/Favicon/DataAccess.php | 40 | ||||
| -rw-r--r-- | lib/Favicon/Favicon.php | 293 | ||||
| -rw-r--r-- | lib/Minz/BadConfigurationException.php | 9 | ||||
| -rw-r--r-- | lib/Minz/Configuration.php | 548 | ||||
| -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/Error.php | 7 | ||||
| -rw-r--r-- | lib/Minz/ExtensionManager.php | 3 | ||||
| -rw-r--r-- | lib/Minz/FrontController.php | 30 | ||||
| -rw-r--r-- | lib/Minz/Log.php | 17 | ||||
| -rw-r--r-- | lib/Minz/ModelPdo.php | 5 | ||||
| -rw-r--r-- | lib/Minz/Request.php | 3 | ||||
| -rw-r--r-- | lib/Minz/Session.php | 2 | ||||
| -rw-r--r-- | lib/Minz/Translate.php | 25 | ||||
| -rw-r--r-- | lib/Minz/View.php | 4 | ||||
| -rw-r--r-- | lib/lib_rss.php | 104 |
17 files changed, 676 insertions, 430 deletions
diff --git a/lib/Favicon/DataAccess.php b/lib/Favicon/DataAccess.php new file mode 100644 index 000000000..2bfdf640e --- /dev/null +++ b/lib/Favicon/DataAccess.php @@ -0,0 +1,40 @@ +<?php + +namespace Favicon; + +/** + * DataAccess is a wrapper used to read/write data locally or remotly + * Aside from SOLID principles, this wrapper is also useful to mock remote resources in unit tests + * Note: remote access warning are silenced because we don't care if a website is unreachable + **/ +class DataAccess { + public function retrieveUrl($url) { + $this->set_context(); + return @file_get_contents($url); + } + + public function retrieveHeader($url) { + $this->set_context(); + return @get_headers($url, TRUE); + } + + public function saveCache($file, $data) { + file_put_contents($file, $data); + } + + public function readCache($file) { + return file_get_contents($file); + } + + private function set_context() { + stream_context_set_default( + array( + 'http' => array( + 'method' => 'GET', + 'timeout' => 10, + 'header' => "User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:20.0; Favicon; +https://github.com/ArthurHoaro/favicon) Gecko/20100101 Firefox/32.0\r\n", + ) + ) + ); + } +}
\ No newline at end of file diff --git a/lib/Favicon/Favicon.php b/lib/Favicon/Favicon.php new file mode 100644 index 000000000..7ea6ccf16 --- /dev/null +++ b/lib/Favicon/Favicon.php @@ -0,0 +1,293 @@ +<?php + +namespace Favicon; + +class Favicon +{ + protected $url = ''; + protected $cacheDir; + protected $cacheTimeout; + protected $dataAccess; + + public function __construct($args = array()) + { + if (isset($args['url'])) { + $this->url = $args['url']; + } + + $this->cacheDir = __DIR__ . '/../../resources/cache'; + $this->dataAccess = new DataAccess(); + } + + public function cache($args = array()) { + if (isset($args['dir'])) { + $this->cacheDir = $args['dir']; + } + + if (!empty($args['timeout'])) { + $this->cacheTimeout = $args['timeout']; + } else { + $this->cacheTimeout = 0; + } + } + + public static function baseUrl($url, $path = false) + { + $return = ''; + + if (!$url = parse_url($url)) { + return FALSE; + } + + // Scheme + $scheme = isset($url['scheme']) ? strtolower($url['scheme']) : null; + if ($scheme != 'http' && $scheme != 'https') { + + return FALSE; + } + $return .= "{$scheme}://"; + + // Username and password + if (isset($url['user'])) { + $return .= $url['user']; + if (isset($url['pass'])) { + $return .= ":{$url['pass']}"; + } + $return .= '@'; + } + + // Hostname + if( !isset($url['host']) ) { + return FALSE; + } + + $return .= $url['host']; + + // Port + if (isset($url['port'])) { + $return .= ":{$url['port']}"; + } + + // Path + if( $path && isset($url['path']) ) { + $return .= $url['path']; + } + $return .= '/'; + + return $return; + } + + public function info($url) + { + if(empty($url) || $url === false) { + return false; + } + + $max_loop = 5; + + // Discover real status by following redirects. + $loop = TRUE; + while ($loop && $max_loop-- > 0) { + $headers = $this->dataAccess->retrieveHeader($url); + $exploded = explode(' ', $headers[0]); + + if( !isset($exploded[1]) ) { + return false; + } + list(,$status) = $exploded; + + switch ($status) { + case '301': + case '302': + $url = $headers['Location']; + break; + default: + $loop = FALSE; + break; + } + } + + return array('status' => $status, 'url' => $url); + } + + public function endRedirect($url) { + $out = $this->info($url); + return !empty($out['url']) ? $out['url'] : false; + } + + /** + * Find remote (or cached) favicon + * @return favicon URL, false if nothing was found + **/ + public function get($url = '') + { + // URLs passed to this method take precedence. + if (!empty($url)) { + $this->url = $url; + } + + // Get the base URL without the path for clearer concatenations. + $original = rtrim($this->baseUrl($this->url, true), '/'); + $url = rtrim($this->endRedirect($this->baseUrl($this->url, false)), '/'); + + if(($favicon = $this->checkCache($url)) || ($favicon = $this->getFavicon($url))) { + $base = true; + } + elseif(($favicon = $this->checkCache($original)) || ($favicon = $this->getFavicon($original, false))) { + $base = false; + } + else + return false; + + // Save cache if necessary + $cache = $this->cacheDir . '/' . md5($base ? $url : $original); + if ($this->cacheTimeout && !file_exists($cache) || (is_writable($cache) && time() - filemtime($cache) > $this->cacheTimeout)) { + $this->dataAccess->saveCache($cache, $favicon); + } + + return $favicon; + } + + private function getFavicon($url, $checkDefault = true) { + $favicon = false; + + if(empty($url)) { + return false; + } + + // Try /favicon.ico first. + if( $checkDefault ) { + $info = $this->info("{$url}/favicon.ico"); + if ($info['status'] == '200') { + $favicon = $info['url']; + } + } + + // See if it's specified in a link tag in domain url. + if (!$favicon) { + $favicon = $this->getInPage($url); + } + + // Make sure the favicon is an absolute URL. + if( $favicon && filter_var($favicon, FILTER_VALIDATE_URL) === false ) { + $favicon = $url . '/' . $favicon; + } + + // Sometimes people lie, so check the status. + // And sometimes, it's not even an image. Sneaky bastards! + // If cacheDir isn't writable, that's not our problem + if ($favicon && is_writable($this->cacheDir) && !$this->checkImageMType($favicon)) { + $favicon = false; + } + + return $favicon; + } + + private function getInPage($url) { + $html = $this->dataAccess->retrieveUrl("{$url}/"); + preg_match('!<head.*?>.*</head>!ims', $html, $match); + + if(empty($match) || count($match) == 0) { + return false; + } + + $head = $match[0]; + + $dom = new \DOMDocument(); + // Use error supression, because the HTML might be too malformed. + if (@$dom->loadHTML($head)) { + $links = $dom->getElementsByTagName('link'); + foreach ($links as $link) { + if ($link->hasAttribute('rel') && strtolower($link->getAttribute('rel')) == 'shortcut icon') { + return $link->getAttribute('href'); + } elseif ($link->hasAttribute('rel') && strtolower($link->getAttribute('rel')) == 'icon') { + return $link->getAttribute('href'); + } elseif ($link->hasAttribute('href') && strpos($link->getAttribute('href'), 'favicon') !== FALSE) { + return $link->getAttribute('href'); + } + } + } + return false; + } + + private function checkCache($url) { + if ($this->cacheTimeout) { + $cache = $this->cacheDir . '/' . md5($url); + if (file_exists($cache) && is_readable($cache) && (time() - filemtime($cache) < $this->cacheTimeout)) { + return $this->dataAccess->readCache($cache); + } + } + return false; + } + + private function checkImageMType($url) { + $tmpFile = $this->cacheDir . '/tmp.ico'; + + $fileContent = $this->dataAccess->retrieveUrl($url); + $this->dataAccess->saveCache($tmpFile, $fileContent); + + $finfo = finfo_open(FILEINFO_MIME_TYPE); + $isImage = strpos(finfo_file($finfo, $tmpFile), 'image') !== false; + finfo_close($finfo); + + unlink($tmpFile); + + return $isImage; + } + + /** + * @return mixed + */ + public function getCacheDir() + { + return $this->cacheDir; + } + + /** + * @param mixed $cacheDir + */ + public function setCacheDir($cacheDir) + { + $this->cacheDir = $cacheDir; + } + + /** + * @return mixed + */ + public function getCacheTimeout() + { + return $this->cacheTimeout; + } + + /** + * @param mixed $cacheTimeout + */ + public function setCacheTimeout($cacheTimeout) + { + $this->cacheTimeout = $cacheTimeout; + } + + /** + * @return string + */ + public function getUrl() + { + return $this->url; + } + + /** + * @param string $url + */ + public function setUrl($url) + { + $this->url = $url; + } + + /** + * @param DataAccess $dataAccess + */ + public function setDataAccess($dataAccess) + { + $this->dataAccess = $dataAccess; + } +} 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/Configuration.php b/lib/Minz/Configuration.php index 4a3221ef5..fe415e22b 100644 --- a/lib/Minz/Configuration.php +++ b/lib/Minz/Configuration.php @@ -1,169 +1,105 @@ <?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 + * @throws Minz_ConfigurationNamespaceException if the namespace already exists. */ - const SILENT = 0; - const PRODUCTION = 1; - const DEVELOPMENT = 2; + public static function register($namespace, $config_filename, $default_filename = null, + $configuration_setter = null) { + if (isset(self::$config_list[$namespace])) { + throw new Minz_ConfigurationNamespaceException( + $namespace . ' namespace already exists' + ); + } + + 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 - * $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 - * $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 $title = ''; - private static $language = 'en'; - private static $default_user = ''; - private static $allow_anonymous = false; - private static $allow_anonymous_refresh = false; - private static $auth_type = 'none'; - private static $api_enabled = false; - private static $unsafe_autologin_enabled = false; + public static function load($filename) { + if (!file_exists($filename)) { + throw new Minz_FileNotExistException($filename); + } - private static $db = array ( - 'type' => 'mysql', - 'host' => '', - 'user' => '', - 'password' => '', - 'base' => '', - 'prefix' => '', - ); + $data = @include($filename); + if (is_array($data)) { + return $data; + } else { + return array(); + } + } - const MAX_SMALL_INT = 16384; - private static $limits = array( - 'cache_duration' => 800, //SimplePie cache duration in seconds - 'timeout' => 10, //SimplePie timeout in seconds - 'max_inactivity' => PHP_INT_MAX, //Time in seconds after which a user who has not used the account is considered inactive (no auto-refresh of feeds). - 'max_feeds' => Minz_Configuration::MAX_SMALL_INT, - 'max_categories' => Minz_Configuration::MAX_SMALL_INT, - ); + /** + * 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' + ); + } - private static $extensions_enabled = array(); + return self::$config_list[$namespace]; + } - /* - * Getteurs + /** + * The namespace of the current configuration. */ - public static function salt () { - return self::$salt; - } - public static function environment ($str = false) { - $env = self::$environment; + private $namespace = ''; - if ($str) { - switch (self::$environment) { - case self::SILENT: - $env = 'silent'; - break; - case self::DEVELOPMENT: - $env = 'development'; - break; - case self::PRODUCTION: - default: - $env = 'production'; - } - } + /** + * The filename for the current configuration. + */ + private $config_filename = ''; - return $env; - } - public static function baseUrl () { - return self::$base_url; - } - public static function title () { - return self::$title; - } - public static function language () { - return self::$language; - } - public static function dataBase () { - return self::$db; - } - public static function limits() { - return self::$limits; - } - public static function defaultUser () { - return 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'; - } - public static function apiEnabled() { - return self::$api_enabled; - } - public static function unsafeAutologinEnabled() { - return self::$unsafe_autologin_enabled; - } - public static function extensionsEnabled() { - return self::$extensions_enabled; - } + /** + * The filename for the current default values, null by default. + */ + private $default_filename = null; - 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(); - } - public static function _authType($value) { - $value = strtolower($value); - switch ($value) { - case 'form': - case 'http_auth': - case 'persona': - case 'none': - self::$auth_type = $value; - break; - } - self::_allowAnonymous(self::$allow_anonymous); - } + /** + * The configuration values, an empty array by default. + */ + private $data = array(); - public static function _enableApi($value = false) { - self::$api_enabled = (bool)$value; - } - public static function _enableAutologin($value = false) { - self::$unsafe_autologin_enabled = (bool)$value; - } + /** + * The default values, an empty array by default. + */ + private $data_default = 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( @@ -179,266 +115,114 @@ class Minz_Configuration { } /** - * 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; + try { - self::parseFile (); - self::setReporting (); + $this->data = self::load($this->config_filename); } catch (Minz_FileNotExistException $e) { - throw $e; - } catch (Minz_BadConfigurationException $e) { - throw $e; + if (is_null($default_filename)) { + throw $e; + } } - } - public static function writeFile() { - $ini_array = array( - 'general' => array( - 'environment' => self::environment(true), - '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, - 'api_enabled' => self::$api_enabled, - 'unsafe_autologin_enabled' => self::$unsafe_autologin_enabled, - ), - 'limits' => self::$limits, - 'db' => self::$db, - 'extensions_enabled' => self::$extensions_enabled, - ); - @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 + $this->default_filename = $default_filename; + if (!is_null($this->default_filename)) { + $this->data_default = self::load($this->default_filename); } - return (bool)$result; + + $this->_configurationSetter($configuration_setter); } /** - * 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é + * 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. */ - 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 _configurationSetter($configuration_setter) { + if (is_callable(array($configuration_setter, 'handle'))) { + $this->configuration_setter = $configuration_setter; } + } - // [general] est obligatoire - if (!isset ($ini_array['general'])) { - throw new Minz_BadConfigurationException ( - '[general]', - Minz_Exception::ERROR - ); - } - $general = $ini_array['general']; - - // 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 - ); - } + /** + * 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 + */ + public function param($key, $default = null) { + if (isset($this->data[$key])) { + return $this->data[$key]; + } elseif (!is_null($default)) { + return $default; + } elseif (isset($this->data_default[$key])) { + return $this->data_default[$key]; + } else { + Minz_Log::warning($key . ' does not exist in configuration'); + return null; } - 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 __get($key) { + return $this->param($key); + } + /** + * 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; } - if (isset ($general['base_url'])) { - self::$base_url = $general['base_url']; - } + } - if (isset ($general['title'])) { - self::$title = $general['title']; - } - if (isset ($general['language'])) { - self::$language = $general['language']; - } - 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') - ); - } - if (isset ($general['api_enabled'])) { - self::$api_enabled = ( - ((bool)($general['api_enabled'])) && - ($general['api_enabled'] !== 'no') - ); - } - if (isset ($general['unsafe_autologin_enabled'])) { - self::$unsafe_autologin_enabled = ( - ((bool)($general['unsafe_autologin_enabled'])) && - ($general['unsafe_autologin_enabled'] !== 'no') - ); - } + /** + * A wrapper for _param(). + */ + public function __set($key, $value) { + $this->_param($key, $value); + } - if (isset($ini_array['limits'])) { - $limits = $ini_array['limits']; - if (isset($limits['cache_duration'])) { - $v = intval($limits['cache_duration']); - if ($v > 0) { - self::$limits['cache_duration'] = $v; - } - } - if (isset($limits['timeout'])) { - $v = intval($limits['timeout']); - if ($v > 0) { - self::$limits['timeout'] = $v; - } - } - if (isset($limits['max_inactivity'])) { - $v = intval($limits['max_inactivity']); - if ($v > 0) { - self::$limits['max_inactivity'] = $v; - } - } - if (isset($limits['max_feeds'])) { - $v = intval($limits['max_feeds']); - if ($v > 0 && $v < Minz_Configuration::MAX_SMALL_INT) { - self::$limits['max_feeds'] = $v; - } - } - if (isset($limits['max_categories'])) { - $v = intval($limits['max_categories']); - if ($v > 0 && $v < Minz_Configuration::MAX_SMALL_INT) { - self::$limits['max_categories'] = $v; - } - } - } + /** + * Save the current configuration in the configuration file. + */ + public function save() { + $back_filename = $this->config_filename . '.bak.php'; + @rename($this->config_filename, $back_filename); - // Extensions - if (isset($ini_array['extensions_enabled']) && - is_array($ini_array['extensions_enabled'])) { - self::$extensions_enabled = $ini_array['extensions_enabled']; + if (file_put_contents($this->config_filename, + "<?php\nreturn " . var_export($this->data, true) . ';', + LOCK_EX) === false) { + return false; } - // Base de données - if (isset ($ini_array['db'])) { - $db = $ini_array['db']; - if (empty($db['type'])) { - throw new Minz_BadConfigurationException ( - 'type', - Minz_Exception::ERROR - ); - } - switch ($db['type']) { - case 'mysql': - 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 - ); - } - 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']; - } - break; - case 'sqlite': - self::$db['host'] = ''; - self::$db['user'] = ''; - self::$db['password'] = ''; - self::$db['base'] = ''; - self::$db['prefix'] = ''; - break; - default: - throw new Minz_BadConfigurationException ( - 'type', - Minz_Exception::ERROR - ); - break; - } - self::$db['type'] = $db['type']; + // 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/Error.php b/lib/Minz/Error.php index e5f3dff07..3eadc6d98 100644 --- a/lib/Minz/Error.php +++ b/lib/Minz/Error.php @@ -82,7 +82,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 (); @@ -98,10 +99,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/ExtensionManager.php b/lib/Minz/ExtensionManager.php index 9e6a3155a..5880e80f6 100644 --- a/lib/Minz/ExtensionManager.php +++ b/lib/Minz/ExtensionManager.php @@ -38,7 +38,8 @@ class Minz_ExtensionManager { array('..', '.') )); - self::$ext_auto_enabled = Minz_Configuration::extensionsEnabled(); + $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; diff --git a/lib/Minz/FrontController.php b/lib/Minz/FrontController.php index e95c56bf3..f9eff3db6 100644 --- a/lib/Minz/FrontController.php +++ b/lib/Minz/FrontController.php @@ -30,14 +30,13 @@ class Minz_FrontController { * 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(); $url = $this->buildUrl(); $url['params'] = array_merge ( @@ -114,4 +113,23 @@ class Minz_FrontController { } exit ('### Application problem ###<br />'."\n".$txt); } + + 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/Log.php b/lib/Minz/Log.php index d3eaec2ae..2a9e10993 100644 --- a/lib/Minz/Log.php +++ b/lib/Minz/Log.php @@ -28,16 +28,21 @@ 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'; + $file_name = join_path(USERS_PATH, Minz_Session::param('currentUser', '_'), 'log.txt'); } switch ($level) { @@ -71,7 +76,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)); diff --git a/lib/Minz/ModelPdo.php b/lib/Minz/ModelPdo.php index 6198cd85c..ac7a1bed7 100644 --- a/lib/Minz/ModelPdo.php +++ b/lib/Minz/ModelPdo.php @@ -44,7 +44,8 @@ class Minz_ModelPdo { return; } - $db = Minz_Configuration::dataBase(); + $conf = Minz_Configuration::get('system'); + $db = $conf->db; if ($currentUser === null) { $currentUser = Minz_Session::param('currentUser', '_'); @@ -63,7 +64,7 @@ class Minz_ModelPdo { ); $this->prefix = $db['prefix'] . $currentUser . '_'; } elseif ($type === 'sqlite') { - $string = 'sqlite:' . DATA_PATH . '/' . $currentUser . '.sqlite'; + $string = 'sqlite:' . join_path(DATA_PATH, 'users', $currentUser, 'db.sqlite'); $driver_options = array( //PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, ); diff --git a/lib/Minz/Request.php b/lib/Minz/Request.php index 4b97a3caf..6db2e9c7a 100644 --- a/lib/Minz/Request.php +++ b/lib/Minz/Request.php @@ -96,7 +96,8 @@ class Minz_Request { * @return la base de l'url */ public static function getBaseUrl() { - $defaultBaseUrl = Minz_Configuration::baseUrl(); + $conf = Minz_Configuration::get('system'); + $defaultBaseUrl = $conf->base_url; if (!empty($defaultBaseUrl)) { return $defaultBaseUrl; } elseif (isset($_SERVER['REQUEST_URI'])) { diff --git a/lib/Minz/Session.php b/lib/Minz/Session.php index af4de75bb..cfe8debe9 100644 --- a/lib/Minz/Session.php +++ b/lib/Minz/Session.php @@ -55,7 +55,7 @@ class Minz_Session { if (!$force) { self::_param('language', $language); - Minz_Translate::reset(); + Minz_Translate::reset($language); } } diff --git a/lib/Minz/Translate.php b/lib/Minz/Translate.php index aa96728f2..b05c9c695 100644 --- a/lib/Minz/Translate.php +++ b/lib/Minz/Translate.php @@ -25,22 +25,31 @@ class Minz_Translate { private static $translates = array(); /** - * Load $lang_name and $lang_path based on configuration and selected language. + * Init the translation object. + * @param $lang_name the lang to show. */ - public static function init() { - $l = Minz_Configuration::language(); - self::$lang_name = Minz_Session::param('language', $l); + public static function init($lang_name) { + self::$lang_name = $lang_name; self::$lang_files = array(); self::$translates = array(); - self::registerPath(APP_PATH . '/i18n'); } /** - * Alias for init(). + * Reset the translation object with a new language. + * @param $lang_name the new language to use + */ + public static function reset($lang_name) { + self::init($lang_name); + } + + /** + * Return the list of available languages. + * @return an array. + * @todo fix this method. */ - public static function reset() { - self::init(); + public static function availableLanguages() { + return array(); } /** diff --git a/lib/Minz/View.php b/lib/Minz/View.php index 44034ae9a..ff5cce4a5 100644 --- a/lib/Minz/View.php +++ b/lib/Minz/View.php @@ -29,7 +29,9 @@ class Minz_View { public function __construct () { $this->change_view(Minz_Request::controllerName(), Minz_Request::actionName()); - self::$title = Minz_Configuration::title (); + + $conf = Minz_Configuration::get('system'); + self::$title = $conf->title; } /** diff --git a/lib/lib_rss.php b/lib/lib_rss.php index c2bd2bfb3..083e87745 100644 --- a/lib/lib_rss.php +++ b/lib/lib_rss.php @@ -15,6 +15,17 @@ if (!function_exists('json_encode')) { } } +/** + * Build a directory path by concatenating a list of directory names. + * + * @param $path_parts a list of directory names + * @return a string corresponding to the final pathname + */ +function join_path() { + $path_parts = func_get_args(); + return join(DIRECTORY_SEPARATOR, $path_parts); +} + //<Auto-loading> function classAutoloader($class) { if (strpos($class, 'FreshRSS') === 0) { @@ -108,7 +119,8 @@ function html_only_entity_decode($text) { } function customSimplePie() { - $limits = Minz_Configuration::limits(); + $system_conf = Minz_Configuration::get('system'); + $limits = $system_conf->limits; $simplePie = new SimplePie(); $simplePie->set_useragent(_t('gen.freshrss') . '/' . FRESHRSS_VERSION . ' (' . PHP_OS . '; ' . FRESHRSS_WEBSITE . ') ' . SIMPLEPIE_NAME . '/' . SIMPLEPIE_VERSION); $simplePie->set_cache_location(CACHE_PATH); @@ -205,21 +217,53 @@ function uSecString() { function invalidateHttpCache() { Minz_Session::_param('touch', uTimeString()); - return touch(LOG_PATH . '/' . Minz_Session::param('currentUser', '_') . '.log'); + return touch(join_path(DATA_PATH, 'users', Minz_Session::param('currentUser', '_'), 'log.txt')); } -function usernameFromPath($userPath) { - if (preg_match('%/([A-Za-z0-9]{1,16})_user\.php$%', $userPath, $matches)) { - return $matches[1]; - } else { - return ''; +function listUsers() { + $final_list = array(); + $base_path = join_path(DATA_PATH, 'users'); + $dir_list = array_values(array_diff( + scandir($base_path), + array('..', '.', '_') + )); + + foreach ($dir_list as $file) { + if (is_dir(join_path($base_path, $file))) { + $final_list[] = $file; + } } + + return $final_list; } -function listUsers() { - return array_map('usernameFromPath', glob(DATA_PATH . '/*_user.php')); + +/** + * Register and return the configuration for a given user. + * + * Note this function has been created to generate temporary configuration + * objects. If you need a long-time configuration, please don't use this function. + * + * @param $username the name of the user of which we want the configuration. + * @return a Minz_Configuration object, null if the configuration cannot be loaded. + */ +function get_user_configuration($username) { + $namespace = time() . '_user_' . $username; + try { + Minz_Configuration::register($namespace, + join_path(USERS_PATH, $username, 'config.php'), + join_path(USERS_PATH, '_', 'config.default.php')); + } catch (Minz_ConfigurationNamespaceException $e) { + // namespace already exists, do nothing. + } catch (Minz_FileNotExistException $e) { + Minz_Log::warning($e->getMessage()); + return null; + } + + return Minz_Configuration::get($namespace); } + function httpAuthUser() { return isset($_SERVER['REMOTE_USER']) ? $_SERVER['REMOTE_USER'] : ''; } @@ -284,7 +328,7 @@ function check_install_files() { return array( 'data' => DATA_PATH && is_writable(DATA_PATH), 'cache' => CACHE_PATH && is_writable(CACHE_PATH), - 'logs' => LOG_PATH && is_writable(LOG_PATH), + 'users' => USERS_PATH && is_writable(USERS_PATH), 'favicons' => is_writable(DATA_PATH . '/favicons'), 'persona' => is_writable(DATA_PATH . '/persona'), 'tokens' => is_writable(DATA_PATH . '/tokens'), @@ -345,3 +389,43 @@ function recursive_unlink($dir) { return rmdir($dir); } + + +/** + * Remove queries where $get is appearing. + * @param $get the get attribute which should be removed. + * @param $queries an array of queries. + * @return the same array whithout those where $get is appearing. + */ +function remove_query_by_get($get, $queries) { + $final_queries = array(); + foreach ($queries as $key => $query) { + if (empty($query['get']) || $query['get'] !== $get) { + $final_queries[$key] = $query; + } + } + return $final_queries; +} + + +/** + * Add a value in an array and take care it is unique. + * @param $array the array in which we add the value. + * @param $value the value to add. + */ +function array_push_unique(&$array, $value) { + $found = array_search($value, $array) !== false; + if (!$found) { + $array[] = $value; + } +} + + +/** + * Remove a value from an array. + * @param $array the array from wich value is removed. + * @param $value the value to remove. + */ +function array_remove(&$array, $value) { + $array = array_diff($array, array($value)); +} |
