commit c441bb366688301d64862b559e095edc4f75bd99 Author: plopoyop Date: Wed Jul 23 15:52:50 2014 +0200 Initial Commit diff --git a/conf/config.php b/conf/config.php new file mode 100644 index 0000000..7f95fc9 --- /dev/null +++ b/conf/config.php @@ -0,0 +1,25 @@ + + array ( + 'environment' => 'production', + 'salt' => 'yunosalt', + 'base_url' => 'yunopath', + 'title' => 'FreshRSS', + 'default_user' => 'yunoadminuser', + 'allow_anonymous' => false, + 'allow_anonymous_refresh' => false, + 'auth_type' => 'http', + 'api_enabled' => true, + 'unsafe_autologin_enabled' => false, + ), + 'db' => + array ( + 'type' => 'mysql', + 'host' => 'localhost', + 'user' => 'yunouser', + 'password' => 'yunopass', + 'base' => 'yunobase', + 'prefix' => false, + ), +); \ No newline at end of file diff --git a/conf/dist_user.conf b/conf/dist_user.conf new file mode 100644 index 0000000..4a5716e --- /dev/null +++ b/conf/dist_user.conf @@ -0,0 +1,61 @@ + 'en', + 'old_entries' => 3, + 'keep_history_default' => 0, + 'ttl_default' => 3600, + 'mail_login' => 'ynoUserEmail', + 'token' => '', + 'passwordHash' => '', + 'apiPasswordHash' => '', + 'posts_per_page' => 20, + 'view_mode' => 'normal', + 'default_view' => 2, + 'auto_load_more' => true, + 'display_posts' => 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' => 'Flat', + 'content_width' => 'thin', + 'shortcuts' => + array ( + 'mark_read' => 'r', + 'mark_favorite' => 'f', + 'go_website' => 'space', + 'next_entry' => 'n', + 'prev_entry' => 'k', + 'first_entry' => 'home', + 'last_entry' => 'end', + 'collapse_entry' => 'c', + 'load_more' => 'm', + 'auto_share' => 's', + 'focus_search' => 'a', + ), + '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 ( + ), + 'user' => 'YnoUser', +); \ No newline at end of file diff --git a/conf/nginx.conf b/conf/nginx.conf new file mode 100644 index 0000000..25d520c --- /dev/null +++ b/conf/nginx.conf @@ -0,0 +1,20 @@ +location PATHTOCHANGE { + alias ALIASTOCHANGE; + if ($scheme = http) { + rewrite ^ https://$server_name$request_uri? permanent; + } + index index.php; + try_files $uri $uri/ /index.php?$args; + location ~ [^/]\.php(/|$) { + fastcgi_split_path_info ^(.+?\.php)(/.*)$; + fastcgi_pass unix:/var/run/php5-fpm.sock; + fastcgi_index index.php; + include fastcgi_params; + fastcgi_param AUTH_USER $remote_user; + fastcgi_param PATH_INFO $fastcgi_path_info; + } + + + # Include SSOWAT user panel. + include conf.d/yunohost_panel.conf.inc; +} \ No newline at end of file diff --git a/manifest.json b/manifest.json new file mode 100644 index 0000000..d67bf48 --- /dev/null +++ b/manifest.json @@ -0,0 +1,42 @@ +{ + "name": "FreshRSS", + "id": "freshrss", + "description": { + "en": "FreshRSS is a selfhostable RSS reader", + "fr": "FreshRSS est un agrégateur de flux RSS à auto-héberger" + }, + "developer": { + "name": "plopoyop", + "email": "plopoyop@gmail.com" + }, + "multi_instance": "true", + "arguments": { + "install" : [ + { + "name": "domain", + "ask": { + "en": "Choose a domain for FreshRSS", + "fr": "Choisissez un domaine pour FreshRSS" + }, + "example": "domain.org" + }, + { + "name": "path", + "ask": { + "en": "Choose a path for FreshRSS", + "fr": "Choisissez un chemin pour FreshRSS" + }, + "example": "/rss", + "default": "/rss" + } + { + "name": "admin", + "ask": { + "en": "Choose the default user (must be an existing YunoHost user)" + "fr": "Choisissez l'utilisateur par defaut (doit être un utiliser YunoHost existant)" + }, + "example": "homer" + } + ] + } +} diff --git a/scripts/install b/scripts/install new file mode 100755 index 0000000..f15adfe --- /dev/null +++ b/scripts/install @@ -0,0 +1,81 @@ +#!/bin/bash + +# Retrieve arguments +domain=$1 +path=$2 +admin_user=$3 + +# Check domain/path availability +sudo yunohost app checkurl $domain$path +if [[ ! $? -eq 0 ]]; then + exit 1 +fi + +# Generate random DES key & password +deskey=$(dd if=/dev/urandom bs=1 count=200 2> /dev/null | tr -c -d 'A-Za-z0-9' | sed -n 's/\(.\{24\}\).*/\1/p') +db_pwd=$(dd if=/dev/urandom bs=1 count=200 2> /dev/null | tr -c -d 'A-Za-z0-9' | sed -n 's/\(.\{24\}\).*/\1/p') +app_salt=$(dd if=/dev/urandom bs=1 count=200 2> /dev/null | tr -c -d 'A-Za-z0-9' | sed -n 's/\(.\{40\}\).*/\1/p') +# Use 'freshrss' as database name and user +db_user=freshrss + +# Initialize database and store mysql password for upgrade +sudo yunohost app initdb $db_user -p $db_pwd +sudo yunohost app setting freshrss mysqlpwd -v $db_pwd + +# Copy files to the right place +final_path=/var/www/freshrss +sudo mkdir -p $final_path +sudo cp -a ../sources/* $final_path +sudo cp -a ../conf/config.php $final_path/data + +# Change variables in freshrss configuration +sudo sed -i "s/yunouser/$db_user/g" $final_path/data/config.php +sudo sed -i "s/yunopass/$db_pwd/g" $final_path/data/config.php +sudo sed -i "s/yunobase/$db_user/g" $final_path/data/config.php +sudo sed -i "s/yunosalt/$app_salt/g" $final_path/data/config.php +sudo sed -i "s/yunopath/$path/g" $final_path/data/config.php +sudo sed -i "s/yunoadminuser/$admin_user/g" $final_path/data/config.php + +# Add users +freshrss_users=$(ldapsearch -h localhost -b ou=users,dc=yunohost,dc=org -x objectClass=mailAccount uid | grep uid: | sed 's/uid: //' | xargs) +for myuser in $freshrss_users +do + #copy sql + sudo cp ../sources/app/SQL/install_ynh.sql /tmp/$myuser-install.sql + #change username in sql + sudo sed -i "s/YnoUser/$myuser/g" /tmp/$myuser-install.sql + #create tables + mysql -u $db_user -p$db_pwd $db_user < /tmp/$myuser-install.sql + #remove temp sql + sudo rm /tmp/$myuser-install.sql + #copy default conf + sudo cp ../conf/dist_user.conf $final_path/data/$myuser\_user.php + #change email + user_email=$(ldapsearch -h localhost -b uid=$myuser,ou=users,dc=yunohost,dc=org -x objectClass=mailAccount mail | grep mail: | grep $myuser| sed 's/mail: //') + sudo sed -i "s/ynoUserEmail/$user_email/g" $final_path/data/$myuser\_user.php + #change username + sudo sed -i "s/YnoUser/$myuser/g" $final_path/data/$myuser\_user.php +done + +# Delete install directive +sudo rm $final_path/data/do-install.txt + +# Modify Nginx configuration file and copy it to Nginx conf directory +sed -i "s@PATHTOCHANGE@$path@g" ../conf/nginx.conf +sed -i "s@ALIASTOCHANGE@$final_path/@g" ../conf/nginx.conf +sudo cp ../conf/nginx.conf /etc/nginx/conf.d/$domain.d/freshrss.conf + +#install php5-cli +sudo apt-get update +sudo apt-get install -y php5-cli +#install update cron +echo "*/10 * * * * www-data /usr/bin/php $final_path/app/actualize_script.php >/tmp/FreshRSS.log 2>&1" > /tmp/cronfreshrss +sudo mv /tmp/cronttrss /etc/cron.d/freshrss +sudo chown root /etc/cron.d/freshrss + +# Set permissions to freshrss directory +sudo chown -R www-data: $final_path + +# Reload Nginx and regenerate SSOwat conf +sudo service nginx reload +sudo yunohost app ssowatconf \ No newline at end of file diff --git a/scripts/remove b/scripts/remove new file mode 100755 index 0000000..1f30428 --- /dev/null +++ b/scripts/remove @@ -0,0 +1,12 @@ +#!/bin/bash + +db_user=freshrss +db_name=freshrss +root_pwd=$(sudo cat /etc/yunohost/mysql) +domain=$(sudo yunohost app setting roundcube domain) + +mysql -u root -p$root_pwd -e "DROP DATABASE $db_name ; DROP USER $db_user@localhost ;" +sudo rm -rf /var/www/freshrss +sudo rm -f /etc/nginx/conf.d/$domain.d/freshrss.conf + +sudo service nginx reload diff --git a/scripts/upgrade b/scripts/upgrade new file mode 100644 index 0000000..e69de29 diff --git a/sources/CHANGELOG b/sources/CHANGELOG new file mode 100755 index 0000000..cd48765 --- /dev/null +++ b/sources/CHANGELOG @@ -0,0 +1,280 @@ +# Journal des modifications + +## 2014-07-21 FreshRSS 0.7.3 + +* New options + * Add system of user queries which are shortcuts to filter the view + * New TTL option to limit the frequency at which feeds are refreshed (by cron or manual refresh button). + It is still possible to manually refresh an individual feed at a higher frequency. +* SQL + * Add support for SQLite (beta) in addition to MySQL +* SimplePie + * Complies with HTTP "301 Moved Permanently" responses by automatically updating the URL of feeds that have changed address. +* Themes + * Flat and Dark designs are based on same template file as Origine +* Statistics + * Refactor code + * Add an idle feed page +* Misc + * Several bug fixes + * Add confirmation option when marking all articles as read + * Fix some typo + + +## 2014-06-13 FreshRSS 0.7.2 + +* API compatible with Google Reader API level 2 + * FreshRSS can now be used from e.g.: + * (Android) News+ https://play.google.com/store/apps/details?id=com.noinnion.android.newsplus.extension.google_reader + * (Android) EasyRSS https://github.com/Alkarex/EasyRSS +* Basic support for audio and video podcasts +* Searching + * New search filters date: and pubdate: accepting ISO 8601 date intervals such as `date:2013-2014` or `pubdate:P1W` + * Possibility to combine search filters, e.g. `date:2014-05 intitle:FreshRSS intitle:Open great reader #Internet` +* Change nav menu with more buttons instead of dropdown menus and add some filters +* New system of import / export + * Support OPML, Json (like Google Reader) and Zip archives + * Can export and import articles (specific option for favorites) +* Refactor "Origine" theme + * Some improvements + * Based on a template file (other themes will use it too) + + +## 2014-02-19 FreshRSS 0.7.1 + +* Mise à jour des flux plus rapide grâce à une meilleure utilisation du cache + * Utilisation d’une signature MD5 du contenu intéressant pour les flux n’implémentant pas les requêtes conditionnelles +* Modification des raccourcis + * "s" partage directement si un seul moyen de partage + * Moyens de partage accessibles par "1", "2", "3", etc. + * Premier article : Home ; Dernier article : End + * Ajout du déplacement au sein des catégories / flux (via modificateurs shift et alt) +* UI + * Séparation des descriptions des raccourcis par groupes + * Revue rapide de la page de connexion + * Amélioration de l'affichage des notifications sur mobile +* Revue du système de rafraîchissement des flux + * Meilleure gestion de la file de flux à rafraîchir en JSON + * Rafraîchissement uniquement pour les flux non rafraîchis récemment + * Possibilité donnée aux anonymes de rafraîchir les flux +* SimplePie + * Mise à jour de la lib + * Corrige fuite de mémoire + * Meilleure tolérance aux flux invalides +* Corrections divers + * Ne déplie plus l'article lors du clic sur l'icône lien externe + * Ne boucle plus à la fin de la navigation dans les articles + * Suppression du champ category.color inutile + * Corrige bug redirection infinie (Persona) + * Amélioration vérification de la requête POST + * Ajout d'un verrou lorsqu'une action mark_read ou mark_favorite est en cours + + +## 2014-01-29 FreshRSS 0.7 + +* Nouveau mode multi-utilisateur + * L’utilisateur par défaut (administrateur) peut créer et supprimer d’autres utilisateurs + * Nécessite un contrôle d’accès, soit : + * par le nouveau mode de connexion par formulaire (nom d’utilisateur + mot de passe) + * relativement sûr même sans HTTPS (le mot de passe n’est pas transmis en clair) + * requiert JavaScript et PHP 5.3+ + * par HTTP (par exemple sous Apache en créant un fichier ./p/i/.htaccess et .htpasswd) + * le nom d’utilisateur HTTP doit correspondre au nom d’utilisateur FreshRSS + * par Mozilla Persona, en renseignant l’adresse courriel des utilisateurs +* Installateur supportant les mises à jour : + * Depuis une v0.6, placer application.ini et Configuration.array.php dans le nouveau répertoire “./data/” + (voir réorganisation ci-dessous) + * Pour les versions suivantes, juste garder le répertoire “./data/” +* Rafraîchissement automatique du nombre d’articles non lus toutes les deux minutes (utilise le cache HTTP à bon escient) + * Permet aussi de conserver la session valide, surtout dans le cas de Persona +* Nouvelle page de statistiques (nombres d’articles par jour / catégorie) +* Importation OPML instantanée et plus tolérante +* Nouvelle gestion des favicons avec téléchargement en parallèle +* Nouvelles options + * Réorganisation des options + * Gestion des utilisateurs + * Améliorations partage vers Shaarli, Poche, Diaspora*, Facebook, Twitter, Google+, courriel + * Raccourci ‘s’ par défaut + * Permet la suppression de tous les articles d’un flux + * Option pour marquer les articles comme lus dès la réception + * Permet de configurer plus finement le nombre d’articles minimum à conserver par flux + * Permet de modifier la description et l’adresse d’un flux RSS ainsi que le site Web associé + * Nouveau raccourci pour ouvrir/fermer un article (‘c’ par défaut) + * Boutons pour effacer les logs et pour purger les vieux articles + * Nouveaux filtres d’affichage : seulement les articles favoris, et seulement les articles lus +* SQL : + * Nouveau moteur de recherche, aussi accessible depuis la vue mobile + * Mots clefs de recherche “intitle:”, “inurl:”, “author:” + * Les articles sont triés selon la date de leur ajout dans FreshRSS plutôt que la date déclarée (souvent erronée) + * Permet de marquer tout comme lu sans affecter les nouveaux articles arrivés en cours de lecture + * Permet une pagination efficace + * Refactorisation + * Les tables sont préfixées avec le nom d’utilisateur afin de permettre le mode multi-utilisateurs + * Amélioration des performances + * Tolère un beaucoup plus grand nombre d’articles + * Compression des données côté MySQL plutôt que côté PHP + * Incompatible avec la version 0.6 (nécessite une mise à jour grâce à l’installateur) + * Affichage de la taille de la base de données dans FreshRSS + * Correction problème de marquage de tous les favoris comme lus +* HTML5 : + * Support des balises HTML5 audio, video, et éléments associés + * Utilisation de preload="none", et réécriture correcte des adresses, aussi en HTTPS + * Protection HTML5 des iframe (sandbox="allow-scripts allow-same-origin") + * Filtrage des object et embed + * Chargement différé HTML5 (postpone="") pour iframe et video + * Chargement différé JavaScript pour iframe +* CSS : + * Nouveau thème sombre + * Chargement plus robuste des thèmes + * Meilleur support des longs titres d’articles sur des écrans étroits + * Meilleure accessibilité + * FreshRSS fonctionne aussi en mode dégradé sans images (alternatives Unicode) et/ou sans CSS + * Diverses améliorations +* PHP : + * Encore plus tolérant pour les flux comportant des erreurs + * Mise à jour automatique de l’URL du flux (en base de données) lorsque SimplePie découvre qu’elle a changé + * Meilleure gestion des caractères spéciaux dans différents cas + * Compatibilité PHP 5.5+ avec OPcache + * Amélioration des performances + * Chargement automatique des classes + * Alternative dans le cas d’absence de librairie JSON + * Pour le développement, le cache HTTP peut être désactivé en créant un fichier “./data/no-cache.txt” +* Réorganisation des fichiers et répertoires, en particulier : + * Tous les fichiers utilisateur sont dans “./data/” (y compris “cache”, “favicons”, et “log”) + * Déplacement de “./app/configuration/application.ini” vers “./data/config.php” + * Meilleure sécurité et compatibilité + * Déplacement de “./public/data/Configuration.array.php” vers “./data/*_user.php” + * Déplacement de “./public/” vers “./p/” + * Déplacement de “./public/index.php” vers “./p/i/index.php” (voir cookie ci-dessous) + * Déplacement de “./actualize_script.php” vers “./app/actualize_script.php” (pour une meilleure sécurité) + * Pensez à mettre à jour votre Cron ! +* Divers : + * Nouvelle politique de cookie de session (témoin de connexion) + * Utilise un nom poli “FreshRSS” (évite des problèmes avec certains filtres) + * Se limite au répertoire “./FreshRSS/p/i/” pour de meilleures performances HTTP + * Les images, CSS, scripts sont servis sans cookie + * Utilise “HttpOnly” pour plus de sécurité + * Nouvel “agent utilisateur” exposé lors du téléchargement des flux, par exemple : + * “FreshRSS/0.7 (Linux; http://freshrss.org) SimplePie/1.3.1” + * Script d’actualisation avec plus de messages + * Sur la sortie standard, ainsi que dans le log système (syslog) + * Affichage du numéro de version dans "À propos" + + +## 2013-11-21 FreshRSS 0.6.1 + +* Corrige bug chargement du JavaScript +* Affiche un message d’erreur plus explicite si fichier de configuration inaccessible + + +## 2013-11-17 FreshRSS 0.6 + +* Nettoyage du code JavaScript + optimisations +* Utilisation d’adresses relatives +* Amélioration des performances coté client +* Mise à jour automatique du nombre d’articles non lus +* Corrections traductions +* Mise en cache de FreshRSS +* Amélioration des retours utilisateur lorsque la configuration n’est pas bonne +* Actualisation des flux après une importation OPML +* Meilleure prise en charge des flux RSS invalides +* Amélioration de la vue globale +* Possibilité de personnaliser les icônes de lecture +* Suppression de champs lors de l’installation (base_url et sel) +* Correction bugs divers + + +## 2013-10-15 FreshRSS 0.5.1 + +* Correction bug des catégories disparues +* Correction traduction i18n/fr et i18n/en +* Suppression de certains appels à la feuille de style fallback.css + + +## 2013-10-12 FreshRSS 0.5.0 + +* Possibilité d’interdire la lecture anonyme +* Option pour garder l’historique d’un flux +* Lors d’un clic sur “Marquer tous les articles comme lus”, FreshRSS peut désormais sauter à la prochaine catégorie / prochain flux avec des articles non lus. +* Ajout d’un token pour accéder aux flux RSS générés par FreshRSS sans nécessiter de connexion +* Possibilité de partager vers Facebook, Twitter et Google+ +* Possibilité de changer de thème +* Le menu de navigation (article précédent / suivant / haut de page) a été ajouté à la vue non mobile +* La police OpenSans est désormais appliquée +* Amélioration de la page de configuration +* Une meilleure sortie pour l’imprimante +* Quelques retouches du design par défaut +* Les vidéos ne dépassent plus du cadre de l’écran +* Nouveau logo +* Possibilité d’ajouter un préfixe aux tables lors de l’installation +* Ajout d’un champ en base de données keep_history à la table feed +* Si possible, création automatique de la base de données si elle n’existe pas lors de l’installation +* L’utilisation d’UTF-8 est forcée +* Le marquage automatique au défilement de la page a été amélioré +* La vue globale a été énormément améliorée et est beaucoup plus utile +* Amélioration des requêtes SQL +* Amélioration du JavaScript +* Correction bugs divers + + +## 2013-07-02 FreshRSS 0.4.0 + +* Correction bug et ajout notification lors de la phase d’installation +* Affichage d’erreur si fichier OPML invalide +* Les tags sont maintenant cliquables pour filtrer dessus +* Amélioration vue mobile (boutons plus gros et ajout d’une barre de navigation) +* Possibilité d’ajouter directement un flux dans une catégorie dès son ajout +* Affichage des flux en erreur (injoignable par exemple) en rouge pour les différencier +* Possibilité de changer les noms des flux +* Ajout d’une option (désactivable donc) pour charger les images en lazyload permettant de ne pas charger toutes les images d’un coup +* Le framework Minz est maintenant directement inclus dans l’archive (plus besoin de passer par ./build.sh) +* Amélioration des performances pour la récupération des flux tronqués +* Possibilité d’importer des flux sans catégorie lors de l’import OPML +* Suppression de “l’API” (qui était de toute façon très basique) et de la fonctionnalité de “notes” +* Amélioration de la recherche (garde en mémoire si l’on a sélectionné une catégorie) par exemple +* Modification apparence des balises hr et pre +* Meilleure vérification des champs de formulaire +* Remise en place du mode “endless” (permettant de simplement charger les articles qui suivent plutôt que de charger une nouvelle page) +* Ajout d’une page de visualisation des logs +* Ajout d’une option pour optimiser la BDD (diminue sa taille) +* Ajout des vues lecture et globale (assez basique) +* Les vidéos YouTube ne débordent plus du cadre sur les petits écrans +* Ajout d’une option pour marquer les articles comme lus lors du défilement (et suppression de celle au chargement de la page) + + +## 2013-05-05 FreshRSS 0.3.0 + +* Fallback pour les icônes SVG (utilisation de PNG à la place) +* Fallback pour les propriétés CSS3 (utilisation de préfixes) +* Affichage des tags associés aux articles +* Internationalisation de l’application (gestion des langues anglaise et française) +* Gestion des flux protégés par authentification HTTP +* Mise en cache des favicons +* Création d’un logo *temporaire* +* Affichage des vidéos dans les articles +* Gestion de la recherche et filtre par tags pleinement fonctionnels +* Création d’un vrai script CRON permettant de mettre tous les flux à jour +* Correction bugs divers + + +## 2013-04-17 FreshRSS 0.2.0 + +* Création d’un installateur +* Actualisation des flux en Ajax +* Partage par mail et Shaarli ajouté +* Export par flux RSS +* Possibilité de vider une catégorie +* Possibilité de sélectionner les catégories en vue mobile +* Les flux peuvent être sortis du flux principal (système de priorité) +* Amélioration ajout / import / export des flux +* Amélioration actualisation (meilleure gestion des erreurs) +* Améliorations CSS +* Changements dans la base de données +* Màj de la librairie SimplePie +* Flux sans auteurs gérés normalement +* Correction bugs divers + + +## 2013-04-08 FreshRSS 0.1.0 + +* “Première” version diff --git a/sources/LICENSE b/sources/LICENSE new file mode 100755 index 0000000..a871fcf --- /dev/null +++ b/sources/LICENSE @@ -0,0 +1,662 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. + diff --git a/sources/README.md b/sources/README.md new file mode 100755 index 0000000..f857bae --- /dev/null +++ b/sources/README.md @@ -0,0 +1,100 @@ +# FreshRSS +FreshRSS est un agrégateur de flux RSS à auto-héberger à l’image de [Leed](http://projet.idleman.fr/leed/) ou de [Kriss Feed](http://tontof.net/kriss/feed/). + +Il se veut léger et facile à prendre en main tout en étant un outil puissant et paramétrable. + +Il permet de gérer plusieurs utilisateurs, et dispose d’un mode de lecture anonyme. + +* Site officiel : http://freshrss.org +* Démo : http://demo.freshrss.org/ +* Développeur : Marien Fressinaud +* Version actuelle : 0.7.3 +* Date de publication 2014-07-21 +* License [GNU AGPL 3](http://www.gnu.org/licenses/agpl-3.0.html) + +![Logo de FreshRSS](http://marienfressinaud.fr/data/images/freshrss/freshrss_title.png) + +# Note sur les branches +**Ce logiciel est encore en développement !** Veuillez vous assurer d'utiliser la branche qui vous correspond : + +* Utilisez [la branche master](https://github.com/marienfressinaud/FreshRSS/tree/master/) si vous visez la stabilité. +* [La branche beta](https://github.com/marienfressinaud/FreshRSS/tree/beta) est celle par défaut : les nouveautés y sont ajoutées environ tous les mois. +* Pour les développeurs et ceux qui savent ce qu'ils font, [la branche dev](https://github.com/marienfressinaud/FreshRSS/tree/dev) vous ouvre les bras ! + +# Disclaimer +Cette application a été développée pour s’adapter à des besoins personnels et non professionnels. +Je ne garantis en aucun cas la sécurité de celle-ci, ni son bon fonctionnement. +Je m’engage néanmoins à répondre dans la mesure du possible aux demandes d’évolution si celles-ci me semblent justifiées. +Privilégiez pour cela des demandes sur GitHub +(https://github.com/marienfressinaud/FreshRSS/issues) ou par mail (dev@marienfressinaud.fr) + +# Pré-requis +* Serveur modeste, par exemple sous Linux ou Windows + * Fonctionne même sur un Raspberry Pi avec des temps de réponse < 1s (testé sur 150 flux, 22k articles, soit 32Mo de données partiellement compressées) +* Serveur Web Apache2 ou Nginx (non testé sur les autres) +* PHP 5.2.1+ (PHP 5.3.7+ recommandé) + * Requis : [PDO_MySQL](http://php.net/pdo-mysql), [cURL](http://php.net/curl), [LibXML](http://php.net/xml), [PCRE](http://php.net/pcre), [ctype](http://php.net/ctype) + * Recommandés : [JSON](http://php.net/json), [zlib](http://php.net/zlib), [mbstring](http://php.net/mbstring), [iconv](http://php.net/iconv), [Zip](http://php.net/zip) +* MySQL 5.0.3+ (recommandé) ou SQLite 3.7.4+ (en bêta) +* Un navigateur Web récent tel Firefox 4+, Chrome, Opera, Safari, Internet Explorer 9+ + * Fonctionne aussi sur mobile + +![Capture d’écran de FreshRSS](http://marienfressinaud.fr/data/images/freshrss/freshrss_default-design.png) + +# Installation +1. Récupérez l’application FreshRSS via la commande git ou [en téléchargeant l’archive](https://github.com/marienfressinaud/FreshRSS/archive/master.zip) +2. Placez l’application sur votre serveur (la partie à exposer au Web est le répertoire `./p/`) +3. Le serveur Web doit avoir les droits d’écriture dans le répertoire `./data/` +4. Accédez à FreshRSS à travers votre navigateur Web et suivez les instructions d’installation +5. Tout devrait fonctionner :) En cas de problème, n’hésitez pas à me contacter. + +# Contrôle d’accès +Il est requis pour le mode multi-utilisateur, et recommandé dans tous les cas, de limiter l’accès à votre FreshRSS. Au choix : +* En utilisant l’identification par formulaire (requiert JavaScript, et PHP 5.3.7+ recommandé – fonctionne avec certaines versions de PHP 5.3.3+) +* En utilisant l’identification par [Mozilla Persona](https://login.persona.org/about) incluse dans FreshRSS +* En utilisant un contrôle d’accès HTTP défini par votre serveur Web + * Voir par exemple la [documentation d’Apache sur l’authentification](http://httpd.apache.org/docs/trunk/howto/auth.html) + * Créer dans ce cas un fichier `./p/i/.htaccess` avec un fichier `.htpasswd` correspondant. + +# Rafraîchissement automatique des flux +* Vous pouvez ajouter une tâche Cron lançant régulièrement le script d’actualisation automatique des flux. +Consultez la documentation de Cron de votre système d’exploitation ([Debian/Ubuntu](http://doc.ubuntu-fr.org/cron), [Red Hat/Fedora](http://doc.fedora-fr.org/wiki/CRON_:_Configuration_de_t%C3%A2ches_automatis%C3%A9es), [Slackware](http://docs.slackware.com/fr:slackbook:process_control?#cron), [Gentoo](http://wiki.gentoo.org/wiki/Cron/fr), [Arch Linux](http://wiki.archlinux.fr/Cron)…). +C’est une bonne idée d’utiliser le même utilisateur que votre serveur Web (souvent “www-data”). +Par exemple, pour exécuter le script toutes les heures : + +``` +7 * * * * php /chemin/vers/FreshRSS/app/actualize_script.php > /tmp/FreshRSS.log 2>&1 +``` + +# Conseils +* Pour une meilleure sécurité, faites en sorte que seul le répertoire `./p/` soit accessible depuis le Web, par exemple en faisant pointer un sous-domaine sur le répertoire `./p/`. + * En particulier, les données personnelles se trouvent dans le répertoire `./data/`. +* Le fichier `./constants.php` définit les chemins d’accès aux répertoires clés de l’application. Si vous les bougez, tout se passe ici. +* En cas de problème, les logs peuvent être utile à lire, soit depuis l’interface de FreshRSS, soit manuellement depuis `./data/log/*.log`. + +# Sauvegarde +* Il faut conserver vos fichiers `./data/config.php` ainsi que `./data/*_user.php` et éventuellement `./data/persona/` +* Vous pouvez exporter votre liste de flux depuis FreshRSS au format OPML +* Pour sauvegarder les articles eux-même, vous pouvez utiliser [phpMyAdmin](http://www.phpmyadmin.net) ou les outils de MySQL : + +```bash +mysqldump -u utilisateur -p --databases freshrss > freshrss.sql +``` + + +# Bibliothèques incluses +* [SimplePie](http://simplepie.org/) +* [MINZ](https://github.com/marienfressinaud/MINZ) +* [php-http-304](http://alexandre.alapetite.fr/doc-alex/php-http-304/) +* [jQuery](http://jquery.com/) +* [keyboard_shortcuts](http://www.openjs.com/scripts/events/keyboard_shortcuts/) +* [flotr2](http://www.humblesoftware.com/flotr2) + +## Uniquement pour certaines options +* [bcrypt.js](https://github.com/dcodeIO/bcrypt.js) +* [phpQuery](http://code.google.com/p/phpquery/) +* [Lazy Load](http://www.appelsiini.net/projects/lazyload) + +## Si les fonctions natives ne sont pas disponibles +* [Services_JSON](http://pear.php.net/pepr/pepr-proposal-show.php?id=198) +* [password_compat](https://github.com/ircmaxell/password_compat) diff --git a/sources/app/.htaccess b/sources/app/.htaccess new file mode 100755 index 0000000..9e76839 --- /dev/null +++ b/sources/app/.htaccess @@ -0,0 +1,3 @@ +Order Allow,Deny +Deny from all +Satisfy all diff --git a/sources/app/Controllers/configureController.php b/sources/app/Controllers/configureController.php new file mode 100755 index 0000000..79f40b3 --- /dev/null +++ b/sources/app/Controllers/configureController.php @@ -0,0 +1,382 @@ +view->loginOk) { + Minz_Error::error( + 403, + array('error' => array(Minz_Translate::t('access_denied'))) + ); + } + + $catDAO = new FreshRSS_CategoryDAO(); + $catDAO->checkDefault(); + } + + public function categorizeAction() { + $feedDAO = FreshRSS_Factory::createFeedDao(); + $catDAO = new FreshRSS_CategoryDAO(); + $defaultCategory = $catDAO->getDefault(); + $defaultId = $defaultCategory->id(); + + if (Minz_Request::isPost()) { + $cats = Minz_Request::param('categories', array()); + $ids = Minz_Request::param('ids', array()); + $newCat = trim(Minz_Request::param('new_category', '')); + + foreach ($cats as $key => $name) { + if (strlen($name) > 0) { + $cat = new FreshRSS_Category($name); + $values = array( + 'name' => $cat->name(), + ); + $catDAO->updateCategory($ids[$key], $values); + } elseif ($ids[$key] != $defaultId) { + $feedDAO->changeCategory($ids[$key], $defaultId); + $catDAO->deleteCategory($ids[$key]); + } + } + + if ($newCat != '') { + $cat = new FreshRSS_Category($newCat); + $values = array( + 'id' => $cat->id(), + 'name' => $cat->name(), + ); + + if ($catDAO->searchByName($newCat) == null) { + $catDAO->addCategory($values); + } + } + invalidateHttpCache(); + + $notif = array( + 'type' => 'good', + 'content' => Minz_Translate::t('categories_updated') + ); + Minz_Session::_param('notification', $notif); + + Minz_Request::forward(array('c' => 'configure', 'a' => 'categorize'), true); + } + + $this->view->categories = $catDAO->listCategories(false); + $this->view->defaultCategory = $catDAO->getDefault(); + $this->view->feeds = $feedDAO->listFeeds(); + + Minz_View::prependTitle(Minz_Translate::t('categories_management') . ' · '); + } + + public function feedAction() { + $catDAO = new FreshRSS_CategoryDAO(); + $this->view->categories = $catDAO->listCategories(false); + + $feedDAO = FreshRSS_Factory::createFeedDao(); + $this->view->feeds = $feedDAO->listFeeds(); + + $id = Minz_Request::param('id'); + if ($id == false && !empty($this->view->feeds)) { + $id = current($this->view->feeds)->id(); + } + + $this->view->flux = false; + if ($id != false) { + $this->view->flux = $this->view->feeds[$id]; + + if (!$this->view->flux) { + Minz_Error::error( + 404, + array('error' => array(Minz_Translate::t('page_not_found'))) + ); + } else { + if (Minz_Request::isPost() && $this->view->flux) { + $user = Minz_Request::param('http_user', ''); + $pass = Minz_Request::param('http_pass', ''); + + $httpAuth = ''; + if ($user != '' || $pass != '') { + $httpAuth = $user . ':' . $pass; + } + + $cat = intval(Minz_Request::param('category', 0)); + + $values = array( + 'name' => Minz_Request::param('name', ''), + 'description' => sanitizeHTML(Minz_Request::param('description', '', true)), + 'website' => Minz_Request::param('website', ''), + 'url' => Minz_Request::param('url', ''), + 'category' => $cat, + 'pathEntries' => Minz_Request::param('path_entries', ''), + 'priority' => intval(Minz_Request::param('priority', 0)), + 'httpAuth' => $httpAuth, + 'keep_history' => intval(Minz_Request::param('keep_history', -2)), + 'ttl' => intval(Minz_Request::param('ttl', -2)), + ); + + if ($feedDAO->updateFeed($id, $values)) { + $this->view->flux->_category($cat); + $this->view->flux->faviconPrepare(); + $notif = array( + 'type' => 'good', + 'content' => Minz_Translate::t('feed_updated') + ); + } else { + $notif = array( + 'type' => 'bad', + 'content' => Minz_Translate::t('error_occurred_update') + ); + } + invalidateHttpCache(); + + Minz_Session::_param('notification', $notif); + Minz_Request::forward(array('c' => 'configure', 'a' => 'feed', 'params' => array('id' => $id)), true); + } + + Minz_View::prependTitle(Minz_Translate::t('rss_feed_management') . ' — ' . $this->view->flux->name() . ' · '); + } + } else { + Minz_View::prependTitle(Minz_Translate::t('rss_feed_management') . ' · '); + } + } + + public function displayAction() { + if (Minz_Request::isPost()) { + $this->view->conf->_language(Minz_Request::param('language', 'en')); + $themeId = Minz_Request::param('theme', ''); + if ($themeId == '') { + $themeId = FreshRSS_Themes::defaultTheme; + } + $this->view->conf->_theme($themeId); + $this->view->conf->_content_width(Minz_Request::param('content_width', 'thin')); + $this->view->conf->_topline_read(Minz_Request::param('topline_read', false)); + $this->view->conf->_topline_favorite(Minz_Request::param('topline_favorite', false)); + $this->view->conf->_topline_date(Minz_Request::param('topline_date', false)); + $this->view->conf->_topline_link(Minz_Request::param('topline_link', false)); + $this->view->conf->_bottomline_read(Minz_Request::param('bottomline_read', false)); + $this->view->conf->_bottomline_favorite(Minz_Request::param('bottomline_favorite', false)); + $this->view->conf->_bottomline_sharing(Minz_Request::param('bottomline_sharing', false)); + $this->view->conf->_bottomline_tags(Minz_Request::param('bottomline_tags', false)); + $this->view->conf->_bottomline_date(Minz_Request::param('bottomline_date', false)); + $this->view->conf->_bottomline_link(Minz_Request::param('bottomline_link', false)); + $this->view->conf->save(); + + Minz_Session::_param('language', $this->view->conf->language); + Minz_Translate::reset(); + invalidateHttpCache(); + + $notif = array( + 'type' => 'good', + 'content' => Minz_Translate::t('configuration_updated') + ); + Minz_Session::_param('notification', $notif); + + Minz_Request::forward(array('c' => 'configure', 'a' => 'display'), true); + } + + $this->view->themes = FreshRSS_Themes::get(); + + Minz_View::prependTitle(Minz_Translate::t('display_configuration') . ' · '); + } + + public function readingAction() { + if (Minz_Request::isPost()) { + $this->view->conf->_posts_per_page(Minz_Request::param('posts_per_page', 10)); + $this->view->conf->_view_mode(Minz_Request::param('view_mode', 'normal')); + $this->view->conf->_default_view((int)Minz_Request::param('default_view', FreshRSS_Entry::STATE_ALL)); + $this->view->conf->_auto_load_more(Minz_Request::param('auto_load_more', false)); + $this->view->conf->_display_posts(Minz_Request::param('display_posts', false)); + $this->view->conf->_onread_jump_next(Minz_Request::param('onread_jump_next', false)); + $this->view->conf->_lazyload(Minz_Request::param('lazyload', false)); + $this->view->conf->_sticky_post(Minz_Request::param('sticky_post', false)); + $this->view->conf->_reading_confirm(Minz_Request::param('reading_confirm', false)); + $this->view->conf->_sort_order(Minz_Request::param('sort_order', 'DESC')); + $this->view->conf->_mark_when(array( + 'article' => Minz_Request::param('mark_open_article', false), + 'site' => Minz_Request::param('mark_open_site', false), + 'scroll' => Minz_Request::param('mark_scroll', false), + 'reception' => Minz_Request::param('mark_upon_reception', false), + )); + $this->view->conf->save(); + + Minz_Session::_param('language', $this->view->conf->language); + Minz_Translate::reset(); + invalidateHttpCache(); + + $notif = array( + 'type' => 'good', + 'content' => Minz_Translate::t('configuration_updated') + ); + Minz_Session::_param('notification', $notif); + + Minz_Request::forward(array('c' => 'configure', 'a' => 'reading'), true); + } + + Minz_View::prependTitle(Minz_Translate::t('reading_configuration') . ' · '); + } + + public function sharingAction() { + if (Minz_Request::isPost()) { + $params = Minz_Request::params(); + $this->view->conf->_sharing($params['share']); + $this->view->conf->save(); + invalidateHttpCache(); + + $notif = array( + 'type' => 'good', + 'content' => Minz_Translate::t('configuration_updated') + ); + Minz_Session::_param('notification', $notif); + + Minz_Request::forward(array('c' => 'configure', 'a' => 'sharing'), true); + } + + Minz_View::prependTitle(Minz_Translate::t('sharing') . ' · '); + } + + public function shortcutAction() { + $list_keys = array('a', 'b', 'backspace', 'c', 'd', 'delete', 'down', 'e', 'end', 'enter', + 'escape', 'f', 'g', 'h', 'home', 'i', 'insert', 'j', 'k', 'l', 'left', + 'm', 'n', 'o', 'p', 'page_down', 'page_up', 'q', 'r', 'return', 'right', + 's', 'space', 't', 'tab', 'u', 'up', 'v', 'w', 'x', 'y', + 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', + '9', 'f1', 'f2', 'f3', 'f4', 'f5', 'f6', 'f7', 'f8', 'f9', + 'f10', 'f11', 'f12'); + $this->view->list_keys = $list_keys; + + if (Minz_Request::isPost()) { + $shortcuts = Minz_Request::param('shortcuts'); + $shortcuts_ok = array(); + + foreach ($shortcuts as $key => $value) { + if (in_array($value, $list_keys)) { + $shortcuts_ok[$key] = $value; + } + } + + $this->view->conf->_shortcuts($shortcuts_ok); + $this->view->conf->save(); + invalidateHttpCache(); + + $notif = array( + 'type' => 'good', + 'content' => Minz_Translate::t('shortcuts_updated') + ); + Minz_Session::_param('notification', $notif); + + Minz_Request::forward(array('c' => 'configure', 'a' => 'shortcut'), true); + } + + Minz_View::prependTitle(Minz_Translate::t('shortcuts') . ' · '); + } + + public function usersAction() { + Minz_View::prependTitle(Minz_Translate::t('users') . ' · '); + } + + public function archivingAction() { + if (Minz_Request::isPost()) { + $old = Minz_Request::param('old_entries', 3); + $keepHistoryDefault = Minz_Request::param('keep_history_default', 0); + $ttlDefault = Minz_Request::param('ttl_default', -2); + + $this->view->conf->_old_entries($old); + $this->view->conf->_keep_history_default($keepHistoryDefault); + $this->view->conf->_ttl_default($ttlDefault); + $this->view->conf->save(); + invalidateHttpCache(); + + $notif = array( + 'type' => 'good', + 'content' => Minz_Translate::t('configuration_updated') + ); + Minz_Session::_param('notification', $notif); + + Minz_Request::forward(array('c' => 'configure', 'a' => 'archiving'), true); + } + + Minz_View::prependTitle(Minz_Translate::t('archiving_configuration') . ' · '); + + $entryDAO = FreshRSS_Factory::createEntryDao(); + $this->view->nb_total = $entryDAO->count(); + $this->view->size_user = $entryDAO->size(); + + if (Minz_Configuration::isAdmin(Minz_Session::param('currentUser', '_'))) { + $this->view->size_total = $entryDAO->size(true); + } + } + + public function queriesAction() { + if (Minz_Request::isPost()) { + $queries = Minz_Request::param('queries', array()); + + foreach ($queries as $key => $query) { + if (!$query['name']) { + $query['name'] = Minz_Translate::t('query_number', $key + 1); + } + } + $this->view->conf->_queries($queries); + $this->view->conf->save(); + + $notif = array( + 'type' => 'good', + 'content' => Minz_Translate::t('configuration_updated') + ); + Minz_Session::_param('notification', $notif); + + Minz_Request::forward(array('c' => 'configure', 'a' => 'queries'), true); + } else { + $this->view->query_get = array(); + foreach ($this->view->conf->queries as $key => $query) { + if (!isset($query['get'])) { + continue; + } + + switch ($query['get'][0]) { + case 'c': + $dao = new FreshRSS_CategoryDAO(); + $category = $dao->searchById(substr($query['get'], 2)); + $this->view->query_get[$key] = array( + 'type' => 'category', + 'name' => $category->name(), + ); + break; + case 'f': + $dao = FreshRSS_Factory::createFeedDao(); + $feed = $dao->searchById(substr($query['get'], 2)); + $this->view->query_get[$key] = array( + 'type' => 'feed', + 'name' => $feed->name(), + ); + break; + case 's': + $this->view->query_get[$key] = array( + 'type' => 'favorite', + 'name' => 'favorite', + ); + break; + case 'a': + $this->view->query_get[$key] = array( + 'type' => 'all', + 'name' => 'all', + ); + break; + } + } + } + + Minz_View::prependTitle(Minz_Translate::t('queries') . ' · '); + } + + public function addQueryAction() { + $queries = $this->view->conf->queries; + $query = Minz_Request::params(); + $query['name'] = Minz_Translate::t('query_number', count($queries) + 1); + unset($query['output']); + unset($query['token']); + $queries[] = $query; + $this->view->conf->_queries($queries); + $this->view->conf->save(); + + // Minz_Request::forward(array('params' => $query), true); + Minz_Request::forward(array('c' => 'configure', 'a' => 'queries'), true); + } +} diff --git a/sources/app/Controllers/entryController.php b/sources/app/Controllers/entryController.php new file mode 100755 index 0000000..ac43587 --- /dev/null +++ b/sources/app/Controllers/entryController.php @@ -0,0 +1,163 @@ +view->loginOk) { + Minz_Error::error ( + 403, + array ('error' => array (Minz_Translate::t ('access_denied'))) + ); + } + + $this->params = array (); + $output = Minz_Request::param('output', ''); + if (($output != '') && ($this->view->conf->view_mode !== $output)) { + $this->params['output'] = $output; + } + + $this->redirect = false; + $ajax = Minz_Request::param ('ajax'); + if ($ajax) { + $this->view->_useLayout (false); + } + } + + public function lastAction () { + $ajax = Minz_Request::param ('ajax'); + if (!$ajax && $this->redirect) { + Minz_Request::forward (array ( + 'c' => 'index', + 'a' => 'index', + 'params' => $this->params + ), true); + } else { + Minz_Request::_param ('ajax'); + } + } + + public function readAction () { + $this->redirect = true; + + $id = Minz_Request::param ('id'); + $get = Minz_Request::param ('get'); + $nextGet = Minz_Request::param ('nextGet', $get); + $idMax = Minz_Request::param ('idMax', 0); + + $entryDAO = FreshRSS_Factory::createEntryDao(); + if ($id == false) { + if (!$get) { + $entryDAO->markReadEntries ($idMax); + } else { + $typeGet = $get[0]; + $get = substr ($get, 2); + switch ($typeGet) { + case 'c': + $entryDAO->markReadCat ($get, $idMax); + break; + case 'f': + $entryDAO->markReadFeed ($get, $idMax); + break; + case 's': + $entryDAO->markReadEntries ($idMax, true); + break; + case 'a': + $entryDAO->markReadEntries ($idMax); + break; + } + if ($nextGet !== 'a') { + $this->params['get'] = $nextGet; + } + } + + $notif = array ( + 'type' => 'good', + 'content' => Minz_Translate::t ('feeds_marked_read') + ); + Minz_Session::_param ('notification', $notif); + } else { + $is_read = (bool)(Minz_Request::param ('is_read', true)); + $entryDAO->markRead ($id, $is_read); + } + } + + public function bookmarkAction () { + $this->redirect = true; + + $id = Minz_Request::param ('id'); + if ($id) { + $entryDAO = FreshRSS_Factory::createEntryDao(); + $entryDAO->markFavorite ($id, (bool)(Minz_Request::param ('is_favorite', true))); + } + } + + public function optimizeAction() { + if (Minz_Request::isPost()) { + @set_time_limit(300); + + // La table des entrées a tendance à grossir énormément + // Cette action permet d'optimiser cette table permettant de grapiller un peu de place + // Cette fonctionnalité n'est à appeler qu'occasionnellement + $entryDAO = FreshRSS_Factory::createEntryDao(); + $entryDAO->optimizeTable(); + + $feedDAO = FreshRSS_Factory::createFeedDao(); + $feedDAO->updateCachedValues(); + + invalidateHttpCache(); + + $notif = array ( + 'type' => 'good', + 'content' => Minz_Translate::t ('optimization_complete') + ); + Minz_Session::_param ('notification', $notif); + } + + Minz_Request::forward(array( + 'c' => 'configure', + 'a' => 'archiving' + ), true); + } + + public function purgeAction() { + @set_time_limit(300); + + $nb_month_old = max($this->view->conf->old_entries, 1); + $date_min = time() - (3600 * 24 * 30 * $nb_month_old); + + $feedDAO = FreshRSS_Factory::createFeedDao(); + $feeds = $feedDAO->listFeeds(); + $nbTotal = 0; + + invalidateHttpCache(); + + foreach ($feeds as $feed) { + $feedHistory = $feed->keepHistory(); + if ($feedHistory == -2) { //default + $feedHistory = $this->view->conf->keep_history_default; + } + if ($feedHistory >= 0) { + $nb = $feedDAO->cleanOldEntries($feed->id(), $date_min, $feedHistory); + if ($nb > 0) { + $nbTotal += $nb; + Minz_Log::record($nb . ' old entries cleaned in feed [' . $feed->url() . ']', Minz_Log::DEBUG); + //$feedDAO->updateLastUpdate($feed->id()); + } + } + } + + $feedDAO->updateCachedValues(); + + invalidateHttpCache(); + + $notif = array( + 'type' => 'good', + 'content' => Minz_Translate::t('purge_completed', $nbTotal) + ); + Minz_Session::_param('notification', $notif); + + Minz_Request::forward(array( + 'c' => 'configure', + 'a' => 'archiving' + ), true); + } +} diff --git a/sources/app/Controllers/errorController.php b/sources/app/Controllers/errorController.php new file mode 100755 index 0000000..dc9a2ee --- /dev/null +++ b/sources/app/Controllers/errorController.php @@ -0,0 +1,26 @@ +view->code = 'Error 403 - Forbidden'; + break; + case 404: + $this->view->code = 'Error 404 - Not found'; + break; + case 500: + $this->view->code = 'Error 500 - Internal Server Error'; + break; + case 503: + $this->view->code = 'Error 503 - Service Unavailable'; + break; + default: + $this->view->code = 'Error 404 - Not found'; + } + + $this->view->logs = Minz_Request::param ('logs'); + + Minz_View::prependTitle ($this->view->code . ' · '); + } +} diff --git a/sources/app/Controllers/feedController.php b/sources/app/Controllers/feedController.php new file mode 100755 index 0000000..3326b20 --- /dev/null +++ b/sources/app/Controllers/feedController.php @@ -0,0 +1,422 @@ +view->loginOk) { + // Token is useful in the case that anonymous refresh is forbidden + // and CRON task cannot be used with php command so the user can + // set a CRON task to refresh his feeds by using token inside url + $token = $this->view->conf->token; + $token_param = Minz_Request::param ('token', ''); + $token_is_ok = ($token != '' && $token == $token_param); + $action = Minz_Request::actionName (); + if (!(($token_is_ok || Minz_Configuration::allowAnonymousRefresh()) && + $action === 'actualize') + ) { + Minz_Error::error ( + 403, + array ('error' => array (Minz_Translate::t ('access_denied'))) + ); + } + } + } + + public function addAction () { + $url = Minz_Request::param('url_rss', false); + + if ($url === false) { + Minz_Request::forward(array( + 'c' => 'configure', + 'a' => 'feed' + ), true); + } + + $feedDAO = FreshRSS_Factory::createFeedDao(); + $this->catDAO = new FreshRSS_CategoryDAO (); + $this->catDAO->checkDefault (); + + if (Minz_Request::isPost()) { + @set_time_limit(300); + + + $cat = Minz_Request::param ('category', false); + if ($cat === 'nc') { + $new_cat = Minz_Request::param ('new_category'); + if (empty($new_cat['name'])) { + $cat = false; + } else { + $cat = $this->catDAO->addCategory($new_cat); + } + } + if ($cat === false) { + $def_cat = $this->catDAO->getDefault (); + $cat = $def_cat->id (); + } + + $user = Minz_Request::param ('http_user'); + $pass = Minz_Request::param ('http_pass'); + $params = array (); + + $transactionStarted = false; + try { + $feed = new FreshRSS_Feed ($url); + $feed->_category ($cat); + + $httpAuth = ''; + if ($user != '' || $pass != '') { + $httpAuth = $user . ':' . $pass; + } + $feed->_httpAuth ($httpAuth); + + $feed->load(true); + + $values = array ( + 'url' => $feed->url (), + 'category' => $feed->category (), + 'name' => $feed->name (), + 'website' => $feed->website (), + 'description' => $feed->description (), + 'lastUpdate' => time (), + 'httpAuth' => $feed->httpAuth (), + ); + + if ($feedDAO->searchByUrl ($values['url'])) { + // on est déjà abonné à ce flux + $notif = array ( + 'type' => 'bad', + 'content' => Minz_Translate::t ('already_subscribed', $feed->name ()) + ); + Minz_Session::_param ('notification', $notif); + } else { + $id = $feedDAO->addFeed ($values); + if (!$id) { + // problème au niveau de la base de données + $notif = array ( + 'type' => 'bad', + 'content' => Minz_Translate::t ('feed_not_added', $feed->name ()) + ); + Minz_Session::_param ('notification', $notif); + } else { + $feed->_id ($id); + $feed->faviconPrepare(); + + $is_read = $this->view->conf->mark_when['reception'] ? 1 : 0; + + $entryDAO = FreshRSS_Factory::createEntryDao(); + $entries = array_reverse($feed->entries()); //We want chronological order and SimplePie uses reverse order + + // on calcule la date des articles les plus anciens qu'on accepte + $nb_month_old = $this->view->conf->old_entries; + $date_min = time () - (3600 * 24 * 30 * $nb_month_old); + + //MySQL: http://docs.oracle.com/cd/E17952_01/refman-5.5-en/optimizing-innodb-transaction-management.html + //SQLite: http://stackoverflow.com/questions/1711631/how-do-i-improve-the-performance-of-sqlite + $preparedStatement = $entryDAO->addEntryPrepare(); + $transactionStarted = true; + $feedDAO->beginTransaction(); + // on ajoute les articles en masse sans vérification + foreach ($entries as $entry) { + $values = $entry->toArray(); + $values['id_feed'] = $feed->id(); + $values['id'] = min(time(), $entry->date(true)) . uSecString(); + $values['is_read'] = $is_read; + $entryDAO->addEntry($values, $preparedStatement); + } + $feedDAO->updateLastUpdate($feed->id()); + if ($transactionStarted) { + $feedDAO->commit(); + } + $transactionStarted = false; + + // ok, ajout terminé + $notif = array ( + 'type' => 'good', + 'content' => Minz_Translate::t ('feed_added', $feed->name ()) + ); + Minz_Session::_param ('notification', $notif); + + // permet de rediriger vers la page de conf du flux + $params['id'] = $feed->id (); + } + } + } catch (FreshRSS_BadUrl_Exception $e) { + Minz_Log::record ($e->getMessage (), Minz_Log::WARNING); + $notif = array ( + 'type' => 'bad', + 'content' => Minz_Translate::t ('invalid_url', $url) + ); + Minz_Session::_param ('notification', $notif); + } catch (FreshRSS_Feed_Exception $e) { + Minz_Log::record ($e->getMessage (), Minz_Log::WARNING); + $notif = array ( + 'type' => 'bad', + 'content' => Minz_Translate::t ('internal_problem_feed', Minz_Url::display(array('a' => 'logs'))) + ); + Minz_Session::_param ('notification', $notif); + } catch (Minz_FileNotExistException $e) { + // Répertoire de cache n'existe pas + Minz_Log::record ($e->getMessage (), Minz_Log::ERROR); + $notif = array ( + 'type' => 'bad', + 'content' => Minz_Translate::t ('internal_problem_feed', Minz_Url::display(array('a' => 'logs'))) + ); + Minz_Session::_param ('notification', $notif); + } + if ($transactionStarted) { + $feedDAO->rollBack (); + } + + Minz_Request::forward (array ('c' => 'configure', 'a' => 'feed', 'params' => $params), true); + } else { + + // GET request so we must ask confirmation to user + Minz_View::prependTitle(Minz_Translate::t('add_rss_feed') . ' · '); + $this->view->categories = $this->catDAO->listCategories(); + $this->view->feed = new FreshRSS_Feed($url); + try { + // We try to get some more information about the feed + $this->view->feed->load(true); + $this->view->load_ok = true; + } catch (Exception $e) { + $this->view->load_ok = false; + } + + $feed = $feedDAO->searchByUrl($this->view->feed->url()); + if ($feed) { + // Already subscribe so we redirect to the feed configuration page + $notif = array( + 'type' => 'bad', + 'content' => Minz_Translate::t( + 'already_subscribed', $feed->name() + ) + ); + Minz_Session::_param('notification', $notif); + + Minz_Request::forward(array( + 'c' => 'configure', + 'a' => 'feed', + 'params' => array( + 'id' => $feed->id() + ) + ), true); + } + } + } + + public function truncateAction () { + if (Minz_Request::isPost ()) { + $id = Minz_Request::param ('id'); + $feedDAO = FreshRSS_Factory::createFeedDao(); + $n = $feedDAO->truncate($id); + $notif = array( + 'type' => $n === false ? 'bad' : 'good', + 'content' => Minz_Translate::t ('n_entries_deleted', $n) + ); + Minz_Session::_param ('notification', $notif); + invalidateHttpCache(); + Minz_Request::forward (array ('c' => 'configure', 'a' => 'feed', 'params' => array('id' => $id)), true); + } + } + + public function actualizeAction () { + @set_time_limit(300); + + $feedDAO = FreshRSS_Factory::createFeedDao(); + $entryDAO = FreshRSS_Factory::createEntryDao(); + + Minz_Session::_param('actualize_feeds', false); + $id = Minz_Request::param ('id'); + $force = Minz_Request::param ('force', false); + + // on créé la liste des flux à mettre à actualiser + // si on veut mettre un flux à jour spécifiquement, on le met + // dans la liste, mais seul (permet d'automatiser le traitement) + $feeds = array (); + if ($id) { + $feed = $feedDAO->searchById ($id); + if ($feed) { + $feeds = array ($feed); + } + } else { + $feeds = $feedDAO->listFeedsOrderUpdate($this->view->conf->ttl_default); + } + + // on calcule la date des articles les plus anciens qu'on accepte + $nb_month_old = max($this->view->conf->old_entries, 1); + $date_min = time () - (3600 * 24 * 30 * $nb_month_old); + + $i = 0; + $flux_update = 0; + $is_read = $this->view->conf->mark_when['reception'] ? 1 : 0; + foreach ($feeds as $feed) { + if (!$feed->lock()) { + Minz_Log::record('Feed already being actualized: ' . $feed->url(), Minz_Log::NOTICE); + continue; + } + try { + $url = $feed->url(); + $feedHistory = $feed->keepHistory(); + + $feed->load(false); + $entries = array_reverse($feed->entries()); //We want chronological order and SimplePie uses reverse order + $hasTransaction = false; + + if (count($entries) > 0) { + //For this feed, check last n entry GUIDs already in database + $existingGuids = array_fill_keys ($entryDAO->listLastGuidsByFeed ($feed->id (), count($entries) + 10), 1); + $useDeclaredDate = empty($existingGuids); + + if ($feedHistory == -2) { //default + $feedHistory = $this->view->conf->keep_history_default; + } + + $preparedStatement = $entryDAO->addEntryPrepare(); + $hasTransaction = true; + $feedDAO->beginTransaction(); + + // On ne vérifie pas strictement que l'article n'est pas déjà en BDD + // La BDD refusera l'ajout car (id_feed, guid) doit être unique + foreach ($entries as $entry) { + $eDate = $entry->date(true); + if ((!isset($existingGuids[$entry->guid()])) && + (($feedHistory != 0) || ($eDate >= $date_min))) { + $values = $entry->toArray(); + //Use declared date at first import, otherwise use discovery date + $values['id'] = ($useDeclaredDate || $eDate < $date_min) ? + min(time(), $eDate) . uSecString() : + uTimeString(); + $values['is_read'] = $is_read; + $entryDAO->addEntry($values, $preparedStatement); + } + } + } + + if (($feedHistory >= 0) && (rand(0, 30) === 1)) { + if (!$hasTransaction) { + $feedDAO->beginTransaction(); + } + $nb = $feedDAO->cleanOldEntries ($feed->id (), $date_min, max($feedHistory, count($entries) + 10)); + if ($nb > 0) { + Minz_Log::record ($nb . ' old entries cleaned in feed [' . $feed->url() . ']', Minz_Log::DEBUG); + } + } + + // on indique que le flux vient d'être mis à jour en BDD + $feedDAO->updateLastUpdate ($feed->id (), 0, $hasTransaction); + if ($hasTransaction) { + $feedDAO->commit(); + } + $flux_update++; + if (($feed->url() !== $url)) { //HTTP 301 Moved Permanently + Minz_Log::record('Feed ' . $url . ' moved permanently to ' . $feed->url(), Minz_Log::NOTICE); + $feedDAO->updateFeed($feed->id(), array('url' => $feed->url())); + } + } catch (FreshRSS_Feed_Exception $e) { + Minz_Log::record ($e->getMessage (), Minz_Log::NOTICE); + $feedDAO->updateLastUpdate ($feed->id (), 1); + } + + $feed->faviconPrepare(); + $feed->unlock(); + unset($feed); + + // On arrête à 10 flux pour ne pas surcharger le serveur + // sauf si le paramètre $force est à vrai + $i++; + if ($i >= 10 && !$force) { + break; + } + } + + $url = array (); + if ($flux_update === 1) { + // on a mis un seul flux à jour + $feed = reset ($feeds); + $notif = array ( + 'type' => 'good', + 'content' => Minz_Translate::t ('feed_actualized', $feed->name ()) + ); + } elseif ($flux_update > 1) { + // plusieurs flux on été mis à jour + $notif = array ( + 'type' => 'good', + 'content' => Minz_Translate::t ('n_feeds_actualized', $flux_update) + ); + } else { + // aucun flux n'a été mis à jour, oups + $notif = array ( + 'type' => 'good', + 'content' => Minz_Translate::t ('no_feed_to_refresh') + ); + } + + if ($i === 1) { + // Si on a voulu mettre à jour qu'un flux + // on filtre l'affichage par ce flux + $feed = reset ($feeds); + $url['params'] = array ('get' => 'f_' . $feed->id ()); + } + + if (Minz_Request::param ('ajax', 0) === 0) { + Minz_Session::_param ('notification', $notif); + Minz_Request::forward ($url, true); + } else { + // Une requête Ajax met un seul flux à jour. + // Comme en principe plusieurs requêtes ont lieu, + // on indique que "plusieurs flux ont été mis à jour". + // Cela permet d'avoir une notification plus proche du + // ressenti utilisateur + $notif = array ( + 'type' => 'good', + 'content' => Minz_Translate::t ('feeds_actualized') + ); + Minz_Session::_param ('notification', $notif); + // et on désactive le layout car ne sert à rien + $this->view->_useLayout (false); + } + } + + public function deleteAction () { + if (Minz_Request::isPost ()) { + $type = Minz_Request::param ('type', 'feed'); + $id = Minz_Request::param ('id'); + + $feedDAO = FreshRSS_Factory::createFeedDao(); + if ($type == 'category') { + if ($feedDAO->deleteFeedByCategory ($id)) { + $notif = array ( + 'type' => 'good', + 'content' => Minz_Translate::t ('category_emptied') + ); + //TODO: Delete old favicons + } else { + $notif = array ( + 'type' => 'bad', + 'content' => Minz_Translate::t ('error_occured') + ); + } + } else { + if ($feedDAO->deleteFeed ($id)) { + $notif = array ( + 'type' => 'good', + 'content' => Minz_Translate::t ('feed_deleted') + ); + //TODO: Delete old favicon + } else { + $notif = array ( + 'type' => 'bad', + 'content' => Minz_Translate::t ('error_occured') + ); + } + } + + Minz_Session::_param ('notification', $notif); + + if ($type == 'category') { + Minz_Request::forward (array ('c' => 'configure', 'a' => 'categorize'), true); + } else { + Minz_Request::forward (array ('c' => 'configure', 'a' => 'feed'), true); + } + } + } +} diff --git a/sources/app/Controllers/importExportController.php b/sources/app/Controllers/importExportController.php new file mode 100755 index 0000000..ba172cc --- /dev/null +++ b/sources/app/Controllers/importExportController.php @@ -0,0 +1,391 @@ +view->loginOk) { + Minz_Error::error( + 403, + array('error' => array(Minz_Translate::t('access_denied'))) + ); + } + + require_once(LIB_PATH . '/lib_opml.php'); + + $this->catDAO = new FreshRSS_CategoryDAO(); + $this->entryDAO = FreshRSS_Factory::createEntryDao(); + $this->feedDAO = FreshRSS_Factory::createFeedDao(); + } + + public function indexAction() { + $this->view->categories = $this->catDAO->listCategories(); + $this->view->feeds = $this->feedDAO->listFeeds(); + + Minz_View::prependTitle(Minz_Translate::t('import_export') . ' · '); + } + + public function importAction() { + if (Minz_Request::isPost() && $_FILES['file']['error'] == 0) { + @set_time_limit(300); + + $file = $_FILES['file']; + $type_file = $this->guessFileType($file['name']); + + $list_files = array( + 'opml' => array(), + 'json_starred' => array(), + 'json_feed' => array() + ); + + // We try to list all files according to their type + // A zip file is first opened and then its files are listed + $list = array(); + if ($type_file === 'zip') { + $zip = zip_open($file['tmp_name']); + + while (($zipfile = zip_read($zip)) !== false) { + $type_zipfile = $this->guessFileType( + zip_entry_name($zipfile) + ); + + if ($type_file !== 'unknown') { + $list_files[$type_zipfile][] = zip_entry_read( + $zipfile, + zip_entry_filesize($zipfile) + ); + } + } + + zip_close($zip); + } elseif ($type_file !== 'unknown') { + $list_files[$type_file][] = file_get_contents( + $file['tmp_name'] + ); + } + + // Import different files. + // OPML first(so categories and feeds are imported) + // Starred articles then so the "favourite" status is already set + // And finally all other files. + $error = false; + foreach ($list_files['opml'] as $opml_file) { + $error = $this->importOpml($opml_file); + } + foreach ($list_files['json_starred'] as $article_file) { + $error = $this->importArticles($article_file, true); + } + foreach ($list_files['json_feed'] as $article_file) { + $error = $this->importArticles($article_file); + } + + // And finally, we get import status and redirect to the home page + $notif = null; + if ($error === true) { + $content_notif = Minz_Translate::t( + 'feeds_imported_with_errors' + ); + } else { + $content_notif = Minz_Translate::t( + 'feeds_imported' + ); + } + + Minz_Session::_param('notification', array( + 'type' => 'good', + 'content' => $content_notif + )); + Minz_Session::_param('actualize_feeds', true); + + Minz_Request::forward(array( + 'c' => 'index', + 'a' => 'index' + ), true); + } + + // What are you doing? you have to call this controller + // with a POST request! + Minz_Request::forward(array( + 'c' => 'importExport', + 'a' => 'index' + )); + } + + private function guessFileType($filename) { + // A *very* basic guess file type function. Only based on filename + // That's could be improved but should be enough, at least for a first + // implementation. + // TODO: improve this function? + + if (substr_compare($filename, '.zip', -4) === 0) { + return 'zip'; + } elseif (substr_compare($filename, '.opml', -5) === 0 || + substr_compare($filename, '.xml', -4) === 0) { + return 'opml'; + } elseif (strcmp($filename, 'starred.json') === 0) { + return 'json_starred'; + } elseif (substr_compare($filename, '.json', -5) === 0 && + strpos($filename, 'feed_') === 0) { + return 'json_feed'; + } else { + return 'unknown'; + } + } + + private function importOpml($opml_file) { + $opml_array = array(); + try { + $opml_array = libopml_parse_string($opml_file); + } catch (LibOPML_Exception $e) { + Minz_Log::warning($e->getMessage()); + return true; + } + + $this->catDAO->checkDefault(); + + return $this->addOpmlElements($opml_array['body']); + } + + private function addOpmlElements($opml_elements, $parent_cat = null) { + $error = false; + foreach ($opml_elements as $elt) { + $res = false; + if (isset($elt['xmlUrl'])) { + $res = $this->addFeedOpml($elt, $parent_cat); + } else { + $res = $this->addCategoryOpml($elt, $parent_cat); + } + + if (!$error && $res) { + // oops: there is at least one error! + $error = $res; + } + } + + return $error; + } + + private function addFeedOpml($feed_elt, $parent_cat) { + if (is_null($parent_cat)) { + // This feed has no parent category so we get the default one + $parent_cat = $this->catDAO->getDefault()->name(); + } + + $cat = $this->catDAO->searchByName($parent_cat); + + if (!$cat) { + return true; + } + + // We get different useful information + $url = html_chars_utf8($feed_elt['xmlUrl']); + $name = html_chars_utf8($feed_elt['text']); + $website = ''; + if (isset($feed_elt['htmlUrl'])) { + $website = html_chars_utf8($feed_elt['htmlUrl']); + } + $description = ''; + if (isset($feed_elt['description'])) { + $description = html_chars_utf8($feed_elt['description']); + } + + $error = false; + try { + // Create a Feed object and add it in DB + $feed = new FreshRSS_Feed($url); + $feed->_category($cat->id()); + $feed->_name($name); + $feed->_website($website); + $feed->_description($description); + + // addFeedObject checks if feed is already in DB so nothing else to + // check here + $id = $this->feedDAO->addFeedObject($feed); + $error = ($id === false); + } catch (FreshRSS_Feed_Exception $e) { + Minz_Log::warning($e->getMessage()); + $error = true; + } + + return $error; + } + + private function addCategoryOpml($cat_elt, $parent_cat) { + // Create a new Category object + $cat = new FreshRSS_Category(html_chars_utf8($cat_elt['text'])); + + $id = $this->catDAO->addCategoryObject($cat); + $error = ($id === false); + + if (isset($cat_elt['@outlines'])) { + // Our cat_elt contains more categories or more feeds, so we + // add them recursively. + // Note: FreshRSS does not support yet category arborescence + $res = $this->addOpmlElements($cat_elt['@outlines'], $cat->name()); + if (!$error && $res) { + $error = true; + } + } + + return $error; + } + + private function importArticles($article_file, $starred = false) { + $article_object = json_decode($article_file, true); + if (is_null($article_object)) { + Minz_Log::warning('Try to import a non-JSON file'); + return true; + } + + $is_read = $this->view->conf->mark_when['reception'] ? 1 : 0; + + $google_compliant = ( + strpos($article_object['id'], 'com.google') !== false + ); + + $error = false; + foreach ($article_object['items'] as $item) { + $feed = $this->addFeedArticles($item['origin'], $google_compliant); + if (is_null($feed)) { + $error = true; + continue; + } + + $author = isset($item['author']) ? $item['author'] : ''; + $key_content = ($google_compliant && !isset($item['content'])) ? + 'summary' : 'content'; + $tags = $item['categories']; + if ($google_compliant) { + $tags = array_filter($tags, function($var) { + return strpos($var, '/state/com.google') === false; + }); + } + + $entry = new FreshRSS_Entry( + $feed->id(), $item['id'], $item['title'], $author, + $item[$key_content]['content'], $item['alternate'][0]['href'], + $item['published'], $is_read, $starred + ); + $entry->_tags($tags); + + //FIME: Use entryDAO->addEntryPrepare(). Do not call entryDAO->listLastGuidsByFeed() for each entry. Consider using a transaction. + $id = $this->entryDAO->addEntryObject( + $entry, $this->view->conf, $feed->keepHistory() + ); + + if (!$error && ($id === false)) { + $error = true; + } + } + + return $error; + } + + private function addFeedArticles($origin, $google_compliant) { + $default_cat = $this->catDAO->getDefault(); + + $return = null; + $key = $google_compliant ? 'htmlUrl' : 'feedUrl'; + $url = $origin[$key]; + $name = $origin['title']; + $website = $origin['htmlUrl']; + $error = false; + try { + // Create a Feed object and add it in DB + $feed = new FreshRSS_Feed($url); + $feed->_category($default_cat->id()); + $feed->_name($name); + $feed->_website($website); + + // addFeedObject checks if feed is already in DB so nothing else to + // check here + $id = $this->feedDAO->addFeedObject($feed); + + if ($id !== false) { + $feed->_id($id); + $return = $feed; + } + } catch (FreshRSS_Feed_Exception $e) { + Minz_Log::warning($e->getMessage()); + } + + return $return; + } + + public function exportAction() { + if (Minz_Request::isPost()) { + $this->view->_useLayout(false); + + $export_opml = Minz_Request::param('export_opml', false); + $export_starred = Minz_Request::param('export_starred', false); + $export_feeds = Minz_Request::param('export_feeds', false); + + // From https://stackoverflow.com/questions/1061710/php-zip-files-on-the-fly + $file = tempnam('tmp', 'zip'); + $zip = new ZipArchive(); + $zip->open($file, ZipArchive::OVERWRITE); + + // Stuff with content + if ($export_opml) { + $zip->addFromString( + 'feeds.opml', $this->generateOpml() + ); + } + if ($export_starred) { + $zip->addFromString( + 'starred.json', $this->generateArticles('starred') + ); + } + foreach ($export_feeds as $feed_id) { + $feed = $this->feedDAO->searchById($feed_id); + $zip->addFromString( + 'feed_' . $feed->category() . '_' . $feed->id() . '.json', + $this->generateArticles('feed', $feed) + ); + } + + // Close and send to user + $zip->close(); + header('Content-Type: application/zip'); + header('Content-Length: ' . filesize($file)); + header('Content-Disposition: attachment; filename="freshrss_export.zip"'); + readfile($file); + unlink($file); + } + } + + private function generateOpml() { + $list = array(); + foreach ($this->catDAO->listCategories() as $key => $cat) { + $list[$key]['name'] = $cat->name(); + $list[$key]['feeds'] = $this->feedDAO->listByCategory($cat->id()); + } + + $this->view->categories = $list; + return $this->view->helperToString('export/opml'); + } + + private function generateArticles($type, $feed = NULL) { + $this->view->categories = $this->catDAO->listCategories(); + + if ($type == 'starred') { + $this->view->list_title = Minz_Translate::t('starred_list'); + $this->view->type = 'starred'; + $unread_fav = $this->entryDAO->countUnreadReadFavorites(); + $this->view->entries = $this->entryDAO->listWhere( + 's', '', FreshRSS_Entry::STATE_ALL, 'ASC', + $unread_fav['all'] + ); + } elseif ($type == 'feed' && !is_null($feed)) { + $this->view->list_title = Minz_Translate::t( + 'feed_list', $feed->name() + ); + $this->view->type = 'feed/' . $feed->id(); + $this->view->entries = $this->entryDAO->listWhere( + 'f', $feed->id(), FreshRSS_Entry::STATE_ALL, 'ASC', + $this->view->conf->posts_per_page + ); + $this->view->feed = $feed; + } + + return $this->view->helperToString('export/articles'); + } +} diff --git a/sources/app/Controllers/indexController.php b/sources/app/Controllers/indexController.php new file mode 100755 index 0000000..9a46bde --- /dev/null +++ b/sources/app/Controllers/indexController.php @@ -0,0 +1,379 @@ +view->conf->token; + + // check if user is logged in + if (!$this->view->loginOk && !Minz_Configuration::allowAnonymous()) { + $token_param = Minz_Request::param ('token', ''); + $token_is_ok = ($token != '' && $token === $token_param); + if ($output === 'rss' && !$token_is_ok) { + Minz_Error::error ( + 403, + array ('error' => array (Minz_Translate::t ('access_denied'))) + ); + return; + } elseif ($output !== 'rss') { + // "hard" redirection is not required, just ask dispatcher to + // forward to the login form without 302 redirection + Minz_Request::forward(array('c' => 'index', 'a' => 'formLogin')); + return; + } + } + + $params = Minz_Request::params (); + if (isset ($params['search'])) { + $params['search'] = urlencode ($params['search']); + } + + $this->view->url = array ( + 'c' => 'index', + 'a' => 'index', + 'params' => $params + ); + + if ($output === 'rss') { + // no layout for RSS output + $this->view->_useLayout (false); + header('Content-Type: application/rss+xml; charset=utf-8'); + } elseif ($output === 'global') { + Minz_View::appendScript (Minz_Url::display ('/scripts/global_view.js?' . @filemtime(PUBLIC_PATH . '/scripts/global_view.js'))); + } + + $catDAO = new FreshRSS_CategoryDAO(); + $entryDAO = FreshRSS_Factory::createEntryDao(); + + $this->view->cat_aside = $catDAO->listCategories (); + $this->view->nb_favorites = $entryDAO->countUnreadReadFavorites (); + $this->view->nb_not_read = FreshRSS_CategoryDAO::CountUnreads($this->view->cat_aside, 1); + $this->view->currentName = ''; + + $this->view->get_c = ''; + $this->view->get_f = ''; + + $get = Minz_Request::param ('get', 'a'); + $getType = $get[0]; + $getId = substr ($get, 2); + if (!$this->checkAndProcessType ($getType, $getId)) { + Minz_Log::record ('Not found [' . $getType . '][' . $getId . ']', Minz_Log::DEBUG); + Minz_Error::error ( + 404, + array ('error' => array (Minz_Translate::t ('page_not_found'))) + ); + return; + } + + // mise à jour des titres + $this->view->rss_title = $this->view->currentName . ' | ' . Minz_View::title(); + if ($this->view->nb_not_read > 0) { + Minz_View::prependTitle('(' . formatNumber($this->view->nb_not_read) . ') '); + } + Minz_View::prependTitle( + ($this->nb_not_read_cat > 0 ? '(' . formatNumber($this->nb_not_read_cat) . ') ' : '') . + $this->view->currentName . + ' · ' + ); + + // On récupère les différents éléments de filtrage + $this->view->state = $state = Minz_Request::param ('state', $this->view->conf->default_view); + $state_param = Minz_Request::param ('state', null); + $filter = Minz_Request::param ('search', ''); + $this->view->order = $order = Minz_Request::param ('order', $this->view->conf->sort_order); + $nb = Minz_Request::param ('nb', $this->view->conf->posts_per_page); + $first = Minz_Request::param ('next', ''); + + if ($state === FreshRSS_Entry::STATE_NOT_READ) { //Any unread article in this category at all? + switch ($getType) { + case 'a': + $hasUnread = $this->view->nb_not_read > 0; + break; + case 's': + // This is deprecated. The favorite button does not exist anymore + $hasUnread = $this->view->nb_favorites['unread'] > 0; + break; + case 'c': + $hasUnread = (!isset($this->view->cat_aside[$getId])) || ($this->view->cat_aside[$getId]->nbNotRead() > 0); + break; + case 'f': + $myFeed = FreshRSS_CategoryDAO::findFeed($this->view->cat_aside, $getId); + $hasUnread = ($myFeed === null) || ($myFeed->nbNotRead() > 0); + break; + default: + $hasUnread = true; + break; + } + if (!$hasUnread && ($state_param === null)) { + $this->view->state = $state = FreshRSS_Entry::STATE_ALL; + } + } + + $today = @strtotime('today'); + $this->view->today = $today; + + // on calcule la date des articles les plus anciens qu'on affiche + $nb_month_old = $this->view->conf->old_entries; + $date_min = $today - (3600 * 24 * 30 * $nb_month_old); //Do not use a fast changing value such as time() to allow SQL caching + $keepHistoryDefault = $this->view->conf->keep_history_default; + + try { + $entries = $entryDAO->listWhere($getType, $getId, $state, $order, $nb + 1, $first, $filter, $date_min, true, $keepHistoryDefault); + + // Si on a récupéré aucun article "non lus" + // on essaye de récupérer tous les articles + if ($state === FreshRSS_Entry::STATE_NOT_READ && empty($entries) && ($state_param === null) && ($filter == '')) { + Minz_Log::record('Conflicting information about nbNotRead!', Minz_Log::DEBUG); + $feedDAO = FreshRSS_Factory::createFeedDao(); + try { + $feedDAO->updateCachedValues(); + } catch (Exception $ex) { + Minz_Log::record('Failed to automatically correct nbNotRead! ' + $ex->getMessage(), Minz_Log::NOTICE); + } + $this->view->state = FreshRSS_Entry::STATE_ALL; + $entries = $entryDAO->listWhere($getType, $getId, $this->view->state, $order, $nb, $first, $filter, $date_min, true, $keepHistoryDefault); + } + + if (count($entries) <= $nb) { + $this->view->nextId = ''; + } else { //We have more elements for pagination + $lastEntry = array_pop($entries); + $this->view->nextId = $lastEntry->id(); + } + + $this->view->entries = $entries; + } catch (FreshRSS_EntriesGetter_Exception $e) { + Minz_Log::record ($e->getMessage (), Minz_Log::NOTICE); + Minz_Error::error ( + 404, + array ('error' => array (Minz_Translate::t ('page_not_found'))) + ); + } + } + + /* + * Vérifie que la catégorie / flux sélectionné existe + * + Initialise correctement les variables de vue get_c et get_f + * + Met à jour la variable $this->nb_not_read_cat + */ + private function checkAndProcessType ($getType, $getId) { + switch ($getType) { + case 'a': + $this->view->currentName = Minz_Translate::t ('your_rss_feeds'); + $this->nb_not_read_cat = $this->view->nb_not_read; + $this->view->get_c = $getType; + return true; + case 's': + $this->view->currentName = Minz_Translate::t ('your_favorites'); + $this->nb_not_read_cat = $this->view->nb_favorites['unread']; + $this->view->get_c = $getType; + return true; + case 'c': + $cat = isset($this->view->cat_aside[$getId]) ? $this->view->cat_aside[$getId] : null; + if ($cat === null) { + $catDAO = new FreshRSS_CategoryDAO(); + $cat = $catDAO->searchById($getId); + } + if ($cat) { + $this->view->currentName = $cat->name (); + $this->nb_not_read_cat = $cat->nbNotRead (); + $this->view->get_c = $getId; + return true; + } else { + return false; + } + case 'f': + $feed = FreshRSS_CategoryDAO::findFeed($this->view->cat_aside, $getId); + if (empty($feed)) { + $feedDAO = FreshRSS_Factory::createFeedDao(); + $feed = $feedDAO->searchById($getId); + } + if ($feed) { + $this->view->currentName = $feed->name (); + $this->nb_not_read_cat = $feed->nbNotRead (); + $this->view->get_f = $getId; + $this->view->get_c = $feed->category (); + return true; + } else { + return false; + } + default: + return false; + } + } + + public function aboutAction () { + Minz_View::prependTitle (Minz_Translate::t ('about') . ' · '); + } + + public function logsAction () { + if (!$this->view->loginOk) { + Minz_Error::error ( + 403, + array ('error' => array (Minz_Translate::t ('access_denied'))) + ); + } + + Minz_View::prependTitle (Minz_Translate::t ('logs') . ' · '); + + if (Minz_Request::isPost ()) { + FreshRSS_LogDAO::truncate(); + } + + $logs = FreshRSS_LogDAO::lines(); //TODO: ask only the necessary lines + + //gestion pagination + $page = Minz_Request::param ('page', 1); + $this->view->logsPaginator = new Minz_Paginator ($logs); + $this->view->logsPaginator->_nbItemsPerPage (50); + $this->view->logsPaginator->_currentPage ($page); + } + + public function loginAction () { + $this->view->_useLayout (false); + + $url = 'https://verifier.login.persona.org/verify'; + $assert = Minz_Request::param ('assertion'); + $params = 'assertion=' . $assert . '&audience=' . + urlencode (Minz_Url::display (null, 'php', true)); + $ch = curl_init (); + $options = array ( + CURLOPT_URL => $url, + CURLOPT_RETURNTRANSFER => TRUE, + CURLOPT_POST => 2, + CURLOPT_POSTFIELDS => $params + ); + curl_setopt_array ($ch, $options); + $result = curl_exec ($ch); + curl_close ($ch); + + $res = json_decode ($result, true); + + $loginOk = false; + $reason = ''; + if ($res['status'] === 'okay') { + $email = filter_var($res['email'], FILTER_VALIDATE_EMAIL); + if ($email != '') { + $personaFile = DATA_PATH . '/persona/' . $email . '.txt'; + if (($currentUser = @file_get_contents($personaFile)) !== false) { + $currentUser = trim($currentUser); + if (ctype_alnum($currentUser)) { + try { + $this->conf = new FreshRSS_Configuration($currentUser); + $loginOk = strcasecmp($email, $this->conf->mail_login) === 0; + } catch (Minz_Exception $e) { + $reason = 'Invalid configuration for user [' . $currentUser . ']! ' . $e->getMessage(); //Permission denied or conf file does not exist + } + } else { + $reason = 'Invalid username format [' . $currentUser . ']!'; + } + } + } else { + $reason = 'Invalid email format [' . $res['email'] . ']!'; + } + } + if ($loginOk) { + Minz_Session::_param('currentUser', $currentUser); + Minz_Session::_param ('mail', $email); + $this->view->loginOk = true; + invalidateHttpCache(); + } else { + $res = array (); + $res['status'] = 'failure'; + $res['reason'] = $reason == '' ? Minz_Translate::t ('invalid_login') : $reason; + Minz_Log::record ('Persona: ' . $res['reason'], Minz_Log::WARNING); + } + + header('Content-Type: application/json; charset=UTF-8'); + $this->view->res = json_encode ($res); + } + + public function logoutAction () { + $this->view->_useLayout(false); + invalidateHttpCache(); + Minz_Session::_param('currentUser'); + Minz_Session::_param('mail'); + Minz_Session::_param('passwordHash'); + } + + public function formLoginAction () { + if (Minz_Request::isPost()) { + $ok = false; + $nonce = Minz_Session::param('nonce'); + $username = Minz_Request::param('username', ''); + $c = Minz_Request::param('challenge', ''); + if (ctype_alnum($username) && ctype_graph($c) && ctype_alnum($nonce)) { + if (!function_exists('password_verify')) { + include_once(LIB_PATH . '/password_compat.php'); + } + try { + $conf = new FreshRSS_Configuration($username); + $s = $conf->passwordHash; + $ok = password_verify($nonce . $s, $c); + if ($ok) { + Minz_Session::_param('currentUser', $username); + Minz_Session::_param('passwordHash', $s); + } else { + Minz_Log::record('Password mismatch for user ' . $username . ', nonce=' . $nonce . ', c=' . $c, Minz_Log::WARNING); + } + } catch (Minz_Exception $me) { + Minz_Log::record('Login failure: ' . $me->getMessage(), Minz_Log::WARNING); + } + } else { + Minz_Log::record('Invalid credential parameters: user=' . $username . ' challenge=' . $c . ' nonce=' . $nonce, Minz_Log::DEBUG); + } + if (!$ok) { + $notif = array( + 'type' => 'bad', + 'content' => Minz_Translate::t('invalid_login') + ); + Minz_Session::_param('notification', $notif); + } + $this->view->_useLayout(false); + Minz_Request::forward(array('c' => 'index', 'a' => 'index'), true); + } elseif (Minz_Configuration::unsafeAutologinEnabled() && isset($_GET['u']) && isset($_GET['p'])) { + Minz_Session::_param('currentUser'); + Minz_Session::_param('mail'); + Minz_Session::_param('passwordHash'); + $username = ctype_alnum($_GET['u']) ? $_GET['u'] : ''; + $passwordPlain = $_GET['p']; + Minz_Request::_param('p'); //Discard plain-text password ASAP + $_GET['p'] = ''; + if (!function_exists('password_verify')) { + include_once(LIB_PATH . '/password_compat.php'); + } + try { + $conf = new FreshRSS_Configuration($username); + $s = $conf->passwordHash; + $ok = password_verify($passwordPlain, $s); + unset($passwordPlain); + if ($ok) { + Minz_Session::_param('currentUser', $username); + Minz_Session::_param('passwordHash', $s); + } else { + Minz_Log::record('Unsafe password mismatch for user ' . $username, Minz_Log::WARNING); + } + } catch (Minz_Exception $me) { + Minz_Log::record('Unsafe login failure: ' . $me->getMessage(), Minz_Log::WARNING); + } + Minz_Request::forward(array('c' => 'index', 'a' => 'index'), true); + } elseif (!Minz_Configuration::canLogIn()) { + Minz_Error::error ( + 403, + array ('error' => array (Minz_Translate::t ('access_denied'))) + ); + } + invalidateHttpCache(); + } + + public function formLogoutAction () { + $this->view->_useLayout(false); + invalidateHttpCache(); + Minz_Session::_param('currentUser'); + Minz_Session::_param('mail'); + Minz_Session::_param('passwordHash'); + Minz_Request::forward(array('c' => 'index', 'a' => 'index'), true); + } +} diff --git a/sources/app/Controllers/javascriptController.php b/sources/app/Controllers/javascriptController.php new file mode 100755 index 0000000..6714835 --- /dev/null +++ b/sources/app/Controllers/javascriptController.php @@ -0,0 +1,46 @@ +view->_useLayout (false); + } + + public function actualizeAction () { + header('Content-Type: text/javascript; charset=UTF-8'); + $feedDAO = FreshRSS_Factory::createFeedDao(); + $this->view->feeds = $feedDAO->listFeedsOrderUpdate($this->view->conf->ttl_default); + } + + public function nbUnreadsPerFeedAction() { + header('Content-Type: application/json; charset=UTF-8'); + $catDAO = new FreshRSS_CategoryDAO(); + $this->view->categories = $catDAO->listCategories(true, false); + } + + //For Web-form login + public function nonceAction() { + header('Content-Type: application/json; charset=UTF-8'); + header('Last-Modified: ' . gmdate('D, d M Y H:i:s \G\M\T')); + header('Expires: 0'); + header('Cache-Control: private, no-cache, no-store, must-revalidate'); + header('Pragma: no-cache'); + + $user = isset($_GET['user']) ? $_GET['user'] : ''; + if (ctype_alnum($user)) { + try { + $conf = new FreshRSS_Configuration($user); + $s = $conf->passwordHash; + if (strlen($s) >= 60) { + $this->view->salt1 = substr($s, 0, 29); //CRYPT_BLOWFISH Salt: "$2a$", a two digit cost parameter, "$", and 22 characters from the alphabet "./0-9A-Za-z". + $this->view->nonce = sha1(Minz_Configuration::salt() . uniqid(mt_rand(), true)); + Minz_Session::_param('nonce', $this->view->nonce); + return; //Success + } + } catch (Minz_Exception $me) { + Minz_Log::record('Nonce failure: ' . $me->getMessage(), Minz_Log::WARNING); + } + } + $this->view->nonce = ''; //Failure + $this->view->salt1 = ''; + } +} diff --git a/sources/app/Controllers/statsController.php b/sources/app/Controllers/statsController.php new file mode 100755 index 0000000..9009468 --- /dev/null +++ b/sources/app/Controllers/statsController.php @@ -0,0 +1,67 @@ +view->repartition = $statsDAO->calculateEntryRepartition(); + $this->view->count = ($statsDAO->calculateEntryCount()); + $this->view->feedByCategory = $statsDAO->calculateFeedByCategory(); + $this->view->entryByCategory = $statsDAO->calculateEntryByCategory(); + $this->view->topFeed = $statsDAO->calculateTopFeed(); + } + + public function idleAction() { + $statsDAO = FreshRSS_Factory::createStatsDAO(); + $feeds = $statsDAO->calculateFeedLastDate(); + $idleFeeds = array(); + $now = new \DateTime(); + $feedDate = clone $now; + $lastWeek = clone $now; + $lastWeek->modify('-1 week'); + $lastMonth = clone $now; + $lastMonth->modify('-1 month'); + $last3Month = clone $now; + $last3Month->modify('-3 month'); + $last6Month = clone $now; + $last6Month->modify('-6 month'); + $lastYear = clone $now; + $lastYear->modify('-1 year'); + + foreach ($feeds as $feed) { + $feedDate->setTimestamp($feed['last_date']); + if ($feedDate >= $lastWeek) { + continue; + } + if ($feedDate < $lastWeek) { + $idleFeeds['last_week'][] = $feed['name']; + } + if ($feedDate < $lastMonth) { + $idleFeeds['last_month'][] = $feed['name']; + } + if ($feedDate < $last3Month) { + $idleFeeds['last_3_month'][] = $feed['name']; + } + if ($feedDate < $last6Month) { + $idleFeeds['last_6_month'][] = $feed['name']; + } + if ($feedDate < $lastYear) { + $idleFeeds['last_year'][] = $feed['name']; + } + } + + $this->view->idleFeeds = array_reverse($idleFeeds); + } + + public function firstAction() { + if (!$this->view->loginOk) { + Minz_Error::error( + 403, array('error' => array(Minz_Translate::t('access_denied'))) + ); + } + + Minz_View::prependTitle(Minz_Translate::t('stats') . ' · '); + } + +} diff --git a/sources/app/Controllers/usersController.php b/sources/app/Controllers/usersController.php new file mode 100755 index 0000000..35fa367 --- /dev/null +++ b/sources/app/Controllers/usersController.php @@ -0,0 +1,203 @@ +view->loginOk) { + Minz_Error::error( + 403, + array('error' => array(Minz_Translate::t('access_denied'))) + ); + } + } + + public function authAction() { + if (Minz_Request::isPost()) { + $ok = true; + + $passwordPlain = Minz_Request::param('passwordPlain', '', true); + if ($passwordPlain != '') { + Minz_Request::_param('passwordPlain'); //Discard plain-text password ASAP + $_POST['passwordPlain'] = ''; + if (!function_exists('password_hash')) { + include_once(LIB_PATH . '/password_compat.php'); + } + $passwordHash = password_hash($passwordPlain, PASSWORD_BCRYPT, array('cost' => self::BCRYPT_COST)); + $passwordPlain = ''; + $passwordHash = preg_replace('/^\$2[xy]\$/', '\$2a\$', $passwordHash); //Compatibility with bcrypt.js + $ok &= ($passwordHash != ''); + $this->view->conf->_passwordHash($passwordHash); + } + Minz_Session::_param('passwordHash', $this->view->conf->passwordHash); + + $passwordPlain = Minz_Request::param('apiPasswordPlain', '', true); + if ($passwordPlain != '') { + if (!function_exists('password_hash')) { + include_once(LIB_PATH . '/password_compat.php'); + } + $passwordHash = password_hash($passwordPlain, PASSWORD_BCRYPT, array('cost' => self::BCRYPT_COST)); + $passwordPlain = ''; + $passwordHash = preg_replace('/^\$2[xy]\$/', '\$2a\$', $passwordHash); //Compatibility with bcrypt.js + $ok &= ($passwordHash != ''); + $this->view->conf->_apiPasswordHash($passwordHash); + } + + if (Minz_Configuration::isAdmin(Minz_Session::param('currentUser', '_'))) { + $this->view->conf->_mail_login(Minz_Request::param('mail_login', '', true)); + } + $email = $this->view->conf->mail_login; + Minz_Session::_param('mail', $email); + + $ok &= $this->view->conf->save(); + + if ($email != '') { + $personaFile = DATA_PATH . '/persona/' . $email . '.txt'; + @unlink($personaFile); + $ok &= (file_put_contents($personaFile, Minz_Session::param('currentUser', '_')) !== false); + } + + if (Minz_Configuration::isAdmin(Minz_Session::param('currentUser', '_'))) { + $current_token = $this->view->conf->token; + $token = Minz_Request::param('token', $current_token); + $this->view->conf->_token($token); + $ok &= $this->view->conf->save(); + + $anon = Minz_Request::param('anon_access', false); + $anon = ((bool)$anon) && ($anon !== 'no'); + $anon_refresh = Minz_Request::param('anon_refresh', false); + $anon_refresh = ((bool)$anon_refresh) && ($anon_refresh !== 'no'); + $auth_type = Minz_Request::param('auth_type', 'none'); + $unsafe_autologin = Minz_Request::param('unsafe_autologin', false); + $api_enabled = Minz_Request::param('api_enabled', false); + if ($anon != Minz_Configuration::allowAnonymous() || + $auth_type != Minz_Configuration::authType() || + $anon_refresh != Minz_Configuration::allowAnonymousRefresh() || + $unsafe_autologin != Minz_Configuration::unsafeAutologinEnabled() || + $api_enabled != Minz_Configuration::apiEnabled()) { + + Minz_Configuration::_authType($auth_type); + Minz_Configuration::_allowAnonymous($anon); + Minz_Configuration::_allowAnonymousRefresh($anon_refresh); + Minz_Configuration::_enableAutologin($unsafe_autologin); + Minz_Configuration::_enableApi($api_enabled); + $ok &= Minz_Configuration::writeFile(); + } + } + + invalidateHttpCache(); + + $notif = array( + 'type' => $ok ? 'good' : 'bad', + 'content' => Minz_Translate::t($ok ? 'configuration_updated' : 'error_occurred') + ); + Minz_Session::_param('notification', $notif); + } + Minz_Request::forward(array('c' => 'configure', 'a' => 'users'), true); + } + + public function createAction() { + if (Minz_Request::isPost() && Minz_Configuration::isAdmin(Minz_Session::param('currentUser', '_'))) { + $db = Minz_Configuration::dataBase(); + require_once(APP_PATH . '/SQL/sql.' . $db['type'] . '.php'); + + $new_user_language = Minz_Request::param('new_user_language', $this->view->conf->language); + if (!in_array($new_user_language, $this->view->conf->availableLanguages())) { + $new_user_language = $this->view->conf->language; + } + + $new_user_name = Minz_Request::param('new_user_name'); + $ok = ($new_user_name != '') && ctype_alnum($new_user_name); + + if ($ok) { + $ok &= (strcasecmp($new_user_name, Minz_Configuration::defaultUser()) !== 0); //It is forbidden to alter the default user + + $ok &= !in_array(strtoupper($new_user_name), array_map('strtoupper', listUsers())); //Not an existing user, case-insensitive + + $configPath = DATA_PATH . '/' . $new_user_name . '_user.php'; + $ok &= !file_exists($configPath); + } + if ($ok) { + + $passwordPlain = Minz_Request::param('new_user_passwordPlain', '', true); + $passwordHash = ''; + if ($passwordPlain != '') { + Minz_Request::_param('new_user_passwordPlain'); //Discard plain-text password ASAP + $_POST['new_user_passwordPlain'] = ''; + if (!function_exists('password_hash')) { + include_once(LIB_PATH . '/password_compat.php'); + } + $passwordHash = password_hash($passwordPlain, PASSWORD_BCRYPT, array('cost' => self::BCRYPT_COST)); + $passwordPlain = ''; + $passwordHash = preg_replace('/^\$2[xy]\$/', '\$2a\$', $passwordHash); //Compatibility with bcrypt.js + $ok &= ($passwordHash != ''); + } + if (empty($passwordHash)) { + $passwordHash = ''; + } + + $new_user_email = filter_var($_POST['new_user_email'], FILTER_VALIDATE_EMAIL); + if (empty($new_user_email)) { + $new_user_email = ''; + } else { + $personaFile = DATA_PATH . '/persona/' . $new_user_email . '.txt'; + @unlink($personaFile); + $ok &= (file_put_contents($personaFile, $new_user_name) !== false); + } + } + if ($ok) { + $config_array = array( + 'language' => $new_user_language, + 'passwordHash' => $passwordHash, + 'mail_login' => $new_user_email, + ); + $ok &= (file_put_contents($configPath, "createUser($new_user_name); + } + invalidateHttpCache(); + + $notif = array( + 'type' => $ok ? 'good' : 'bad', + 'content' => Minz_Translate::t($ok ? 'user_created' : 'error_occurred', $new_user_name) + ); + Minz_Session::_param('notification', $notif); + } + Minz_Request::forward(array('c' => 'configure', 'a' => 'users'), true); + } + + public function deleteAction() { + if (Minz_Request::isPost() && Minz_Configuration::isAdmin(Minz_Session::param('currentUser', '_'))) { + $db = Minz_Configuration::dataBase(); + require_once(APP_PATH . '/SQL/sql.' . $db['type'] . '.php'); + + $username = Minz_Request::param('username'); + $ok = ctype_alnum($username); + + if ($ok) { + $ok &= (strcasecmp($username, Minz_Configuration::defaultUser()) !== 0); //It is forbidden to delete the default user + } + if ($ok) { + $configPath = DATA_PATH . '/' . $username . '_user.php'; + $ok &= file_exists($configPath); + } + if ($ok) { + $userDAO = new FreshRSS_UserDAO(); + $ok &= $userDAO->deleteUser($username); + $ok &= unlink($configPath); + //TODO: delete Persona file + } + invalidateHttpCache(); + + $notif = array( + 'type' => $ok ? 'good' : 'bad', + 'content' => Minz_Translate::t($ok ? 'user_deleted' : 'error_occurred', $username) + ); + Minz_Session::_param('notification', $notif); + } + Minz_Request::forward(array('c' => 'configure', 'a' => 'users'), true); + } +} diff --git a/sources/app/Exceptions/BadUrlException.php b/sources/app/Exceptions/BadUrlException.php new file mode 100755 index 0000000..7d1fe11 --- /dev/null +++ b/sources/app/Exceptions/BadUrlException.php @@ -0,0 +1,6 @@ +accessControl(Minz_Session::param('currentUser', '')); + $this->loadParamsView(); + $this->loadStylesAndScripts($loginOk); //TODO: Do not load that when not needed, e.g. some Ajax requests + $this->loadNotifications(); + } + + private function accessControl($currentUser) { + if ($currentUser == '') { + switch (Minz_Configuration::authType()) { + case 'form': + $currentUser = Minz_Configuration::defaultUser(); + Minz_Session::_param('passwordHash'); + $loginOk = false; + break; + case 'http_auth': + $currentUser = httpAuthUser(); + $loginOk = $currentUser != ''; + break; + case 'persona': + $loginOk = false; + $email = filter_var(Minz_Session::param('mail'), FILTER_VALIDATE_EMAIL); + if ($email != '') { //TODO: Remove redundancy with indexController + $personaFile = DATA_PATH . '/persona/' . $email . '.txt'; + if (($currentUser = @file_get_contents($personaFile)) !== false) { + $currentUser = trim($currentUser); + $loginOk = true; + } + } + if (!$loginOk) { + $currentUser = Minz_Configuration::defaultUser(); + } + break; + case 'none': + $currentUser = Minz_Configuration::defaultUser(); + $loginOk = true; + break; + default: + $currentUser = Minz_Configuration::defaultUser(); + $loginOk = false; + break; + } + } else { + $loginOk = true; + } + + if (!ctype_alnum($currentUser)) { + Minz_Session::_param('currentUser', ''); + die('Invalid username [' . $currentUser . ']!'); + } + + try { + $this->conf = new FreshRSS_Configuration($currentUser); + Minz_View::_param ('conf', $this->conf); + Minz_Session::_param('currentUser', $currentUser); + } catch (Minz_Exception $me) { + $loginOk = false; + try { + $this->conf = new FreshRSS_Configuration(Minz_Configuration::defaultUser()); + Minz_Session::_param('currentUser', Minz_Configuration::defaultUser()); + Minz_View::_param('conf', $this->conf); + $notif = array( + 'type' => 'bad', + 'content' => 'Invalid configuration for user [' . $currentUser . ']!', + ); + Minz_Session::_param ('notification', $notif); + Minz_Log::record ($notif['content'] . ' ' . $me->getMessage(), Minz_Log::WARNING); + Minz_Session::_param('currentUser', ''); + } catch (Exception $e) { + die($e->getMessage()); + } + } + + if ($loginOk) { + switch (Minz_Configuration::authType()) { + case 'form': + $loginOk = Minz_Session::param('passwordHash') === $this->conf->passwordHash; + break; + case 'http_auth': + $loginOk = strcasecmp($currentUser, httpAuthUser()) === 0; + break; + case 'persona': + $loginOk = strcasecmp(Minz_Session::param('mail'), $this->conf->mail_login) === 0; + break; + case 'none': + $loginOk = true; + break; + default: + $loginOk = false; + break; + } + } + Minz_View::_param ('loginOk', $loginOk); + return $loginOk; + } + + private function loadParamsView () { + Minz_Session::_param ('language', $this->conf->language); + Minz_Translate::init(); + $output = Minz_Request::param ('output', ''); + if (($output === '') || ($output !== 'normal' && $output !== 'rss' && $output !== 'reader' && $output !== 'global')) { + $output = $this->conf->view_mode; + Minz_Request::_param ('output', $output); + } + } + + private function loadStylesAndScripts ($loginOk) { + $theme = FreshRSS_Themes::load($this->conf->theme); + if ($theme) { + foreach($theme['files'] as $file) { + Minz_View::appendStyle (Minz_Url::display ('/themes/' . $theme['id'] . '/' . $file . '?' . @filemtime(PUBLIC_PATH . '/themes/' . $theme['id'] . '/' . $file))); + } + } + + switch (Minz_Configuration::authType()) { + case 'form': + if (!$loginOk) { + Minz_View::appendScript(Minz_Url::display ('/scripts/bcrypt.min.js?' . @filemtime(PUBLIC_PATH . '/scripts/bcrypt.min.js'))); + } + break; + case 'persona': + Minz_View::appendScript('https://login.persona.org/include.js'); + break; + } + $includeLazyLoad = $this->conf->lazyload && ($this->conf->display_posts || Minz_Request::param ('output') === 'reader'); + Minz_View::appendScript (Minz_Url::display ('/scripts/jquery.min.js?' . @filemtime(PUBLIC_PATH . '/scripts/jquery.min.js')), false, !$includeLazyLoad, !$includeLazyLoad); + if ($includeLazyLoad) { + Minz_View::appendScript (Minz_Url::display ('/scripts/jquery.lazyload.min.js?' . @filemtime(PUBLIC_PATH . '/scripts/jquery.lazyload.min.js'))); + } + Minz_View::appendScript (Minz_Url::display ('/scripts/shortcut.js?' . @filemtime(PUBLIC_PATH . '/scripts/shortcut.js'))); + Minz_View::appendScript (Minz_Url::display ('/scripts/main.js?' . @filemtime(PUBLIC_PATH . '/scripts/main.js'))); + } + + private function loadNotifications () { + $notif = Minz_Session::param ('notification'); + if ($notif) { + Minz_View::_param ('notification', $notif); + Minz_Session::_param ('notification'); + } + } +} diff --git a/sources/app/Models/Category.php b/sources/app/Models/Category.php new file mode 100755 index 0000000..0a0dbd3 --- /dev/null +++ b/sources/app/Models/Category.php @@ -0,0 +1,73 @@ +_name ($name); + if (isset ($feeds)) { + $this->_feeds ($feeds); + $this->nbFeed = 0; + $this->nbNotRead = 0; + foreach ($feeds as $feed) { + $this->nbFeed++; + $this->nbNotRead += $feed->nbNotRead (); + } + } + } + + public function id () { + return $this->id; + } + public function name () { + return $this->name; + } + public function nbFeed () { + if ($this->nbFeed < 0) { + $catDAO = new FreshRSS_CategoryDAO (); + $this->nbFeed = $catDAO->countFeed ($this->id ()); + } + + return $this->nbFeed; + } + public function nbNotRead () { + if ($this->nbNotRead < 0) { + $catDAO = new FreshRSS_CategoryDAO (); + $this->nbNotRead = $catDAO->countNotRead ($this->id ()); + } + + return $this->nbNotRead; + } + public function feeds () { + if ($this->feeds === null) { + $feedDAO = FreshRSS_Factory::createFeedDao(); + $this->feeds = $feedDAO->listByCategory ($this->id ()); + $this->nbFeed = 0; + $this->nbNotRead = 0; + foreach ($this->feeds as $feed) { + $this->nbFeed++; + $this->nbNotRead += $feed->nbNotRead (); + } + } + + return $this->feeds; + } + + public function _id ($value) { + $this->id = $value; + } + public function _name ($value) { + $this->name = $value; + } + public function _feeds ($values) { + if (!is_array ($values)) { + $values = array ($values); + } + + $this->feeds = $values; + } +} diff --git a/sources/app/Models/CategoryDAO.php b/sources/app/Models/CategoryDAO.php new file mode 100755 index 0000000..f11f87f --- /dev/null +++ b/sources/app/Models/CategoryDAO.php @@ -0,0 +1,257 @@ +prefix . 'category` (name) VALUES(?)'; + $stm = $this->bd->prepare ($sql); + + $values = array ( + substr($valuesTmp['name'], 0, 255), + ); + + if ($stm && $stm->execute ($values)) { + return $this->bd->lastInsertId(); + } else { + $info = $stm == null ? array(2 => 'syntax error') : $stm->errorInfo(); + Minz_Log::record('SQL error addCategory: ' . $info[2], Minz_Log::ERROR); + return false; + } + } + + public function addCategoryObject($category) { + $cat = $this->searchByName($category->name()); + if (!$cat) { + // Category does not exist yet in DB so we add it before continue + $values = array( + 'name' => $category->name(), + ); + return $this->addCategory($values); + } + + return $cat->id(); + } + + public function updateCategory ($id, $valuesTmp) { + $sql = 'UPDATE `' . $this->prefix . 'category` SET name=? WHERE id=?'; + $stm = $this->bd->prepare ($sql); + + $values = array ( + $valuesTmp['name'], + $id + ); + + if ($stm && $stm->execute ($values)) { + return $stm->rowCount(); + } else { + $info = $stm == null ? array(2 => 'syntax error') : $stm->errorInfo(); + Minz_Log::record('SQL error updateCategory: ' . $info[2], Minz_Log::ERROR); + return false; + } + } + + public function deleteCategory ($id) { + $sql = 'DELETE FROM `' . $this->prefix . 'category` WHERE id=?'; + $stm = $this->bd->prepare ($sql); + + $values = array ($id); + + if ($stm && $stm->execute ($values)) { + return $stm->rowCount(); + } else { + $info = $stm == null ? array(2 => 'syntax error') : $stm->errorInfo(); + Minz_Log::record('SQL error deleteCategory: ' . $info[2], Minz_Log::ERROR); + return false; + } + } + + public function searchById ($id) { + $sql = 'SELECT * FROM `' . $this->prefix . 'category` WHERE id=?'; + $stm = $this->bd->prepare ($sql); + + $values = array ($id); + + $stm->execute ($values); + $res = $stm->fetchAll (PDO::FETCH_ASSOC); + $cat = self::daoToCategory ($res); + + if (isset ($cat[0])) { + return $cat[0]; + } else { + return null; + } + } + public function searchByName ($name) { + $sql = 'SELECT * FROM `' . $this->prefix . 'category` WHERE name=?'; + $stm = $this->bd->prepare ($sql); + + $values = array ($name); + + $stm->execute ($values); + $res = $stm->fetchAll (PDO::FETCH_ASSOC); + $cat = self::daoToCategory ($res); + + if (isset ($cat[0])) { + return $cat[0]; + } else { + return null; + } + } + + 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 ') + . 'FROM `' . $this->prefix . 'category` c ' + . 'LEFT OUTER JOIN `' . $this->prefix . 'feed` f ON f.category=c.id ' + . 'GROUP BY f.id ' + . 'ORDER BY c.name, f.name'; + $stm = $this->bd->prepare ($sql); + $stm->execute (); + return self::daoToCategoryPrepopulated ($stm->fetchAll (PDO::FETCH_ASSOC)); + } else { + $sql = 'SELECT * FROM `' . $this->prefix . 'category` ORDER BY name'; + $stm = $this->bd->prepare ($sql); + $stm->execute (); + return self::daoToCategory ($stm->fetchAll (PDO::FETCH_ASSOC)); + } + } + + public function getDefault () { + $sql = 'SELECT * FROM `' . $this->prefix . 'category` WHERE id=1'; + $stm = $this->bd->prepare ($sql); + + $stm->execute (); + $res = $stm->fetchAll (PDO::FETCH_ASSOC); + $cat = self::daoToCategory ($res); + + if (isset ($cat[0])) { + return $cat[0]; + } else { + return false; + } + } + public function checkDefault () { + $def_cat = $this->searchById (1); + + if ($def_cat == null) { + $cat = new FreshRSS_Category (Minz_Translate::t ('default_category')); + $cat->_id (1); + + $values = array ( + 'id' => $cat->id (), + 'name' => $cat->name (), + ); + + $this->addCategory ($values); + } + } + + public function count () { + $sql = 'SELECT COUNT(*) AS count FROM `' . $this->prefix . 'category`'; + $stm = $this->bd->prepare ($sql); + $stm->execute (); + $res = $stm->fetchAll (PDO::FETCH_ASSOC); + + return $res[0]['count']; + } + + public function countFeed ($id) { + $sql = 'SELECT COUNT(*) AS count FROM `' . $this->prefix . 'feed` WHERE category=?'; + $stm = $this->bd->prepare ($sql); + $values = array ($id); + $stm->execute ($values); + $res = $stm->fetchAll (PDO::FETCH_ASSOC); + + return $res[0]['count']; + } + + public function countNotRead ($id) { + $sql = 'SELECT COUNT(*) AS count FROM `' . $this->prefix . 'entry` e INNER JOIN `' . $this->prefix . 'feed` f ON e.id_feed=f.id WHERE category=? AND e.is_read=0'; + $stm = $this->bd->prepare ($sql); + $values = array ($id); + $stm->execute ($values); + $res = $stm->fetchAll (PDO::FETCH_ASSOC); + + return $res[0]['count']; + } + + public static function findFeed($categories, $feed_id) { + foreach ($categories as $category) { + foreach ($category->feeds () as $feed) { + if ($feed->id () === $feed_id) { + return $feed; + } + } + } + return null; + } + + public static function CountUnreads($categories, $minPriority = 0) { + $n = 0; + foreach ($categories as $category) { + foreach ($category->feeds () as $feed) { + if ($feed->priority () >= $minPriority) { + $n += $feed->nbNotRead(); + } + } + } + return $n; + } + + public static function daoToCategoryPrepopulated ($listDAO) { + $list = array (); + + if (!is_array ($listDAO)) { + $listDAO = array ($listDAO); + } + + $previousLine = null; + $feedsDao = array(); + 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']) + ); + $cat->_id ($previousLine['c_id']); + $list[$previousLine['c_id']] = $cat; + + $feedsDao = array(); //Prepare for next category + } + + $previousLine = $line; + $feedsDao[] = $line; + } + + // add the last category + if ($previousLine != null) { + $cat = new FreshRSS_Category ( + $previousLine['c_name'], + FreshRSS_FeedDAO::daoToFeed ($feedsDao, $previousLine['c_id']) + ); + $cat->_id ($previousLine['c_id']); + $list[$previousLine['c_id']] = $cat; + } + + return $list; + } + + public static function daoToCategory ($listDAO) { + $list = array (); + + if (!is_array ($listDAO)) { + $listDAO = array ($listDAO); + } + + foreach ($listDAO as $key => $dao) { + $cat = new FreshRSS_Category ( + $dao['name'] + ); + $cat->_id ($dao['id']); + $list[$key] = $cat; + } + + return $list; + } +} diff --git a/sources/app/Models/Configuration.php b/sources/app/Models/Configuration.php new file mode 100755 index 0000000..7596c54 --- /dev/null +++ b/sources/app/Models/Configuration.php @@ -0,0 +1,292 @@ + '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, + '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', + ), + '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(), + ); + + 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, "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 _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) { + $this->data['default_view'] = $value === FreshRSS_Entry::STATE_ALL ? FreshRSS_Entry::STATE_ALL : FreshRSS_Entry::STATE_NOT_READ; + } + public function _display_posts ($value) { + $this->data['display_posts'] = ((bool)$value) && $value !== 'no'; + } + 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(); + 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']; + } + + $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 _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/sources/app/Models/Days.php b/sources/app/Models/Days.php new file mode 100755 index 0000000..2d770c3 --- /dev/null +++ b/sources/app/Models/Days.php @@ -0,0 +1,7 @@ +_guid ($guid); + $this->_title ($title); + $this->_author ($author); + $this->_content ($content); + $this->_link ($link); + $this->_date ($pubdate); + $this->_isRead ($is_read); + $this->_isFavorite ($is_favorite); + $this->_feed ($feed); + $this->_tags (preg_split('/[\s#]/', $tags)); + } + + public function id () { + return $this->id; + } + public function guid () { + return $this->guid; + } + public function title () { + return $this->title; + } + public function author () { + return $this->author === null ? '' : $this->author; + } + public function content () { + return $this->content; + } + public function link () { + return $this->link; + } + public function date ($raw = false) { + if ($raw) { + return $this->date; + } else { + return timestamptodate ($this->date); + } + } + public function dateAdded ($raw = false) { + $date = intval(substr($this->id, 0, -6)); + if ($raw) { + return $date; + } else { + return timestamptodate ($date); + } + } + public function isRead () { + return $this->is_read; + } + public function isFavorite () { + return $this->is_favorite; + } + public function feed ($object = false) { + if ($object) { + $feedDAO = FreshRSS_Factory::createFeedDao(); + return $feedDAO->searchById ($this->feed); + } else { + return $this->feed; + } + } + public function tags ($inString = false) { + if ($inString) { + return empty ($this->tags) ? '' : '#' . implode(' #', $this->tags); + } else { + return $this->tags; + } + } + + public function _id ($value) { + $this->id = $value; + } + public function _guid ($value) { + $this->guid = $value; + } + public function _title ($value) { + $this->title = $value; + } + public function _author ($value) { + $this->author = $value; + } + public function _content ($value) { + $this->content = $value; + } + public function _link ($value) { + $this->link = $value; + } + public function _date ($value) { + $value = intval($value); + $this->date = $value > 1 ? $value : time(); + } + public function _isRead ($value) { + $this->is_read = $value; + } + public function _isFavorite ($value) { + $this->is_favorite = $value; + } + public function _feed ($value) { + $this->feed = $value; + } + public function _tags ($value) { + if (!is_array ($value)) { + $value = array ($value); + } + + foreach ($value as $key => $t) { + if (!$t) { + unset ($value[$key]); + } + } + + $this->tags = $value; + } + + public function isDay ($day, $today) { + $date = $this->dateAdded(true); + switch ($day) { + case FreshRSS_Days::TODAY: + $tomorrow = $today + 86400; + return $date >= $today && $date < $tomorrow; + case FreshRSS_Days::YESTERDAY: + $yesterday = $today - 86400; + return $date >= $yesterday && $date < $today; + case FreshRSS_Days::BEFORE_YESTERDAY: + $yesterday = $today - 86400; + return $date < $yesterday; + default: + return false; + } + } + + public function loadCompleteContent($pathEntries) { + // Gestion du contenu + // On cherche à récupérer les articles en entier... même si le flux ne le propose pas + if ($pathEntries) { + $entryDAO = FreshRSS_Factory::createEntryDao(); + $entry = $entryDAO->searchByGuid($this->feed, $this->guid); + + if($entry) { + // l'article existe déjà en BDD, en se contente de recharger ce contenu + $this->content = $entry->content(); + } else { + try { + // l'article n'est pas en BDD, on va le chercher sur le site + $this->content = get_content_by_parsing( + htmlspecialchars_decode($this->link(), ENT_QUOTES), $pathEntries + ); + } catch (Exception $e) { + // rien à faire, on garde l'ancien contenu (requête a échoué) + } + } + } + } + + public function toArray () { + return array ( + 'id' => $this->id (), + 'guid' => $this->guid (), + 'title' => $this->title (), + 'author' => $this->author (), + 'content' => $this->content (), + 'link' => $this->link (), + 'date' => $this->date (true), + 'is_read' => $this->isRead (), + 'is_favorite' => $this->isFavorite (), + 'id_feed' => $this->feed (), + 'tags' => $this->tags (true), + ); + } +} diff --git a/sources/app/Models/EntryDAO.php b/sources/app/Models/EntryDAO.php new file mode 100755 index 0000000..8c001e7 --- /dev/null +++ b/sources/app/Models/EntryDAO.php @@ -0,0 +1,562 @@ +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 addEntry($valuesTmp, $preparedStatement = null) { + $stm = $preparedStatement === null ? addEntryPrepare() : $preparedStatement; + + $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), + ); + + 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::record('SQL error addEntry: ' . $info[0] . ': ' . $info[1] . ' ' . $info[2] + . ' while adding entry in feed ' . $valuesTmp['id_feed'] . ' with title: ' . $valuesTmp['title'], Minz_Log::ERROR); + } /*else { + Minz_Log::record ('SQL error ' . $info[0] . ': ' . $info[1] . ' ' . $info[2] + . ' while adding entry in feed ' . $valuesTmp['id_feed'] . ' with title: ' . $valuesTmp['title'], Minz_Log::DEBUG); + }*/ + 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); + + $eDate = $entry->date(true); + + if ($feedHistory == -2) { + $feedHistory = $conf->keep_history_default; + } + + if (!isset($existingGuids[$entry->guid()]) && + ($feedHistory != 0 || $eDate >= $date_min)) { + $values = $entry->toArray(); + + $useDeclaredDate = empty($existingGuids); + $values['id'] = ($useDeclaredDate || $eDate < $date_min) ? + min(time(), $eDate) . uSecString() : + uTimeString(); + + return $this->addEntry($values); + } + + // We don't return Entry object to avoid a research in DB + return -1; + } + + public function markFavorite($ids, $is_favorite = true) { + if (!is_array($ids)) { + $ids = array($ids); + } + $sql = 'UPDATE `' . $this->prefix . 'entry` ' + . 'SET is_favorite=? ' + . 'WHERE id IN (' . str_repeat('?,', count($ids) - 1). '?)'; + $values = array($is_favorite ? 1 : 0); + $values = array_merge($values, $ids); + $stm = $this->bd->prepare($sql); + if ($stm && $stm->execute($values)) { + return $stm->rowCount(); + } else { + $info = $stm == null ? array(2 => 'syntax error') : $stm->errorInfo(); + Minz_Log::record('SQL error markFavorite: ' . $info[2], Minz_Log::ERROR); + return false; + } + } + + protected function updateCacheUnreads($catId = false, $feedId = false) { + $sql = 'UPDATE `' . $this->prefix . 'feed` f ' + . 'LEFT OUTER JOIN (' + . 'SELECT e.id_feed, ' + . 'COUNT(*) AS nbUnreads ' + . 'FROM `' . $this->prefix . 'entry` e ' + . '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'; + $values = array(); + if ($feedId !== false) { + $sql .= ' AND f.id=?'; + $values[] = $id; + } + if ($catId !== false) { + $sql .= ' AND f.category=?'; + $values[] = $catId; + } + $stm = $this->bd->prepare($sql); + if ($stm && $stm->execute($values)) { + return true; + } else { + $info = $stm == null ? array(2 => 'syntax error') : $stm->errorInfo(); + Minz_Log::record('SQL error updateCacheUnreads: ' . $info[2], Minz_Log::ERROR); + return false; + } + } + + public function markRead($ids, $is_read = true) { + if (is_array($ids)) { //Many IDs at once (used by API) + if (count($ids) < 6) { //Speed heuristics + $affected = 0; + foreach ($ids as $id) { + $affected += $this->markRead($id, $is_read); + } + return $affected; + } + + $sql = 'UPDATE `' . $this->prefix . 'entry` ' + . 'SET is_read=? ' + . 'WHERE id IN (' . str_repeat('?,', count($ids) - 1). '?)'; + $values = array($is_read ? 1 : 0); + $values = array_merge($values, $ids); + $stm = $this->bd->prepare($sql); + if (!($stm && $stm->execute($values))) { + $info = $stm == null ? array(2 => 'syntax error') : $stm->errorInfo(); + Minz_Log::record('SQL error markRead: ' . $info[2], Minz_Log::ERROR); + return false; + } + $affected = $stm->rowCount(); + if (($affected > 0) && (!$this->updateCacheUnreads(false, false))) { + return false; + } + return $affected; + } 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 ' + . 'WHERE e.id=? AND e.is_read=?'; + $values = array($is_read ? 1 : 0, $ids, $is_read ? 0 : 1); + $stm = $this->bd->prepare($sql); + if ($stm && $stm->execute($values)) { + return $stm->rowCount(); + } else { + $info = $stm == null ? array(2 => 'syntax error') : $stm->errorInfo(); + Minz_Log::record('SQL error markRead: ' . $info[2], Minz_Log::ERROR); + return false; + } + } + } + + public function markReadEntries($idMax = 0, $onlyFavorites = false, $priorityMin = 0) { + if ($idMax == 0) { + $idMax = time() . '000000'; + Minz_Log::record($nb . 'Calling markReadEntries(0) is deprecated!', Minz_Log::DEBUG); + } + + $sql = 'UPDATE `' . $this->prefix . 'entry` e INNER JOIN `' . $this->prefix . 'feed` f ON e.id_feed=f.id ' + . 'SET e.is_read=1 ' + . 'WHERE e.is_read=0 AND e.id <= ?'; + if ($onlyFavorites) { + $sql .= ' AND e.is_favorite=1'; + } elseif ($priorityMin >= 0) { + $sql .= ' AND f.priority > ' . intval($priorityMin); + } + $values = array($idMax); + $stm = $this->bd->prepare($sql); + if (!($stm && $stm->execute($values))) { + $info = $stm == null ? array(2 => 'syntax error') : $stm->errorInfo(); + Minz_Log::record('SQL error markReadEntries: ' . $info[2], Minz_Log::ERROR); + return false; + } + $affected = $stm->rowCount(); + if (($affected > 0) && (!$this->updateCacheUnreads(false, false))) { + return false; + } + return $affected; + } + + public function markReadCat($id, $idMax = 0) { + if ($idMax == 0) { + $idMax = time() . '000000'; + Minz_Log::record($nb . 'Calling markReadCat(0) is deprecated!', Minz_Log::DEBUG); + } + + $sql = 'UPDATE `' . $this->prefix . 'entry` e INNER JOIN `' . $this->prefix . 'feed` f ON e.id_feed=f.id ' + . '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))) { + $info = $stm == null ? array(2 => 'syntax error') : $stm->errorInfo(); + Minz_Log::record('SQL error markReadCat: ' . $info[2], Minz_Log::ERROR); + return false; + } + $affected = $stm->rowCount(); + if (($affected > 0) && (!$this->updateCacheUnreads($id, false))) { + return false; + } + return $affected; + } + + public function markReadFeed($id, $idMax = 0) { + if ($idMax == 0) { + $idMax = time() . '000000'; + Minz_Log::record($nb . 'Calling markReadFeed(0) is deprecated!', Minz_Log::DEBUG); + } + $this->bd->beginTransaction(); + + $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))) { + $info = $stm == null ? array(2 => 'syntax error') : $stm->errorInfo(); + Minz_Log::record('SQL error markReadFeed: ' . $info[2], Minz_Log::ERROR); + $this->bd->rollBack(); + return false; + } + $affected = $stm->rowCount(); + + if ($affected > 0) { + $sql = 'UPDATE `' . $this->prefix . 'feed` ' + . 'SET cache_nbUnreads=cache_nbUnreads-' . $affected + . ' WHERE id=?'; + $values = array($id); + $stm = $this->bd->prepare($sql); + if (!($stm && $stm->execute($values))) { + $info = $stm == null ? array(2 => 'syntax error') : $stm->errorInfo(); + Minz_Log::record('SQL error markReadFeed: ' . $info[2], Minz_Log::ERROR); + $this->bd->rollBack(); + return false; + } + } + + $this->bd->commit(); + return $affected; + } + + public function searchByGuid($feed_id, $id) { + // un guid est unique pour un flux donné + $sql = 'SELECT id, guid, title, author, ' + . ($this->isCompressed() ? 'UNCOMPRESS(content_bin) AS content' : 'content') + . ', link, date, is_read, is_favorite, id_feed, tags ' + . 'FROM `' . $this->prefix . 'entry` WHERE id_feed=? AND guid=?'; + $stm = $this->bd->prepare($sql); + + $values = array( + $feed_id, + $id + ); + + $stm->execute($values); + $res = $stm->fetchAll(PDO::FETCH_ASSOC); + $entries = self::daoToEntry($res); + return isset($entries[0]) ? $entries[0] : null; + } + + public function searchById($id) { + $sql = 'SELECT id, guid, title, author, ' + . ($this->isCompressed() ? 'UNCOMPRESS(content_bin) AS content' : 'content') + . ', link, date, is_read, is_favorite, id_feed, tags ' + . 'FROM `' . $this->prefix . 'entry` WHERE id=?'; + $stm = $this->bd->prepare($sql); + + $values = array($id); + + $stm->execute($values); + $res = $stm->fetchAll(PDO::FETCH_ASSOC); + $entries = self::daoToEntry($res); + return isset($entries[0]) ? $entries[0] : null; + } + + protected function sqlConcat($s1, $s2) { + return 'CONCAT(' . $s1 . ',' . $s2 . ')'; //MySQL + } + + private function sqlListWhere($type = 'a', $id = '', $state = FreshRSS_Entry::STATE_ALL, $order = 'DESC', $limit = 1, $firstId = '', $filter = '', $date_min = 0, $showOlderUnreadsorFavorites = false, $keepHistoryDefault = 0) { + 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 .= '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_READ) { + $where .= 'AND e1.is_read=1 '; + } + if ($state & FreshRSS_Entry::STATE_FAVORITE) { + if (!($state & FreshRSS_Entry::STATE_NOT_FAVORITE)) { + $where .= 'AND e1.is_favorite=1 '; + } + } + elseif ($state & FreshRSS_Entry::STATE_NOT_FAVORITE) { + $where .= 'AND e1.is_favorite=0 '; + } + + switch ($order) { + case 'DESC': + case 'ASC': + break; + default: + throw new FreshRSS_EntriesGetter_Exception('Bad order in Entry->listByType: [' . $order . ']!'); + } + if ($firstId === '' && parent::$sharedDbType === 'mysql') { + $firstId = $order === 'DESC' ? '9000000000'. '000000' : '0'; //MySQL optimization. Tested on MySQL 5.5 with 150k articles + } + if ($firstId !== '') { + $where .= 'AND e1.id ' . ($order === 'DESC' ? '<=' : '>=') . $firstId . ' '; + } + if (($date_min > 0) && ($type !== 's')) { + $where .= 'AND (e1.id >= ' . $date_min . '000000'; + if ($showOlderUnreadsorFavorites) { //Lax date constraint + $where .= ' OR e1.is_read=0 OR e1.is_favorite=1 OR (f.keep_history <> 0'; + if (intval($keepHistoryDefault) === 0) { + $where .= ' AND f.keep_history <> -2'; //default + } + $where .= ')'; + } + $where .= ') '; + $joinFeed = true; + } + $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 .'%'; + } + } + } + } + + return array($values, + 'SELECT e1.id FROM `' . $this->prefix . 'entry` e1 ' + . ($joinFeed ? 'INNER JOIN `' . $this->prefix . 'feed` f ON e1.id_feed=f.id ' : '') + . 'WHERE ' . $where + . $search + . 'ORDER BY e1.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, $showOlderUnreadsorFavorites = false, $keepHistoryDefault = 0) { + list($values, $sql) = $this->sqlListWhere($type, $id, $state, $order, $limit, $firstId, $filter, $date_min, $showOlderUnreadsorFavorites, $keepHistoryDefault); + + $sql = 'SELECT e.id, e.guid, e.title, e.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 ' + . 'INNER JOIN (' + . $sql + . ') e2 ON e2.id=e.id ' + . 'ORDER BY e.id ' . $order; + + $stm = $this->bd->prepare($sql); + $stm->execute($values); + + return self::daoToEntry($stm->fetchAll(PDO::FETCH_ASSOC)); + } + + public function listIdsWhere($type = 'a', $id = '', $state = FreshRSS_Entry::STATE_ALL, $order = 'DESC', $limit = 1, $firstId = '', $filter = '', $date_min = 0, $showOlderUnreadsorFavorites = false, $keepHistoryDefault = 0) { //For API + list($values, $sql) = $this->sqlListWhere($type, $id, $state, $order, $limit, $firstId, $filter, $date_min, $showOlderUnreadsorFavorites, $keepHistoryDefault); + + $stm = $this->bd->prepare($sql); + $stm->execute($values); + + 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); + $stm = $this->bd->prepare($sql); + $values = array($id); + $stm->execute($values); + return $stm->fetchAll(PDO::FETCH_COLUMN, 0); + } + + public function countUnreadRead() { + $sql = 'SELECT COUNT(e.id) AS count FROM `' . $this->prefix . 'entry` e INNER JOIN `' . $this->prefix . 'feed` f ON e.id_feed=f.id WHERE priority > 0' + . ' UNION SELECT COUNT(e.id) AS count FROM `' . $this->prefix . 'entry` e INNER JOIN `' . $this->prefix . 'feed` f ON e.id_feed=f.id WHERE priority > 0 AND is_read=0'; + $stm = $this->bd->prepare($sql); + $stm->execute(); + $res = $stm->fetchAll(PDO::FETCH_COLUMN, 0); + $all = empty($res[0]) ? 0 : $res[0]; + $unread = empty($res[1]) ? 0 : $res[1]; + return array('all' => $all, 'unread' => $unread, 'read' => $all - $unread); + } + public function count($minPriority = null) { + $sql = 'SELECT COUNT(e.id) AS count FROM `' . $this->prefix . 'entry` e INNER JOIN `' . $this->prefix . 'feed` f ON e.id_feed=f.id'; + if ($minPriority !== null) { + $sql = ' WHERE priority > ' . intval($minPriority); + } + $stm = $this->bd->prepare($sql); + $stm->execute(); + $res = $stm->fetchAll(PDO::FETCH_COLUMN, 0); + return $res[0]; + } + public function countNotRead($minPriority = null) { + $sql = 'SELECT COUNT(e.id) AS count FROM `' . $this->prefix . 'entry` e INNER JOIN `' . $this->prefix . 'feed` f ON e.id_feed=f.id WHERE is_read=0'; + if ($minPriority !== null) { + $sql = ' AND priority > ' . intval($minPriority); + } + $stm = $this->bd->prepare($sql); + $stm->execute(); + $res = $stm->fetchAll(PDO::FETCH_COLUMN, 0); + return $res[0]; + } + + public function countUnreadReadFavorites() { + $sql = 'SELECT c FROM (' + . 'SELECT COUNT(id) AS c, 1 as o FROM `' . $this->prefix . 'entry` WHERE is_favorite=1 ' + . 'UNION SELECT COUNT(id) AS c, 2 AS o FROM `' . $this->prefix . 'entry` WHERE is_favorite=1 AND is_read=0' + . ') u ORDER BY o'; + $stm = $this->bd->prepare($sql); + $stm->execute(); + $res = $stm->fetchAll(PDO::FETCH_COLUMN, 0); + $all = empty($res[0]) ? 0 : $res[0]; + $unread = empty($res[1]) ? 0 : $res[1]; + return array('all' => $all, 'unread' => $unread, 'read' => $all - $unread); + } + + public function optimizeTable() { + $sql = 'OPTIMIZE TABLE `' . $this->prefix . 'entry`'; //MySQL + $stm = $this->bd->prepare($sql); + $stm->execute(); + } + + public function size($all = false) { + $db = Minz_Configuration::dataBase(); + $sql = 'SELECT SUM(data_length + index_length) FROM information_schema.TABLES WHERE table_schema=?'; //MySQL + $values = array($db['base']); + if (!$all) { + $sql .= ' AND table_name LIKE ?'; + $values[] = $this->prefix . '%'; + } + $stm = $this->bd->prepare($sql); + $stm->execute($values); + $res = $stm->fetchAll(PDO::FETCH_COLUMN, 0); + return $res[0]; + } + + public static function daoToEntry($listDAO) { + $list = array(); + + if (!is_array($listDAO)) { + $listDAO = array($listDAO); + } + + foreach ($listDAO as $key => $dao) { + $entry = new FreshRSS_Entry( + $dao['id_feed'], + $dao['guid'], + $dao['title'], + $dao['author'], + $dao['content'], + $dao['link'], + $dao['date'], + $dao['is_read'], + $dao['is_favorite'], + $dao['tags'] + ); + if (isset($dao['id'])) { + $entry->_id($dao['id']); + } + $list[] = $entry; + } + + unset($listDAO); + + return $list; + } +} diff --git a/sources/app/Models/EntryDAOSQLite.php b/sources/app/Models/EntryDAOSQLite.php new file mode 100755 index 0000000..3dabce4 --- /dev/null +++ b/sources/app/Models/EntryDAOSQLite.php @@ -0,0 +1,129 @@ +prefix . 'feed` ' + . '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'; + $values = array(); + if ($feedId !== false) { + $sql .= ' AND id=?'; + $values[] = $feedId; + } + if ($catId !== false) { + $sql .= ' AND category=?'; + $values[] = $catId; + } + $stm = $this->bd->prepare($sql); + if ($stm && $stm->execute($values)) { + return true; + } else { + $info = $stm == null ? array(2 => 'syntax error') : $stm->errorInfo(); + Minz_Log::record('SQL error updateCacheUnreads: ' . $info[2], Minz_Log::ERROR); + return false; + } + } + + 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) + $affected = 0; + foreach ($ids as $id) { + $affected += $this->markRead($id, $is_read); + } + return $affected; + } + } else { + $this->bd->beginTransaction(); + $sql = 'UPDATE `' . $this->prefix . 'entry` SET is_read=? WHERE id=? AND is_read=?'; + $values = array($is_read ? 1 : 0, $ids, $is_read ? 0 : 1); + $stm = $this->bd->prepare($sql); + if (!($stm && $stm->execute($values))) { + $info = $stm == null ? array(2 => 'syntax error') : $stm->errorInfo(); + Minz_Log::record('SQL error markRead 1: ' . $info[2], Minz_Log::ERROR); + $this->bd->rollBack(); + return false; + } + $affected = $stm->rowCount(); + if ($affected > 0) { + $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); + if (!($stm && $stm->execute($values))) { + $info = $stm == null ? array(2 => 'syntax error') : $stm->errorInfo(); + Minz_Log::record('SQL error markRead 2: ' . $info[2], Minz_Log::ERROR); + $this->bd->rollBack(); + return false; + } + } + $this->bd->commit(); + return $affected; + } + } + + public function markReadEntries($idMax = 0, $onlyFavorites = false, $priorityMin = 0) { + if ($idMax == 0) { + $idMax = time() . '000000'; + Minz_Log::record($nb . 'Calling markReadEntries(0) is deprecated!', Minz_Log::DEBUG); + } + + $sql = 'UPDATE `' . $this->prefix . 'entry` SET is_read=1 WHERE is_read=0 AND id <= ?'; + if ($onlyFavorites) { + $sql .= ' AND is_favorite=1'; + } elseif ($priorityMin >= 0) { + $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))) { + $info = $stm == null ? array(2 => 'syntax error') : $stm->errorInfo(); + Minz_Log::record('SQL error markReadEntries: ' . $info[2], Minz_Log::ERROR); + return false; + } + $affected = $stm->rowCount(); + if (($affected > 0) && (!$this->updateCacheUnreads(false, false))) { + return false; + } + return $affected; + } + + public function markReadCat($id, $idMax = 0) { + if ($idMax == 0) { + $idMax = time() . '000000'; + Minz_Log::record($nb . 'Calling markReadCat(0) is deprecated!', Minz_Log::DEBUG); + } + + $sql = 'UPDATE `' . $this->prefix . 'entry` ' + . 'SET is_read=1 ' + . '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))) { + $info = $stm == null ? array(2 => 'syntax error') : $stm->errorInfo(); + Minz_Log::record('SQL error markReadCat: ' . $info[2], Minz_Log::ERROR); + return false; + } + $affected = $stm->rowCount(); + if (($affected > 0) && (!$this->updateCacheUnreads($id, false))) { + return false; + } + return $affected; + } + + public function optimizeTable() { + //TODO: Search for an equivalent in SQLite + } + + public function size($all = false) { + return @filesize(DATA_PATH . '/' . Minz_Session::param('currentUser', '_') . '.sqlite'); + } +} diff --git a/sources/app/Models/Factory.php b/sources/app/Models/Factory.php new file mode 100755 index 0000000..08569b2 --- /dev/null +++ b/sources/app/Models/Factory.php @@ -0,0 +1,32 @@ +_url($url); + } else { + $this->url = $url; + } + } + + public function id() { + return $this->id; + } + + public function hash() { + if ($this->hash === null) { + $this->hash = hash('crc32b', Minz_Configuration::salt() . $this->url); + } + return $this->hash; + } + + public function url() { + return $this->url; + } + public function category() { + return $this->category; + } + public function entries() { + return $this->entries === null ? array() : $this->entries; + } + public function name() { + return $this->name; + } + public function website() { + return $this->website; + } + public function description() { + return $this->description; + } + public function lastUpdate() { + return $this->lastUpdate; + } + public function priority() { + return $this->priority; + } + public function pathEntries() { + return $this->pathEntries; + } + public function httpAuth($raw = true) { + if ($raw) { + return $this->httpAuth; + } else { + $pos_colon = strpos($this->httpAuth, ':'); + $user = substr($this->httpAuth, 0, $pos_colon); + $pass = substr($this->httpAuth, $pos_colon + 1); + + return array( + 'username' => $user, + 'password' => $pass + ); + } + } + public function inError() { + return $this->error; + } + public function keepHistory() { + return $this->keep_history; + } + public function ttl() { + return $this->ttl; + } + public function nbEntries() { + if ($this->nbEntries < 0) { + $feedDAO = FreshRSS_Factory::createFeedDao(); + $this->nbEntries = $feedDAO->countEntries($this->id()); + } + + return $this->nbEntries; + } + public function nbNotRead() { + if ($this->nbNotRead < 0) { + $feedDAO = FreshRSS_Factory::createFeedDao(); + $this->nbNotRead = $feedDAO->countNotRead($this->id()); + } + + 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; + } + file_put_contents($file, $t); + } + } + public static function faviconDelete($hash) { + $path = DATA_PATH . '/favicons/' . $hash; + @unlink($path . '.ico'); + @unlink($path . '.txt'); + } + public function favicon() { + return Minz_Url::display('/f.php?' . $this->hash()); + } + + public function _id($value) { + $this->id = $value; + } + public function _url($value, $validate=true) { + $this->hash = null; + if ($validate) { + $value = checkUrl($value); + } + if (empty($value)) { + throw new FreshRSS_BadUrl_Exception($value); + } + $this->url = $value; + } + public function _category($value) { + $value = intval($value); + $this->category = $value >= 0 ? $value : 0; + } + public function _name($value) { + $this->name = $value === null ? '' : $value; + } + public function _website($value, $validate=true) { + if ($validate) { + $value = checkUrl($value); + } + if (empty($value)) { + $value = ''; + } + $this->website = $value; + } + public function _description($value) { + $this->description = $value === null ? '' : $value; + } + public function _lastUpdate($value) { + $this->lastUpdate = $value; + } + public function _priority($value) { + $value = intval($value); + $this->priority = $value >= 0 ? $value : 10; + } + public function _pathEntries($value) { + $this->pathEntries = $value; + } + public function _httpAuth($value) { + $this->httpAuth = $value; + } + public function _error($value) { + $this->error = (bool)$value; + } + public function _keepHistory($value) { + $value = intval($value); + $value = min($value, 1000000); + $value = max($value, -2); + $this->keep_history = $value; + } + public function _ttl($value) { + $value = intval($value); + $value = min($value, 100000000); + $value = max($value, -2); + $this->ttl = $value; + } + public function _nbNotRead($value) { + $this->nbNotRead = intval($value); + } + public function _nbEntries($value) { + $this->nbEntries = intval($value); + } + + public function load($loadDetails = false) { + if ($this->url !== null) { + if (CACHE_PATH === false) { + throw new Minz_FileNotExistException( + 'CACHE_PATH', + Minz_Exception::ERROR + ); + } else { + $url = htmlspecialchars_decode($this->url, ENT_QUOTES); + if ($this->httpAuth != '') { + $url = preg_replace('#((.+)://)(.+)#', '${1}' . $this->httpAuth . '@${3}', $url); + } + $feed = customSimplePie(); + $feed->set_feed_url($url); + if (!$loadDetails) { //Only activates auto-discovery when adding a new feed + $feed->set_autodiscovery_level(SIMPLEPIE_LOCATOR_NONE); + } + $mtime = $feed->init(); + + if ((!$mtime) || $feed->error()) { + throw new FreshRSS_Feed_Exception($feed->error() . ' [' . $url . ']'); + } + + 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('<' => '<', '>' => '>', '"' => '"')); //HTML to HTML-PRE //ENT_COMPAT except & + $this->_name($title == '' ? $this->url : $title); + + $this->_website(html_only_entity_decode($feed->get_link())); + $this->_description(html_only_entity_decode($feed->get_description())); + } else { + //The case of HTTP 301 Moved Permanently + $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); + } + + if (($mtime === true) ||($mtime > $this->lastUpdate)) { + syslog(LOG_DEBUG, 'FreshRSS no cache ' . $mtime . ' > ' . $this->lastUpdate . ' for ' . $subscribe_url); + $this->loadEntries($feed); // et on charge les articles du flux + } else { + syslog(LOG_DEBUG, 'FreshRSS use cache for ' . $subscribe_url); + $this->entries = array(); + } + + $feed->__destruct(); //http://simplepie.org/wiki/faq/i_m_getting_memory_leaks + unset($feed); + } + } + } + + private function loadEntries($feed) { + $entries = array(); + + foreach ($feed->get_items() as $item) { + $title = html_only_entity_decode(strip_tags($item->get_title())); + $author = $item->get_author(); + $link = $item->get_permalink(); + $date = @strtotime($item->get_date()); + + // gestion des tags (catégorie == tag) + $tags_tmp = $item->get_categories(); + $tags = array(); + if ($tags_tmp !== null) { + foreach ($tags_tmp as $tag) { + $tags[] = html_only_entity_decode($tag->get_label()); + } + } + + $content = html_only_entity_decode($item->get_content()); + + $elinks = array(); + foreach ($item->get_enclosures() as $enclosure) { + $elink = $enclosure->get_link(); + if (empty($elinks[$elink])) { + $elinks[$elink] = '1'; + $mime = strtolower($enclosure->get_type()); + if (strpos($mime, 'image/') === 0) { + $content .= '
'; + } elseif (strpos($mime, 'audio/') === 0) { + $content .= '