aboutsummaryrefslogtreecommitdiff
path: root/app/Models
diff options
context:
space:
mode:
authorGravatar Clément <clement@selfhost.fr> 2017-02-15 14:12:25 +0100
committerGravatar Clément <clement@selfhost.fr> 2017-02-15 14:12:25 +0100
commit2d097bc855dbd1ad06c7c306c05e78a198209084 (patch)
tree67028e45792c575c25c92616633f64cc7a4a13eb /app/Models
parentfe293900061263a1917fc1cf18ca369c8e07cb99 (diff)
parent5f637bd816b7323885bfe1751a1724ee59a822f6 (diff)
Merge remote-tracking branch 'FreshRSS/master' into dev
Diffstat (limited to 'app/Models')
-rw-r--r--app/Models/Auth.php109
-rw-r--r--app/Models/Category.php7
-rw-r--r--app/Models/CategoryDAO.php29
-rw-r--r--app/Models/Configuration.php336
-rw-r--r--app/Models/ConfigurationSetter.php380
-rw-r--r--app/Models/Context.php322
-rw-r--r--app/Models/DatabaseDAOPGSQL.php43
-rw-r--r--app/Models/Entry.php23
-rw-r--r--app/Models/EntryDAO.php690
-rw-r--r--app/Models/EntryDAOPGSQL.php31
-rw-r--r--app/Models/EntryDAOSQLite.php101
-rw-r--r--app/Models/Factory.php51
-rw-r--r--app/Models/Feed.php220
-rw-r--r--app/Models/FeedDAO.php78
-rw-r--r--app/Models/FeedDAOSQLite.php4
-rw-r--r--app/Models/LogDAO.php9
-rw-r--r--app/Models/Search.php229
-rw-r--r--app/Models/Searchable.php6
-rw-r--r--app/Models/Share.php230
-rw-r--r--app/Models/StatsDAO.php175
-rw-r--r--app/Models/StatsDAOPGSQL.php67
-rw-r--r--app/Models/StatsDAOSQLite.php59
-rw-r--r--app/Models/Themes.php4
-rw-r--r--app/Models/UserDAO.php75
-rw-r--r--app/Models/UserQuery.php226
25 files changed, 2614 insertions, 890 deletions
diff --git a/app/Models/Auth.php b/app/Models/Auth.php
index cc23d7974..b3255cfbd 100644
--- a/app/Models/Auth.php
+++ b/app/Models/Auth.php
@@ -16,14 +16,16 @@ class FreshRSS_Auth {
self::$login_ok = Minz_Session::param('loginOk', false);
$current_user = Minz_Session::param('currentUser', '');
if ($current_user === '') {
- $current_user = Minz_Configuration::defaultUser();
+ $conf = Minz_Configuration::get('system');
+ $current_user = $conf->default_user;
Minz_Session::_param('currentUser', $current_user);
}
- $access_ok = self::accessControl();
-
- if ($access_ok) {
+ if (self::$login_ok) {
self::giveAccess();
+ } elseif (self::accessControl()) {
+ self::giveAccess();
+ FreshRSS_UserDAO::touch();
} else {
// Be sure all accesses are removed!
self::removeAccess();
@@ -38,12 +40,10 @@ class FreshRSS_Auth {
*
* @return boolean true if user can be connected, false else.
*/
- public static function accessControl() {
- if (self::$login_ok) {
- return true;
- }
-
- switch (Minz_Configuration::authType()) {
+ 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 = '';
@@ -60,16 +60,6 @@ class FreshRSS_Auth {
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:
@@ -83,22 +73,16 @@ class FreshRSS_Auth {
*/
public static function giveAccess() {
$current_user = Minz_Session::param('currentUser');
- try {
- $conf = new FreshRSS_Configuration($current_user);
- } catch(Minz_Exception $e) {
- die($e->getMessage());
- }
+ $user_conf = get_user_configuration($current_user);
+ $system_conf = Minz_Configuration::get('system');
- switch (Minz_Configuration::authType()) {
+ switch ($system_conf->auth_type) {
case 'form':
- self::$login_ok = Minz_Session::param('passwordHash') === $conf->passwordHash;
+ 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'), $conf->mail_login) === 0;
- break;
case 'none':
self::$login_ok = true;
break;
@@ -117,12 +101,14 @@ class FreshRSS_Auth {
* @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') === Minz_Configuration::defaultUser();
+ $ok &= Minz_Session::param('currentUser') === $default_user;
break;
default:
$ok = false;
@@ -136,16 +122,15 @@ class FreshRSS_Auth {
public static function removeAccess() {
Minz_Session::_param('loginOk');
self::$login_ok = false;
- Minz_Session::_param('currentUser', Minz_Configuration::defaultUser());
+ $conf = Minz_Configuration::get('system');
+ Minz_Session::_param('currentUser', $conf->default_user);
+ Minz_Session::_param('csrf');
- switch (Minz_Configuration::authType()) {
+ 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...
@@ -154,6 +139,44 @@ class FreshRSS_Auth {
// 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';
+ }
+
+ public static function csrfToken() {
+ $csrf = Minz_Session::param('csrf');
+ if ($csrf == '') {
+ $salt = FreshRSS_Context::$system_conf->salt;
+ $csrf = sha1($salt . uniqid(mt_rand(), true));
+ Minz_Session::_param('csrf', $csrf);
+ }
+ return $csrf;
+ }
+ public static function isCsrfOk($token = null) {
+ $csrf = Minz_Session::param('csrf');
+ if ($csrf == '') {
+ return true; //Not logged in yet
+ }
+ if ($token === null) {
+ $token = Minz_Request::fetchPOST('_csrf');
+ }
+ return $token === $csrf;
+ }
}
@@ -196,8 +219,9 @@ class FreshRSS_FormAuth {
}
public static function makeCookie($username, $password_hash) {
+ $conf = Minz_Configuration::get('system');
do {
- $token = sha1(Minz_Configuration::salt() . $username . uniqid(mt_rand(), true));
+ $token = sha1($conf->salt . $username . uniqid(mt_rand(), true));
$token_file = DATA_PATH . '/tokens/' . $token . '.txt';
} while (file_exists($token_file));
@@ -205,15 +229,17 @@ class FreshRSS_FormAuth {
return false;
}
- $expire = time() + 2629744; //1 month //TODO: Use a configuration instead
+ $limits = $conf->limits;
+ $cookie_duration = empty($limits['cookie_duration']) ? 2629744 : $limits['cookie_duration'];
+ $expire = time() + $cookie_duration;
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)) {
+ Minz_Session::deleteLongTermCookie('FreshRSS_login');
@unlink(DATA_PATH . '/tokens/' . $token . '.txt');
}
@@ -223,7 +249,10 @@ class FreshRSS_FormAuth {
}
public static function purgeTokens() {
- $oldest = time() - 2629744; // 1 month // TODO: Use a configuration instead
+ $conf = Minz_Configuration::get('system');
+ $limits = $conf->limits;
+ $cookie_duration = empty($limits['cookie_duration']) ? 2629744 : $limits['cookie_duration'];
+ $oldest = time() - $cookie_duration;
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);
diff --git a/app/Models/Category.php b/app/Models/Category.php
index 37cb44dc3..9a44a2d09 100644
--- a/app/Models/Category.php
+++ b/app/Models/Category.php
@@ -6,6 +6,7 @@ class FreshRSS_Category extends Minz_Model {
private $nbFeed = -1;
private $nbNotRead = -1;
private $feeds = null;
+ private $hasFeedsWithError = false;
public function __construct($name = '', $feeds = null) {
$this->_name($name);
@@ -16,6 +17,7 @@ class FreshRSS_Category extends Minz_Model {
foreach ($feeds as $feed) {
$this->nbFeed++;
$this->nbNotRead += $feed->nbNotRead();
+ $this->hasFeedsWithError |= $feed->inError();
}
}
}
@@ -51,12 +53,17 @@ class FreshRSS_Category extends Minz_Model {
foreach ($this->feeds as $feed) {
$this->nbFeed++;
$this->nbNotRead += $feed->nbNotRead();
+ $this->hasFeedsWithError |= $feed->inError();
}
}
return $this->feeds;
}
+ public function hasFeedsWithError() {
+ return $this->hasFeedsWithError;
+ }
+
public function _id($value) {
$this->id = $value;
}
diff --git a/app/Models/CategoryDAO.php b/app/Models/CategoryDAO.php
index 2e333d2f1..c2d57c241 100644
--- a/app/Models/CategoryDAO.php
+++ b/app/Models/CategoryDAO.php
@@ -1,6 +1,9 @@
<?php
-class FreshRSS_CategoryDAO extends Minz_ModelPdo {
+class FreshRSS_CategoryDAO extends Minz_ModelPdo implements FreshRSS_Searchable {
+
+ const defaultCategoryId = 1;
+
public function addCategory($valuesTmp) {
$sql = 'INSERT INTO `' . $this->prefix . 'category`(name) VALUES(?)';
$stm = $this->bd->prepare($sql);
@@ -10,10 +13,10 @@ class FreshRSS_CategoryDAO extends Minz_ModelPdo {
);
if ($stm && $stm->execute($values)) {
- return $this->bd->lastInsertId();
+ return $this->bd->lastInsertId('"' . $this->prefix . 'category_id_seq"');
} else {
$info = $stm == null ? array(2 => 'syntax error') : $stm->errorInfo();
- Minz_Log::error('SQL error addCategory: ' . $info[2] );
+ Minz_Log::error('SQL error addCategory: ' . $info[2]);
return false;
}
}
@@ -50,6 +53,9 @@ class FreshRSS_CategoryDAO extends Minz_ModelPdo {
}
public function deleteCategory($id) {
+ if ($id <= self::defaultCategoryId) {
+ return false;
+ }
$sql = 'DELETE FROM `' . $this->prefix . 'category` WHERE id=?';
$stm = $this->bd->prepare($sql);
@@ -100,10 +106,10 @@ class FreshRSS_CategoryDAO extends Minz_ModelPdo {
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 ')
+ . ($details ? 'f.* ' : 'f.id, f.name, f.url, f.website, f.priority, f.error, f.`cache_nbEntries`, f.`cache_nbUnreads` ')
. 'FROM `' . $this->prefix . 'category` c '
. 'LEFT OUTER JOIN `' . $this->prefix . 'feed` f ON f.category=c.id '
- . 'GROUP BY f.id '
+ . 'GROUP BY f.id, c_id '
. 'ORDER BY c.name, f.name';
$stm = $this->bd->prepare($sql);
$stm->execute();
@@ -117,7 +123,7 @@ class FreshRSS_CategoryDAO extends Minz_ModelPdo {
}
public function getDefault() {
- $sql = 'SELECT * FROM `' . $this->prefix . 'category` WHERE id=1';
+ $sql = 'SELECT * FROM `' . $this->prefix . 'category` WHERE id=' . self::defaultCategoryId;
$stm = $this->bd->prepare($sql);
$stm->execute();
@@ -131,11 +137,11 @@ class FreshRSS_CategoryDAO extends Minz_ModelPdo {
}
}
public function checkDefault() {
- $def_cat = $this->searchById(1);
+ $def_cat = $this->searchById(self::defaultCategoryId);
if ($def_cat == null) {
- $cat = new FreshRSS_Category(_t('default_category'));
- $cat->_id(1);
+ $cat = new FreshRSS_Category(_t('gen.short.default_category'));
+ $cat->_id(self::defaultCategoryId);
$values = array(
'id' => $cat->id(),
@@ -207,12 +213,13 @@ class FreshRSS_CategoryDAO extends Minz_ModelPdo {
$previousLine = null;
$feedsDao = array();
+ $feedDao = FreshRSS_Factory::createFeedDAO();
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(
$previousLine['c_name'],
- FreshRSS_FeedDAO::daoToFeed($feedsDao, $previousLine['c_id'])
+ $feedDao->daoToFeed($feedsDao, $previousLine['c_id'])
);
$cat->_id($previousLine['c_id']);
$list[$previousLine['c_id']] = $cat;
@@ -228,7 +235,7 @@ class FreshRSS_CategoryDAO extends Minz_ModelPdo {
if ($previousLine != null) {
$cat = new FreshRSS_Category(
$previousLine['c_name'],
- FreshRSS_FeedDAO::daoToFeed($feedsDao, $previousLine['c_id'])
+ $feedDao->daoToFeed($feedsDao, $previousLine['c_id'])
);
$cat->_id($previousLine['c_id']);
$list[$previousLine['c_id']] = $cat;
diff --git a/app/Models/Configuration.php b/app/Models/Configuration.php
deleted file mode 100644
index 2f208e509..000000000
--- a/app/Models/Configuration.php
+++ /dev/null
@@ -1,336 +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',
- 'close_dropdown' => 'escape',
- ),
- '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..046f54955
--- /dev/null
+++ b/app/Models/ConfigurationSetter.php
@@ -0,0 +1,380 @@
+<?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 _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) {
+ if ($value instanceof FreshRSS_UserQuery) {
+ $data['queries'][] = $value->toArray();
+ } elseif (is_array($value)) {
+ $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);
+ 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 _mark_updated_article_unread(&$data, $value) {
+ $data['mark_updated_article_unread'] = $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', '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':
+ case 'pgsql':
+ 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,
+ ),
+ 'max_registrations' => array(
+ 'min' => 0,
+ ),
+ );
+
+ foreach ($values as $key => $value) {
+ if (!isset($limits_keys[$key])) {
+ continue;
+ }
+
+ $value = intval($value);
+ $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);
+ }
+
+ private function _auto_update_url(&$data, $value) {
+ if (!$value) {
+ return;
+ }
+
+ $data['auto_update_url'] = $value;
+ }
+}
diff --git a/app/Models/Context.php b/app/Models/Context.php
index d984fece7..fd0e79fc1 100644
--- a/app/Models/Context.php
+++ b/app/Models/Context.php
@@ -5,28 +5,322 @@
* useful functions associated to the current view state.
*/
class FreshRSS_Context {
- public static $conf = null;
+ public static $user_conf = null;
+ public static $system_conf = null;
+ public static $categories = array();
+
+ public static $name = '';
+ public static $description = '';
+
+ 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 = '';
+ public static $sinceHours = 0;
+ public static $isCli = false;
+
+ /**
+ * Initialize the context.
+ *
+ * Set the correct configurations and $categories variables.
+ */
public static function init() {
// Init configuration.
- $current_user = Minz_Session::param('currentUser');
- try {
- self::$conf = new FreshRSS_Configuration($current_user);
- } catch(Minz_Exception $e) {
- Minz_Log::error('Cannot load configuration file of user `' . $current_user . '`');
- die($e->getMessage());
+ self::$system_conf = Minz_Configuration::get('system');
+ self::$user_conf = Minz_Configuration::get('user');
+ }
+
+ /**
+ * 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;
}
+ }
- // Init i18n.
- Minz_Session::_param('language', self::$conf->language);
- Minz_Translate::init();
+ /**
+ * 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'];
+ }
+ }
+ }
- // Get the current state.
- self::$state = self::$conf->default_view;
+ /**
+ * Return true if the current request targets a feed (and not a category or all articles), false otherwise.
+ */
+ public static function isFeed() {
+ return self::$current_get['feed'] != false;
}
- public static function stateEnabled($state) {
- return self::$state & $state;
+ /**
+ * 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;
+
+ if (empty(self::$categories)) {
+ $catDAO = new FreshRSS_CategoryDAO();
+ self::$categories = $catDAO->listCategories();
+ }
+
+ switch($type) {
+ case 'a':
+ self::$current_get['all'] = true;
+ self::$name = _t('index.feed.title');
+ self::$description = self::$system_conf->meta_description;
+ self::$get_unread = self::$total_unread;
+ break;
+ case 's':
+ self::$current_get['starred'] = true;
+ self::$name = _t('index.feed.title_fav');
+ self::$description = self::$system_conf->meta_description;
+ 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. When allowing robots, always retrieve the full feed including description
+ $feed = FreshRSS_Context::$system_conf->allow_robots ? null : 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::$description = $feed->description();
+ 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.
+ */
+ private static function _nextGet() {
+ $get = self::currentGet();
+ // By default, $next_get == $get
+ self::$next_get = $get;
+
+ if (empty(self::$categories)) {
+ $catDAO = new FreshRSS_CategoryDAO();
+ self::$categories = $catDAO->listCategories();
+ }
+
+ 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/DatabaseDAOPGSQL.php b/app/Models/DatabaseDAOPGSQL.php
new file mode 100644
index 000000000..a4edaa448
--- /dev/null
+++ b/app/Models/DatabaseDAOPGSQL.php
@@ -0,0 +1,43 @@
+<?php
+
+/**
+ * This class is used to test database is well-constructed.
+ */
+class FreshRSS_DatabaseDAOPGSQL extends FreshRSS_DatabaseDAO {
+ public function tablesAreCorrect() {
+ $db = FreshRSS_Context::$system_conf->db;
+ $dbowner = $db['user'];
+ $sql = 'SELECT * FROM pg_catalog.pg_tables where tableowner=?';
+ $stm = $this->bd->prepare($sql);
+ $values = array($dbowner);
+ $stm->execute($values);
+ $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 = 'select column_name as field, data_type as type, column_default as default, is_nullable as null from INFORMATION_SCHEMA.COLUMNS where table_name = ?';
+ $stm = $this->bd->prepare($sql);
+ $stm->execute(array($this->prefix . $table));
+ return $this->listDaoToSchema($stm->fetchAll(PDO::FETCH_ASSOC));
+ }
+
+ public function daoToSchema($dao) {
+ return array(
+ 'name' => $dao['field'],
+ 'type' => strtolower($dao['type']),
+ 'notnull' => (bool)$dao['null'],
+ 'default' => $dao['default'],
+ );
+ }
+}
diff --git a/app/Models/Entry.php b/app/Models/Entry.php
index ee94d1110..a562a963a 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;
@@ -15,7 +14,8 @@ class FreshRSS_Entry extends Minz_Model {
private $content;
private $link;
private $date;
- private $is_read;
+ private $hash = null;
+ private $is_read; //Nullable boolean
private $is_favorite;
private $feed;
private $tags;
@@ -89,6 +89,14 @@ class FreshRSS_Entry extends Minz_Model {
}
}
+ public function hash() {
+ if ($this->hash === null) {
+ //Do not include $this->date because it may be automatically generated when lacking
+ $this->hash = md5($this->link . $this->title . $this->author . $this->content . $this->tags(true));
+ }
+ return $this->hash;
+ }
+
public function _id($value) {
$this->id = $value;
}
@@ -96,23 +104,28 @@ class FreshRSS_Entry extends Minz_Model {
$this->guid = $value;
}
public function _title($value) {
+ $this->hash = null;
$this->title = $value;
}
public function _author($value) {
+ $this->hash = null;
$this->author = $value;
}
public function _content($value) {
+ $this->hash = null;
$this->content = $value;
}
public function _link($value) {
+ $this->hash = null;
$this->link = $value;
}
public function _date($value) {
+ $this->hash = null;
$value = intval($value);
$this->date = $value > 1 ? $value : time();
}
public function _isRead($value) {
- $this->is_read = $value;
+ $this->is_read = $value === null ? null : (bool)$value;
}
public function _isFavorite($value) {
$this->is_favorite = $value;
@@ -121,6 +134,7 @@ class FreshRSS_Entry extends Minz_Model {
$this->feed = $value;
}
public function _tags($value) {
+ $this->hash = null;
if (!is_array($value)) {
$value = array($value);
}
@@ -183,6 +197,7 @@ class FreshRSS_Entry extends Minz_Model {
'content' => $this->content(),
'link' => $this->link(),
'date' => $this->date(true),
+ 'hash' => $this->hash(),
'is_read' => $this->isRead(),
'is_favorite' => $this->isFavorite(),
'id_feed' => $this->feed(),
diff --git a/app/Models/EntryDAO.php b/app/Models/EntryDAO.php
index 5a136499a..397471baa 100644
--- a/app/Models/EntryDAO.php
+++ b/app/Models/EntryDAO.php
@@ -1,89 +1,247 @@
<?php
-class FreshRSS_EntryDAO extends Minz_ModelPdo {
+class FreshRSS_EntryDAO extends Minz_ModelPdo implements FreshRSS_Searchable {
public function isCompressed() {
+ return parent::$sharedDbType === 'mysql';
+ }
+
+ public function hasNativeHex() {
return parent::$sharedDbType !== 'sqlite';
}
- public function addEntryPrepare() {
- $sql = 'INSERT INTO `' . $this->prefix . 'entry`(id, guid, title, author, '
- . ($this->isCompressed() ? 'content_bin' : 'content')
- . ', link, date, is_read, is_favorite, id_feed, tags) '
- . 'VALUES(?, ?, ?, ?, '
- . ($this->isCompressed() ? 'COMPRESS(?)' : '?')
- . ', ?, ?, ?, ?, ?, ?)';
- return $this->bd->prepare($sql);
+ public function sqlHexDecode($x) {
+ return 'unhex(' . $x . ')';
}
- public function addEntry($valuesTmp, $preparedStatement = null) {
- $stm = $preparedStatement === null ?
- FreshRSS_EntryDAO::addEntryPrepare() :
- $preparedStatement;
+ public function sqlHexEncode($x) {
+ return 'hex(' . $x . ')';
+ }
- $values = array(
- $valuesTmp['id'],
- substr($valuesTmp['guid'], 0, 760),
- substr($valuesTmp['title'], 0, 255),
- substr($valuesTmp['author'], 0, 255),
- $valuesTmp['content'],
- substr($valuesTmp['link'], 0, 1023),
- $valuesTmp['date'],
- $valuesTmp['is_read'] ? 1 : 0,
- $valuesTmp['is_favorite'] ? 1 : 0,
- $valuesTmp['id_feed'],
- substr($valuesTmp['tags'], 0, 1023),
- );
+ protected function addColumn($name) {
+ Minz_Log::warning('FreshRSS_EntryDAO::addColumn: ' . $name);
+ $hasTransaction = false;
+ try {
+ $stm = null;
+ if ($name === 'lastSeen') { //v1.1.1
+ if (!$this->bd->inTransaction()) {
+ $this->bd->beginTransaction();
+ $hasTransaction = true;
+ }
+ $stm = $this->bd->prepare('ALTER TABLE `' . $this->prefix . 'entry` ADD COLUMN `lastSeen` INT(11) DEFAULT 0');
+ if ($stm && $stm->execute()) {
+ $stm = $this->bd->prepare('CREATE INDEX entry_lastSeen_index ON `' . $this->prefix . 'entry`(`lastSeen`);'); //"IF NOT EXISTS" does not exist in MySQL 5.7
+ if ($stm && $stm->execute()) {
+ if ($hasTransaction) {
+ $this->bd->commit();
+ }
+ return true;
+ }
+ }
+ if ($hasTransaction) {
+ $this->bd->rollBack();
+ }
+ } elseif ($name === 'hash') { //v1.1.1
+ $stm = $this->bd->prepare('ALTER TABLE `' . $this->prefix . 'entry` ADD COLUMN hash BINARY(16)');
+ return $stm && $stm->execute();
+ }
+ } catch (Exception $e) {
+ Minz_Log::error('FreshRSS_EntryDAO::addColumn error: ' . $e->getMessage());
+ if ($hasTransaction) {
+ $this->bd->rollBack();
+ }
+ }
+ return false;
+ }
- if ($stm && $stm->execute($values)) {
- return $this->bd->lastInsertId();
- } 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::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::debug('SQL error ' . $info[0] . ': ' . $info[1] . ' ' . $info[2]
- . ' while adding entry in feed ' . $valuesTmp['id_feed'] . ' with title: ' . $valuesTmp['title']);
- }*/
+ private $triedUpdateToUtf8mb4 = false;
+
+ protected function updateToUtf8mb4() {
+ if ($this->triedUpdateToUtf8mb4) {
return false;
}
+ $this->triedUpdateToUtf8mb4 = true;
+ $db = FreshRSS_Context::$system_conf->db;
+ if ($db['type'] === 'mysql') {
+ include_once(APP_PATH . '/SQL/install.sql.mysql.php');
+ if (defined('SQL_UPDATE_UTF8MB4')) {
+ Minz_Log::warning('Updating MySQL to UTF8MB4...');
+ $hadTransaction = $this->bd->inTransaction();
+ if ($hadTransaction) {
+ $this->bd->commit();
+ }
+ $ok = false;
+ try {
+ $sql = sprintf(SQL_UPDATE_UTF8MB4, $this->prefix, $db['base']);
+ $stm = $this->bd->prepare($sql);
+ $ok = $stm->execute();
+ } catch (Exception $e) {
+ Minz_Log::error('FreshRSS_EntryDAO::updateToUtf8mb4 error: ' . $e->getMessage());
+ }
+ if ($hadTransaction) {
+ $this->bd->beginTransaction();
+ //NB: Transaction not starting. Why? (tested on PHP 7.0.8-0ubuntu and MySQL 5.7.13-0ubuntu)
+ }
+ return $ok;
+ }
+ }
+ return false;
}
- public function addEntryObject($entry, $conf, $feedHistory) {
- $existingGuids = array_fill_keys(
- $this->listLastGuidsByFeed($entry->feed(), 20), 1
- );
-
- $nb_month_old = max($conf->old_entries, 1);
- $date_min = time() - (3600 * 24 * 30 * $nb_month_old);
+ protected function autoUpdateDb($errorInfo) {
+ if (isset($errorInfo[0])) {
+ if ($errorInfo[0] === '42S22') { //ER_BAD_FIELD_ERROR
+ //autoAddColumn
+ foreach (array('lastSeen', 'hash') as $column) {
+ if (stripos($errorInfo[2], $column) !== false) {
+ return $this->addColumn($column);
+ }
+ }
+ }
+ }
+ if (isset($errorInfo[1])) {
+ if ($errorInfo[1] == '1366') { //ER_TRUNCATED_WRONG_VALUE_FOR_FIELD
+ return $this->updateToUtf8mb4();
+ }
+ }
+ return false;
+ }
- $eDate = $entry->date(true);
+ private $addEntryPrepared = null;
+
+ public function addEntry($valuesTmp) {
+ if ($this->addEntryPrepared === null) {
+ $sql = 'INSERT INTO `' . $this->prefix . 'entry` (id, guid, title, author, '
+ . ($this->isCompressed() ? 'content_bin' : 'content')
+ . ', link, date, `lastSeen`, hash, is_read, is_favorite, id_feed, tags) '
+ . 'VALUES(:id, :guid, :title, :author, '
+ . ($this->isCompressed() ? 'COMPRESS(:content)' : ':content')
+ . ', :link, :date, :last_seen, '
+ . $this->sqlHexDecode(':hash')
+ . ', :is_read, :is_favorite, :id_feed, :tags)';
+ $this->addEntryPrepared = $this->bd->prepare($sql);
+ }
+ $this->addEntryPrepared->bindParam(':id', $valuesTmp['id']);
+ $valuesTmp['guid'] = substr($valuesTmp['guid'], 0, 760);
+ $valuesTmp['guid'] = safe_ascii($valuesTmp['guid']);
+ $this->addEntryPrepared->bindParam(':guid', $valuesTmp['guid']);
+ $valuesTmp['title'] = substr($valuesTmp['title'], 0, 255);
+ $this->addEntryPrepared->bindParam(':title', $valuesTmp['title']);
+ $valuesTmp['author'] = substr($valuesTmp['author'], 0, 255);
+ $this->addEntryPrepared->bindParam(':author', $valuesTmp['author']);
+ $this->addEntryPrepared->bindParam(':content', $valuesTmp['content']);
+ $valuesTmp['link'] = substr($valuesTmp['link'], 0, 1023);
+ $valuesTmp['link'] = safe_ascii($valuesTmp['link']);
+ $this->addEntryPrepared->bindParam(':link', $valuesTmp['link']);
+ $this->addEntryPrepared->bindParam(':date', $valuesTmp['date'], PDO::PARAM_INT);
+ $valuesTmp['lastSeen'] = time();
+ $this->addEntryPrepared->bindParam(':last_seen', $valuesTmp['lastSeen'], PDO::PARAM_INT);
+ $valuesTmp['is_read'] = $valuesTmp['is_read'] ? 1 : 0;
+ $this->addEntryPrepared->bindParam(':is_read', $valuesTmp['is_read'], PDO::PARAM_INT);
+ $valuesTmp['is_favorite'] = $valuesTmp['is_favorite'] ? 1 : 0;
+ $this->addEntryPrepared->bindParam(':is_favorite', $valuesTmp['is_favorite'], PDO::PARAM_INT);
+ $this->addEntryPrepared->bindParam(':id_feed', $valuesTmp['id_feed'], PDO::PARAM_INT);
+ $valuesTmp['tags'] = substr($valuesTmp['tags'], 0, 1023);
+ $this->addEntryPrepared->bindParam(':tags', $valuesTmp['tags']);
+
+ if ($this->hasNativeHex()) {
+ $this->addEntryPrepared->bindParam(':hash', $valuesTmp['hash']);
+ } else {
+ $valuesTmp['hashBin'] = pack('H*', $valuesTmp['hash']); //hex2bin() is PHP5.4+
+ $this->addEntryPrepared->bindParam(':hash', $valuesTmp['hashBin']);
+ }
- if ($feedHistory == -2) {
- $feedHistory = $conf->keep_history_default;
+ if ($this->addEntryPrepared && $this->addEntryPrepared->execute()) {
+ return $this->bd->lastInsertId();
+ } else {
+ $info = $this->addEntryPrepared == null ? array(0 => '', 1 => '', 2 => 'syntax error') : $this->addEntryPrepared->errorInfo();
+ if ($this->autoUpdateDb($info)) {
+ return $this->addEntry($valuesTmp);
+ } elseif ((int)($info[0] / 1000) !== 23) { //Filter out "SQLSTATE Class code 23: Constraint Violation" because of expected duplicate entries
+ Minz_Log::error('SQL error addEntry: ' . $info[0] . ': ' . $info[1] . ' ' . $info[2]
+ . ' while adding entry in feed ' . $valuesTmp['id_feed'] . ' with title: ' . $valuesTmp['title']);
+ }
+ return false;
}
+ }
- if (!isset($existingGuids[$entry->guid()]) &&
- ($feedHistory != 0 || $eDate >= $date_min || $entry->isFavorite())) {
- $values = $entry->toArray();
+ private $updateEntryPrepared = null;
- $useDeclaredDate = empty($existingGuids);
- $values['id'] = ($useDeclaredDate || $eDate < $date_min) ?
- min(time(), $eDate) . uSecString() :
- uTimeString();
+ public function updateEntry($valuesTmp) {
+ if (!isset($valuesTmp['is_read'])) {
+ $valuesTmp['is_read'] = null;
+ }
- return $this->addEntry($values);
+ if ($this->updateEntryPrepared === null) {
+ $sql = 'UPDATE `' . $this->prefix . 'entry` '
+ . 'SET title=:title, author=:author, '
+ . ($this->isCompressed() ? 'content_bin=COMPRESS(:content)' : 'content=:content')
+ . ', link=:link, date=:date, `lastSeen`=:last_seen, '
+ . 'hash=' . $this->sqlHexDecode(':hash')
+ . ', ' . ($valuesTmp['is_read'] === null ? '' : 'is_read=:is_read, ')
+ . 'tags=:tags '
+ . 'WHERE id_feed=:id_feed AND guid=:guid';
+ $this->updateEntryPrepared = $this->bd->prepare($sql);
+ }
+
+ $valuesTmp['guid'] = substr($valuesTmp['guid'], 0, 760);
+ $this->updateEntryPrepared->bindParam(':guid', $valuesTmp['guid']);
+ $valuesTmp['title'] = substr($valuesTmp['title'], 0, 255);
+ $this->updateEntryPrepared->bindParam(':title', $valuesTmp['title']);
+ $valuesTmp['author'] = substr($valuesTmp['author'], 0, 255);
+ $this->updateEntryPrepared->bindParam(':author', $valuesTmp['author']);
+ $this->updateEntryPrepared->bindParam(':content', $valuesTmp['content']);
+ $valuesTmp['link'] = substr($valuesTmp['link'], 0, 1023);
+ $valuesTmp['link'] = safe_ascii($valuesTmp['link']);
+ $this->updateEntryPrepared->bindParam(':link', $valuesTmp['link']);
+ $this->updateEntryPrepared->bindParam(':date', $valuesTmp['date'], PDO::PARAM_INT);
+ $valuesTmp['lastSeen'] = time();
+ $this->updateEntryPrepared->bindParam(':last_seen', $valuesTmp['lastSeen'], PDO::PARAM_INT);
+ if ($valuesTmp['is_read'] !== null) {
+ $this->updateEntryPrepared->bindValue(':is_read', $valuesTmp['is_read'] ? 1 : 0, PDO::PARAM_INT);
+ }
+ $this->updateEntryPrepared->bindParam(':id_feed', $valuesTmp['id_feed'], PDO::PARAM_INT);
+ $valuesTmp['tags'] = substr($valuesTmp['tags'], 0, 1023);
+ $this->updateEntryPrepared->bindParam(':tags', $valuesTmp['tags']);
+
+ if ($this->hasNativeHex()) {
+ $this->updateEntryPrepared->bindParam(':hash', $valuesTmp['hash']);
+ } else {
+ $valuesTmp['hashBin'] = pack('H*', $valuesTmp['hash']); //hex2bin() is PHP5.4+
+ $this->updateEntryPrepared->bindParam(':hash', $valuesTmp['hashBin']);
}
- // We don't return Entry object to avoid a research in DB
- return -1;
+ if ($this->updateEntryPrepared && $this->updateEntryPrepared->execute()) {
+ return $this->bd->lastInsertId();
+ } else {
+ $info = $this->updateEntryPrepared == null ? array(0 => '', 1 => '', 2 => 'syntax error') : $this->updateEntryPrepared->errorInfo();
+ if ($this->autoUpdateDb($info)) {
+ return $this->updateEntry($valuesTmp);
+ }
+ Minz_Log::error('SQL error updateEntry: ' . $info[0] . ': ' . $info[1] . ' ' . $info[2]
+ . ' while updating entry with GUID ' . $valuesTmp['guid'] . ' in feed ' . $valuesTmp['id_feed']);
+ return false;
+ }
}
+ /**
+ * 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);
}
+ if (count($ids) < 1) {
+ return 0;
+ }
+ FreshRSS_UserDAO::touch();
$sql = 'UPDATE `' . $this->prefix . 'entry` '
. 'SET is_favorite=? '
. 'WHERE id IN (' . str_repeat('?,', count($ids) - 1). '?)';
@@ -99,6 +257,17 @@ class FreshRSS_EntryDAO extends Minz_ModelPdo {
}
}
+ /**
+ * 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 ('
@@ -108,15 +277,19 @@ class FreshRSS_EntryDAO extends Minz_ModelPdo {
. 'WHERE e.is_read=0 '
. 'GROUP BY e.id_feed'
. ') x ON x.id_feed=f.id '
- . 'SET f.cache_nbUnreads=COALESCE(x.nbUnreads, 0) '
- . 'WHERE 1';
+ . 'SET f.`cache_nbUnreads`=COALESCE(x.nbUnreads, 0)';
+ $hasWhere = false;
$values = array();
if ($feedId !== false) {
- $sql .= ' AND f.id=?';
+ $sql .= $hasWhere ? ' AND' : ' WHERE';
+ $hasWhere = true;
+ $sql .= ' f.id=?';
$values[] = $id;
}
if ($catId !== false) {
- $sql .= ' AND f.category=?';
+ $sql .= $hasWhere ? ' AND' : ' WHERE';
+ $hasWhere = true;
+ $sql .= ' f.category=?';
$values[] = $catId;
}
$stm = $this->bd->prepare($sql);
@@ -129,7 +302,21 @@ class FreshRSS_EntryDAO extends Minz_ModelPdo {
}
}
+ /**
+ * 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) {
+ FreshRSS_UserDAO::touch();
if (is_array($ids)) { //Many IDs at once (used by API)
if (count($ids) < 6) { //Speed heuristics
$affected = 0;
@@ -158,7 +345,7 @@ class FreshRSS_EntryDAO extends Minz_ModelPdo {
} else {
$sql = 'UPDATE `' . $this->prefix . 'entry` e INNER JOIN `' . $this->prefix . 'feed` f ON e.id_feed=f.id '
. 'SET e.is_read=?,'
- . 'f.cache_nbUnreads=f.cache_nbUnreads' . ($is_read ? '-' : '+') . '1 '
+ . 'f.`cache_nbUnreads`=f.`cache_nbUnreads`' . ($is_read ? '-' : '+') . '1 '
. 'WHERE e.id=? AND e.is_read=?';
$values = array($is_read ? 1 : 0, $ids, $is_read ? 0 : 1);
$stm = $this->bd->prepare($sql);
@@ -172,7 +359,29 @@ class FreshRSS_EntryDAO extends Minz_ModelPdo {
}
}
- public function markReadEntries($idMax = 0, $onlyFavorites = false, $priorityMin = 0) {
+ /**
+ * 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, $filter = null, $state = 0) {
+ FreshRSS_UserDAO::touch();
if ($idMax == 0) {
$idMax = time() . '000000';
Minz_Log::debug('Calling markReadEntries(0) is deprecated!');
@@ -187,8 +396,11 @@ class FreshRSS_EntryDAO extends Minz_ModelPdo {
$sql .= ' AND f.priority > ' . intval($priorityMin);
}
$values = array($idMax);
- $stm = $this->bd->prepare($sql);
- if (!($stm && $stm->execute($values))) {
+
+ list($searchValues, $search) = $this->sqlListEntriesWhere('e.', $filter, $state);
+
+ $stm = $this->bd->prepare($sql . $search);
+ if (!($stm && $stm->execute(array_merge($values, $searchValues)))) {
$info = $stm == null ? array(2 => 'syntax error') : $stm->errorInfo();
Minz_Log::error('SQL error markReadEntries: ' . $info[2]);
return false;
@@ -200,7 +412,19 @@ class FreshRSS_EntryDAO extends Minz_ModelPdo {
return $affected;
}
- public function markReadCat($id, $idMax = 0) {
+ /**
+ * 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, $filter = null, $state = 0) {
+ FreshRSS_UserDAO::touch();
if ($idMax == 0) {
$idMax = time() . '000000';
Minz_Log::debug('Calling markReadCat(0) is deprecated!');
@@ -210,8 +434,11 @@ class FreshRSS_EntryDAO extends Minz_ModelPdo {
. 'SET e.is_read=1 '
. 'WHERE f.category=? AND e.is_read=0 AND e.id <= ?';
$values = array($id, $idMax);
- $stm = $this->bd->prepare($sql);
- if (!($stm && $stm->execute($values))) {
+
+ list($searchValues, $search) = $this->sqlListEntriesWhere('e.', $filter, $state);
+
+ $stm = $this->bd->prepare($sql . $search);
+ if (!($stm && $stm->execute(array_merge($values, $searchValues)))) {
$info = $stm == null ? array(2 => 'syntax error') : $stm->errorInfo();
Minz_Log::error('SQL error markReadCat: ' . $info[2]);
return false;
@@ -223,7 +450,19 @@ class FreshRSS_EntryDAO extends Minz_ModelPdo {
return $affected;
}
- public function markReadFeed($id, $idMax = 0) {
+ /**
+ * 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 feed ID
+ * @param integer $idMax fail safe article ID
+ * @return integer affected rows
+ */
+ public function markReadFeed($id_feed, $idMax = 0, $filter = null, $state = 0) {
+ FreshRSS_UserDAO::touch();
if ($idMax == 0) {
$idMax = time() . '000000';
Minz_Log::debug('Calling markReadFeed(0) is deprecated!');
@@ -233,11 +472,14 @@ class FreshRSS_EntryDAO extends Minz_ModelPdo {
$sql = 'UPDATE `' . $this->prefix . 'entry` '
. 'SET is_read=1 '
. 'WHERE id_feed=? AND is_read=0 AND id <= ?';
- $values = array($id, $idMax);
- $stm = $this->bd->prepare($sql);
- if (!($stm && $stm->execute($values))) {
+ $values = array($id_feed, $idMax);
+
+ list($searchValues, $search) = $this->sqlListEntriesWhere('', $filter, $state);
+
+ $stm = $this->bd->prepare($sql . $search);
+ if (!($stm && $stm->execute(array_merge($values, $searchValues)))) {
$info = $stm == null ? array(2 => 'syntax error') : $stm->errorInfo();
- Minz_Log::error('SQL error markReadFeed: ' . $info[2]);
+ Minz_Log::error('SQL error markReadFeed: ' . $info[2] . ' with SQL: ' . $sql . $search);
$this->bd->rollBack();
return false;
}
@@ -245,13 +487,13 @@ class FreshRSS_EntryDAO extends Minz_ModelPdo {
if ($affected > 0) {
$sql = 'UPDATE `' . $this->prefix . 'feed` '
- . 'SET cache_nbUnreads=cache_nbUnreads-' . $affected
+ . 'SET `cache_nbUnreads`=`cache_nbUnreads`-' . $affected
. ' WHERE id=?';
- $values = array($id);
+ $values = array($id_feed);
$stm = $this->bd->prepare($sql);
if (!($stm && $stm->execute($values))) {
$info = $stm == null ? array(2 => 'syntax error') : $stm->errorInfo();
- Minz_Log::error('SQL error markReadFeed: ' . $info[2]);
+ Minz_Log::error('SQL error markReadFeed cache: ' . $info[2]);
$this->bd->rollBack();
return false;
}
@@ -261,7 +503,7 @@ class FreshRSS_EntryDAO extends Minz_ModelPdo {
return $affected;
}
- public function searchByGuid($feed_id, $id) {
+ public function searchByGuid($id_feed, $guid) {
// un guid est unique pour un flux donné
$sql = 'SELECT id, guid, title, author, '
. ($this->isCompressed() ? 'UNCOMPRESS(content_bin) AS content' : 'content')
@@ -270,13 +512,13 @@ class FreshRSS_EntryDAO extends Minz_ModelPdo {
$stm = $this->bd->prepare($sql);
$values = array(
- $feed_id,
- $id
+ $id_feed,
+ $guid,
);
$stm->execute($values);
$res = $stm->fetchAll(PDO::FETCH_ASSOC);
- $entries = self::daoToEntry($res);
+ $entries = self::daoToEntries($res);
return isset($entries[0]) ? $entries[0] : null;
}
@@ -291,7 +533,7 @@ class FreshRSS_EntryDAO extends Minz_ModelPdo {
$stm->execute($values);
$res = $stm->fetchAll(PDO::FETCH_ASSOC);
- $entries = self::daoToEntry($res);
+ $entries = self::daoToEntries($res);
return isset($entries[0]) ? $entries[0] : null;
}
@@ -299,54 +541,24 @@ 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) {
- if (!$state) {
- $state = FreshRSS_Entry::STATE_ALL;
- }
- $where = '';
- $joinFeed = false;
+ protected function sqlListEntriesWhere($alias = '', $filter = null, $state = FreshRSS_Entry::STATE_ALL, $order = 'DESC', $firstId = '', $date_min = 0) {
+ $search = ' ';
$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 . ']!');
- }
-
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 ';
+ $search .= 'AND ' . $alias . 'is_read=0 ';
}
}
elseif ($state & FreshRSS_Entry::STATE_READ) {
- $where .= 'AND e1.is_read=1 ';
+ $search .= 'AND ' . $alias . 'is_read=1 ';
}
if ($state & FreshRSS_Entry::STATE_FAVORITE) {
if (!($state & FreshRSS_Entry::STATE_NOT_FAVORITE)) {
- $where .= 'AND e1.is_favorite=1 ';
+ $search .= 'AND ' . $alias . 'is_favorite=1 ';
}
}
elseif ($state & FreshRSS_Entry::STATE_NOT_FAVORITE) {
- $where .= 'AND e1.is_favorite=0 ';
+ $search .= 'AND ' . $alias . 'is_favorite=0 ';
}
switch ($order) {
@@ -360,87 +572,120 @@ class FreshRSS_EntryDAO extends Minz_ModelPdo {
$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 . ' ';
+ $search .= 'AND ' . $alias . 'id ' . ($order === 'DESC' ? '<=' : '>=') . $firstId . ' ';
}
if ($date_min > 0) {
- $where .= 'AND e1.id >= ' . $date_min . '000000 ';
- }
- $search = '';
- if ($filter !== '') {
- require_once(LIB_PATH . '/lib_date.php');
- $filter = trim($filter);
- $filter = addcslashes($filter, '\\%_');
- $terms = array_unique(explode(' ', $filter));
- //sort($terms); //Put #tags first //TODO: Put the cheapest filters first
- foreach ($terms as $word) {
- $word = trim($word);
- if (stripos($word, 'intitle:') === 0) {
- $word = substr($word, strlen('intitle:'));
- $search .= 'AND e1.title LIKE ? ';
- $values[] = '%' . $word .'%';
- } elseif (stripos($word, 'inurl:') === 0) {
- $word = substr($word, strlen('inurl:'));
- $search .= 'AND CONCAT(e1.link, e1.guid) LIKE ? ';
- $values[] = '%' . $word .'%';
- } elseif (stripos($word, 'author:') === 0) {
- $word = substr($word, strlen('author:'));
- $search .= 'AND e1.author LIKE ? ';
- $values[] = '%' . $word .'%';
- } elseif (stripos($word, 'date:') === 0) {
- $word = substr($word, strlen('date:'));
- list($minDate, $maxDate) = parseDateInterval($word);
- if ($minDate) {
- $search .= 'AND e1.id >= ' . $minDate . '000000 ';
- }
- if ($maxDate) {
- $search .= 'AND e1.id <= ' . $maxDate . '000000 ';
- }
- } elseif (stripos($word, 'pubdate:') === 0) {
- $word = substr($word, strlen('pubdate:'));
- list($minDate, $maxDate) = parseDateInterval($word);
- if ($minDate) {
- $search .= 'AND e1.date >= ' . $minDate . ' ';
- }
- if ($maxDate) {
- $search .= 'AND e1.date <= ' . $maxDate . ' ';
- }
- } else {
- if ($word[0] === '#' && isset($word[1])) {
- $search .= 'AND e1.tags LIKE ? ';
- $values[] = '%' . $word .'%';
- } else {
- $search .= 'AND ' . $this->sqlconcat('e1.title', $this->isCompressed() ? 'UNCOMPRESS(content_bin)' : 'content') . ' LIKE ? ';
- $values[] = '%' . $word .'%';
- }
+ $search .= 'AND ' . $alias . 'id >= ' . $date_min . '000000 ';
+ }
+ if ($filter) {
+ if ($filter->getIntitle()) {
+ $search .= 'AND ' . $alias . 'title LIKE ? ';
+ $values[] = "%{$filter->getIntitle()}%";
+ }
+ if ($filter->getInurl()) {
+ $search .= 'AND CONCAT(' . $alias . 'link, ' . $alias . 'guid) LIKE ? ';
+ $values[] = "%{$filter->getInurl()}%";
+ }
+ if ($filter->getAuthor()) {
+ $search .= 'AND ' . $alias . 'author LIKE ? ';
+ $values[] = "%{$filter->getAuthor()}%";
+ }
+ if ($filter->getMinDate()) {
+ $search .= 'AND ' . $alias . 'id >= ? ';
+ $values[] = "{$filter->getMinDate()}000000";
+ }
+ if ($filter->getMaxDate()) {
+ $search .= 'AND ' . $alias . 'id <= ? ';
+ $values[] = "{$filter->getMaxDate()}000000";
+ }
+ if ($filter->getMinPubdate()) {
+ $search .= 'AND ' . $alias . 'date >= ? ';
+ $values[] = $filter->getMinPubdate();
+ }
+ if ($filter->getMaxPubdate()) {
+ $search .= 'AND ' . $alias . 'date <= ? ';
+ $values[] = $filter->getMaxPubdate();
+ }
+ if ($filter->getTags()) {
+ $tags = $filter->getTags();
+ foreach ($tags as $tag) {
+ $search .= 'AND ' . $alias . 'tags LIKE ? ';
+ $values[] = "%{$tag}%";
+ }
+ }
+ if ($filter->getSearch()) {
+ $search_values = $filter->getSearch();
+ foreach ($search_values as $search_value) {
+ $search .= 'AND ' . $this->sqlconcat($alias . 'title', $this->isCompressed() ? 'UNCOMPRESS(' . $alias . 'content_bin)' : '' . $alias . 'content') . ' LIKE ? ';
+ $values[] = "%{$search_value}%";
}
}
}
+ return array($values, $search);
+ }
+
+ 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;
+ }
+ $where = '';
+ $joinFeed = false;
+ $values = array();
+ switch ($type) {
+ case 'a':
+ $where .= 'f.priority > 0 ';
+ $joinFeed = true;
+ break;
+ case 's': //Deprecated: use $state instead
+ $where .= 'e.is_favorite=1 ';
+ break;
+ case 'c':
+ $where .= 'f.category=? ';
+ $values[] = intval($id);
+ $joinFeed = true;
+ break;
+ case 'f':
+ $where .= 'e.id_feed=? ';
+ $values[] = intval($id);
+ break;
+ case 'A':
+ $where .= '1 ';
+ break;
+ default:
+ throw new FreshRSS_EntriesGetter_Exception('Bad type in Entry->listByType: [' . $type . ']!');
+ }
+
+ list($searchValues, $search) = $this->sqlListEntriesWhere('e.', $filter, $state, $order, $firstId, $date_min);
- return array($values,
- 'SELECT e1.id FROM `' . $this->prefix . 'entry` e1 '
- . ($joinFeed ? 'INNER JOIN `' . $this->prefix . 'feed` f ON e1.id_feed=f.id ' : '')
+ return array(array_merge($values, $searchValues),
+ 'SELECT e.id FROM `' . $this->prefix . 'entry` e '
+ . ($joinFeed ? 'INNER JOIN `' . $this->prefix . 'feed` f ON e.id_feed=f.id ' : '')
. 'WHERE ' . $where
. $search
- . 'ORDER BY e1.id ' . $order
+ . 'ORDER BY e.id ' . $order
. ($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) {
+ public function listWhereRaw($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, '
+ $sql = 'SELECT e0.id, e0.guid, e0.title, e0.author, '
. ($this->isCompressed() ? 'UNCOMPRESS(content_bin) AS content' : 'content')
- . ', e.link, e.date, e.is_read, e.is_favorite, e.id_feed, e.tags '
- . 'FROM `' . $this->prefix . 'entry` e '
+ . ', e0.link, e0.date, e0.is_read, e0.is_favorite, e0.id_feed, e0.tags '
+ . 'FROM `' . $this->prefix . 'entry` e0 '
. 'INNER JOIN ('
. $sql
- . ') e2 ON e2.id=e.id '
- . 'ORDER BY e.id ' . $order;
+ . ') e2 ON e2.id=e0.id '
+ . 'ORDER BY e0.id ' . $order;
$stm = $this->bd->prepare($sql);
$stm->execute($values);
+ return $stm;
+ }
- return self::daoToEntry($stm->fetchAll(PDO::FETCH_ASSOC));
+ public function listWhere($type = 'a', $id = '', $state = FreshRSS_Entry::STATE_ALL, $order = 'DESC', $limit = 1, $firstId = '', $filter = '', $date_min = 0) {
+ $stm = $this->listWhereRaw($type, $id, $state, $order, $limit, $firstId, $filter, $date_min);
+ return self::daoToEntries($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) { //For API
@@ -452,12 +697,55 @@ class FreshRSS_EntryDAO extends Minz_ModelPdo {
return $stm->fetchAll(PDO::FETCH_COLUMN, 0);
}
- public function listLastGuidsByFeed($id, $n) {
- $sql = 'SELECT guid FROM `' . $this->prefix . 'entry` WHERE id_feed=? ORDER BY id DESC LIMIT ' . intval($n);
+ public function listHashForFeedGuids($id_feed, $guids) {
+ if (count($guids) < 1) {
+ return array();
+ }
+ $guids = array_unique($guids);
+ $sql = 'SELECT guid, ' . $this->sqlHexEncode('hash') . ' AS hex_hash FROM `' . $this->prefix . 'entry` WHERE id_feed=? AND guid IN (' . str_repeat('?,', count($guids) - 1). '?)';
$stm = $this->bd->prepare($sql);
- $values = array($id);
- $stm->execute($values);
- return $stm->fetchAll(PDO::FETCH_COLUMN, 0);
+ $values = array($id_feed);
+ $values = array_merge($values, $guids);
+ if ($stm && $stm->execute($values)) {
+ $result = array();
+ $rows = $stm->fetchAll(PDO::FETCH_ASSOC);
+ foreach ($rows as $row) {
+ $result[$row['guid']] = $row['hex_hash'];
+ }
+ return $result;
+ } else {
+ $info = $stm == null ? array(0 => '', 1 => '', 2 => 'syntax error') : $stm->errorInfo();
+ if ($this->autoUpdateDb($info)) {
+ return $this->listHashForFeedGuids($id_feed, $guids);
+ }
+ Minz_Log::error('SQL error listHashForFeedGuids: ' . $info[0] . ': ' . $info[1] . ' ' . $info[2]
+ . ' while querying feed ' . $id_feed);
+ return false;
+ }
+ }
+
+ public function updateLastSeen($id_feed, $guids, $mtime = 0) {
+ if (count($guids) < 1) {
+ return 0;
+ }
+ $sql = 'UPDATE `' . $this->prefix . 'entry` SET `lastSeen`=? WHERE id_feed=? AND guid IN (' . str_repeat('?,', count($guids) - 1). '?)';
+ $stm = $this->bd->prepare($sql);
+ if ($mtime <= 0) {
+ $mtime = time();
+ }
+ $values = array($mtime, $id_feed);
+ $values = array_merge($values, $guids);
+ if ($stm && $stm->execute($values)) {
+ return $stm->rowCount();
+ } else {
+ $info = $stm == null ? array(0 => '', 1 => '', 2 => 'syntax error') : $stm->errorInfo();
+ if ($this->autoUpdateDb($info)) {
+ return $this->updateLastSeen($id_feed, $guids);
+ }
+ Minz_Log::error('SQL error updateLastSeen: ' . $info[0] . ': ' . $info[1] . ' ' . $info[2]
+ . ' while updating feed ' . $id_feed);
+ return false;
+ }
}
public function countUnreadRead() {
@@ -507,11 +795,13 @@ class FreshRSS_EntryDAO extends Minz_ModelPdo {
public function optimizeTable() {
$sql = 'OPTIMIZE TABLE `' . $this->prefix . 'entry`'; //MySQL
$stm = $this->bd->prepare($sql);
- $stm->execute();
+ if ($stm) {
+ return $stm->execute();
+ }
}
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) {
@@ -524,15 +814,8 @@ class FreshRSS_EntryDAO extends Minz_ModelPdo {
return $res[0];
}
- public static function daoToEntry($listDAO) {
- $list = array();
-
- if (!is_array($listDAO)) {
- $listDAO = array($listDAO);
- }
-
- foreach ($listDAO as $key => $dao) {
- $entry = new FreshRSS_Entry(
+ public static function daoToEntry($dao) {
+ $entry = new FreshRSS_Entry(
$dao['id_feed'],
$dao['guid'],
$dao['title'],
@@ -544,10 +827,21 @@ class FreshRSS_EntryDAO extends Minz_ModelPdo {
$dao['is_favorite'],
$dao['tags']
);
- if (isset($dao['id'])) {
- $entry->_id($dao['id']);
- }
- $list[] = $entry;
+ if (isset($dao['id'])) {
+ $entry->_id($dao['id']);
+ }
+ return $entry;
+ }
+
+ private static function daoToEntries($listDAO) {
+ $list = array();
+
+ if (!is_array($listDAO)) {
+ $listDAO = array($listDAO);
+ }
+
+ foreach ($listDAO as $key => $dao) {
+ $list[] = self::daoToEntry($dao);
}
unset($listDAO);
diff --git a/app/Models/EntryDAOPGSQL.php b/app/Models/EntryDAOPGSQL.php
new file mode 100644
index 000000000..b96a62ebc
--- /dev/null
+++ b/app/Models/EntryDAOPGSQL.php
@@ -0,0 +1,31 @@
+<?php
+
+class FreshRSS_EntryDAOPGSQL extends FreshRSS_EntryDAOSQLite {
+
+ public function sqlHexDecode($x) {
+ return 'decode(' . $x . ", 'hex')";
+ }
+
+ public function sqlHexEncode($x) {
+ return 'encode(' . $x . ", 'hex')";
+ }
+
+ protected function autoUpdateDb($errorInfo) {
+ return false;
+ }
+
+ protected function addColumn($name) {
+ return false;
+ }
+
+ public function size($all = true) {
+ $db = FreshRSS_Context::$system_conf->db;
+ $sql = 'SELECT pg_size_pretty(pg_database_size(?))';
+ $values = array($db['base']);
+ $stm = $this->bd->prepare($sql);
+ $stm->execute($values);
+ $res = $stm->fetchAll(PDO::FETCH_COLUMN, 0);
+ return $res[0];
+ }
+
+}
diff --git a/app/Models/EntryDAOSQLite.php b/app/Models/EntryDAOSQLite.php
index 4a3fe24a2..34e854608 100644
--- a/app/Models/EntryDAOSQLite.php
+++ b/app/Models/EntryDAOSQLite.php
@@ -2,23 +2,47 @@
class FreshRSS_EntryDAOSQLite extends FreshRSS_EntryDAO {
+ public function sqlHexDecode($x) {
+ return $x;
+ }
+
+ protected function autoUpdateDb($errorInfo) {
+ if (empty($errorInfo[0]) || $errorInfo[0] == '42S22') { //ER_BAD_FIELD_ERROR
+ //autoAddColumn
+ if ($tableInfo = $this->bd->query("SELECT sql FROM sqlite_master where name='entry'")) {
+ $showCreate = $tableInfo->fetchColumn();
+ Minz_Log::debug('FreshRSS_EntryDAOSQLite::autoUpdateDb: ' . $showCreate);
+ foreach (array('lastSeen', 'hash') as $column) {
+ if (stripos($showCreate, $column) === false) {
+ return $this->addColumn($column);
+ }
+ }
+ }
+ }
+ return false;
+ }
+
protected function sqlConcat($s1, $s2) {
return $s1 . '||' . $s2;
}
protected function updateCacheUnreads($catId = false, $feedId = false) {
$sql = 'UPDATE `' . $this->prefix . 'feed` '
- . 'SET cache_nbUnreads=('
+ . 'SET `cache_nbUnreads`=('
. 'SELECT COUNT(*) AS nbUnreads FROM `' . $this->prefix . 'entry` e '
- . 'WHERE e.id_feed=`' . $this->prefix . 'feed`.id AND e.is_read=0) '
- . 'WHERE 1';
+ . 'WHERE e.id_feed=`' . $this->prefix . 'feed`.id AND e.is_read=0)';
+ $hasWhere = false;
$values = array();
if ($feedId !== false) {
- $sql .= ' AND id=?';
+ $sql .= $hasWhere ? ' AND' : ' WHERE';
+ $hasWhere = true;
+ $sql .= ' id=?';
$values[] = $feedId;
}
if ($catId !== false) {
- $sql .= ' AND category=?';
+ $sql .= $hasWhere ? ' AND' : ' WHERE';
+ $hasWhere = true;
+ $sql .= ' category=?';
$values[] = $catId;
}
$stm = $this->bd->prepare($sql);
@@ -31,6 +55,19 @@ class FreshRSS_EntryDAOSQLite extends FreshRSS_EntryDAO {
}
}
+ /**
+ * 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)
@@ -53,7 +90,7 @@ class FreshRSS_EntryDAOSQLite extends FreshRSS_EntryDAO {
}
$affected = $stm->rowCount();
if ($affected > 0) {
- $sql = 'UPDATE `' . $this->prefix . 'feed` SET cache_nbUnreads=cache_nbUnreads' . ($is_read ? '-' : '+') . '1 '
+ $sql = 'UPDATE `' . $this->prefix . 'feed` SET `cache_nbUnreads`=`cache_nbUnreads`' . ($is_read ? '-' : '+') . '1 '
. 'WHERE id=(SELECT e.id_feed FROM `' . $this->prefix . 'entry` e WHERE e.id=?)';
$values = array($ids);
$stm = $this->bd->prepare($sql);
@@ -69,7 +106,28 @@ class FreshRSS_EntryDAOSQLite extends FreshRSS_EntryDAO {
}
}
- public function markReadEntries($idMax = 0, $onlyFavorites = false, $priorityMin = 0) {
+ /**
+ * 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, $filter = null, $state = 0) {
if ($idMax == 0) {
$idMax = time() . '000000';
Minz_Log::debug('Calling markReadEntries(0) is deprecated!');
@@ -82,8 +140,11 @@ class FreshRSS_EntryDAOSQLite extends FreshRSS_EntryDAO {
$sql .= ' AND id_feed IN (SELECT f.id FROM `' . $this->prefix . 'feed` f WHERE f.priority > ' . intval($priorityMin) . ')';
}
$values = array($idMax);
- $stm = $this->bd->prepare($sql);
- if (!($stm && $stm->execute($values))) {
+
+ list($searchValues, $search) = $this->sqlListEntriesWhere('', $filter, $state);
+
+ $stm = $this->bd->prepare($sql . $search);
+ if (!($stm && $stm->execute(array_merge($values, $searchValues)))) {
$info = $stm == null ? array(2 => 'syntax error') : $stm->errorInfo();
Minz_Log::error('SQL error markReadEntries: ' . $info[2]);
return false;
@@ -95,7 +156,18 @@ class FreshRSS_EntryDAOSQLite extends FreshRSS_EntryDAO {
return $affected;
}
- public function markReadCat($id, $idMax = 0) {
+ /**
+ * 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, $filter = null, $state = 0) {
if ($idMax == 0) {
$idMax = time() . '000000';
Minz_Log::debug('Calling markReadCat(0) is deprecated!');
@@ -106,8 +178,11 @@ class FreshRSS_EntryDAOSQLite extends FreshRSS_EntryDAO {
. 'WHERE is_read=0 AND id <= ? AND '
. 'id_feed IN (SELECT f.id FROM `' . $this->prefix . 'feed` f WHERE f.category=?)';
$values = array($idMax, $id);
- $stm = $this->bd->prepare($sql);
- if (!($stm && $stm->execute($values))) {
+
+ list($searchValues, $search) = $this->sqlListEntriesWhere('', $filter, $state);
+
+ $stm = $this->bd->prepare($sql . $search);
+ if (!($stm && $stm->execute(array_merge($values, $searchValues)))) {
$info = $stm == null ? array(2 => 'syntax error') : $stm->errorInfo();
Minz_Log::error('SQL error markReadCat: ' . $info[2]);
return false;
@@ -124,6 +199,6 @@ class FreshRSS_EntryDAOSQLite extends FreshRSS_EntryDAO {
}
public function size($all = false) {
- return @filesize(DATA_PATH . '/' . $this->current_user . '.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 91cb84998..6502c38b7 100644
--- a/app/Models/Factory.php
+++ b/app/Models/Factory.php
@@ -3,38 +3,49 @@
class FreshRSS_Factory {
public static function createFeedDao($username = null) {
- $db = Minz_Configuration::dataBase();
- if ($db['type'] === 'sqlite') {
- return new FreshRSS_FeedDAOSQLite($username);
- } else {
- return new FreshRSS_FeedDAO($username);
+ $conf = Minz_Configuration::get('system');
+ switch ($conf->db['type']) {
+ case 'sqlite':
+ case 'pgsql':
+ return new FreshRSS_FeedDAOSQLite($username);
+ default:
+ return new FreshRSS_FeedDAO($username);
}
}
public static function createEntryDao($username = null) {
- $db = Minz_Configuration::dataBase();
- if ($db['type'] === 'sqlite') {
- return new FreshRSS_EntryDAOSQLite($username);
- } else {
- return new FreshRSS_EntryDAO($username);
+ $conf = Minz_Configuration::get('system');
+ switch ($conf->db['type']) {
+ case 'sqlite':
+ return new FreshRSS_EntryDAOSQLite($username);
+ case 'pgsql':
+ return new FreshRSS_EntryDAOPGSQL($username);
+ default:
+ return new FreshRSS_EntryDAO($username);
}
}
public static function createStatsDAO($username = null) {
- $db = Minz_Configuration::dataBase();
- if ($db['type'] === 'sqlite') {
- return new FreshRSS_StatsDAOSQLite($username);
- } else {
- return new FreshRSS_StatsDAO($username);
+ $conf = Minz_Configuration::get('system');
+ switch ($conf->db['type']) {
+ case 'sqlite':
+ return new FreshRSS_StatsDAOSQLite($username);
+ case 'pgsql':
+ return new FreshRSS_StatsDAOPGSQL($username);
+ default:
+ return new FreshRSS_StatsDAO($username);
}
}
public static function createDatabaseDAO($username = null) {
- $db = Minz_Configuration::dataBase();
- if ($db['type'] === 'sqlite') {
- return new FreshRSS_DatabaseDAOSQLite($username);
- } else {
- return new FreshRSS_DatabaseDAO($username);
+ $conf = Minz_Configuration::get('system');
+ switch ($conf->db['type']) {
+ case 'sqlite':
+ return new FreshRSS_DatabaseDAOSQLite($username);
+ case 'pgsql':
+ return new FreshRSS_DatabaseDAOPGSQL($username);
+ default:
+ return new FreshRSS_DatabaseDAO($username);
}
}
diff --git a/app/Models/Feed.php b/app/Models/Feed.php
index 03baf3ad2..97cb1c47e 100644
--- a/app/Models/Feed.php
+++ b/app/Models/Feed.php
@@ -19,6 +19,8 @@ class FreshRSS_Feed extends Minz_Model {
private $ttl = -2;
private $hash = null;
private $lockPath = '';
+ private $hubUrl = '';
+ private $selfUrl = '';
public function __construct($url, $validate=true) {
if ($validate) {
@@ -40,7 +42,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;
}
@@ -48,6 +51,12 @@ class FreshRSS_Feed extends Minz_Model {
public function url() {
return $this->url;
}
+ public function selfUrl() {
+ return $this->selfUrl;
+ }
+ public function hubUrl() {
+ return $this->hubUrl;
+ }
public function category() {
return $this->category;
}
@@ -95,6 +104,16 @@ class FreshRSS_Feed extends Minz_Model {
public function ttl() {
return $this->ttl;
}
+ // public function ttlExpire() {
+ // $ttl = $this->ttl;
+ // if ($ttl == -2) { //Default
+ // $ttl = FreshRSS_Context::$user_conf->ttl_default;
+ // }
+ // if ($ttl == -1) { //Never
+ // $ttl = 64000000; //~2 years. Good enough for PubSubHubbub logic
+ // }
+ // return $this->lastUpdate + $ttl;
+ // }
public function nbEntries() {
if ($this->nbEntries < 0) {
$feedDAO = FreshRSS_Factory::createFeedDao();
@@ -112,13 +131,26 @@ class FreshRSS_Feed extends Minz_Model {
return $this->nbNotRead;
}
public function faviconPrepare() {
- $file = DATA_PATH . '/favicons/' . $this->hash() . '.txt';
- if (!file_exists($file)) {
- $t = $this->website;
- if ($t == '') {
- $t = $this->url;
+ global $favicons_dir;
+ require_once(LIB_PATH . '/favicons.php');
+ $url = $this->website;
+ if ($url == '') {
+ $url = $this->url;
+ }
+ $txt = $favicons_dir . $this->hash() . '.txt';
+ if (!file_exists($txt)) {
+ file_put_contents($txt, $url);
+ }
+ if (FreshRSS_Context::$isCli) {
+ $ico = $favicons_dir . $this->hash() . '.ico';
+ $ico_mtime = @filemtime($ico);
+ $txt_mtime = @filemtime($txt);
+ if ($txt_mtime != false &&
+ ($ico_mtime == false || $ico_mtime < $txt_mtime || ($ico_mtime < time() - (14 * 86400)))) {
+ // no ico file or we should download a new one.
+ $url = file_get_contents($txt);
+ download_favicon($url, $ico) || touch($ico);
}
- file_put_contents($file, $t);
}
}
public static function faviconDelete($hash) {
@@ -197,7 +229,7 @@ class FreshRSS_Feed extends Minz_Model {
$this->nbEntries = intval($value);
}
- public function load($loadDetails = false) {
+ public function load($loadDetails = false, $noCache = false) {
if ($this->url !== null) {
if (CACHE_PATH === false) {
throw new Minz_FileNotExistException(
@@ -210,6 +242,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,15 +253,21 @@ 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 == '' ? 'Unknown error for feed' : $errorMessage) . ' [' . $url . ']');
}
+ $links = $feed->get_links('self');
+ $this->selfUrl = isset($links[0]) ? $links[0] : null;
+ $links = $feed->get_links('hub');
+ $this->hubUrl = isset($links[0]) ? $links[0] : null;
+
if ($loadDetails) {
// si on a utilisé l'auto-discover, notre url va avoir changé
$subscribe_url = $feed->subscribe_url(false);
$title = strtr(html_only_entity_decode($feed->get_title()), array('<' => '&lt;', '>' => '&gt;', '"' => '&quot;')); //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 +276,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 = SimplePie_Misc::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);
+ if (($mtime === true) || ($mtime > $this->lastUpdate) || $noCache) {
+ //Minz_Log::debug('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::debug('FreshRSS use cache for ' . $clean_url);
$this->entries = array();
}
@@ -256,7 +295,7 @@ class FreshRSS_Feed extends Minz_Model {
}
}
- private function loadEntries($feed) {
+ public function loadEntries($feed) {
$entries = array();
foreach ($feed->get_items() as $item) {
@@ -283,11 +322,11 @@ class FreshRSS_Feed extends Minz_Model {
$elinks[$elink] = '1';
$mime = strtolower($enclosure->get_type());
if (strpos($mime, 'image/') === 0) {
- $content .= '<br /><img lazyload="" postpone="" src="' . $elink . '" alt="" />';
+ $content .= '<p class="enclosure"><img src="' . $elink . '" alt="" /></p>';
} elseif (strpos($mime, 'audio/') === 0) {
- $content .= '<br /><audio lazyload="" postpone="" preload="none" src="' . $elink . '" controls="controls" />';
+ $content .= '<p class="enclosure"><audio preload="none" src="' . $elink . '" controls="controls"></audio> <a download="" href="' . $elink . '">💾</a></p>';
} elseif (strpos($mime, 'video/') === 0) {
- $content .= '<br /><video lazyload="" postpone="" preload="none" src="' . $elink . '" controls="controls" />';
+ $content .= '<p class="enclosure"><video preload="none" src="' . $elink . '" controls="controls"></video> <a download="" href="' . $elink . '">💾</a></p>';
} else {
unset($elinks[$elink]);
}
@@ -314,6 +353,10 @@ class FreshRSS_Feed extends Minz_Model {
$this->entries = $entries;
}
+ function cacheModifiedTime() {
+ return @filemtime(CACHE_PATH . '/' . md5($this->url) . '.spc');
+ }
+
function lock() {
$this->lockPath = TMP_PATH . '/' . $this->hash() . '.freshrss.lock';
if (file_exists($this->lockPath) && ((time() - @filemtime($this->lockPath)) > 3600)) {
@@ -330,4 +373,135 @@ class FreshRSS_Feed extends Minz_Model {
function unlock() {
@unlink($this->lockPath);
}
+
+ //<PubSubHubbub>
+
+ function pubSubHubbubEnabled() {
+ $url = $this->selfUrl ? $this->selfUrl : $this->url;
+ $hubFilename = PSHB_PATH . '/feeds/' . base64url_encode($url) . '/!hub.json';
+ if ($hubFile = @file_get_contents($hubFilename)) {
+ $hubJson = json_decode($hubFile, true);
+ if ($hubJson && empty($hubJson['error']) &&
+ (empty($hubJson['lease_end']) || $hubJson['lease_end'] > time())) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ function pubSubHubbubError($error = true) {
+ $url = $this->selfUrl ? $this->selfUrl : $this->url;
+ $hubFilename = PSHB_PATH . '/feeds/' . base64url_encode($url) . '/!hub.json';
+ $hubFile = @file_get_contents($hubFilename);
+ $hubJson = $hubFile ? json_decode($hubFile, true) : array();
+ if (!isset($hubJson['error']) || $hubJson['error'] !== (bool)$error) {
+ $hubJson['error'] = (bool)$error;
+ file_put_contents($hubFilename, json_encode($hubJson));
+ file_put_contents(USERS_PATH . '/_/log_pshb.txt', date('c') . "\t"
+ . 'Set error to ' . ($error ? 1 : 0) . ' for ' . $url . "\n", FILE_APPEND);
+ }
+ return false;
+ }
+
+ function pubSubHubbubPrepare() {
+ $key = '';
+ if (FreshRSS_Context::$system_conf->base_url && $this->hubUrl && $this->selfUrl && @is_dir(PSHB_PATH)) {
+ $path = PSHB_PATH . '/feeds/' . base64url_encode($this->selfUrl);
+ $hubFilename = $path . '/!hub.json';
+ if ($hubFile = @file_get_contents($hubFilename)) {
+ $hubJson = json_decode($hubFile, true);
+ if (!$hubJson || empty($hubJson['key']) || !ctype_xdigit($hubJson['key'])) {
+ $text = 'Invalid JSON for PubSubHubbub: ' . $this->url;
+ Minz_Log::warning($text);
+ file_put_contents(USERS_PATH . '/_/log_pshb.txt', date('c') . "\t" . $text . "\n", FILE_APPEND);
+ return false;
+ }
+ if ((!empty($hubJson['lease_end'])) && ($hubJson['lease_end'] < (time() + (3600 * 23)))) { //TODO: Make a better policy
+ $text = 'PubSubHubbub lease ends at '
+ . date('c', empty($hubJson['lease_end']) ? time() : $hubJson['lease_end'])
+ . ' and needs renewal: ' . $this->url;
+ Minz_Log::warning($text);
+ file_put_contents(USERS_PATH . '/_/log_pshb.txt', date('c') . "\t" . $text . "\n", FILE_APPEND);
+ $key = $hubJson['key']; //To renew our lease
+ } elseif (((!empty($hubJson['error'])) || empty($hubJson['lease_end'])) &&
+ (empty($hubJson['lease_start']) || $hubJson['lease_start'] < time() - (3600 * 23))) { //Do not renew too often
+ $key = $hubJson['key']; //To renew our lease
+ }
+ } else {
+ @mkdir($path, 0777, true);
+ $key = sha1($path . FreshRSS_Context::$system_conf->salt . uniqid(mt_rand(), true));
+ $hubJson = array(
+ 'hub' => $this->hubUrl,
+ 'key' => $key,
+ );
+ file_put_contents($hubFilename, json_encode($hubJson));
+ @mkdir(PSHB_PATH . '/keys/');
+ file_put_contents(PSHB_PATH . '/keys/' . $key . '.txt', base64url_encode($this->selfUrl));
+ $text = 'PubSubHubbub prepared for ' . $this->url;
+ Minz_Log::debug($text);
+ file_put_contents(USERS_PATH . '/_/log_pshb.txt', date('c') . "\t" . $text . "\n", FILE_APPEND);
+ }
+ $currentUser = Minz_Session::param('currentUser');
+ if (ctype_alnum($currentUser) && !file_exists($path . '/' . $currentUser . '.txt')) {
+ touch($path . '/' . $currentUser . '.txt');
+ }
+ }
+ return $key;
+ }
+
+ //Parameter true to subscribe, false to unsubscribe.
+ function pubSubHubbubSubscribe($state) {
+ if (FreshRSS_Context::$system_conf->base_url && $this->hubUrl && $this->selfUrl) {
+ $hubFilename = PSHB_PATH . '/feeds/' . base64url_encode($this->selfUrl) . '/!hub.json';
+ $hubFile = @file_get_contents($hubFilename);
+ if ($hubFile === false) {
+ Minz_Log::warning('JSON not found for PubSubHubbub: ' . $this->url);
+ return false;
+ }
+ $hubJson = json_decode($hubFile, true);
+ if (!$hubJson || empty($hubJson['key']) || !ctype_xdigit($hubJson['key'])) {
+ Minz_Log::warning('Invalid JSON for PubSubHubbub: ' . $this->url);
+ return false;
+ }
+ $callbackUrl = checkUrl(Minz_Request::getBaseUrl() . '/api/pshb.php?k=' . $hubJson['key']);
+ if ($callbackUrl == '') {
+ Minz_Log::warning('Invalid callback for PubSubHubbub: ' . $this->url);
+ return false;
+ }
+ if (!$state) { //unsubscribe
+ $hubJson['lease_end'] = time() - 60;
+ file_put_contents($hubFilename, json_encode($hubJson));
+ }
+ $ch = curl_init();
+ curl_setopt_array($ch, array(
+ CURLOPT_URL => $this->hubUrl,
+ CURLOPT_FOLLOWLOCATION => true,
+ CURLOPT_RETURNTRANSFER => true,
+ CURLOPT_USERAGENT => 'FreshRSS/' . FRESHRSS_VERSION . ' (' . PHP_OS . '; ' . FRESHRSS_WEBSITE . ')',
+ CURLOPT_POSTFIELDS => 'hub.verify=sync'
+ . '&hub.mode=' . ($state ? 'subscribe' : 'unsubscribe')
+ . '&hub.topic=' . urlencode($this->selfUrl)
+ . '&hub.callback=' . urlencode($callbackUrl)
+ )
+ );
+ $response = curl_exec($ch);
+ $info = curl_getinfo($ch);
+
+ file_put_contents(USERS_PATH . '/_/log_pshb.txt', date('c') . "\t" .
+ 'PubSubHubbub ' . ($state ? 'subscribe' : 'unsubscribe') . ' to ' . $this->selfUrl .
+ ' with callback ' . $callbackUrl . ': ' . $info['http_code'] . ' ' . $response . "\n", FILE_APPEND);
+
+ if (substr($info['http_code'], 0, 1) == '2') {
+ return true;
+ } else {
+ $hubJson['lease_start'] = time(); //Prevent trying again too soon
+ $hubJson['error'] = true;
+ file_put_contents($hubFilename, json_encode($hubJson));
+ return false;
+ }
+ }
+ return false;
+ }
+
+ //</PubSubHubbub>
}
diff --git a/app/Models/FeedDAO.php b/app/Models/FeedDAO.php
index 852de6e36..68398efd5 100644
--- a/app/Models/FeedDAO.php
+++ b/app/Models/FeedDAO.php
@@ -1,10 +1,13 @@
<?php
-class FreshRSS_FeedDAO extends Minz_ModelPdo {
+class FreshRSS_FeedDAO extends Minz_ModelPdo implements FreshRSS_Searchable {
public function addFeed($valuesTmp) {
- $sql = 'INSERT INTO `' . $this->prefix . 'feed` (url, category, name, website, description, lastUpdate, priority, httpAuth, error, keep_history, ttl) VALUES(?, ?, ?, ?, ?, ?, 10, ?, 0, -2, -2)';
+ $sql = 'INSERT INTO `' . $this->prefix . 'feed` (url, category, name, website, description, `lastUpdate`, priority, `httpAuth`, error, keep_history, ttl) VALUES(?, ?, ?, ?, ?, ?, 10, ?, 0, -2, -2)';
$stm = $this->bd->prepare($sql);
+ $valuesTmp['url'] = safe_ascii($valuesTmp['url']);
+ $valuesTmp['website'] = safe_ascii($valuesTmp['website']);
+
$values = array(
substr($valuesTmp['url'], 0, 511),
$valuesTmp['category'],
@@ -16,7 +19,7 @@ class FreshRSS_FeedDAO extends Minz_ModelPdo {
);
if ($stm && $stm->execute($values)) {
- return $this->bd->lastInsertId();
+ return $this->bd->lastInsertId('"' . $this->prefix . 'feed_id_seq"');
} else {
$info = $stm == null ? array(2 => 'syntax error') : $stm->errorInfo();
Minz_Log::error('SQL error addFeed: ' . $info[2]);
@@ -55,6 +58,13 @@ class FreshRSS_FeedDAO extends Minz_ModelPdo {
}
public function updateFeed($id, $valuesTmp) {
+ if (isset($valuesTmp['url'])) {
+ $valuesTmp['url'] = safe_ascii($valuesTmp['url']);
+ }
+ if (isset($valuesTmp['website'])) {
+ $valuesTmp['website'] = safe_ascii($valuesTmp['website']);
+ }
+
$set = '';
foreach ($valuesTmp as $key => $v) {
$set .= $key . '=?, ';
@@ -82,22 +92,26 @@ class FreshRSS_FeedDAO extends Minz_ModelPdo {
}
}
- public function updateLastUpdate($id, $inError = 0, $updateCache = true) {
+ public function updateLastUpdate($id, $inError = false, $updateCache = true, $mtime = 0) {
if ($updateCache) {
$sql = 'UPDATE `' . $this->prefix . 'feed` ' //2 sub-requests with FOREIGN KEY(e.id_feed), INDEX(e.is_read) faster than 1 request with GROUP BY or CASE
- . 'SET cache_nbEntries=(SELECT COUNT(e1.id) FROM `' . $this->prefix . 'entry` e1 WHERE e1.id_feed=`' . $this->prefix . 'feed`.id),'
- . 'cache_nbUnreads=(SELECT COUNT(e2.id) FROM `' . $this->prefix . 'entry` e2 WHERE e2.id_feed=`' . $this->prefix . 'feed`.id AND e2.is_read=0),'
- . 'lastUpdate=?, error=? '
+ . 'SET `cache_nbEntries`=(SELECT COUNT(e1.id) FROM `' . $this->prefix . 'entry` e1 WHERE e1.id_feed=`' . $this->prefix . 'feed`.id),'
+ . '`cache_nbUnreads`=(SELECT COUNT(e2.id) FROM `' . $this->prefix . 'entry` e2 WHERE e2.id_feed=`' . $this->prefix . 'feed`.id AND e2.is_read=0),'
+ . '`lastUpdate`=?, error=? '
. 'WHERE id=?';
} else {
$sql = 'UPDATE `' . $this->prefix . 'feed` '
- . 'SET lastUpdate=?, error=? '
+ . 'SET `lastUpdate`=?, error=? '
. 'WHERE id=?';
}
+ if ($mtime <= 0) {
+ $mtime = time();
+ }
+
$values = array(
- time(),
- $inError,
+ $mtime,
+ $inError ? 1 : 0,
$id,
);
@@ -191,13 +205,20 @@ 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;
}
}
+ public function listFeedsIds() {
+ $sql = 'SELECT id FROM `' . $this->prefix . 'feed`';
+ $stm = $this->bd->prepare($sql);
+ $stm->execute();
+ return $stm->fetchAll(PDO::FETCH_COLUMN, 0);
+ }
+
public function listFeeds() {
$sql = 'SELECT * FROM `' . $this->prefix . 'feed` ORDER BY name';
$stm = $this->bd->prepare($sql);
@@ -222,14 +243,14 @@ class FreshRSS_FeedDAO extends Minz_ModelPdo {
return $feedCategoryNames;
}
+ /**
+ * Use $defaultCacheDuration == -1 to return all feeds, without filtering them by TTL.
+ */
public function listFeedsOrderUpdate($defaultCacheDuration = 3600) {
- if ($defaultCacheDuration < 0) {
- $defaultCacheDuration = 2147483647;
- }
- $sql = 'SELECT id, url, name, website, lastUpdate, pathEntries, httpAuth, keep_history, ttl '
+ $sql = 'SELECT id, url, name, website, `lastUpdate`, `pathEntries`, `httpAuth`, keep_history, ttl '
. 'FROM `' . $this->prefix . 'feed` '
- . 'WHERE ttl <> -1 AND lastUpdate < (' . (time() + 60) . '-(CASE WHEN ttl=-2 THEN ' . intval($defaultCacheDuration) . ' ELSE ttl END)) '
- . 'ORDER BY lastUpdate';
+ . ($defaultCacheDuration < 0 ? '' : 'WHERE ttl <> -1 AND `lastUpdate` < (' . (time() + 60) . '-(CASE WHEN ttl=-2 THEN ' . intval($defaultCacheDuration) . ' ELSE ttl END)) ')
+ . 'ORDER BY `lastUpdate`';
$stm = $this->bd->prepare($sql);
if (!($stm && $stm->execute())) {
$sql2 = 'ALTER TABLE `' . $this->prefix . 'feed` ADD COLUMN ttl INT NOT NULL DEFAULT -2'; //v0.7.3
@@ -282,7 +303,7 @@ class FreshRSS_FeedDAO extends Minz_ModelPdo {
. 'FROM `' . $this->prefix . 'entry` e '
. 'GROUP BY e.id_feed'
. ') x ON x.id_feed=f.id '
- . 'SET f.cache_nbEntries=x.nbEntries, f.cache_nbUnreads=x.nbUnreads';
+ . 'SET f.`cache_nbEntries`=x.nbEntries, f.`cache_nbUnreads`=x.nbUnreads';
$stm = $this->bd->prepare($sql);
if ($stm && $stm->execute()) {
@@ -308,7 +329,7 @@ class FreshRSS_FeedDAO extends Minz_ModelPdo {
$affected = $stm->rowCount();
$sql = 'UPDATE `' . $this->prefix . 'feed` '
- . 'SET cache_nbEntries=0, cache_nbUnreads=0 WHERE id=?';
+ . 'SET `cache_nbEntries`=0, `cache_nbUnreads`=0 WHERE id=?';
$values = array($id);
$stm = $this->bd->prepare($sql);
if (!($stm && $stm->execute($values))) {
@@ -322,17 +343,20 @@ class FreshRSS_FeedDAO extends Minz_ModelPdo {
return $affected;
}
- public function cleanOldEntries($id, $date_min, $keep = 15) { //Remember to call updateLastUpdate($id) just after
+ public function cleanOldEntries($id, $date_min, $keep = 15) { //Remember to call updateLastUpdate($id) or updateCachedValues() just after
$sql = 'DELETE FROM `' . $this->prefix . 'entry` '
- . 'WHERE id_feed = :id_feed AND id <= :id_max AND is_favorite=0 AND id NOT IN '
- . '(SELECT id FROM (SELECT e2.id FROM `' . $this->prefix . 'entry` e2 WHERE e2.id_feed = :id_feed ORDER BY id DESC LIMIT :keep) keep)'; //Double select MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery'
+ . 'WHERE id_feed=:id_feed AND id<=:id_max '
+ . 'AND is_favorite=0 ' //Do not remove favourites
+ . 'AND `lastSeen` < (SELECT maxLastSeen FROM (SELECT (MAX(e3.`lastSeen`)-99) AS maxLastSeen FROM `' . $this->prefix . 'entry` e3 WHERE e3.id_feed=:id_feed) recent) ' //Do not remove the most newly seen articles, plus a few seconds of tolerance
+ . 'AND id NOT IN (SELECT id FROM (SELECT e2.id FROM `' . $this->prefix . 'entry` e2 WHERE e2.id_feed=:id_feed ORDER BY id DESC LIMIT :keep) keep)'; //Double select: MySQL doesn't support 'LIMIT & IN/ALL/ANY/SOME subquery'
$stm = $this->bd->prepare($sql);
- $id_max = intval($date_min) . '000000';
-
- $stm->bindParam(':id_feed', $id, PDO::PARAM_INT);
- $stm->bindParam(':id_max', $id_max, PDO::PARAM_STR);
- $stm->bindParam(':keep', $keep, PDO::PARAM_INT);
+ if ($stm) {
+ $id_max = intval($date_min) . '000000';
+ $stm->bindParam(':id_feed', $id, PDO::PARAM_INT);
+ $stm->bindParam(':id_max', $id_max, PDO::PARAM_STR);
+ $stm->bindParam(':keep', $keep, PDO::PARAM_INT);
+ }
if ($stm && $stm->execute()) {
return $stm->rowCount();
diff --git a/app/Models/FeedDAOSQLite.php b/app/Models/FeedDAOSQLite.php
index 7599fda53..440ae74da 100644
--- a/app/Models/FeedDAOSQLite.php
+++ b/app/Models/FeedDAOSQLite.php
@@ -4,8 +4,8 @@ class FreshRSS_FeedDAOSQLite extends FreshRSS_FeedDAO {
public function updateCachedValues() { //For one single feed, call updateLastUpdate($id)
$sql = 'UPDATE `' . $this->prefix . 'feed` '
- . 'SET cache_nbEntries=(SELECT COUNT(e1.id) FROM `' . $this->prefix . 'entry` e1 WHERE e1.id_feed=`' . $this->prefix . 'feed`.id),'
- . 'cache_nbUnreads=(SELECT COUNT(e2.id) FROM `' . $this->prefix . 'entry` e2 WHERE e2.id_feed=`' . $this->prefix . 'feed`.id AND e2.is_read=0)';
+ . 'SET `cache_nbEntries`=(SELECT COUNT(e1.id) FROM `' . $this->prefix . 'entry` e1 WHERE e1.id_feed=`' . $this->prefix . 'feed`.id),'
+ . '`cache_nbUnreads`=(SELECT COUNT(e2.id) FROM `' . $this->prefix . 'entry` e2 WHERE e2.id_feed=`' . $this->prefix . 'feed`.id AND e2.is_read=0)';
$stm = $this->bd->prepare($sql);
if ($stm && $stm->execute()) {
return $stm->rowCount();
diff --git a/app/Models/LogDAO.php b/app/Models/LogDAO.php
index 21593435d..ab258cd58 100644
--- a/app/Models/LogDAO.php
+++ b/app/Models/LogDAO.php
@@ -3,7 +3,7 @@
class FreshRSS_LogDAO {
public static function lines() {
$logs = array();
- $handle = @fopen(LOG_PATH . '/' . Minz_Session::param('currentUser', '_') . '.log', 'r');
+ $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)) {
@@ -20,6 +20,11 @@ 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'), '');
+ if (FreshRSS_Auth::hasAccess('admin')) {
+ file_put_contents(join_path(DATA_PATH, 'users', '_', 'log.txt'), '');
+ file_put_contents(join_path(DATA_PATH, 'users', '_', 'log_api.txt'), '');
+ file_put_contents(join_path(DATA_PATH, 'users', '_', 'log_pshb.txt'), '');
+ }
}
}
diff --git a/app/Models/Search.php b/app/Models/Search.php
new file mode 100644
index 000000000..575a9a2cb
--- /dev/null
+++ b/app/Models/Search.php
@@ -0,0 +1,229 @@
+<?php
+
+require_once(LIB_PATH . '/lib_date.php');
+
+/**
+ * Contains a search from the search form.
+ *
+ * It allows to extract meaningful bits of the search and store them in a
+ * convenient object
+ */
+class FreshRSS_Search {
+
+ // This contains the user input string
+ private $raw_input = '';
+ // The following properties are extracted from the raw input
+ private $intitle;
+ private $min_date;
+ private $max_date;
+ private $min_pubdate;
+ private $max_pubdate;
+ private $inurl;
+ private $author;
+ private $tags;
+ private $search;
+
+ public function __construct($input) {
+ if (strcmp($input, '') == 0) {
+ return;
+ }
+ $this->raw_input = $input;
+ $input = $this->parseIntitleSearch($input);
+ $input = $this->parseAuthorSearch($input);
+ $input = $this->parseInurlSearch($input);
+ $input = $this->parsePubdateSearch($input);
+ $input = $this->parseDateSearch($input);
+ $input = $this->parseTagsSeach($input);
+ $this->parseSearch($input);
+ }
+
+ public function __toString() {
+ return $this->getRawInput();
+ }
+
+ public function getRawInput() {
+ return $this->raw_input;
+ }
+
+ public function getIntitle() {
+ return $this->intitle;
+ }
+
+ public function getMinDate() {
+ return $this->min_date;
+ }
+
+ public function getMaxDate() {
+ return $this->max_date;
+ }
+
+ public function getMinPubdate() {
+ return $this->min_pubdate;
+ }
+
+ public function getMaxPubdate() {
+ return $this->max_pubdate;
+ }
+
+ public function getInurl() {
+ return $this->inurl;
+ }
+
+ public function getAuthor() {
+ return $this->author;
+ }
+
+ public function getTags() {
+ return $this->tags;
+ }
+
+ public function getSearch() {
+ return $this->search;
+ }
+
+ /**
+ * Parse the search string to find intitle keyword and the search related
+ * to it.
+ * The search is the first word following the keyword.
+ *
+ * @param string $input
+ * @return string
+ */
+ private function parseIntitleSearch($input) {
+ if (preg_match('/intitle:(?P<delim>[\'"])(?P<search>.*)(?P=delim)/U', $input, $matches)) {
+ $this->intitle = $matches['search'];
+ return str_replace($matches[0], '', $input);
+ }
+ if (preg_match('/intitle:(?P<search>\w*)/', $input, $matches)) {
+ $this->intitle = $matches['search'];
+ return str_replace($matches[0], '', $input);
+ }
+ return $input;
+ }
+
+ /**
+ * Parse the search string to find author keyword and the search related
+ * to it.
+ * The search is the first word following the keyword except when using
+ * a delimiter. Supported delimiters are single quote (') and double
+ * quotes (").
+ *
+ * @param string $input
+ * @return string
+ */
+ private function parseAuthorSearch($input) {
+ if (preg_match('/author:(?P<delim>[\'"])(?P<search>.*)(?P=delim)/U', $input, $matches)) {
+ $this->author = $matches['search'];
+ return str_replace($matches[0], '', $input);
+ }
+ if (preg_match('/author:(?P<search>\w*)/', $input, $matches)) {
+ $this->author = $matches['search'];
+ return str_replace($matches[0], '', $input);
+ }
+ return $input;
+ }
+
+ /**
+ * Parse the search string to find inurl keyword and the search related
+ * to it.
+ * The search is the first word following the keyword except.
+ *
+ * @param string $input
+ * @return string
+ */
+ private function parseInurlSearch($input) {
+ if (preg_match('/inurl:(?P<search>[^\s]*)/', $input, $matches)) {
+ $this->inurl = $matches['search'];
+ return str_replace($matches[0], '', $input);
+ }
+ return $input;
+ }
+
+ /**
+ * Parse the search string to find date keyword and the search related
+ * to it.
+ * The search is the first word following the keyword.
+ *
+ * @param string $input
+ * @return string
+ */
+ private function parseDateSearch($input) {
+ if (preg_match('/date:(?P<search>[^\s]*)/', $input, $matches)) {
+ list($this->min_date, $this->max_date) = parseDateInterval($matches['search']);
+ return str_replace($matches[0], '', $input);
+ }
+ return $input;
+ }
+
+ /**
+ * Parse the search string to find pubdate keyword and the search related
+ * to it.
+ * The search is the first word following the keyword.
+ *
+ * @param string $input
+ * @return string
+ */
+ private function parsePubdateSearch($input) {
+ if (preg_match('/pubdate:(?P<search>[^\s]*)/', $input, $matches)) {
+ list($this->min_pubdate, $this->max_pubdate) = parseDateInterval($matches['search']);
+ return str_replace($matches[0], '', $input);
+ }
+ return $input;
+ }
+
+ /**
+ * Parse the search string to find tags keyword (# followed by a word)
+ * and the search related to it.
+ * The search is the first word following the #.
+ *
+ * @param string $input
+ * @return string
+ */
+ private function parseTagsSeach($input) {
+ if (preg_match_all('/#(?P<search>[^\s]+)/', $input, $matches)) {
+ $this->tags = $matches['search'];
+ return str_replace($matches[0], '', $input);
+ }
+ return $input;
+ }
+
+ /**
+ * Parse the search string to find search values.
+ * Every word is a distinct search value, except when using a delimiter.
+ * Supported delimiters are single quote (') and double quotes (").
+ *
+ * @param string $input
+ * @return string
+ */
+ private function parseSearch($input) {
+ $input = $this->cleanSearch($input);
+ if (strcmp($input, '') == 0) {
+ return;
+ }
+ if (preg_match_all('/(?P<delim>[\'"])(?P<search>.*)(?P=delim)/U', $input, $matches)) {
+ $this->search = $matches['search'];
+ $input = str_replace($matches[0], '', $input);
+ }
+ $input = $this->cleanSearch($input);
+ if (strcmp($input, '') == 0) {
+ return;
+ }
+ if (is_array($this->search)) {
+ $this->search = array_merge($this->search, explode(' ', $input));
+ } else {
+ $this->search = explode(' ', $input);
+ }
+ }
+
+ /**
+ * Remove all unnecessary spaces in the search
+ *
+ * @param string $input
+ * @return string
+ */
+ private function cleanSearch($input) {
+ $input = preg_replace('/\s+/', ' ', $input);
+ return trim($input);
+ }
+
+}
diff --git a/app/Models/Searchable.php b/app/Models/Searchable.php
new file mode 100644
index 000000000..d5bcea49d
--- /dev/null
+++ b/app/Models/Searchable.php
@@ -0,0 +1,6 @@
+<?php
+
+interface FreshRSS_Searchable {
+
+ public function searchById($id);
+}
diff --git a/app/Models/Share.php b/app/Models/Share.php
index b146db722..1c8a7e767 100644
--- a/app/Models/Share.php
+++ b/app/Models/Share.php
@@ -1,44 +1,238 @@
<?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])) {
+ $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) || empty($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 283d5dcb1..2ce4f2944 100644
--- a/app/Models/StatsDAO.php
+++ b/app/Models/StatsDAO.php
@@ -4,67 +4,77 @@ class FreshRSS_StatsDAO extends Minz_ModelPdo {
const ENTRY_COUNT_PERIOD = 30;
+ protected function sqlFloor($s) {
+ return "FLOOR($s)";
+ }
+
/**
* 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`,
-SUM(e.is_read) AS `read`,
-SUM(e.is_favorite) AS `favorite`
-FROM {$this->prefix}entry AS e
-, {$this->prefix}feed AS f
+SELECT COUNT(1) AS total,
+COUNT(1) - SUM(e.is_read) AS count_unreads,
+SUM(e.is_read) AS count_reads,
+SUM(e.is_favorite) AS count_favorites
+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];
}
/**
* Calculates entry count per day on a 30 days period.
- * Returns the result as a JSON string.
+ * Returns the result as a JSON object.
*
- * @return string
+ * @return JSON object
*/
public function calculateEntryCount() {
$count = $this->initEntryCountArray();
- $period = self::ENTRY_COUNT_PERIOD;
+ $midnight = mktime(0, 0, 0);
+ $oldest = $midnight - (self::ENTRY_COUNT_PERIOD * 86400);
// Get stats per day for the last 30 days
+ $sqlDay = $this->sqlFloor("(date - $midnight) / 86400");
$sql = <<<SQL
-SELECT DATEDIFF(FROM_UNIXTIME(e.date), NOW()) AS day,
-COUNT(1) AS count
-FROM {$this->prefix}entry AS e
-WHERE FROM_UNIXTIME(e.date, '%Y%m%d') BETWEEN DATE_FORMAT(DATE_ADD(NOW(), INTERVAL -{$period} DAY), '%Y%m%d') AND DATE_FORMAT(DATE_ADD(NOW(), INTERVAL -1 DAY), '%Y%m%d')
+SELECT {$sqlDay} AS day,
+COUNT(*) as count
+FROM `{$this->prefix}entry`
+WHERE date >= {$oldest} AND date < {$midnight}
GROUP BY day
ORDER BY day ASC
SQL;
@@ -76,28 +86,7 @@ SQL;
$count[$value['day']] = (int) $value['count'];
}
- return $this->convertToSerie($count);
- }
-
- /**
- * Calculates entry average per day on a 30 days period.
- *
- * @return integer
- */
- public function calculateEntryAverage() {
- $period = self::ENTRY_COUNT_PERIOD;
-
- // Get stats per day for the last 30 days
- $sql = <<<SQL
-SELECT COUNT(1) / {$period} AS average
-FROM {$this->prefix}entry AS e
-WHERE FROM_UNIXTIME(e.date, '%Y%m%d') BETWEEN DATE_FORMAT(DATE_ADD(NOW(), INTERVAL -{$period} DAY), '%Y%m%d') AND DATE_FORMAT(DATE_ADD(NOW(), INTERVAL -1 DAY), '%Y%m%d')
-SQL;
- $stm = $this->bd->prepare($sql);
- $stm->execute();
- $res = $stm->fetch(PDO::FETCH_NAMED);
-
- return round($res['average'], 2);
+ return $count;
}
/**
@@ -147,15 +136,14 @@ 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
, COUNT(1) AS count
-FROM {$this->prefix}entry AS e
+FROM `{$this->prefix}entry` AS e
{$restrict}
GROUP BY period
ORDER BY period ASC
@@ -165,11 +153,12 @@ SQL;
$stm->execute();
$res = $stm->fetchAll(PDO::FETCH_NAMED);
+ $repartition = array();
foreach ($res as $value) {
$repartition[(int) $value['period']] = (int) $value['count'];
}
- return $this->convertToSerie($repartition);
+ return $repartition;
}
/**
@@ -179,7 +168,7 @@ SQL;
* @return integer
*/
public function calculateEntryAveragePerFeedPerHour($feed = null) {
- return $this->calculateEntryAveragePerFeedPerPeriod(1/24, $feed);
+ return $this->calculateEntryAveragePerFeedPerPeriod(1 / 24, $feed);
}
/**
@@ -210,16 +199,15 @@ 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
, MIN(date) AS date_min
, MAX(date) AS date_max
-FROM {$this->prefix}entry AS e
+FROM `{$this->prefix}entry` AS e
{$restrict}
SQL;
$stm = $this->bd->prepare($sql);
@@ -255,16 +243,16 @@ SQL;
/**
* Calculates feed count per category.
- * Returns the result as a JSON string.
+ * Returns the result as a JSON object.
*
- * @return string
+ * @return JSON object
*/
public function calculateFeedByCategory() {
$sql = <<<SQL
SELECT c.name AS label
, COUNT(f.id) AS data
-FROM {$this->prefix}category AS c,
-{$this->prefix}feed AS f
+FROM `{$this->prefix}category` AS c,
+`{$this->prefix}feed` AS f
WHERE c.id = f.category
GROUP BY label
ORDER BY data DESC
@@ -273,22 +261,22 @@ SQL;
$stm->execute();
$res = $stm->fetchAll(PDO::FETCH_ASSOC);
- return $this->convertToPieSerie($res);
+ return $res;
}
/**
* Calculates entry count per category.
* Returns the result as a JSON string.
*
- * @return string
+ * @return JSON object
*/
public function calculateEntryByCategory() {
$sql = <<<SQL
SELECT c.name AS label
, COUNT(e.id) AS data
-FROM {$this->prefix}category AS c,
-{$this->prefix}feed AS f,
-{$this->prefix}entry AS e
+FROM `{$this->prefix}category` AS c,
+`{$this->prefix}feed` AS f,
+`{$this->prefix}entry` AS e
WHERE c.id = f.category
AND f.id = e.id_feed
GROUP BY label
@@ -298,7 +286,7 @@ SQL;
$stm->execute();
$res = $stm->fetchAll(PDO::FETCH_ASSOC);
- return $this->convertToPieSerie($res);
+ return $res;
}
/**
@@ -312,9 +300,9 @@ SELECT f.id AS id
, MAX(f.name) AS name
, MAX(c.name) AS category
, COUNT(e.id) AS count
-FROM {$this->prefix}category AS c,
-{$this->prefix}feed AS f,
-{$this->prefix}entry AS e
+FROM `{$this->prefix}category` AS c,
+`{$this->prefix}feed` AS f,
+`{$this->prefix}entry` AS e
WHERE c.id = f.category
AND f.id = e.id_feed
GROUP BY f.id
@@ -337,8 +325,8 @@ SELECT MAX(f.id) as id
, MAX(f.name) AS name
, MAX(date) AS last_date
, COUNT(*) AS nb_articles
-FROM {$this->prefix}feed AS f,
-{$this->prefix}entry AS e
+FROM `{$this->prefix}feed` AS f,
+`{$this->prefix}entry` AS e
WHERE f.id = e.id_feed
GROUP BY f.id
ORDER BY name
@@ -348,27 +336,6 @@ SQL;
return $stm->fetchAll(PDO::FETCH_ASSOC);
}
- protected function convertToSerie($data) {
- $serie = array();
-
- foreach ($data as $key => $value) {
- $serie[] = array($key, $value);
- }
-
- return json_encode($serie);
- }
-
- protected function convertToPieSerie($data) {
- $serie = array();
-
- foreach ($data as $value) {
- $value['data'] = array(array(0, (int) $value['data']));
- $serie[] = $value;
- }
-
- return json_encode($serie);
- }
-
/**
* Gets days ready for graphs
*
@@ -409,17 +376,17 @@ SQL;
}
/**
- * Translates array content and encode it as JSON
+ * Translates array content
*
* @param array $data
- * @return string
+ * @return JSON object
*/
private function convertToTranslatedJson($data = array()) {
$translated = array_map(function($a) {
- return _t($a);
+ return _t('gen.date.' . $a);
}, $data);
- return json_encode($translated);
+ return $translated;
}
}
diff --git a/app/Models/StatsDAOPGSQL.php b/app/Models/StatsDAOPGSQL.php
new file mode 100644
index 000000000..1effbb64b
--- /dev/null
+++ b/app/Models/StatsDAOPGSQL.php
@@ -0,0 +1,67 @@
+<?php
+
+class FreshRSS_StatsDAOPGSQL extends FreshRSS_StatsDAO {
+
+ /**
+ * Calculates the number of article per hour of the day per feed
+ *
+ * @param integer $feed id
+ * @return string
+ */
+ public function calculateEntryRepartitionPerFeedPerHour($feed = null) {
+ return $this->calculateEntryRepartitionPerFeedPerPeriod('hour', $feed);
+ }
+
+ /**
+ * Calculates the number of article per day of week per feed
+ *
+ * @param integer $feed id
+ * @return string
+ */
+ public function calculateEntryRepartitionPerFeedPerDayOfWeek($feed = null) {
+ return $this->calculateEntryRepartitionPerFeedPerPeriod('day', $feed);
+ }
+
+ /**
+ * Calculates the number of article per month per feed
+ *
+ * @param integer $feed
+ * @return string
+ */
+ public function calculateEntryRepartitionPerFeedPerMonth($feed = null) {
+ return $this->calculateEntryRepartitionPerFeedPerPeriod('month', $feed);
+ }
+
+ /**
+ * Calculates the number of article per period per feed
+ *
+ * @param string $period format string to use for grouping
+ * @param integer $feed id
+ * @return string
+ */
+ protected function calculateEntryRepartitionPerFeedPerPeriod($period, $feed = null) {
+ $restrict = '';
+ if ($feed) {
+ $restrict = "WHERE e.id_feed = {$feed}";
+ }
+ $sql = <<<SQL
+SELECT extract( {$period} from to_timestamp(e.date)) AS period
+, COUNT(1) AS count
+FROM "{$this->prefix}entry" AS e
+{$restrict}
+GROUP BY period
+ORDER BY period ASC
+SQL;
+
+ $stm = $this->bd->prepare($sql);
+ $stm->execute();
+ $res = $stm->fetchAll(PDO::FETCH_NAMED);
+
+ foreach ($res as $value) {
+ $repartition[(int) $value['period']] = (int) $value['count'];
+ }
+
+ return $repartition;
+ }
+
+}
diff --git a/app/Models/StatsDAOSQLite.php b/app/Models/StatsDAOSQLite.php
index bb2336532..6cfc20463 100644
--- a/app/Models/StatsDAOSQLite.php
+++ b/app/Models/StatsDAOSQLite.php
@@ -2,59 +2,8 @@
class FreshRSS_StatsDAOSQLite extends FreshRSS_StatsDAO {
- /**
- * Calculates entry count per day on a 30 days period.
- * Returns the result as a JSON string.
- *
- * @return string
- */
- public function calculateEntryCount() {
- $count = $this->initEntryCountArray();
- $period = parent::ENTRY_COUNT_PERIOD;
-
- // Get stats per day for the last 30 days
- $sql = <<<SQL
-SELECT round(julianday(e.date, 'unixepoch') - julianday('now')) AS day,
-COUNT(1) AS count
-FROM {$this->prefix}entry AS e
-WHERE strftime('%Y%m%d', e.date, 'unixepoch')
- BETWEEN strftime('%Y%m%d', 'now', '-{$period} days')
- AND strftime('%Y%m%d', 'now', '-1 day')
-GROUP BY day
-ORDER BY day ASC
-SQL;
- $stm = $this->bd->prepare($sql);
- $stm->execute();
- $res = $stm->fetchAll(PDO::FETCH_ASSOC);
-
- foreach ($res as $value) {
- $count[(int) $value['day']] = (int) $value['count'];
- }
-
- return $this->convertToSerie($count);
- }
-
- /**
- * Calculates entry average per day on a 30 days period.
- *
- * @return integer
- */
- public function calculateEntryAverage() {
- $period = self::ENTRY_COUNT_PERIOD;
-
- // Get stats per day for the last 30 days
- $sql = <<<SQL
-SELECT COUNT(1) / {$period} AS average
-FROM {$this->prefix}entry AS e
-WHERE strftime('%Y%m%d', e.date, 'unixepoch')
- BETWEEN strftime('%Y%m%d', 'now', '-{$period} days')
- AND strftime('%Y%m%d', 'now', '-1 day')
-SQL;
- $stm = $this->bd->prepare($sql);
- $stm->execute();
- $res = $stm->fetch(PDO::FETCH_NAMED);
-
- return round($res['average'], 2);
+ protected function sqlFloor($s) {
+ return "CAST(($s) AS INT)";
}
protected function calculateEntryRepartitionPerFeedPerPeriod($period, $feed = null) {
@@ -66,7 +15,7 @@ SQL;
$sql = <<<SQL
SELECT strftime('{$period}', e.date, 'unixepoch') AS period
, COUNT(1) AS count
-FROM {$this->prefix}entry AS e
+FROM `{$this->prefix}entry` AS e
{$restrict}
GROUP BY period
ORDER BY period ASC
@@ -81,7 +30,7 @@ SQL;
$repartition[(int) $value['period']] = (int) $value['count'];
}
- return $this->convertToSerie($repartition);
+ return $repartition;
}
}
diff --git a/app/Models/Themes.php b/app/Models/Themes.php
index e3b260261..5a6ec0a05 100644
--- a/app/Models/Themes.php
+++ b/app/Models/Themes.php
@@ -116,7 +116,3 @@ class FreshRSS_Themes extends Minz_Model {
'<img class="icon" src="' . Minz_Url::display($url) . '" alt="' . $alts[$name] . '" />';
}
}
-
-function _i($icon, $url_only = false) {
- return FreshRSS_Themes::icon($icon, $url_only);
-}
diff --git a/app/Models/UserDAO.php b/app/Models/UserDAO.php
index 85b45c4a7..32bc6de2f 100644
--- a/app/Models/UserDAO.php
+++ b/app/Models/UserDAO.php
@@ -1,44 +1,70 @@
<?php
class FreshRSS_UserDAO extends Minz_ModelPdo {
- public function createUser($username) {
- $db = Minz_Configuration::dataBase();
+ public function createUser($username, $new_user_language, $insertDefaultFeeds = true) {
+ $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 . '_', _t('default_category'));
- $stm = $userPDO->bd->prepare($sql);
- $ok = $stm && $stm->execute();
- } else { //E.g. SQLite
- global $SQL_CREATE_TABLES;
- if (is_array($SQL_CREATE_TABLES)) {
- $ok = true;
- foreach ($SQL_CREATE_TABLES as $instruction) {
- $sql = sprintf($instruction, '', _t('default_category'));
+ $currentLanguage = Minz_Translate::language();
+
+ try {
+ Minz_Translate::reset($new_user_language);
+ $ok = false;
+ $bd_prefix_user = $db['prefix'] . $username . '_';
+ if (defined('SQL_CREATE_TABLES')) { //E.g. MySQL
+ $sql = sprintf(SQL_CREATE_TABLES, $bd_prefix_user, _t('gen.short.default_category'));
+ $stm = $userPDO->bd->prepare($sql);
+ $ok = $stm && $stm->execute();
+ } else { //E.g. SQLite
+ global $SQL_CREATE_TABLES;
+ if (is_array($SQL_CREATE_TABLES)) {
+ $ok = true;
+ foreach ($SQL_CREATE_TABLES as $instruction) {
+ $sql = sprintf($instruction, $bd_prefix_user, _t('gen.short.default_category'));
+ $stm = $userPDO->bd->prepare($sql);
+ $ok &= ($stm && $stm->execute());
+ }
+ }
+ }
+ if ($insertDefaultFeeds) {
+ if (defined('SQL_INSERT_FEEDS')) { //E.g. MySQL
+ $sql = sprintf(SQL_INSERT_FEEDS, $bd_prefix_user);
$stm = $userPDO->bd->prepare($sql);
- $ok &= ($stm && $stm->execute());
+ $ok &= $stm && $stm->execute();
+ } else { //E.g. SQLite
+ global $SQL_INSERT_FEEDS;
+ if (is_array($SQL_INSERT_FEEDS)) {
+ foreach ($SQL_INSERT_FEEDS as $instruction) {
+ $sql = sprintf($instruction, $bd_prefix_user);
+ $stm = $userPDO->bd->prepare($sql);
+ $ok &= ($stm && $stm->execute());
+ }
+ }
}
}
+ } catch (Exception $e) {
+ Minz_Log::error('Error while creating user: ' . $e->getMessage());
}
+ Minz_Translate::reset($currentLanguage);
+
if ($ok) {
return true;
} else {
$info = empty($stm) ? array(2 => 'syntax error') : $stm->errorInfo();
- Minz_Log::error('SQL error : ' . $info[2]);
+ 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);
@@ -54,7 +80,18 @@ class FreshRSS_UserDAO extends Minz_ModelPdo {
}
}
- public function exist($username) {
- return file_exists(DATA_PATH . '/' . $username . '_user.php');
+ public static function exist($username) {
+ return is_dir(join_path(DATA_PATH , 'users', $username));
+ }
+
+ public static function touch($username = '') {
+ if (($username == '') || (!ctype_alnum($username))) {
+ $username = Minz_Session::param('currentUser', '_');
+ }
+ 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'));
}
}
diff --git a/app/Models/UserQuery.php b/app/Models/UserQuery.php
new file mode 100644
index 000000000..52747f538
--- /dev/null
+++ b/app/Models/UserQuery.php
@@ -0,0 +1,226 @@
+<?php
+
+/**
+ * Contains the description of a user query
+ *
+ * It allows to extract the meaningful bits of the query to be manipulated in an
+ * easy way.
+ */
+class FreshRSS_UserQuery {
+
+ private $deprecated = false;
+ private $get;
+ private $get_name;
+ private $get_type;
+ private $name;
+ private $order;
+ private $search;
+ private $state;
+ private $url;
+ private $feed_dao;
+ private $category_dao;
+
+ /**
+ * @param array $query
+ * @param FreshRSS_Searchable $feed_dao
+ * @param FreshRSS_Searchable $category_dao
+ */
+ public function __construct($query, FreshRSS_Searchable $feed_dao = null, FreshRSS_Searchable $category_dao = null) {
+ $this->category_dao = $category_dao;
+ $this->feed_dao = $feed_dao;
+ if (isset($query['get'])) {
+ $this->parseGet($query['get']);
+ }
+ if (isset($query['name'])) {
+ $this->name = $query['name'];
+ }
+ if (isset($query['order'])) {
+ $this->order = $query['order'];
+ }
+ if (!isset($query['search'])) {
+ $query['search'] = '';
+ }
+ // linked to deeply with the search object, need to use dependency injection
+ $this->search = new FreshRSS_Search($query['search']);
+ if (isset($query['state'])) {
+ $this->state = $query['state'];
+ }
+ if (isset($query['url'])) {
+ $this->url = $query['url'];
+ }
+ }
+
+ /**
+ * Convert the current object to an array.
+ *
+ * @return array
+ */
+ public function toArray() {
+ return array_filter(array(
+ 'get' => $this->get,
+ 'name' => $this->name,
+ 'order' => $this->order,
+ 'search' => $this->search->__toString(),
+ 'state' => $this->state,
+ 'url' => $this->url,
+ ));
+ }
+
+ /**
+ * Parse the get parameter in the query string to extract its name and
+ * type
+ *
+ * @param string $get
+ */
+ private function parseGet($get) {
+ $this->get = $get;
+ if (preg_match('/(?P<type>[acfs])(_(?P<id>\d+))?/', $get, $matches)) {
+ switch ($matches['type']) {
+ case 'a':
+ $this->parseAll();
+ break;
+ case 'c':
+ $this->parseCategory($matches['id']);
+ break;
+ case 'f':
+ $this->parseFeed($matches['id']);
+ break;
+ case 's':
+ $this->parseFavorite();
+ break;
+ }
+ }
+ }
+
+ /**
+ * Parse the query string when it is an "all" query
+ */
+ private function parseAll() {
+ $this->get_name = 'all';
+ $this->get_type = 'all';
+ }
+
+ /**
+ * Parse the query string when it is a "category" query
+ *
+ * @param integer $id
+ * @throws FreshRSS_DAO_Exception
+ */
+ private function parseCategory($id) {
+ if (is_null($this->category_dao)) {
+ throw new FreshRSS_DAO_Exception('Category DAO is not loaded in UserQuery');
+ }
+ $category = $this->category_dao->searchById($id);
+ if ($category) {
+ $this->get_name = $category->name();
+ } else {
+ $this->deprecated = true;
+ }
+ $this->get_type = 'category';
+ }
+
+ /**
+ * Parse the query string when it is a "feed" query
+ *
+ * @param integer $id
+ * @throws FreshRSS_DAO_Exception
+ */
+ private function parseFeed($id) {
+ if (is_null($this->feed_dao)) {
+ throw new FreshRSS_DAO_Exception('Feed DAO is not loaded in UserQuery');
+ }
+ $feed = $this->feed_dao->searchById($id);
+ if ($feed) {
+ $this->get_name = $feed->name();
+ } else {
+ $this->deprecated = true;
+ }
+ $this->get_type = 'feed';
+ }
+
+ /**
+ * Parse the query string when it is a "favorite" query
+ */
+ private function parseFavorite() {
+ $this->get_name = 'favorite';
+ $this->get_type = 'favorite';
+ }
+
+ /**
+ * Check if the current user query is deprecated.
+ * It is deprecated if the category or the feed used in the query are
+ * not existing.
+ *
+ * @return boolean
+ */
+ public function isDeprecated() {
+ return $this->deprecated;
+ }
+
+ /**
+ * Check if the user query has parameters.
+ * If the type is 'all', it is considered equal to no parameters
+ *
+ * @return boolean
+ */
+ public function hasParameters() {
+ if ($this->get_type === 'all') {
+ return false;
+ }
+ if ($this->hasSearch()) {
+ return true;
+ }
+ if ($this->state) {
+ return true;
+ }
+ if ($this->order) {
+ return true;
+ }
+ if ($this->get) {
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * Check if there is a search in the search object
+ *
+ * @return boolean
+ */
+ public function hasSearch() {
+ return $this->search->getRawInput() != "";
+ }
+
+ public function getGet() {
+ return $this->get;
+ }
+
+ public function getGetName() {
+ return $this->get_name;
+ }
+
+ public function getGetType() {
+ return $this->get_type;
+ }
+
+ public function getName() {
+ return $this->name;
+ }
+
+ public function getOrder() {
+ return $this->order;
+ }
+
+ public function getSearch() {
+ return $this->search;
+ }
+
+ public function getState() {
+ return $this->state;
+ }
+
+ public function getUrl() {
+ return $this->url;
+ }
+
+}