diff options
Diffstat (limited to 'app/Models')
| -rw-r--r-- | app/Models/Auth.php | 254 | ||||
| -rw-r--r-- | app/Models/Category.php | 44 | ||||
| -rw-r--r-- | app/Models/CategoryDAO.php | 170 | ||||
| -rw-r--r-- | app/Models/Configuration.php | 335 | ||||
| -rw-r--r-- | app/Models/ConfigurationSetter.php | 374 | ||||
| -rw-r--r-- | app/Models/Context.php | 304 | ||||
| -rw-r--r-- | app/Models/DatabaseDAO.php | 83 | ||||
| -rw-r--r-- | app/Models/DatabaseDAOSQLite.php | 48 | ||||
| -rw-r--r-- | app/Models/Entry.php | 141 | ||||
| -rw-r--r-- | app/Models/EntryDAO.php | 182 | ||||
| -rw-r--r-- | app/Models/EntryDAOSQLite.php | 61 | ||||
| -rw-r--r-- | app/Models/Factory.php | 39 | ||||
| -rw-r--r-- | app/Models/Feed.php | 25 | ||||
| -rw-r--r-- | app/Models/FeedDAO.php | 22 | ||||
| -rw-r--r-- | app/Models/FeedDAOSQLite.php | 2 | ||||
| -rw-r--r-- | app/Models/Log.php | 12 | ||||
| -rw-r--r-- | app/Models/LogDAO.php | 14 | ||||
| -rw-r--r-- | app/Models/Share.php | 232 | ||||
| -rw-r--r-- | app/Models/StatsDAO.php | 60 | ||||
| -rw-r--r-- | app/Models/Themes.php | 1 | ||||
| -rw-r--r-- | app/Models/UserDAO.php | 26 |
21 files changed, 1745 insertions, 684 deletions
diff --git a/app/Models/Auth.php b/app/Models/Auth.php new file mode 100644 index 000000000..4e7a71947 --- /dev/null +++ b/app/Models/Auth.php @@ -0,0 +1,254 @@ +<?php + +/** + * This class handles all authentication process. + */ +class FreshRSS_Auth { + /** + * Determines if user is connected. + */ + private static $login_ok = false; + + /** + * This method initializes authentication system. + */ + public static function init() { + self::$login_ok = Minz_Session::param('loginOk', false); + $current_user = Minz_Session::param('currentUser', ''); + if ($current_user === '') { + $conf = Minz_Configuration::get('system'); + $current_user = $conf->default_user; + Minz_Session::_param('currentUser', $current_user); + } + + if (self::$login_ok) { + self::giveAccess(); + } elseif (self::accessControl()) { + self::giveAccess(); + FreshRSS_UserDAO::touch($current_user); + } else { + // Be sure all accesses are removed! + self::removeAccess(); + } + } + + /** + * This method checks if user is allowed to connect. + * + * Required session parameters are also set in this method (such as + * currentUser). + * + * @return boolean true if user can be connected, false else. + */ + private static function accessControl() { + $conf = Minz_Configuration::get('system'); + $auth_type = $conf->auth_type; + switch ($auth_type) { + case 'form': + $credentials = FreshRSS_FormAuth::getCredentialsFromCookie(); + $current_user = ''; + if (isset($credentials[1])) { + $current_user = trim($credentials[0]); + Minz_Session::_param('currentUser', $current_user); + Minz_Session::_param('passwordHash', trim($credentials[1])); + } + return $current_user != ''; + case 'http_auth': + $current_user = httpAuthUser(); + $login_ok = $current_user != ''; + if ($login_ok) { + Minz_Session::_param('currentUser', $current_user); + } + return $login_ok; + case 'persona': + $email = filter_var(Minz_Session::param('mail'), FILTER_VALIDATE_EMAIL); + $persona_file = DATA_PATH . '/persona/' . $email . '.txt'; + if (($current_user = @file_get_contents($persona_file)) !== false) { + $current_user = trim($current_user); + Minz_Session::_param('currentUser', $current_user); + Minz_Session::_param('mail', $email); + return true; + } + return false; + case 'none': + return true; + default: + // TODO load extension + return false; + } + } + + /** + * Gives access to the current user. + */ + public static function giveAccess() { + $current_user = Minz_Session::param('currentUser'); + $user_conf = get_user_configuration($current_user); + $system_conf = Minz_Configuration::get('system'); + + switch ($system_conf->auth_type) { + case 'form': + self::$login_ok = Minz_Session::param('passwordHash') === $user_conf->passwordHash; + break; + case 'http_auth': + self::$login_ok = strcasecmp($current_user, httpAuthUser()) === 0; + break; + case 'persona': + self::$login_ok = strcasecmp(Minz_Session::param('mail'), $user_conf->mail_login) === 0; + break; + case 'none': + self::$login_ok = true; + break; + default: + // TODO: extensions + self::$login_ok = false; + } + + Minz_Session::_param('loginOk', self::$login_ok); + } + + /** + * Returns if current user has access to the given scope. + * + * @param string $scope general (default) or admin + * @return boolean true if user has corresponding access, false else. + */ + public static function hasAccess($scope = 'general') { + $conf = Minz_Configuration::get('system'); + $default_user = $conf->default_user; + $ok = self::$login_ok; + switch ($scope) { + case 'general': + break; + case 'admin': + $ok &= Minz_Session::param('currentUser') === $default_user; + break; + default: + $ok = false; + } + return $ok; + } + + /** + * Removes all accesses for the current user. + */ + public static function removeAccess() { + Minz_Session::_param('loginOk'); + self::$login_ok = false; + $conf = Minz_Configuration::get('system'); + Minz_Session::_param('currentUser', $conf->default_user); + + switch ($conf->auth_type) { + case 'form': + Minz_Session::_param('passwordHash'); + FreshRSS_FormAuth::deleteCookie(); + break; + case 'persona': + Minz_Session::_param('mail'); + break; + case 'http_auth': + case 'none': + // Nothing to do... + break; + default: + // TODO: extensions + } + } + + /** + * Return if authentication is enabled on this instance of FRSS. + */ + public static function accessNeedsLogin() { + $conf = Minz_Configuration::get('system'); + $auth_type = $conf->auth_type; + return $auth_type !== 'none'; + } + + /** + * Return if authentication requires a PHP action. + */ + public static function accessNeedsAction() { + $conf = Minz_Configuration::get('system'); + $auth_type = $conf->auth_type; + return $auth_type === 'form' || $auth_type === 'persona'; + } +} + + +class FreshRSS_FormAuth { + public static function checkCredentials($username, $hash, $nonce, $challenge) { + if (!ctype_alnum($username) || + !ctype_graph($challenge) || + !ctype_alnum($nonce)) { + Minz_Log::debug('Invalid credential parameters:' . + ' user=' . $username . + ' challenge=' . $challenge . + ' nonce=' . $nonce); + return false; + } + + if (!function_exists('password_verify')) { + include_once(LIB_PATH . '/password_compat.php'); + } + + return password_verify($nonce . $hash, $challenge); + } + + public static function getCredentialsFromCookie() { + $token = Minz_Session::getLongTermCookie('FreshRSS_login'); + if (!ctype_alnum($token)) { + return array(); + } + + $token_file = DATA_PATH . '/tokens/' . $token . '.txt'; + $mtime = @filemtime($token_file); + if ($mtime + 2629744 < time()) { + // Token has expired (> 1 month) or does not exist. + // TODO: 1 month -> use a configuration instead + @unlink($token_file); + return array(); + } + + $credentials = @file_get_contents($token_file); + return $credentials === false ? array() : explode("\t", $credentials, 2); + } + + public static function makeCookie($username, $password_hash) { + do { + $conf = Minz_Configuration::get('system'); + $token = sha1($conf->salt . $username . uniqid(mt_rand(), true)); + $token_file = DATA_PATH . '/tokens/' . $token . '.txt'; + } while (file_exists($token_file)); + + if (@file_put_contents($token_file, $username . "\t" . $password_hash) === false) { + return false; + } + + $expire = time() + 2629744; //1 month //TODO: Use a configuration instead + Minz_Session::setLongTermCookie('FreshRSS_login', $token, $expire); + return $token; + } + + public static function deleteCookie() { + $token = Minz_Session::getLongTermCookie('FreshRSS_login'); + Minz_Session::deleteLongTermCookie('FreshRSS_login'); + if (ctype_alnum($token)) { + @unlink(DATA_PATH . '/tokens/' . $token . '.txt'); + } + + if (rand(0, 10) === 1) { + self::purgeTokens(); + } + } + + public static function purgeTokens() { + $oldest = time() - 2629744; // 1 month // TODO: Use a configuration instead + foreach (new DirectoryIterator(DATA_PATH . '/tokens/') as $file_info) { + // $extension = $file_info->getExtension(); doesn't work in PHP < 5.3.7 + $extension = pathinfo($file_info->getFilename(), PATHINFO_EXTENSION); + if ($extension === 'txt' && $file_info->getMTime() < $oldest) { + @unlink($file_info->getPathname()); + } + } + } +} diff --git a/app/Models/Category.php b/app/Models/Category.php index 0a0dbd3ca..37cb44dc3 100644 --- a/app/Models/Category.php +++ b/app/Models/Category.php @@ -7,65 +7,65 @@ class FreshRSS_Category extends Minz_Model { private $nbNotRead = -1; private $feeds = null; - public function __construct ($name = '', $feeds = null) { - $this->_name ($name); - if (isset ($feeds)) { - $this->_feeds ($feeds); + public function __construct($name = '', $feeds = null) { + $this->_name($name); + if (isset($feeds)) { + $this->_feeds($feeds); $this->nbFeed = 0; $this->nbNotRead = 0; foreach ($feeds as $feed) { $this->nbFeed++; - $this->nbNotRead += $feed->nbNotRead (); + $this->nbNotRead += $feed->nbNotRead(); } } } - public function id () { + public function id() { return $this->id; } - public function name () { + public function name() { return $this->name; } - public function nbFeed () { + public function nbFeed() { if ($this->nbFeed < 0) { - $catDAO = new FreshRSS_CategoryDAO (); - $this->nbFeed = $catDAO->countFeed ($this->id ()); + $catDAO = new FreshRSS_CategoryDAO(); + $this->nbFeed = $catDAO->countFeed($this->id()); } return $this->nbFeed; } - public function nbNotRead () { + public function nbNotRead() { if ($this->nbNotRead < 0) { - $catDAO = new FreshRSS_CategoryDAO (); - $this->nbNotRead = $catDAO->countNotRead ($this->id ()); + $catDAO = new FreshRSS_CategoryDAO(); + $this->nbNotRead = $catDAO->countNotRead($this->id()); } return $this->nbNotRead; } - public function feeds () { + public function feeds() { if ($this->feeds === null) { $feedDAO = FreshRSS_Factory::createFeedDao(); - $this->feeds = $feedDAO->listByCategory ($this->id ()); + $this->feeds = $feedDAO->listByCategory($this->id()); $this->nbFeed = 0; $this->nbNotRead = 0; foreach ($this->feeds as $feed) { $this->nbFeed++; - $this->nbNotRead += $feed->nbNotRead (); + $this->nbNotRead += $feed->nbNotRead(); } } return $this->feeds; } - public function _id ($value) { + public function _id($value) { $this->id = $value; } - public function _name ($value) { - $this->name = $value; + public function _name($value) { + $this->name = substr(trim($value), 0, 255); } - public function _feeds ($values) { - if (!is_array ($values)) { - $values = array ($values); + public function _feeds($values) { + if (!is_array($values)) { + $values = array($values); } $this->feeds = $values; diff --git a/app/Models/CategoryDAO.php b/app/Models/CategoryDAO.php index f11f87f47..27a558522 100644 --- a/app/Models/CategoryDAO.php +++ b/app/Models/CategoryDAO.php @@ -1,19 +1,19 @@ <?php class FreshRSS_CategoryDAO extends Minz_ModelPdo { - public function addCategory ($valuesTmp) { - $sql = 'INSERT INTO `' . $this->prefix . 'category` (name) VALUES(?)'; - $stm = $this->bd->prepare ($sql); + public function addCategory($valuesTmp) { + $sql = 'INSERT INTO `' . $this->prefix . 'category`(name) VALUES(?)'; + $stm = $this->bd->prepare($sql); - $values = array ( + $values = array( substr($valuesTmp['name'], 0, 255), ); - if ($stm && $stm->execute ($values)) { + if ($stm && $stm->execute($values)) { return $this->bd->lastInsertId(); } else { $info = $stm == null ? array(2 => 'syntax error') : $stm->errorInfo(); - Minz_Log::record('SQL error addCategory: ' . $info[2], Minz_Log::ERROR); + Minz_Log::error('SQL error addCategory: ' . $info[2] ); return false; } } @@ -31,73 +31,73 @@ class FreshRSS_CategoryDAO extends Minz_ModelPdo { return $cat->id(); } - public function updateCategory ($id, $valuesTmp) { + public function updateCategory($id, $valuesTmp) { $sql = 'UPDATE `' . $this->prefix . 'category` SET name=? WHERE id=?'; - $stm = $this->bd->prepare ($sql); + $stm = $this->bd->prepare($sql); - $values = array ( + $values = array( $valuesTmp['name'], $id ); - if ($stm && $stm->execute ($values)) { + if ($stm && $stm->execute($values)) { return $stm->rowCount(); } else { $info = $stm == null ? array(2 => 'syntax error') : $stm->errorInfo(); - Minz_Log::record('SQL error updateCategory: ' . $info[2], Minz_Log::ERROR); + Minz_Log::error('SQL error updateCategory: ' . $info[2]); return false; } } - public function deleteCategory ($id) { + public function deleteCategory($id) { $sql = 'DELETE FROM `' . $this->prefix . 'category` WHERE id=?'; - $stm = $this->bd->prepare ($sql); + $stm = $this->bd->prepare($sql); - $values = array ($id); + $values = array($id); - if ($stm && $stm->execute ($values)) { + if ($stm && $stm->execute($values)) { return $stm->rowCount(); } else { $info = $stm == null ? array(2 => 'syntax error') : $stm->errorInfo(); - Minz_Log::record('SQL error deleteCategory: ' . $info[2], Minz_Log::ERROR); + Minz_Log::error('SQL error deleteCategory: ' . $info[2]); return false; } } - public function searchById ($id) { + public function searchById($id) { $sql = 'SELECT * FROM `' . $this->prefix . 'category` WHERE id=?'; - $stm = $this->bd->prepare ($sql); + $stm = $this->bd->prepare($sql); - $values = array ($id); + $values = array($id); - $stm->execute ($values); - $res = $stm->fetchAll (PDO::FETCH_ASSOC); - $cat = self::daoToCategory ($res); + $stm->execute($values); + $res = $stm->fetchAll(PDO::FETCH_ASSOC); + $cat = self::daoToCategory($res); - if (isset ($cat[0])) { + if (isset($cat[0])) { return $cat[0]; } else { return null; } } - public function searchByName ($name) { + public function searchByName($name) { $sql = 'SELECT * FROM `' . $this->prefix . 'category` WHERE name=?'; - $stm = $this->bd->prepare ($sql); + $stm = $this->bd->prepare($sql); - $values = array ($name); + $values = array($name); - $stm->execute ($values); - $res = $stm->fetchAll (PDO::FETCH_ASSOC); - $cat = self::daoToCategory ($res); + $stm->execute($values); + $res = $stm->fetchAll(PDO::FETCH_ASSOC); + $cat = self::daoToCategory($res); - if (isset ($cat[0])) { + if (isset($cat[0])) { return $cat[0]; } else { return null; } } - public function listCategories ($prePopulateFeeds = true, $details = false) { + public function listCategories($prePopulateFeeds = true, $details = false) { if ($prePopulateFeeds) { $sql = 'SELECT c.id AS c_id, c.name AS c_name, ' . ($details ? 'f.* ' : 'f.id, f.name, f.url, f.website, f.priority, f.error, f.cache_nbEntries, f.cache_nbUnreads ') @@ -105,80 +105,80 @@ class FreshRSS_CategoryDAO extends Minz_ModelPdo { . 'LEFT OUTER JOIN `' . $this->prefix . 'feed` f ON f.category=c.id ' . 'GROUP BY f.id ' . 'ORDER BY c.name, f.name'; - $stm = $this->bd->prepare ($sql); - $stm->execute (); - return self::daoToCategoryPrepopulated ($stm->fetchAll (PDO::FETCH_ASSOC)); + $stm = $this->bd->prepare($sql); + $stm->execute(); + return self::daoToCategoryPrepopulated($stm->fetchAll(PDO::FETCH_ASSOC)); } else { $sql = 'SELECT * FROM `' . $this->prefix . 'category` ORDER BY name'; - $stm = $this->bd->prepare ($sql); - $stm->execute (); - return self::daoToCategory ($stm->fetchAll (PDO::FETCH_ASSOC)); + $stm = $this->bd->prepare($sql); + $stm->execute(); + return self::daoToCategory($stm->fetchAll(PDO::FETCH_ASSOC)); } } - public function getDefault () { + public function getDefault() { $sql = 'SELECT * FROM `' . $this->prefix . 'category` WHERE id=1'; - $stm = $this->bd->prepare ($sql); + $stm = $this->bd->prepare($sql); - $stm->execute (); - $res = $stm->fetchAll (PDO::FETCH_ASSOC); - $cat = self::daoToCategory ($res); + $stm->execute(); + $res = $stm->fetchAll(PDO::FETCH_ASSOC); + $cat = self::daoToCategory($res); - if (isset ($cat[0])) { + if (isset($cat[0])) { return $cat[0]; } else { return false; } } - public function checkDefault () { - $def_cat = $this->searchById (1); + public function checkDefault() { + $def_cat = $this->searchById(1); if ($def_cat == null) { - $cat = new FreshRSS_Category (Minz_Translate::t ('default_category')); - $cat->_id (1); + $cat = new FreshRSS_Category(_t('gen.short.default_category')); + $cat->_id(1); - $values = array ( - 'id' => $cat->id (), - 'name' => $cat->name (), + $values = array( + 'id' => $cat->id(), + 'name' => $cat->name(), ); - $this->addCategory ($values); + $this->addCategory($values); } } - public function count () { + public function count() { $sql = 'SELECT COUNT(*) AS count FROM `' . $this->prefix . 'category`'; - $stm = $this->bd->prepare ($sql); - $stm->execute (); - $res = $stm->fetchAll (PDO::FETCH_ASSOC); + $stm = $this->bd->prepare($sql); + $stm->execute(); + $res = $stm->fetchAll(PDO::FETCH_ASSOC); return $res[0]['count']; } - public function countFeed ($id) { + public function countFeed($id) { $sql = 'SELECT COUNT(*) AS count FROM `' . $this->prefix . 'feed` WHERE category=?'; - $stm = $this->bd->prepare ($sql); - $values = array ($id); - $stm->execute ($values); - $res = $stm->fetchAll (PDO::FETCH_ASSOC); + $stm = $this->bd->prepare($sql); + $values = array($id); + $stm->execute($values); + $res = $stm->fetchAll(PDO::FETCH_ASSOC); return $res[0]['count']; } - public function countNotRead ($id) { + public function countNotRead($id) { $sql = 'SELECT COUNT(*) AS count FROM `' . $this->prefix . 'entry` e INNER JOIN `' . $this->prefix . 'feed` f ON e.id_feed=f.id WHERE category=? AND e.is_read=0'; - $stm = $this->bd->prepare ($sql); - $values = array ($id); - $stm->execute ($values); - $res = $stm->fetchAll (PDO::FETCH_ASSOC); + $stm = $this->bd->prepare($sql); + $values = array($id); + $stm->execute($values); + $res = $stm->fetchAll(PDO::FETCH_ASSOC); return $res[0]['count']; } public static function findFeed($categories, $feed_id) { foreach ($categories as $category) { - foreach ($category->feeds () as $feed) { - if ($feed->id () === $feed_id) { + foreach ($category->feeds() as $feed) { + if ($feed->id() === $feed_id) { return $feed; } } @@ -189,8 +189,8 @@ class FreshRSS_CategoryDAO extends Minz_ModelPdo { public static function CountUnreads($categories, $minPriority = 0) { $n = 0; foreach ($categories as $category) { - foreach ($category->feeds () as $feed) { - if ($feed->priority () >= $minPriority) { + foreach ($category->feeds() as $feed) { + if ($feed->priority() >= $minPriority) { $n += $feed->nbNotRead(); } } @@ -198,11 +198,11 @@ class FreshRSS_CategoryDAO extends Minz_ModelPdo { return $n; } - public static function daoToCategoryPrepopulated ($listDAO) { - $list = array (); + public static function daoToCategoryPrepopulated($listDAO) { + $list = array(); - if (!is_array ($listDAO)) { - $listDAO = array ($listDAO); + if (!is_array($listDAO)) { + $listDAO = array($listDAO); } $previousLine = null; @@ -210,11 +210,11 @@ class FreshRSS_CategoryDAO extends Minz_ModelPdo { foreach ($listDAO as $line) { if ($previousLine['c_id'] != null && $line['c_id'] !== $previousLine['c_id']) { // End of the current category, we add it to the $list - $cat = new FreshRSS_Category ( + $cat = new FreshRSS_Category( $previousLine['c_name'], - FreshRSS_FeedDAO::daoToFeed ($feedsDao, $previousLine['c_id']) + FreshRSS_FeedDAO::daoToFeed($feedsDao, $previousLine['c_id']) ); - $cat->_id ($previousLine['c_id']); + $cat->_id($previousLine['c_id']); $list[$previousLine['c_id']] = $cat; $feedsDao = array(); //Prepare for next category @@ -226,29 +226,29 @@ class FreshRSS_CategoryDAO extends Minz_ModelPdo { // add the last category if ($previousLine != null) { - $cat = new FreshRSS_Category ( + $cat = new FreshRSS_Category( $previousLine['c_name'], - FreshRSS_FeedDAO::daoToFeed ($feedsDao, $previousLine['c_id']) + FreshRSS_FeedDAO::daoToFeed($feedsDao, $previousLine['c_id']) ); - $cat->_id ($previousLine['c_id']); + $cat->_id($previousLine['c_id']); $list[$previousLine['c_id']] = $cat; } return $list; } - public static function daoToCategory ($listDAO) { - $list = array (); + public static function daoToCategory($listDAO) { + $list = array(); - if (!is_array ($listDAO)) { - $listDAO = array ($listDAO); + if (!is_array($listDAO)) { + $listDAO = array($listDAO); } foreach ($listDAO as $key => $dao) { - $cat = new FreshRSS_Category ( + $cat = new FreshRSS_Category( $dao['name'] ); - $cat->_id ($dao['id']); + $cat->_id($dao['id']); $list[$key] = $cat; } diff --git a/app/Models/Configuration.php b/app/Models/Configuration.php deleted file mode 100644 index 95f819779..000000000 --- a/app/Models/Configuration.php +++ /dev/null @@ -1,335 +0,0 @@ -<?php - -class FreshRSS_Configuration { - private $filename; - - private $data = array( - 'language' => 'en', - 'old_entries' => 3, - 'keep_history_default' => 0, - 'ttl_default' => 3600, - 'mail_login' => '', - 'token' => '', - 'passwordHash' => '', //CRYPT_BLOWFISH - 'apiPasswordHash' => '', //CRYPT_BLOWFISH - 'posts_per_page' => 20, - 'view_mode' => 'normal', - 'default_view' => FreshRSS_Entry::STATE_NOT_READ, - 'auto_load_more' => true, - 'display_posts' => false, - 'display_categories' => false, - 'hide_read_feeds' => true, - 'onread_jump_next' => true, - 'lazyload' => true, - 'sticky_post' => true, - 'reading_confirm' => false, - 'sort_order' => 'DESC', - 'anon_access' => false, - 'mark_when' => array( - 'article' => true, - 'site' => true, - 'scroll' => false, - 'reception' => false, - ), - 'theme' => 'Origine', - 'content_width' => 'thin', - 'shortcuts' => array( - 'mark_read' => 'r', - 'mark_favorite' => 'f', - 'go_website' => 'space', - 'next_entry' => 'j', - 'prev_entry' => 'k', - 'first_entry' => 'home', - 'last_entry' => 'end', - 'collapse_entry' => 'c', - 'load_more' => 'm', - 'auto_share' => 's', - 'focus_search' => 'a', - 'user_filter' => 'u', - 'help' => 'f1', - ), - 'topline_read' => true, - 'topline_favorite' => true, - 'topline_date' => true, - 'topline_link' => true, - 'bottomline_read' => true, - 'bottomline_favorite' => true, - 'bottomline_sharing' => true, - 'bottomline_tags' => true, - 'bottomline_date' => true, - 'bottomline_link' => true, - 'sharing' => array(), - 'queries' => array(), - 'html5_notif_timeout' => 0, - ); - - private $available_languages = array( - 'en' => 'English', - 'fr' => 'Français', - ); - - private $shares; - - public function __construct($user) { - $this->filename = DATA_PATH . DIRECTORY_SEPARATOR . $user . '_user.php'; - - $data = @include($this->filename); - if (!is_array($data)) { - throw new Minz_PermissionDeniedException($this->filename); - } - - foreach ($data as $key => $value) { - if (isset($this->data[$key])) { - $function = '_' . $key; - $this->$function($value); - } - } - $this->data['user'] = $user; - - $this->shares = DATA_PATH . DIRECTORY_SEPARATOR . 'shares.php'; - - $shares = @include($this->shares); - if (!is_array($shares)) { - throw new Minz_PermissionDeniedException($this->shares); - } - - $this->data['shares'] = $shares; - } - - public function save() { - @rename($this->filename, $this->filename . '.bak.php'); - unset($this->data['shares']); // Remove shares because it is not intended to be stored in user configuration - if (file_put_contents($this->filename, "<?php\n return " . var_export($this->data, true) . ';', LOCK_EX) === false) { - throw new Minz_PermissionDeniedException($this->filename); - } - if (function_exists('opcache_invalidate')) { - opcache_invalidate($this->filename); //Clear PHP 5.5+ cache for include - } - invalidateHttpCache(); - return true; - } - - public function __get($name) { - if (array_key_exists($name, $this->data)) { - return $this->data[$name]; - } else { - $trace = debug_backtrace(); - trigger_error('Undefined FreshRSS_Configuration->' . $name . 'in ' . $trace[0]['file'] . ' line ' . $trace[0]['line'], E_USER_NOTICE); //TODO: Use Minz exceptions - return null; - } - } - - public function availableLanguages() { - return $this->available_languages; - } - - public function remove_query_by_get($get) { - $final_queries = array(); - foreach ($this->queries as $key => $query) { - if (empty($query['get']) || $query['get'] !== $get) { - $final_queries[$key] = $query; - } - } - $this->_queries($final_queries); - } - - public function _language($value) { - if (!isset($this->available_languages[$value])) { - $value = 'en'; - } - $this->data['language'] = $value; - } - public function _posts_per_page ($value) { - $value = intval($value); - $this->data['posts_per_page'] = $value > 0 ? $value : 10; - } - public function _view_mode ($value) { - if ($value === 'global' || $value === 'reader') { - $this->data['view_mode'] = $value; - } else { - $this->data['view_mode'] = 'normal'; - } - } - public function _default_view ($value) { - switch ($value) { - case FreshRSS_Entry::STATE_ALL: - // left blank on purpose - case FreshRSS_Entry::STATE_NOT_READ: - // left blank on purpose - case FreshRSS_Entry::STATE_STRICT + FreshRSS_Entry::STATE_NOT_READ: - $this->data['default_view'] = $value; - break; - default: - $this->data['default_view'] = FreshRSS_Entry::STATE_ALL; - break; - } - } - public function _display_posts ($value) { - $this->data['display_posts'] = ((bool)$value) && $value !== 'no'; - } - public function _display_categories ($value) { - $this->data['display_categories'] = ((bool)$value) && $value !== 'no'; - } - public function _hide_read_feeds($value) { - $this->data['hide_read_feeds'] = (bool)$value; - } - public function _onread_jump_next ($value) { - $this->data['onread_jump_next'] = ((bool)$value) && $value !== 'no'; - } - public function _lazyload ($value) { - $this->data['lazyload'] = ((bool)$value) && $value !== 'no'; - } - public function _sticky_post($value) { - $this->data['sticky_post'] = ((bool)$value) && $value !== 'no'; - } - public function _reading_confirm($value) { - $this->data['reading_confirm'] = ((bool)$value) && $value !== 'no'; - } - public function _sort_order ($value) { - $this->data['sort_order'] = $value === 'ASC' ? 'ASC' : 'DESC'; - } - public function _old_entries($value) { - $value = intval($value); - $this->data['old_entries'] = $value > 0 ? $value : 3; - } - public function _keep_history_default($value) { - $value = intval($value); - $this->data['keep_history_default'] = $value >= -1 ? $value : 0; - } - public function _ttl_default($value) { - $value = intval($value); - $this->data['ttl_default'] = $value >= -1 ? $value : 3600; - } - public function _shortcuts ($values) { - foreach ($values as $key => $value) { - if (isset($this->data['shortcuts'][$key])) { - $this->data['shortcuts'][$key] = $value; - } - } - } - public function _passwordHash ($value) { - $this->data['passwordHash'] = ctype_graph($value) && (strlen($value) >= 60) ? $value : ''; - } - public function _apiPasswordHash ($value) { - $this->data['apiPasswordHash'] = ctype_graph($value) && (strlen($value) >= 60) ? $value : ''; - } - public function _mail_login ($value) { - $value = filter_var($value, FILTER_VALIDATE_EMAIL); - if ($value) { - $this->data['mail_login'] = $value; - } else { - $this->data['mail_login'] = ''; - } - } - public function _anon_access ($value) { - $this->data['anon_access'] = ((bool)$value) && $value !== 'no'; - } - public function _mark_when ($values) { - foreach ($values as $key => $value) { - if (isset($this->data['mark_when'][$key])) { - $this->data['mark_when'][$key] = ((bool)$value) && $value !== 'no'; - } - } - } - public function _sharing ($values) { - $this->data['sharing'] = array(); - $unique = array(); - foreach ($values as $value) { - if (!is_array($value)) { - continue; - } - - // Verify URL and add default value when needed - if (isset($value['url'])) { - $is_url = ( - filter_var ($value['url'], FILTER_VALIDATE_URL) || - (version_compare(PHP_VERSION, '5.3.3', '<') && - (strpos($value, '-') > 0) && - ($value === filter_var($value, FILTER_SANITIZE_URL))) - ); //PHP bug #51192 - if (!$is_url) { - continue; - } - } else { - $value['url'] = null; - } - - // Add a default name - if (empty($value['name'])) { - $value['name'] = $value['type']; - } - - $json_value = json_encode($value); - if (!in_array($json_value, $unique)) { - $unique[] = $json_value; - $this->data['sharing'][] = $value; - } - } - } - public function _queries ($values) { - $this->data['queries'] = array(); - foreach ($values as $value) { - $value = array_filter($value); - $params = $value; - unset($params['name']); - unset($params['url']); - $value['url'] = Minz_Url::display(array('params' => $params)); - - $this->data['queries'][] = $value; - } - } - public function _theme($value) { - $this->data['theme'] = $value; - } - public function _content_width($value) { - if ($value === 'medium' || - $value === 'large' || - $value === 'no_limit') { - $this->data['content_width'] = $value; - } else { - $this->data['content_width'] = 'thin'; - } - } - - public function _html5_notif_timeout ($value) { - $value = intval($value); - $this->data['html5_notif_timeout'] = $value >= 0 ? $value : 0; - } - - public function _token($value) { - $this->data['token'] = $value; - } - public function _auto_load_more($value) { - $this->data['auto_load_more'] = ((bool)$value) && $value !== 'no'; - } - public function _topline_read($value) { - $this->data['topline_read'] = ((bool)$value) && $value !== 'no'; - } - public function _topline_favorite($value) { - $this->data['topline_favorite'] = ((bool)$value) && $value !== 'no'; - } - public function _topline_date($value) { - $this->data['topline_date'] = ((bool)$value) && $value !== 'no'; - } - public function _topline_link($value) { - $this->data['topline_link'] = ((bool)$value) && $value !== 'no'; - } - public function _bottomline_read($value) { - $this->data['bottomline_read'] = ((bool)$value) && $value !== 'no'; - } - public function _bottomline_favorite($value) { - $this->data['bottomline_favorite'] = ((bool)$value) && $value !== 'no'; - } - public function _bottomline_sharing($value) { - $this->data['bottomline_sharing'] = ((bool)$value) && $value !== 'no'; - } - public function _bottomline_tags($value) { - $this->data['bottomline_tags'] = ((bool)$value) && $value !== 'no'; - } - public function _bottomline_date($value) { - $this->data['bottomline_date'] = ((bool)$value) && $value !== 'no'; - } - public function _bottomline_link($value) { - $this->data['bottomline_link'] = ((bool)$value) && $value !== 'no'; - } -} diff --git a/app/Models/ConfigurationSetter.php b/app/Models/ConfigurationSetter.php new file mode 100644 index 000000000..eeb1f2f4c --- /dev/null +++ b/app/Models/ConfigurationSetter.php @@ -0,0 +1,374 @@ +<?php + +class FreshRSS_ConfigurationSetter { + /** + * Return if the given key is supported by this setter. + * @param $key the key to test. + * @return true if the key is supported, false else. + */ + public function support($key) { + $name_setter = '_' . $key; + return is_callable(array($this, $name_setter)); + } + + /** + * Set the given key in data with the current value. + * @param $data an array containing the list of all configuration data. + * @param $key the key to update. + * @param $value the value to set. + */ + public function handle(&$data, $key, $value) { + $name_setter = '_' . $key; + call_user_func_array(array($this, $name_setter), array(&$data, $value)); + } + + /** + * A helper to set boolean values. + * + * @param $value the tested value. + * @return true if value is true and different from no, false else. + */ + private function handleBool($value) { + return ((bool)$value) && $value !== 'no'; + } + + /** + * The (long) list of setters for user configuration. + */ + private function _apiPasswordHash(&$data, $value) { + $data['apiPasswordHash'] = ctype_graph($value) && (strlen($value) >= 60) ? $value : ''; + } + + private function _content_width(&$data, $value) { + $value = strtolower($value); + if (!in_array($value, array('thin', 'medium', 'large', 'no_limit'))) { + $value = 'thin'; + } + + $data['content_width'] = $value; + } + + private function _default_state(&$data, $value) { + $data['default_state'] = (int)$value; + } + + private function _default_view(&$data, $value) { + switch ($value) { + case 'all': + $data['default_view'] = $value; + $data['default_state'] = (FreshRSS_Entry::STATE_READ + + FreshRSS_Entry::STATE_NOT_READ); + break; + case 'adaptive': + case 'unread': + default: + $data['default_view'] = $value; + $data['default_state'] = FreshRSS_Entry::STATE_NOT_READ; + } + } + + // It works for system config too! + private function _extensions_enabled(&$data, $value) { + if (!is_array($value)) { + $value = array($value); + } + $data['extensions_enabled'] = $value; + } + + private function _html5_notif_timeout(&$data, $value) { + $value = intval($value); + $data['html5_notif_timeout'] = $value >= 0 ? $value : 0; + } + + private function _keep_history_default(&$data, $value) { + $value = intval($value); + $data['keep_history_default'] = $value >= -1 ? $value : 0; + } + + // It works for system config too! + private function _language(&$data, $value) { + $value = strtolower($value); + $languages = Minz_Translate::availableLanguages(); + if (!in_array($value, $languages)) { + $value = 'en'; + } + $data['language'] = $value; + } + + private function _mail_login(&$data, $value) { + $value = filter_var($value, FILTER_VALIDATE_EMAIL); + $data['mail_login'] = $value ? $value : ''; + } + + private function _old_entries(&$data, $value) { + $value = intval($value); + $data['old_entries'] = $value > 0 ? $value : 3; + } + + private function _passwordHash(&$data, $value) { + $data['passwordHash'] = ctype_graph($value) && (strlen($value) >= 60) ? $value : ''; + } + + private function _posts_per_page(&$data, $value) { + $value = intval($value); + $data['posts_per_page'] = $value > 0 ? $value : 10; + } + + private function _queries(&$data, $values) { + $data['queries'] = array(); + foreach ($values as $value) { + $value = array_filter($value); + $params = $value; + unset($params['name']); + unset($params['url']); + $value['url'] = Minz_Url::display(array('params' => $params)); + $data['queries'][] = $value; + } + } + + private function _sharing(&$data, $values) { + $data['sharing'] = array(); + foreach ($values as $value) { + if (!is_array($value)) { + continue; + } + + // Verify URL and add default value when needed + if (isset($value['url'])) { + $is_url = ( + filter_var($value['url'], FILTER_VALIDATE_URL) || + (version_compare(PHP_VERSION, '5.3.3', '<') && + (strpos($value, '-') > 0) && + ($value === filter_var($value, FILTER_SANITIZE_URL))) + ); //PHP bug #51192 + if (!$is_url) { + continue; + } + } else { + $value['url'] = null; + } + + $data['sharing'][] = $value; + } + } + + private function _shortcuts(&$data, $values) { + if (!is_array($values)) { + return; + } + + $data['shortcuts'] = $values; + } + + private function _sort_order(&$data, $value) { + $data['sort_order'] = $value === 'ASC' ? 'ASC' : 'DESC'; + } + + private function _ttl_default(&$data, $value) { + $value = intval($value); + $data['ttl_default'] = $value >= -1 ? $value : 3600; + } + + private function _view_mode(&$data, $value) { + $value = strtolower($value); + if (!in_array($value, array('global', 'normal', 'reader'))) { + $value = 'normal'; + } + $data['view_mode'] = $value; + } + + /** + * A list of boolean setters. + */ + private function _anon_access(&$data, $value) { + $data['anon_access'] = $this->handleBool($value); + } + + private function _auto_load_more(&$data, $value) { + $data['auto_load_more'] = $this->handleBool($value); + } + + private function _auto_remove_article(&$data, $value) { + $data['auto_remove_article'] = $this->handleBool($value); + } + + private function _display_categories(&$data, $value) { + $data['display_categories'] = $this->handleBool($value); + } + + private function _display_posts(&$data, $value) { + $data['display_posts'] = $this->handleBool($value); + } + + private function _hide_read_feeds(&$data, $value) { + $data['hide_read_feeds'] = $this->handleBool($value); + } + + private function _lazyload(&$data, $value) { + $data['lazyload'] = $this->handleBool($value); + } + + private function _mark_when(&$data, $values) { + foreach ($values as $key => $value) { + $data['mark_when'][$key] = $this->handleBool($value); + } + } + + private function _onread_jump_next(&$data, $value) { + $data['onread_jump_next'] = $this->handleBool($value); + } + + private function _reading_confirm(&$data, $value) { + $data['reading_confirm'] = $this->handleBool($value); + } + + private function _sticky_post(&$data, $value) { + $data['sticky_post'] = $this->handleBool($value); + } + + private function _bottomline_date(&$data, $value) { + $data['bottomline_date'] = $this->handleBool($value); + } + private function _bottomline_favorite(&$data, $value) { + $data['bottomline_favorite'] = $this->handleBool($value); + } + private function _bottomline_link(&$data, $value) { + $data['bottomline_link'] = $this->handleBool($value); + } + private function _bottomline_read(&$data, $value) { + $data['bottomline_read'] = $this->handleBool($value); + } + private function _bottomline_sharing(&$data, $value) { + $data['bottomline_sharing'] = $this->handleBool($value); + } + private function _bottomline_tags(&$data, $value) { + $data['bottomline_tags'] = $this->handleBool($value); + } + + private function _topline_date(&$data, $value) { + $data['topline_date'] = $this->handleBool($value); + } + private function _topline_favorite(&$data, $value) { + $data['topline_favorite'] = $this->handleBool($value); + } + private function _topline_link(&$data, $value) { + $data['topline_link'] = $this->handleBool($value); + } + private function _topline_read(&$data, $value) { + $data['topline_read'] = $this->handleBool($value); + } + + /** + * The (not so long) list of setters for system configuration. + */ + private function _allow_anonymous(&$data, $value) { + $data['allow_anonymous'] = $this->handleBool($value) && FreshRSS_Auth::accessNeedsAction(); + } + + private function _allow_anonymous_refresh(&$data, $value) { + $data['allow_anonymous_refresh'] = $this->handleBool($value) && $data['allow_anonymous']; + } + + private function _api_enabled(&$data, $value) { + $data['api_enabled'] = $this->handleBool($value); + } + + private function _auth_type(&$data, $value) { + $value = strtolower($value); + if (!in_array($value, array('form', 'http_auth', 'persona', 'none'))) { + $value = 'none'; + } + $data['auth_type'] = $value; + $this->_allow_anonymous($data, $data['allow_anonymous']); + } + + private function _db(&$data, $value) { + if (!isset($value['type'])) { + return; + } + + switch ($value['type']) { + case 'mysql': + if (empty($value['host']) || + empty($value['user']) || + empty($value['base']) || + !isset($value['password'])) { + return; + } + + $data['db']['type'] = $value['type']; + $data['db']['host'] = $value['host']; + $data['db']['user'] = $value['user']; + $data['db']['base'] = $value['base']; + $data['db']['password'] = $value['password']; + $data['db']['prefix'] = isset($value['prefix']) ? $value['prefix'] : ''; + break; + case 'sqlite': + $data['db']['type'] = $value['type']; + $data['db']['host'] = ''; + $data['db']['user'] = ''; + $data['db']['base'] = ''; + $data['db']['password'] = ''; + $data['db']['prefix'] = ''; + break; + default: + return; + } + } + + private function _default_user(&$data, $value) { + $user_list = listUsers(); + if (in_array($value, $user_list)) { + $data['default_user'] = $value; + } + } + + private function _environment(&$data, $value) { + $value = strtolower($value); + if (!in_array($value, array('silent', 'development', 'production'))) { + $value = 'production'; + } + $data['environment'] = $value; + } + + private function _limits(&$data, $values) { + $max_small_int = 16384; + $limits_keys = array( + 'cache_duration' => array( + 'min' => 0, + ), + 'timeout' => array( + 'min' => 0, + ), + 'max_inactivity' => array( + 'min' => 0, + ), + 'max_feeds' => array( + 'min' => 0, + 'max' => $max_small_int, + ), + 'max_categories' => array( + 'min' => 0, + 'max' => $max_small_int, + ), + ); + + foreach ($values as $key => $value) { + if (!isset($limits_keys[$key])) { + continue; + } + + $limits = $limits_keys[$key]; + if ( + (!isset($limits['min']) || $value > $limits['min']) && + (!isset($limits['max']) || $value < $limits['max']) + ) { + $data['limits'][$key] = $value; + } + } + } + + private function _unsafe_autologin_enabled(&$data, $value) { + $data['unsafe_autologin_enabled'] = $this->handleBool($value); + } +} diff --git a/app/Models/Context.php b/app/Models/Context.php new file mode 100644 index 000000000..1c770c756 --- /dev/null +++ b/app/Models/Context.php @@ -0,0 +1,304 @@ +<?php + +/** + * The context object handles the current configuration file and different + * useful functions associated to the current view state. + */ +class FreshRSS_Context { + public static $user_conf = null; + public static $system_conf = null; + public static $categories = array(); + + public static $name = ''; + + public static $total_unread = 0; + public static $total_starred = array( + 'all' => 0, + 'read' => 0, + 'unread' => 0, + ); + + public static $get_unread = 0; + public static $current_get = array( + 'all' => false, + 'starred' => false, + 'feed' => false, + 'category' => false, + ); + public static $next_get = 'a'; + + public static $state = 0; + public static $order = 'DESC'; + public static $number = 0; + public static $search = ''; + public static $first_id = ''; + public static $next_id = ''; + public static $id_max = ''; + + /** + * Initialize the context. + * + * Set the correct configurations and $categories variables. + */ + public static function init() { + // Init configuration. + self::$system_conf = Minz_Configuration::get('system'); + self::$user_conf = Minz_Configuration::get('user'); + + $catDAO = new FreshRSS_CategoryDAO(); + self::$categories = $catDAO->listCategories(); + } + + /** + * Returns if the current state includes $state parameter. + */ + public static function isStateEnabled($state) { + return self::$state & $state; + } + + /** + * Returns the current state with or without $state parameter. + */ + public static function getRevertState($state) { + if (self::$state & $state) { + return self::$state & ~$state; + } else { + return self::$state | $state; + } + } + + /** + * Return the current get as a string or an array. + * + * If $array is true, the first item of the returned value is 'f' or 'c' and + * the second is the id. + */ + public static function currentGet($array = false) { + if (self::$current_get['all']) { + return 'a'; + } elseif (self::$current_get['starred']) { + return 's'; + } elseif (self::$current_get['feed']) { + if ($array) { + return array('f', self::$current_get['feed']); + } else { + return 'f_' . self::$current_get['feed']; + } + } elseif (self::$current_get['category']) { + if ($array) { + return array('c', self::$current_get['category']); + } else { + return 'c_' . self::$current_get['category']; + } + } + } + + /** + * Return true if $get parameter correspond to the $current_get attribute. + */ + public static function isCurrentGet($get) { + $type = $get[0]; + $id = substr($get, 2); + + switch($type) { + case 'a': + return self::$current_get['all']; + case 's': + return self::$current_get['starred']; + case 'f': + return self::$current_get['feed'] == $id; + case 'c': + return self::$current_get['category'] == $id; + default: + return false; + } + } + + /** + * Set the current $get attribute. + * + * Valid $get parameter are: + * - a + * - s + * - f_<feed id> + * - c_<category id> + * + * $name and $get_unread attributes are also updated as $next_get + * Raise an exception if id or $get is invalid. + */ + public static function _get($get) { + $type = $get[0]; + $id = substr($get, 2); + $nb_unread = 0; + + switch($type) { + case 'a': + self::$current_get['all'] = true; + self::$name = _t('index.feed.title'); + self::$get_unread = self::$total_unread; + break; + case 's': + self::$current_get['starred'] = true; + self::$name = _t('index.feed.title_fav'); + self::$get_unread = self::$total_starred['unread']; + + // Update state if favorite is not yet enabled. + self::$state = self::$state | FreshRSS_Entry::STATE_FAVORITE; + break; + case 'f': + // We try to find the corresponding feed. + $feed = FreshRSS_CategoryDAO::findFeed(self::$categories, $id); + if ($feed === null) { + $feedDAO = FreshRSS_Factory::createFeedDao(); + $feed = $feedDAO->searchById($id); + + if (!$feed) { + throw new FreshRSS_Context_Exception('Invalid feed: ' . $id); + } + } + + self::$current_get['feed'] = $id; + self::$current_get['category'] = $feed->category(); + self::$name = $feed->name(); + self::$get_unread = $feed->nbNotRead(); + break; + case 'c': + // We try to find the corresponding category. + self::$current_get['category'] = $id; + if (!isset(self::$categories[$id])) { + $catDAO = new FreshRSS_CategoryDAO(); + $cat = $catDAO->searchById($id); + + if (!$cat) { + throw new FreshRSS_Context_Exception('Invalid category: ' . $id); + } + } else { + $cat = self::$categories[$id]; + } + + self::$name = $cat->name(); + self::$get_unread = $cat->nbNotRead(); + break; + default: + throw new FreshRSS_Context_Exception('Invalid getter: ' . $get); + } + + self::_nextGet(); + } + + /** + * Set the value of $next_get attribute. + */ + public static function _nextGet() { + $get = self::currentGet(); + // By default, $next_get == $get + self::$next_get = $get; + + if (self::$user_conf->onread_jump_next && strlen($get) > 2) { + $another_unread_id = ''; + $found_current_get = false; + switch ($get[0]) { + case 'f': + // We search the next feed with at least one unread article in + // same category as the currend feed. + foreach (self::$categories as $cat) { + if ($cat->id() != self::$current_get['category']) { + // We look into the category of the current feed! + continue; + } + + foreach ($cat->feeds() as $feed) { + if ($feed->id() == self::$current_get['feed']) { + // Here is our current feed! Fine, the next one will + // be a potential candidate. + $found_current_get = true; + continue; + } + + if ($feed->nbNotRead() > 0) { + $another_unread_id = $feed->id(); + if ($found_current_get) { + // We have found our current feed and now we + // have an feed with unread articles. Leave the + // loop! + break; + } + } + } + break; + } + + // If no feed have been found, next_get is the current category. + self::$next_get = empty($another_unread_id) ? + 'c_' . self::$current_get['category'] : + 'f_' . $another_unread_id; + break; + case 'c': + // We search the next category with at least one unread article. + foreach (self::$categories as $cat) { + if ($cat->id() == self::$current_get['category']) { + // Here is our current category! Next one could be our + // champion if it has unread articles. + $found_current_get = true; + continue; + } + + if ($cat->nbNotRead() > 0) { + $another_unread_id = $cat->id(); + if ($found_current_get) { + // Unread articles and the current category has + // already been found? Leave the loop! + break; + } + } + } + + // No unread category? The main stream will be our destination! + self::$next_get = empty($another_unread_id) ? + 'a' : + 'c_' . $another_unread_id; + break; + } + } + } + + /** + * Determine if the auto remove is available in the current context. + * This feature is available if: + * - it is activated in the configuration + * - the "read" state is not enable + * - the "unread" state is enable + * + * @return boolean + */ + public static function isAutoRemoveAvailable() { + if (!self::$user_conf->auto_remove_article) { + return false; + } + if (self::isStateEnabled(FreshRSS_Entry::STATE_READ)) { + return false; + } + if (!self::isStateEnabled(FreshRSS_Entry::STATE_NOT_READ)) { + return false; + } + return true; + } + + /** + * Determine if the "sticky post" option is enabled. It can be enable + * by the user when it is selected in the configuration page or by the + * application when the context allows to auto-remove articles when they + * are read. + * + * @return boolean + */ + public static function isStickyPostEnabled() { + if (self::$user_conf->sticky_post) { + return true; + } + if (self::isAutoRemoveAvailable()) { + return true; + } + return false; + } +} diff --git a/app/Models/DatabaseDAO.php b/app/Models/DatabaseDAO.php new file mode 100644 index 000000000..0d85718e3 --- /dev/null +++ b/app/Models/DatabaseDAO.php @@ -0,0 +1,83 @@ +<?php + +/** + * This class is used to test database is well-constructed. + */ +class FreshRSS_DatabaseDAO extends Minz_ModelPdo { + public function tablesAreCorrect() { + $sql = 'SHOW TABLES'; + $stm = $this->bd->prepare($sql); + $stm->execute(); + $res = $stm->fetchAll(PDO::FETCH_ASSOC); + + $tables = array( + $this->prefix . 'category' => false, + $this->prefix . 'feed' => false, + $this->prefix . 'entry' => false, + ); + foreach ($res as $value) { + $tables[array_pop($value)] = true; + } + + return count(array_keys($tables, true, true)) == count($tables); + } + + public function getSchema($table) { + $sql = 'DESC ' . $this->prefix . $table; + $stm = $this->bd->prepare($sql); + $stm->execute(); + + return $this->listDaoToSchema($stm->fetchAll(PDO::FETCH_ASSOC)); + } + + public function checkTable($table, $schema) { + $columns = $this->getSchema($table); + + $ok = (count($columns) == count($schema)); + foreach ($columns as $c) { + $ok &= in_array($c['name'], $schema); + } + + return $ok; + } + + public function categoryIsCorrect() { + return $this->checkTable('category', array( + 'id', 'name' + )); + } + + public function feedIsCorrect() { + return $this->checkTable('feed', array( + 'id', 'url', 'category', 'name', 'website', 'description', 'lastUpdate', + 'priority', 'pathEntries', 'httpAuth', 'error', 'keep_history', 'ttl', + 'cache_nbEntries', 'cache_nbUnreads' + )); + } + + public function entryIsCorrect() { + return $this->checkTable('entry', array( + 'id', 'guid', 'title', 'author', 'content_bin', 'link', 'date', 'is_read', + 'is_favorite', 'id_feed', 'tags' + )); + } + + public function daoToSchema($dao) { + return array( + 'name' => $dao['Field'], + 'type' => strtolower($dao['Type']), + 'notnull' => (bool)$dao['Null'], + 'default' => $dao['Default'], + ); + } + + public function listDaoToSchema($listDAO) { + $list = array(); + + foreach ($listDAO as $dao) { + $list[] = $this->daoToSchema($dao); + } + + return $list; + } +} diff --git a/app/Models/DatabaseDAOSQLite.php b/app/Models/DatabaseDAOSQLite.php new file mode 100644 index 000000000..7f53f967d --- /dev/null +++ b/app/Models/DatabaseDAOSQLite.php @@ -0,0 +1,48 @@ +<?php + +/** + * This class is used to test database is well-constructed (SQLite). + */ +class FreshRSS_DatabaseDAOSQLite extends FreshRSS_DatabaseDAO { + public function tablesAreCorrect() { + $sql = 'SELECT name FROM sqlite_master WHERE type="table"'; + $stm = $this->bd->prepare($sql); + $stm->execute(); + $res = $stm->fetchAll(PDO::FETCH_ASSOC); + + $tables = array( + 'category' => false, + 'feed' => false, + 'entry' => false, + ); + foreach ($res as $value) { + $tables[$value['name']] = true; + } + + return count(array_keys($tables, true, true)) == count($tables); + } + + public function getSchema($table) { + $sql = 'PRAGMA table_info(' . $table . ')'; + $stm = $this->bd->prepare($sql); + $stm->execute(); + + return $this->listDaoToSchema($stm->fetchAll(PDO::FETCH_ASSOC)); + } + + public function entryIsCorrect() { + return $this->checkTable('entry', array( + 'id', 'guid', 'title', 'author', 'content', 'link', 'date', 'is_read', + 'is_favorite', 'id_feed', 'tags' + )); + } + + public function daoToSchema($dao) { + return array( + 'name' => $dao['name'], + 'type' => strtolower($dao['type']), + 'notnull' => $dao['notnull'] === '1' ? true : false, + 'default' => $dao['dflt_value'], + ); + } +} diff --git a/app/Models/Entry.php b/app/Models/Entry.php index 9d7dd5dc4..346c98a92 100644 --- a/app/Models/Entry.php +++ b/app/Models/Entry.php @@ -1,12 +1,11 @@ <?php class FreshRSS_Entry extends Minz_Model { - const STATE_ALL = 0; const STATE_READ = 1; const STATE_NOT_READ = 2; + const STATE_ALL = 3; const STATE_FAVORITE = 4; const STATE_NOT_FAVORITE = 8; - const STATE_STRICT = 16; private $id = 0; private $guid; @@ -20,134 +19,134 @@ class FreshRSS_Entry extends Minz_Model { private $feed; private $tags; - public function __construct ($feed = '', $guid = '', $title = '', $author = '', $content = '', - $link = '', $pubdate = 0, $is_read = false, $is_favorite = false, $tags = '') { - $this->_guid ($guid); - $this->_title ($title); - $this->_author ($author); - $this->_content ($content); - $this->_link ($link); - $this->_date ($pubdate); - $this->_isRead ($is_read); - $this->_isFavorite ($is_favorite); - $this->_feed ($feed); - $this->_tags (preg_split('/[\s#]/', $tags)); + public function __construct($feed = '', $guid = '', $title = '', $author = '', $content = '', + $link = '', $pubdate = 0, $is_read = false, $is_favorite = false, $tags = '') { + $this->_guid($guid); + $this->_title($title); + $this->_author($author); + $this->_content($content); + $this->_link($link); + $this->_date($pubdate); + $this->_isRead($is_read); + $this->_isFavorite($is_favorite); + $this->_feed($feed); + $this->_tags(preg_split('/[\s#]/', $tags)); } - public function id () { + public function id() { return $this->id; } - public function guid () { + public function guid() { return $this->guid; } - public function title () { + public function title() { return $this->title; } - public function author () { + public function author() { return $this->author === null ? '' : $this->author; } - public function content () { + public function content() { return $this->content; } - public function link () { + public function link() { return $this->link; } - public function date ($raw = false) { + public function date($raw = false) { if ($raw) { return $this->date; } else { - return timestamptodate ($this->date); + return timestamptodate($this->date); } } - public function dateAdded ($raw = false) { + public function dateAdded($raw = false) { $date = intval(substr($this->id, 0, -6)); if ($raw) { return $date; } else { - return timestamptodate ($date); + return timestamptodate($date); } } - public function isRead () { + public function isRead() { return $this->is_read; } - public function isFavorite () { + public function isFavorite() { return $this->is_favorite; } - public function feed ($object = false) { + public function feed($object = false) { if ($object) { $feedDAO = FreshRSS_Factory::createFeedDao(); - return $feedDAO->searchById ($this->feed); + return $feedDAO->searchById($this->feed); } else { return $this->feed; } } - public function tags ($inString = false) { + public function tags($inString = false) { if ($inString) { - return empty ($this->tags) ? '' : '#' . implode(' #', $this->tags); + return empty($this->tags) ? '' : '#' . implode(' #', $this->tags); } else { return $this->tags; } } - public function _id ($value) { + public function _id($value) { $this->id = $value; } - public function _guid ($value) { + public function _guid($value) { $this->guid = $value; } - public function _title ($value) { + public function _title($value) { $this->title = $value; } - public function _author ($value) { + public function _author($value) { $this->author = $value; } - public function _content ($value) { + public function _content($value) { $this->content = $value; } - public function _link ($value) { + public function _link($value) { $this->link = $value; } - public function _date ($value) { + public function _date($value) { $value = intval($value); $this->date = $value > 1 ? $value : time(); } - public function _isRead ($value) { + public function _isRead($value) { $this->is_read = $value; } - public function _isFavorite ($value) { + public function _isFavorite($value) { $this->is_favorite = $value; } - public function _feed ($value) { + public function _feed($value) { $this->feed = $value; } - public function _tags ($value) { - if (!is_array ($value)) { - $value = array ($value); + public function _tags($value) { + if (!is_array($value)) { + $value = array($value); } foreach ($value as $key => $t) { if (!$t) { - unset ($value[$key]); + unset($value[$key]); } } $this->tags = $value; } - public function isDay ($day, $today) { + public function isDay($day, $today) { $date = $this->dateAdded(true); switch ($day) { - case FreshRSS_Days::TODAY: - $tomorrow = $today + 86400; - return $date >= $today && $date < $tomorrow; - case FreshRSS_Days::YESTERDAY: - $yesterday = $today - 86400; - return $date >= $yesterday && $date < $today; - case FreshRSS_Days::BEFORE_YESTERDAY: - $yesterday = $today - 86400; - return $date < $yesterday; - default: - return false; + case FreshRSS_Days::TODAY: + $tomorrow = $today + 86400; + return $date >= $today && $date < $tomorrow; + case FreshRSS_Days::YESTERDAY: + $yesterday = $today - 86400; + return $date >= $yesterday && $date < $today; + case FreshRSS_Days::BEFORE_YESTERDAY: + $yesterday = $today - 86400; + return $date < $yesterday; + default: + return false; } } @@ -158,7 +157,7 @@ class FreshRSS_Entry extends Minz_Model { $entryDAO = FreshRSS_Factory::createEntryDao(); $entry = $entryDAO->searchByGuid($this->feed, $this->guid); - if($entry) { + if ($entry) { // l'article existe déjà en BDD, en se contente de recharger ce contenu $this->content = $entry->content(); } else { @@ -168,25 +167,25 @@ class FreshRSS_Entry extends Minz_Model { htmlspecialchars_decode($this->link(), ENT_QUOTES), $pathEntries ); } catch (Exception $e) { - // rien à faire, on garde l'ancien contenu (requête a échoué) + // rien à faire, on garde l'ancien contenu(requête a échoué) } } } } - public function toArray () { - return array ( - 'id' => $this->id (), - 'guid' => $this->guid (), - 'title' => $this->title (), - 'author' => $this->author (), - 'content' => $this->content (), - 'link' => $this->link (), - 'date' => $this->date (true), - 'is_read' => $this->isRead (), - 'is_favorite' => $this->isFavorite (), - 'id_feed' => $this->feed (), - 'tags' => $this->tags (true), + public function toArray() { + return array( + 'id' => $this->id(), + 'guid' => $this->guid(), + 'title' => $this->title(), + 'author' => $this->author(), + 'content' => $this->content(), + 'link' => $this->link(), + 'date' => $this->date(true), + 'is_read' => $this->isRead(), + 'is_favorite' => $this->isFavorite(), + 'id_feed' => $this->feed(), + 'tags' => $this->tags(true), ); } } diff --git a/app/Models/EntryDAO.php b/app/Models/EntryDAO.php index c1f87ee34..61beeea13 100644 --- a/app/Models/EntryDAO.php +++ b/app/Models/EntryDAO.php @@ -40,11 +40,11 @@ class FreshRSS_EntryDAO extends Minz_ModelPdo { } else { $info = $stm == null ? array(2 => 'syntax error') : $stm->errorInfo(); if ((int)($info[0] / 1000) !== 23) { //Filter out "SQLSTATE Class code 23: Constraint Violation" because of expected duplicate entries - Minz_Log::record('SQL error addEntry: ' . $info[0] . ': ' . $info[1] . ' ' . $info[2] - . ' while adding entry in feed ' . $valuesTmp['id_feed'] . ' with title: ' . $valuesTmp['title'], Minz_Log::ERROR); + Minz_Log::error('SQL error addEntry: ' . $info[0] . ': ' . $info[1] . ' ' . $info[2] + . ' while adding entry in feed ' . $valuesTmp['id_feed'] . ' with title: ' . $valuesTmp['title']); } /*else { - Minz_Log::record ('SQL error ' . $info[0] . ': ' . $info[1] . ' ' . $info[2] - . ' while adding entry in feed ' . $valuesTmp['id_feed'] . ' with title: ' . $valuesTmp['title'], Minz_Log::DEBUG); + Minz_Log::debug('SQL error ' . $info[0] . ': ' . $info[1] . ' ' . $info[2] + . ' while adding entry in feed ' . $valuesTmp['id_feed'] . ' with title: ' . $valuesTmp['title']); }*/ return false; } @@ -80,6 +80,16 @@ class FreshRSS_EntryDAO extends Minz_ModelPdo { return -1; } + /** + * Toggle favorite marker on one or more article + * + * @todo simplify the query by removing the str_repeat. I am pretty sure + * there is an other way to do that. + * + * @param integer|array $ids + * @param boolean $is_favorite + * @return false|integer + */ public function markFavorite($ids, $is_favorite = true) { if (!is_array($ids)) { $ids = array($ids); @@ -94,11 +104,22 @@ class FreshRSS_EntryDAO extends Minz_ModelPdo { return $stm->rowCount(); } else { $info = $stm == null ? array(2 => 'syntax error') : $stm->errorInfo(); - Minz_Log::record('SQL error markFavorite: ' . $info[2], Minz_Log::ERROR); + Minz_Log::error('SQL error markFavorite: ' . $info[2]); return false; } } + /** + * Update the unread article cache held on every feed details. + * Depending on the parameters, it updates the cache on one feed, on all + * feeds from one category or on all feeds. + * + * @todo It can use the query builder refactoring to build that query + * + * @param false|integer $catId category ID + * @param false|integer $feedId feed ID + * @return boolean + */ protected function updateCacheUnreads($catId = false, $feedId = false) { $sql = 'UPDATE `' . $this->prefix . 'feed` f ' . 'LEFT OUTER JOIN (' @@ -124,11 +145,24 @@ class FreshRSS_EntryDAO extends Minz_ModelPdo { return true; } else { $info = $stm == null ? array(2 => 'syntax error') : $stm->errorInfo(); - Minz_Log::record('SQL error updateCacheUnreads: ' . $info[2], Minz_Log::ERROR); + Minz_Log::error('SQL error updateCacheUnreads: ' . $info[2]); return false; } } + /** + * Toggle the read marker on one or more article. + * Then the cache is updated. + * + * @todo change the way the query is build because it seems there is + * unnecessary code in here. For instance, the part with the str_repeat. + * @todo remove code duplication. It seems the code is basically the + * same if it is an array or not. + * + * @param integer|array $ids + * @param boolean $is_read + * @return integer affected rows + */ public function markRead($ids, $is_read = true) { if (is_array($ids)) { //Many IDs at once (used by API) if (count($ids) < 6) { //Speed heuristics @@ -147,7 +181,7 @@ class FreshRSS_EntryDAO extends Minz_ModelPdo { $stm = $this->bd->prepare($sql); if (!($stm && $stm->execute($values))) { $info = $stm == null ? array(2 => 'syntax error') : $stm->errorInfo(); - Minz_Log::record('SQL error markRead: ' . $info[2], Minz_Log::ERROR); + Minz_Log::error('SQL error markRead: ' . $info[2]); return false; } $affected = $stm->rowCount(); @@ -166,16 +200,37 @@ class FreshRSS_EntryDAO extends Minz_ModelPdo { return $stm->rowCount(); } else { $info = $stm == null ? array(2 => 'syntax error') : $stm->errorInfo(); - Minz_Log::record('SQL error markRead: ' . $info[2], Minz_Log::ERROR); + Minz_Log::error('SQL error markRead: ' . $info[2]); return false; } } } + /** + * Mark all entries as read depending on parameters. + * If $onlyFavorites is true, it is used when the user mark as read in + * the favorite pseudo-category. + * If $priorityMin is greater than 0, it is used when the user mark as + * read in the main feed pseudo-category. + * Then the cache is updated. + * + * If $idMax equals 0, a deprecated debug message is logged + * + * @todo refactor this method along with markReadCat and markReadFeed + * since they are all doing the same thing. I think we need to build a + * tool to generate the query instead of having queries all over the + * place. It will be reused also for the filtering making every thing + * separated. + * + * @param integer $idMax fail safe article ID + * @param boolean $onlyFavorites + * @param integer $priorityMin + * @return integer affected rows + */ public function markReadEntries($idMax = 0, $onlyFavorites = false, $priorityMin = 0) { if ($idMax == 0) { $idMax = time() . '000000'; - Minz_Log::record('Calling markReadEntries(0) is deprecated!', Minz_Log::DEBUG); + Minz_Log::debug('Calling markReadEntries(0) is deprecated!'); } $sql = 'UPDATE `' . $this->prefix . 'entry` e INNER JOIN `' . $this->prefix . 'feed` f ON e.id_feed=f.id ' @@ -190,7 +245,7 @@ class FreshRSS_EntryDAO extends Minz_ModelPdo { $stm = $this->bd->prepare($sql); if (!($stm && $stm->execute($values))) { $info = $stm == null ? array(2 => 'syntax error') : $stm->errorInfo(); - Minz_Log::record('SQL error markReadEntries: ' . $info[2], Minz_Log::ERROR); + Minz_Log::error('SQL error markReadEntries: ' . $info[2]); return false; } $affected = $stm->rowCount(); @@ -200,10 +255,21 @@ class FreshRSS_EntryDAO extends Minz_ModelPdo { return $affected; } + /** + * Mark all the articles in a category as read. + * There is a fail safe to prevent to mark as read articles that are + * loaded during the mark as read action. Then the cache is updated. + * + * If $idMax equals 0, a deprecated debug message is logged + * + * @param integer $id category ID + * @param integer $idMax fail safe article ID + * @return integer affected rows + */ public function markReadCat($id, $idMax = 0) { if ($idMax == 0) { $idMax = time() . '000000'; - Minz_Log::record('Calling markReadCat(0) is deprecated!', Minz_Log::DEBUG); + Minz_Log::debug('Calling markReadCat(0) is deprecated!'); } $sql = 'UPDATE `' . $this->prefix . 'entry` e INNER JOIN `' . $this->prefix . 'feed` f ON e.id_feed=f.id ' @@ -213,7 +279,7 @@ class FreshRSS_EntryDAO extends Minz_ModelPdo { $stm = $this->bd->prepare($sql); if (!($stm && $stm->execute($values))) { $info = $stm == null ? array(2 => 'syntax error') : $stm->errorInfo(); - Minz_Log::record('SQL error markReadCat: ' . $info[2], Minz_Log::ERROR); + Minz_Log::error('SQL error markReadCat: ' . $info[2]); return false; } $affected = $stm->rowCount(); @@ -223,10 +289,21 @@ class FreshRSS_EntryDAO extends Minz_ModelPdo { return $affected; } + /** + * Mark all the articles in a feed as read. + * There is a fail safe to prevent to mark as read articles that are + * loaded during the mark as read action. Then the cache is updated. + * + * If $idMax equals 0, a deprecated debug message is logged + * + * @param integer $id feed ID + * @param integer $idMax fail safe article ID + * @return integer affected rows + */ public function markReadFeed($id, $idMax = 0) { if ($idMax == 0) { $idMax = time() . '000000'; - Minz_Log::record('Calling markReadFeed(0) is deprecated!', Minz_Log::DEBUG); + Minz_Log::debug('Calling markReadFeed(0) is deprecated!'); } $this->bd->beginTransaction(); @@ -237,7 +314,7 @@ class FreshRSS_EntryDAO extends Minz_ModelPdo { $stm = $this->bd->prepare($sql); if (!($stm && $stm->execute($values))) { $info = $stm == null ? array(2 => 'syntax error') : $stm->errorInfo(); - Minz_Log::record('SQL error markReadFeed: ' . $info[2], Minz_Log::ERROR); + Minz_Log::error('SQL error markReadFeed: ' . $info[2]); $this->bd->rollBack(); return false; } @@ -251,7 +328,7 @@ class FreshRSS_EntryDAO extends Minz_ModelPdo { $stm = $this->bd->prepare($sql); if (!($stm && $stm->execute($values))) { $info = $stm == null ? array(2 => 'syntax error') : $stm->errorInfo(); - Minz_Log::record('SQL error markReadFeed: ' . $info[2], Minz_Log::ERROR); + Minz_Log::error('SQL error markReadFeed: ' . $info[2]); $this->bd->rollBack(); return false; } @@ -299,7 +376,7 @@ class FreshRSS_EntryDAO extends Minz_ModelPdo { return 'CONCAT(' . $s1 . ',' . $s2 . ')'; //MySQL } - private function sqlListWhere($type = 'a', $id = '', $state = FreshRSS_Entry::STATE_ALL, $order = 'DESC', $limit = 1, $firstId = '', $filter = '', $date_min = 0, $showOlderUnreadsorFavorites = false, $keepHistoryDefault = 0) { + private function sqlListWhere($type = 'a', $id = '', $state = FreshRSS_Entry::STATE_ALL, $order = 'DESC', $limit = 1, $firstId = '', $filter = '', $date_min = 0) { if (!$state) { $state = FreshRSS_Entry::STATE_ALL; } @@ -307,34 +384,32 @@ class FreshRSS_EntryDAO extends Minz_ModelPdo { $joinFeed = false; $values = array(); switch ($type) { - case 'a': - $where .= 'f.priority > 0 '; - $joinFeed = true; - break; - case 's': //Deprecated: use $state instead - $where .= 'e1.is_favorite=1 '; - break; - case 'c': - $where .= 'f.category=? '; - $values[] = intval($id); - $joinFeed = true; - break; - case 'f': - $where .= 'e1.id_feed=? '; - $values[] = intval($id); - break; - case 'A': - $where .= '1 '; - break; - default: - throw new FreshRSS_EntriesGetter_Exception('Bad type in Entry->listByType: [' . $type . ']!'); + case 'a': + $where .= 'f.priority > 0 '; + $joinFeed = true; + break; + case 's': //Deprecated: use $state instead + $where .= 'e1.is_favorite=1 '; + break; + case 'c': + $where .= 'f.category=? '; + $values[] = intval($id); + $joinFeed = true; + break; + case 'f': + $where .= 'e1.id_feed=? '; + $values[] = intval($id); + break; + case 'A': + $where .= '1 '; + break; + default: + throw new FreshRSS_EntriesGetter_Exception('Bad type in Entry->listByType: [' . $type . ']!'); } if ($state & FreshRSS_Entry::STATE_NOT_READ) { if (!($state & FreshRSS_Entry::STATE_READ)) { $where .= 'AND e1.is_read=0 '; - } elseif ($state & FreshRSS_Entry::STATE_STRICT) { - $where .= 'AND e1.is_read=0 '; } } elseif ($state & FreshRSS_Entry::STATE_READ) { @@ -356,23 +431,14 @@ class FreshRSS_EntryDAO extends Minz_ModelPdo { default: throw new FreshRSS_EntriesGetter_Exception('Bad order in Entry->listByType: [' . $order . ']!'); } - if ($firstId === '' && parent::$sharedDbType === 'mysql') { - $firstId = $order === 'DESC' ? '9000000000'. '000000' : '0'; //MySQL optimization. Tested on MySQL 5.5 with 150k articles - } + /*if ($firstId === '' && parent::$sharedDbType === 'mysql') { + $firstId = $order === 'DESC' ? '9000000000'. '000000' : '0'; //MySQL optimization. TODO: check if this is needed again, after the filtering for old articles has been removed in 0.9-dev + }*/ if ($firstId !== '') { $where .= 'AND e1.id ' . ($order === 'DESC' ? '<=' : '>=') . $firstId . ' '; } - if (($date_min > 0) && ($type !== 's')) { - $where .= 'AND (e1.id >= ' . $date_min . '000000'; - if ($showOlderUnreadsorFavorites) { //Lax date constraint - $where .= ' OR e1.is_read=0 OR e1.is_favorite=1 OR (f.keep_history <> 0'; - if (intval($keepHistoryDefault) === 0) { - $where .= ' AND f.keep_history <> -2'; //default - } - $where .= ')'; - } - $where .= ') '; - $joinFeed = true; + if ($date_min > 0) { + $where .= 'AND e1.id >= ' . $date_min . '000000 '; } $search = ''; if ($filter !== '') { @@ -434,8 +500,8 @@ class FreshRSS_EntryDAO extends Minz_ModelPdo { . ($limit > 0 ? ' LIMIT ' . $limit : '')); //TODO: See http://explainextended.com/2009/10/23/mysql-order-by-limit-performance-late-row-lookups/ } - public function listWhere($type = 'a', $id = '', $state = FreshRSS_Entry::STATE_ALL, $order = 'DESC', $limit = 1, $firstId = '', $filter = '', $date_min = 0, $showOlderUnreadsorFavorites = false, $keepHistoryDefault = 0) { - list($values, $sql) = $this->sqlListWhere($type, $id, $state, $order, $limit, $firstId, $filter, $date_min, $showOlderUnreadsorFavorites, $keepHistoryDefault); + public function listWhere($type = 'a', $id = '', $state = FreshRSS_Entry::STATE_ALL, $order = 'DESC', $limit = 1, $firstId = '', $filter = '', $date_min = 0) { + list($values, $sql) = $this->sqlListWhere($type, $id, $state, $order, $limit, $firstId, $filter, $date_min); $sql = 'SELECT e.id, e.guid, e.title, e.author, ' . ($this->isCompressed() ? 'UNCOMPRESS(content_bin) AS content' : 'content') @@ -452,8 +518,8 @@ class FreshRSS_EntryDAO extends Minz_ModelPdo { return self::daoToEntry($stm->fetchAll(PDO::FETCH_ASSOC)); } - public function listIdsWhere($type = 'a', $id = '', $state = FreshRSS_Entry::STATE_ALL, $order = 'DESC', $limit = 1, $firstId = '', $filter = '', $date_min = 0, $showOlderUnreadsorFavorites = false, $keepHistoryDefault = 0) { //For API - list($values, $sql) = $this->sqlListWhere($type, $id, $state, $order, $limit, $firstId, $filter, $date_min, $showOlderUnreadsorFavorites, $keepHistoryDefault); + public function listIdsWhere($type = 'a', $id = '', $state = FreshRSS_Entry::STATE_ALL, $order = 'DESC', $limit = 1, $firstId = '', $filter = '', $date_min = 0) { //For API + list($values, $sql) = $this->sqlListWhere($type, $id, $state, $order, $limit, $firstId, $filter, $date_min); $stm = $this->bd->prepare($sql); $stm->execute($values); @@ -520,7 +586,7 @@ class FreshRSS_EntryDAO extends Minz_ModelPdo { } public function size($all = false) { - $db = Minz_Configuration::dataBase(); + $db = FreshRSS_Context::$system_conf->db; $sql = 'SELECT SUM(data_length + index_length) FROM information_schema.TABLES WHERE table_schema=?'; //MySQL $values = array($db['base']); if (!$all) { diff --git a/app/Models/EntryDAOSQLite.php b/app/Models/EntryDAOSQLite.php index 9dc395c3c..ffe0f037c 100644 --- a/app/Models/EntryDAOSQLite.php +++ b/app/Models/EntryDAOSQLite.php @@ -26,11 +26,24 @@ class FreshRSS_EntryDAOSQLite extends FreshRSS_EntryDAO { return true; } else { $info = $stm == null ? array(2 => 'syntax error') : $stm->errorInfo(); - Minz_Log::record('SQL error updateCacheUnreads: ' . $info[2], Minz_Log::ERROR); + Minz_Log::error('SQL error updateCacheUnreads: ' . $info[2]); return false; } } + /** + * Toggle the read marker on one or more article. + * Then the cache is updated. + * + * @todo change the way the query is build because it seems there is + * unnecessary code in here. For instance, the part with the str_repeat. + * @todo remove code duplication. It seems the code is basically the + * same if it is an array or not. + * + * @param integer|array $ids + * @param boolean $is_read + * @return integer affected rows + */ public function markRead($ids, $is_read = true) { if (is_array($ids)) { //Many IDs at once (used by API) if (true) { //Speed heuristics //TODO: Not implemented yet for SQLite (so always call IDs one by one) @@ -47,7 +60,7 @@ class FreshRSS_EntryDAOSQLite extends FreshRSS_EntryDAO { $stm = $this->bd->prepare($sql); if (!($stm && $stm->execute($values))) { $info = $stm == null ? array(2 => 'syntax error') : $stm->errorInfo(); - Minz_Log::record('SQL error markRead 1: ' . $info[2], Minz_Log::ERROR); + Minz_Log::error('SQL error markRead 1: ' . $info[2]); $this->bd->rollBack(); return false; } @@ -59,7 +72,7 @@ class FreshRSS_EntryDAOSQLite extends FreshRSS_EntryDAO { $stm = $this->bd->prepare($sql); if (!($stm && $stm->execute($values))) { $info = $stm == null ? array(2 => 'syntax error') : $stm->errorInfo(); - Minz_Log::record('SQL error markRead 2: ' . $info[2], Minz_Log::ERROR); + Minz_Log::error('SQL error markRead 2: ' . $info[2]); $this->bd->rollBack(); return false; } @@ -69,10 +82,31 @@ class FreshRSS_EntryDAOSQLite extends FreshRSS_EntryDAO { } } + /** + * Mark all entries as read depending on parameters. + * If $onlyFavorites is true, it is used when the user mark as read in + * the favorite pseudo-category. + * If $priorityMin is greater than 0, it is used when the user mark as + * read in the main feed pseudo-category. + * Then the cache is updated. + * + * If $idMax equals 0, a deprecated debug message is logged + * + * @todo refactor this method along with markReadCat and markReadFeed + * since they are all doing the same thing. I think we need to build a + * tool to generate the query instead of having queries all over the + * place. It will be reused also for the filtering making every thing + * separated. + * + * @param integer $idMax fail safe article ID + * @param boolean $onlyFavorites + * @param integer $priorityMin + * @return integer affected rows + */ public function markReadEntries($idMax = 0, $onlyFavorites = false, $priorityMin = 0) { if ($idMax == 0) { $idMax = time() . '000000'; - Minz_Log::record('Calling markReadEntries(0) is deprecated!', Minz_Log::DEBUG); + Minz_Log::debug('Calling markReadEntries(0) is deprecated!'); } $sql = 'UPDATE `' . $this->prefix . 'entry` SET is_read=1 WHERE is_read=0 AND id <= ?'; @@ -85,7 +119,7 @@ class FreshRSS_EntryDAOSQLite extends FreshRSS_EntryDAO { $stm = $this->bd->prepare($sql); if (!($stm && $stm->execute($values))) { $info = $stm == null ? array(2 => 'syntax error') : $stm->errorInfo(); - Minz_Log::record('SQL error markReadEntries: ' . $info[2], Minz_Log::ERROR); + Minz_Log::error('SQL error markReadEntries: ' . $info[2]); return false; } $affected = $stm->rowCount(); @@ -95,10 +129,21 @@ class FreshRSS_EntryDAOSQLite extends FreshRSS_EntryDAO { return $affected; } + /** + * Mark all the articles in a category as read. + * There is a fail safe to prevent to mark as read articles that are + * loaded during the mark as read action. Then the cache is updated. + * + * If $idMax equals 0, a deprecated debug message is logged + * + * @param integer $id category ID + * @param integer $idMax fail safe article ID + * @return integer affected rows + */ public function markReadCat($id, $idMax = 0) { if ($idMax == 0) { $idMax = time() . '000000'; - Minz_Log::record('Calling markReadCat(0) is deprecated!', Minz_Log::DEBUG); + Minz_Log::debug('Calling markReadCat(0) is deprecated!'); } $sql = 'UPDATE `' . $this->prefix . 'entry` ' @@ -109,7 +154,7 @@ class FreshRSS_EntryDAOSQLite extends FreshRSS_EntryDAO { $stm = $this->bd->prepare($sql); if (!($stm && $stm->execute($values))) { $info = $stm == null ? array(2 => 'syntax error') : $stm->errorInfo(); - Minz_Log::record('SQL error markReadCat: ' . $info[2], Minz_Log::ERROR); + Minz_Log::error('SQL error markReadCat: ' . $info[2]); return false; } $affected = $stm->rowCount(); @@ -124,6 +169,6 @@ class FreshRSS_EntryDAOSQLite extends FreshRSS_EntryDAO { } public function size($all = false) { - return @filesize(DATA_PATH . '/' . Minz_Session::param('currentUser', '_') . '.sqlite'); + return @filesize(join_path(DATA_PATH, 'users', $this->current_user, 'db.sqlite')); } } diff --git a/app/Models/Factory.php b/app/Models/Factory.php index 08569b2e2..db09d155d 100644 --- a/app/Models/Factory.php +++ b/app/Models/Factory.php @@ -2,30 +2,39 @@ class FreshRSS_Factory { - public static function createFeedDao() { - $db = Minz_Configuration::dataBase(); - if ($db['type'] === 'sqlite') { - return new FreshRSS_FeedDAOSQLite(); + public static function createFeedDao($username = null) { + $conf = Minz_Configuration::get('system'); + if ($conf->db['type'] === 'sqlite') { + return new FreshRSS_FeedDAOSQLite($username); } else { - return new FreshRSS_FeedDAO(); + return new FreshRSS_FeedDAO($username); } } - public static function createEntryDao() { - $db = Minz_Configuration::dataBase(); - if ($db['type'] === 'sqlite') { - return new FreshRSS_EntryDAOSQLite(); + public static function createEntryDao($username = null) { + $conf = Minz_Configuration::get('system'); + if ($conf->db['type'] === 'sqlite') { + return new FreshRSS_EntryDAOSQLite($username); } else { - return new FreshRSS_EntryDAO(); + return new FreshRSS_EntryDAO($username); } } - public static function createStatsDAO() { - $db = Minz_Configuration::dataBase(); - if ($db['type'] === 'sqlite') { - return new FreshRSS_StatsDAOSQLite(); + public static function createStatsDAO($username = null) { + $conf = Minz_Configuration::get('system'); + if ($conf->db['type'] === 'sqlite') { + return new FreshRSS_StatsDAOSQLite($username); } else { - return new FreshRSS_StatsDAO(); + return new FreshRSS_StatsDAO($username); + } + } + + public static function createDatabaseDAO($username = null) { + $conf = Minz_Configuration::get('system'); + if ($conf->db['type'] === 'sqlite') { + return new FreshRSS_DatabaseDAOSQLite($username); + } else { + return new FreshRSS_DatabaseDAO($username); } } diff --git a/app/Models/Feed.php b/app/Models/Feed.php index 03baf3ad2..5ce03be5d 100644 --- a/app/Models/Feed.php +++ b/app/Models/Feed.php @@ -40,7 +40,8 @@ class FreshRSS_Feed extends Minz_Model { public function hash() { if ($this->hash === null) { - $this->hash = hash('crc32b', Minz_Configuration::salt() . $this->url); + $salt = FreshRSS_Context::$system_conf->salt; + $this->hash = hash('crc32b', $salt . $this->url); } return $this->hash; } @@ -210,6 +211,10 @@ class FreshRSS_Feed extends Minz_Model { $url = preg_replace('#((.+)://)(.+)#', '${1}' . $this->httpAuth . '@${3}', $url); } $feed = customSimplePie(); + if (substr($url, -11) === '#force_feed') { + $feed->force_feed(true); + $url = substr($url, 0, -11); + } $feed->set_feed_url($url); if (!$loadDetails) { //Only activates auto-discovery when adding a new feed $feed->set_autodiscovery_level(SIMPLEPIE_LOCATOR_NONE); @@ -217,7 +222,8 @@ class FreshRSS_Feed extends Minz_Model { $mtime = $feed->init(); if ((!$mtime) || $feed->error()) { - throw new FreshRSS_Feed_Exception($feed->error() . ' [' . $url . ']'); + $errorMessage = $feed->error(); + throw new FreshRSS_Feed_Exception(($errorMessage == '' ? 'Feed error' : $errorMessage) . ' [' . $url . ']'); } if ($loadDetails) { @@ -225,7 +231,7 @@ class FreshRSS_Feed extends Minz_Model { $subscribe_url = $feed->subscribe_url(false); $title = strtr(html_only_entity_decode($feed->get_title()), array('<' => '<', '>' => '>', '"' => '"')); //HTML to HTML-PRE //ENT_COMPAT except & - $this->_name($title == '' ? $this->url : $title); + $this->_name($title == '' ? $url : $title); $this->_website(html_only_entity_decode($feed->get_link())); $this->_description(html_only_entity_decode($feed->get_description())); @@ -234,19 +240,16 @@ class FreshRSS_Feed extends Minz_Model { $subscribe_url = $feed->subscribe_url(true); } - if ($subscribe_url !== null && $subscribe_url !== $this->url) { - if ($this->httpAuth != '') { - // on enlève les id si authentification HTTP - $subscribe_url = preg_replace('#((.+)://)((.+)@)(.+)#', '${1}${5}', $subscribe_url); - } - $this->_url($subscribe_url); + $clean_url = url_remove_credentials($subscribe_url); + if ($subscribe_url !== null && $subscribe_url !== $url) { + $this->_url($clean_url); } if (($mtime === true) ||($mtime > $this->lastUpdate)) { - syslog(LOG_DEBUG, 'FreshRSS no cache ' . $mtime . ' > ' . $this->lastUpdate . ' for ' . $subscribe_url); + Minz_Log::notice('FreshRSS no cache ' . $mtime . ' > ' . $this->lastUpdate . ' for ' . $clean_url); $this->loadEntries($feed); // et on charge les articles du flux } else { - syslog(LOG_DEBUG, 'FreshRSS use cache for ' . $subscribe_url); + Minz_Log::notice('FreshRSS use cache for ' . $clean_url); $this->entries = array(); } diff --git a/app/Models/FeedDAO.php b/app/Models/FeedDAO.php index b89ae2045..74597c730 100644 --- a/app/Models/FeedDAO.php +++ b/app/Models/FeedDAO.php @@ -19,7 +19,7 @@ class FreshRSS_FeedDAO extends Minz_ModelPdo { return $this->bd->lastInsertId(); } else { $info = $stm == null ? array(2 => 'syntax error') : $stm->errorInfo(); - Minz_Log::record('SQL error addFeed: ' . $info[2], Minz_Log::ERROR); + Minz_Log::error('SQL error addFeed: ' . $info[2]); return false; } } @@ -77,7 +77,7 @@ class FreshRSS_FeedDAO extends Minz_ModelPdo { return $stm->rowCount(); } else { $info = $stm == null ? array(2 => 'syntax error') : $stm->errorInfo(); - Minz_Log::record('SQL error updateFeed: ' . $info[2], Minz_Log::ERROR); + Minz_Log::error('SQL error updateFeed: ' . $info[2]); return false; } } @@ -107,7 +107,7 @@ class FreshRSS_FeedDAO extends Minz_ModelPdo { return $stm->rowCount(); } else { $info = $stm == null ? array(2 => 'syntax error') : $stm->errorInfo(); - Minz_Log::record('SQL error updateLastUpdate: ' . $info[2], Minz_Log::ERROR); + Minz_Log::error('SQL error updateLastUpdate: ' . $info[2]); return false; } } @@ -131,7 +131,7 @@ class FreshRSS_FeedDAO extends Minz_ModelPdo { return $stm->rowCount(); } else { $info = $stm == null ? array(2 => 'syntax error') : $stm->errorInfo(); - Minz_Log::record('SQL error changeCategory: ' . $info[2], Minz_Log::ERROR); + Minz_Log::error('SQL error changeCategory: ' . $info[2]); return false; } } @@ -146,7 +146,7 @@ class FreshRSS_FeedDAO extends Minz_ModelPdo { return $stm->rowCount(); } else { $info = $stm == null ? array(2 => 'syntax error') : $stm->errorInfo(); - Minz_Log::record('SQL error deleteFeed: ' . $info[2], Minz_Log::ERROR); + Minz_Log::error('SQL error deleteFeed: ' . $info[2]); return false; } } @@ -160,7 +160,7 @@ class FreshRSS_FeedDAO extends Minz_ModelPdo { return $stm->rowCount(); } else { $info = $stm == null ? array(2 => 'syntax error') : $stm->errorInfo(); - Minz_Log::record('SQL error deleteFeedByCategory: ' . $info[2], Minz_Log::ERROR); + Minz_Log::error('SQL error deleteFeedByCategory: ' . $info[2]); return false; } } @@ -191,7 +191,7 @@ class FreshRSS_FeedDAO extends Minz_ModelPdo { $res = $stm->fetchAll(PDO::FETCH_ASSOC); $feed = current(self::daoToFeed($res)); - if (isset($feed)) { + if (isset($feed) && $feed !== false) { return $feed; } else { return null; @@ -289,7 +289,7 @@ class FreshRSS_FeedDAO extends Minz_ModelPdo { return $stm->rowCount(); } else { $info = $stm == null ? array(2 => 'syntax error') : $stm->errorInfo(); - Minz_Log::record('SQL error updateCachedValues: ' . $info[2], Minz_Log::ERROR); + Minz_Log::error('SQL error updateCachedValues: ' . $info[2]); return false; } } @@ -301,7 +301,7 @@ class FreshRSS_FeedDAO extends Minz_ModelPdo { $this->bd->beginTransaction(); if (!($stm && $stm->execute($values))) { $info = $stm == null ? array(2 => 'syntax error') : $stm->errorInfo(); - Minz_Log::record('SQL error truncate: ' . $info[2], Minz_Log::ERROR); + Minz_Log::error('SQL error truncate: ' . $info[2]); $this->bd->rollBack(); return false; } @@ -313,7 +313,7 @@ class FreshRSS_FeedDAO extends Minz_ModelPdo { $stm = $this->bd->prepare($sql); if (!($stm && $stm->execute($values))) { $info = $stm == null ? array(2 => 'syntax error') : $stm->errorInfo(); - Minz_Log::record('SQL error truncate: ' . $info[2], Minz_Log::ERROR); + Minz_Log::error('SQL error truncate: ' . $info[2]); $this->bd->rollBack(); return false; } @@ -338,7 +338,7 @@ class FreshRSS_FeedDAO extends Minz_ModelPdo { return $stm->rowCount(); } else { $info = $stm == null ? array(2 => 'syntax error') : $stm->errorInfo(); - Minz_Log::record('SQL error cleanOldEntries: ' . $info[2], Minz_Log::ERROR); + Minz_Log::error('SQL error cleanOldEntries: ' . $info[2]); return false; } } diff --git a/app/Models/FeedDAOSQLite.php b/app/Models/FeedDAOSQLite.php index 0d1872389..7599fda53 100644 --- a/app/Models/FeedDAOSQLite.php +++ b/app/Models/FeedDAOSQLite.php @@ -11,7 +11,7 @@ class FreshRSS_FeedDAOSQLite extends FreshRSS_FeedDAO { return $stm->rowCount(); } else { $info = $stm == null ? array(2 => 'syntax error') : $stm->errorInfo(); - Minz_Log::record('SQL error updateCachedValues: ' . $info[2], Minz_Log::ERROR); + Minz_Log::error('SQL error updateCachedValues: ' . $info[2]); return false; } } diff --git a/app/Models/Log.php b/app/Models/Log.php index d2794458b..df2de72ac 100644 --- a/app/Models/Log.php +++ b/app/Models/Log.php @@ -5,22 +5,22 @@ class FreshRSS_Log extends Minz_Model { private $level; private $information; - public function date () { + public function date() { return $this->date; } - public function level () { + public function level() { return $this->level; } - public function info () { + public function info() { return $this->information; } - public function _date ($date) { + public function _date($date) { $this->date = $date; } - public function _level ($level) { + public function _level($level) { $this->level = $level; } - public function _info ($information) { + public function _info($information) { $this->information = $information; } } diff --git a/app/Models/LogDAO.php b/app/Models/LogDAO.php index d1e515200..4c56e3150 100644 --- a/app/Models/LogDAO.php +++ b/app/Models/LogDAO.php @@ -2,15 +2,15 @@ class FreshRSS_LogDAO { public static function lines() { - $logs = array (); - $handle = @fopen(LOG_PATH . '/' . Minz_Session::param('currentUser', '_') . '.log', 'r'); + $logs = array(); + $handle = @fopen(join_path(DATA_PATH, 'users', Minz_Session::param('currentUser', '_'), 'log.txt'), 'r'); if ($handle) { while (($line = fgets($handle)) !== false) { - if (preg_match ('/^\[([^\[]+)\] \[([^\[]+)\] --- (.*)$/', $line, $matches)) { + if (preg_match('/^\[([^\[]+)\] \[([^\[]+)\] --- (.*)$/', $line, $matches)) { $myLog = new FreshRSS_Log (); - $myLog->_date ($matches[1]); - $myLog->_level ($matches[2]); - $myLog->_info ($matches[3]); + $myLog->_date($matches[1]); + $myLog->_level($matches[2]); + $myLog->_info($matches[3]); $logs[] = $myLog; } } @@ -20,6 +20,6 @@ class FreshRSS_LogDAO { } public static function truncate() { - file_put_contents(LOG_PATH . '/' . Minz_Session::param('currentUser', '_') . '.log', ''); + file_put_contents(join_path(DATA_PATH, 'users', Minz_Session::param('currentUser', '_'), 'log.txt'), ''); } } diff --git a/app/Models/Share.php b/app/Models/Share.php index b146db722..db6feda19 100644 --- a/app/Models/Share.php +++ b/app/Models/Share.php @@ -1,44 +1,240 @@ <?php +/** + * Manage the sharing options in FreshRSS. + */ class FreshRSS_Share { + /** + * The list of available sharing options. + */ + private static $list_sharing = array(); - static public function generateUrl($options, $selected, $link, $title) { - $share = $options[$selected['type']]; + /** + * Register a new sharing option. + * @param $share_options is an array defining the share option. + */ + public static function register($share_options) { + $type = $share_options['type']; + + if (isset(self::$list_sharing[$type])) { + return; + } + + $help_url = isset($share_options['help']) ? $share_options['help'] : ''; + self::$list_sharing[$type] = new FreshRSS_Share( + $type, $share_options['url'], $share_options['transform'], + $share_options['form'], $help_url + ); + } + + /** + * Register sharing options in a file. + * @param $filename the name of the file to load. + */ + public static function load($filename) { + $shares_from_file = @include($filename); + if (!is_array($shares_from_file)) { + $shares_from_file = array(); + } + + foreach ($shares_from_file as $share_type => $share_options) { + $share_options['type'] = $share_type; + self::register($share_options); + } + } + + /** + * Return the list of sharing options. + * @return an array of FreshRSS_Share objects. + */ + public static function enum() { + return self::$list_sharing; + } + + /** + * Return FreshRSS_Share object related to the given type. + * @param $type the share type, null if $type is not registered. + */ + public static function get($type) { + if (!isset(self::$list_sharing[$type])) { + return null; + } + + return self::$list_sharing[$type]; + } + + /** + * + */ + private $type = ''; + private $name = ''; + private $url_transform = ''; + private $transform = array(); + private $form_type = 'simple'; + private $help_url = ''; + private $custom_name = null; + private $base_url = null; + private $title = null; + private $link = null; + + /** + * Create a FreshRSS_Share object. + * @param $type is a unique string defining the kind of share option. + * @param $url_transform defines the url format to use in order to share. + * @param $transform is an array of transformations to apply on link and title. + * @param $form_type defines which form we have to use to complete. "simple" + * is typically for a centralized service while "advanced" is for + * decentralized ones. + * @param $help_url is an optional url to give help on this option. + */ + private function __construct($type, $url_transform, $transform = array(), + $form_type, $help_url = '') { + $this->type = $type; + $this->name = _t('gen.share.' . $type); + $this->url_transform = $url_transform; + $this->help_url = $help_url; + + if (!is_array($transform)) { + $transform = array(); + } + $this->transform = $transform; + + if (!in_array($form_type, array('simple', 'advanced'))) { + $form_type = 'simple'; + } + $this->form_type = $form_type; + } + + /** + * Update a FreshRSS_Share object with information from an array. + * @param $options is a list of informations to update where keys should be + * in this list: name, url, title, link. + */ + public function update($options) { + $available_options = array( + 'name' => 'custom_name', + 'url' => 'base_url', + 'title' => 'title', + 'link' => 'link', + ); + + foreach ($options as $key => $value) { + if (!isset($available_options[$key])) { + continue; + } + + $this->$available_options[$key] = $value; + } + } + + /** + * Return the current type of the share option. + */ + public function type() { + return $this->type; + } + + /** + * Return the current form type of the share option. + */ + public function formType() { + return $this->form_type; + } + + /** + * Return the current help url of the share option. + */ + public function help() { + return $this->help_url; + } + + /** + * Return the current name of the share option. + */ + public function name($real = false) { + if ($real || is_null($this->custom_name)) { + return $this->name; + } else { + return $this->custom_name; + } + } + + /** + * Return the current base url of the share option. + */ + public function baseUrl() { + return $this->base_url; + } + + /** + * Return the current url by merging url_transform and base_url. + */ + public function url() { $matches = array( '~URL~', '~TITLE~', '~LINK~', ); $replaces = array( - $selected['url'], - self::transformData($title, self::getTransform($share, 'title')), - self::transformData($link, self::getTransform($share, 'link')), + $this->base_url, + $this->title(), + $this->link(), ); - $url = str_replace($matches, $replaces, $share['url']); - return $url; + return str_replace($matches, $replaces, $this->url_transform); } - static private function transformData($data, $transform) { - if (!is_array($transform)) { - return $data; + /** + * Return the title. + * @param $raw true if we should get the title without transformations. + */ + public function title($raw = false) { + if ($raw) { + return $this->title; } - if (count($transform) === 0) { + + return $this->transform($this->title, $this->getTransform('title')); + } + + /** + * Return the link. + * @param $raw true if we should get the link without transformations. + */ + public function link($raw = false) { + if ($raw) { + return $this->link; + } + + return $this->transform($this->link, $this->getTransform('link')); + } + + /** + * Transform a data with the given functions. + * @param $data the data to transform. + * @param $tranform an array containing a list of functions to apply. + * @return the transformed data. + */ + private static function transform($data, $transform) { + if (!is_array($transform) || empty($transform)) { return $data; } + foreach ($transform as $action) { $data = call_user_func($action, $data); } + return $data; } - static private function getTransform($options, $type) { - $transform = $options['transform']; - - if (array_key_exists($type, $transform)) { - return $transform[$type]; + /** + * Get the list of transformations for the given attribute. + * @param $attr the attribute of which we want the transformations. + * @return an array containing a list of transformations to apply. + */ + private function getTransform($attr) { + if (array_key_exists($attr, $this->transform)) { + return $this->transform[$attr]; } - return $transform; + return $this->transform; } - } diff --git a/app/Models/StatsDAO.php b/app/Models/StatsDAO.php index 08dd4cd5c..80caccc49 100644 --- a/app/Models/StatsDAO.php +++ b/app/Models/StatsDAO.php @@ -6,18 +6,36 @@ class FreshRSS_StatsDAO extends Minz_ModelPdo { /** * Calculates entry repartition for all feeds and for main stream. + * + * @return array + */ + public function calculateEntryRepartition() { + return array( + 'main_stream' => $this->calculateEntryRepartitionPerFeed(null, true), + 'all_feeds' => $this->calculateEntryRepartitionPerFeed(null, false), + ); + } + + /** + * Calculates entry repartition for the selection. * The repartition includes: * - total entries * - read entries * - unread entries * - favorite entries * - * @return type + * @param null|integer $feed feed id + * @param boolean $only_main + * @return array */ - public function calculateEntryRepartition() { - $repartition = array(); - - // Generates the repartition for the main stream of entry + public function calculateEntryRepartitionPerFeed($feed = null, $only_main = false) { + $filter = ''; + if ($only_main) { + $filter .= 'AND f.priority = 10'; + } + if (!is_null($feed)) { + $filter .= "AND e.id_feed = {$feed}"; + } $sql = <<<SQL SELECT COUNT(1) AS `total`, COUNT(1) - SUM(e.is_read) AS `unread`, @@ -26,27 +44,13 @@ SUM(e.is_favorite) AS `favorite` FROM {$this->prefix}entry AS e , {$this->prefix}feed AS f WHERE e.id_feed = f.id -AND f.priority = 10 -SQL; - $stm = $this->bd->prepare($sql); - $stm->execute(); - $res = $stm->fetchAll(PDO::FETCH_ASSOC); - $repartition['main_stream'] = $res[0]; - - // Generates the repartition for all entries - $sql = <<<SQL -SELECT COUNT(1) AS `total`, -COUNT(1) - SUM(e.is_read) AS `unread`, -SUM(e.is_read) AS `read`, -SUM(e.is_favorite) AS `favorite` -FROM {$this->prefix}entry AS e +{$filter} SQL; $stm = $this->bd->prepare($sql); $stm->execute(); $res = $stm->fetchAll(PDO::FETCH_ASSOC); - $repartition['all_feeds'] = $res[0]; - return $repartition; + return $res[0]; } /** @@ -147,10 +151,9 @@ SQL; * @return string */ protected function calculateEntryRepartitionPerFeedPerPeriod($period, $feed = null) { + $restrict = ''; if ($feed) { $restrict = "WHERE e.id_feed = {$feed}"; - } else { - $restrict = ''; } $sql = <<<SQL SELECT DATE_FORMAT(FROM_UNIXTIME(e.date), '{$period}') AS period @@ -179,7 +182,7 @@ SQL; * @return integer */ public function calculateEntryAveragePerFeedPerHour($feed = null) { - return $this->calculateEntryAveragePerFeedPerPeriod(1/24, $feed); + return $this->calculateEntryAveragePerFeedPerPeriod(1 / 24, $feed); } /** @@ -210,10 +213,9 @@ SQL; * @return integer */ protected function calculateEntryAveragePerFeedPerPeriod($period, $feed = null) { + $restrict = ''; if ($feed) { $restrict = "WHERE e.id_feed = {$feed}"; - } else { - $restrict = ''; } $sql = <<<SQL SELECT COUNT(1) AS count @@ -237,7 +239,7 @@ SQL; $interval_in_days = $period; } - return round($res['count'] / ($interval_in_days / $period), 2); + return $res['count'] / ($interval_in_days / $period); } /** @@ -415,8 +417,8 @@ SQL; * @return string */ private function convertToTranslatedJson($data = array()) { - $translated = array_map(function ($a) { - return Minz_Translate::t($a); + $translated = array_map(function($a) { + return _t('gen.date.' . $a); }, $data); return json_encode($translated); diff --git a/app/Models/Themes.php b/app/Models/Themes.php index 68fc17a2b..e3b260261 100644 --- a/app/Models/Themes.php +++ b/app/Models/Themes.php @@ -82,6 +82,7 @@ class FreshRSS_Themes extends Minz_Model { 'favorite' => '★', 'help' => 'ⓘ', 'icon' => '⊚', + 'import' => '⤓', 'key' => '⚿', 'link' => '↗', 'login' => '🔒', diff --git a/app/Models/UserDAO.php b/app/Models/UserDAO.php index 9f64fb4a7..b55766ab4 100644 --- a/app/Models/UserDAO.php +++ b/app/Models/UserDAO.php @@ -2,14 +2,14 @@ class FreshRSS_UserDAO extends Minz_ModelPdo { public function createUser($username) { - $db = Minz_Configuration::dataBase(); + $db = FreshRSS_Context::$system_conf->db; require_once(APP_PATH . '/SQL/install.sql.' . $db['type'] . '.php'); $userPDO = new Minz_ModelPdo($username); $ok = false; if (defined('SQL_CREATE_TABLES')) { //E.g. MySQL - $sql = sprintf(SQL_CREATE_TABLES, $db['prefix'] . $username . '_', Minz_Translate::t('default_category')); + $sql = sprintf(SQL_CREATE_TABLES, $db['prefix'] . $username . '_', _t('gen.short.default_category')); $stm = $userPDO->bd->prepare($sql); $ok = $stm && $stm->execute(); } else { //E.g. SQLite @@ -17,7 +17,7 @@ class FreshRSS_UserDAO extends Minz_ModelPdo { if (is_array($SQL_CREATE_TABLES)) { $ok = true; foreach ($SQL_CREATE_TABLES as $instruction) { - $sql = sprintf($instruction, '', Minz_Translate::t('default_category')); + $sql = sprintf($instruction, '', _t('gen.short.default_category')); $stm = $userPDO->bd->prepare($sql); $ok &= ($stm && $stm->execute()); } @@ -28,17 +28,17 @@ class FreshRSS_UserDAO extends Minz_ModelPdo { return true; } else { $info = empty($stm) ? array(2 => 'syntax error') : $stm->errorInfo(); - Minz_Log::record ('SQL error : ' . $info[2], Minz_Log::ERROR); + Minz_Log::error('SQL error : ' . $info[2]); return false; } } public function deleteUser($username) { - $db = Minz_Configuration::dataBase(); + $db = FreshRSS_Context::$system_conf->db; require_once(APP_PATH . '/SQL/install.sql.' . $db['type'] . '.php'); if ($db['type'] === 'sqlite') { - return unlink(DATA_PATH . '/' . $username . '.sqlite'); + return unlink(join_path(DATA_PATH, 'users', $username, 'db.sqlite')); } else { $userPDO = new Minz_ModelPdo($username); @@ -48,9 +48,21 @@ class FreshRSS_UserDAO extends Minz_ModelPdo { return true; } else { $info = $stm == null ? array(2 => 'syntax error') : $stm->errorInfo(); - Minz_Log::record ('SQL error : ' . $info[2], Minz_Log::ERROR); + Minz_Log::error('SQL error : ' . $info[2]); return false; } } } + + public static function exist($username) { + return is_dir(join_path(DATA_PATH , 'users', $username)); + } + + public static function touch($username) { + return touch(join_path(DATA_PATH , 'users', $username, 'config.php')); + } + + public static function mtime($username) { + return @filemtime(join_path(DATA_PATH , 'users', $username, 'config.php')); + } } |
