Browse Source

Merge branch 'dev'

Marien Fressinaud 11 years ago
parent
commit
147a3d21bb
100 changed files with 6546 additions and 2609 deletions
  1. 82 0
      CHANGELOG
  2. 101 0
      README.fr.md
  3. 68 59
      README.md
  4. 378 210
      app/Controllers/configureController.php
  5. 15 6
      app/Controllers/entryController.php
  6. 32 20
      app/Controllers/errorController.php
  7. 102 115
      app/Controllers/feedController.php
  8. 447 0
      app/Controllers/importExportController.php
  9. 171 44
      app/Controllers/indexController.php
  10. 2 2
      app/Controllers/javascriptController.php
  11. 129 0
      app/Controllers/statsController.php
  12. 129 0
      app/Controllers/updateController.php
  13. 26 6
      app/Controllers/usersController.php
  14. 0 6
      app/Exceptions/OpmlException.php
  15. 49 13
      app/FreshRSS.php
  16. 1 1
      app/Models/Category.php
  17. 24 11
      app/Models/CategoryDAO.php
  18. 119 33
      app/Models/Configuration.php
  19. 8 2
      app/Models/Entry.php
  20. 392 298
      app/Models/EntryDAO.php
  21. 129 0
      app/Models/EntryDAOSQLite.php
  22. 32 0
      app/Models/Factory.php
  23. 123 94
      app/Models/Feed.php
  24. 190 156
      app/Models/FeedDAO.php
  25. 19 0
      app/Models/FeedDAOSQLite.php
  26. 44 0
      app/Models/Share.php
  27. 240 41
      app/Models/StatsDAO.php
  28. 64 0
      app/Models/StatsDAOSQLite.php
  29. 16 1
      app/Models/Themes.php
  30. 36 16
      app/Models/UserDAO.php
  31. 4 1
      app/SQL/install.sql.mysql.php
  32. 59 0
      app/SQL/install.sql.sqlite.php
  33. 0 1
      app/actualize_script.php
  34. 155 27
      app/i18n/en.php
  35. 175 47
      app/i18n/fr.php
  36. 5 3
      app/i18n/install.en.php
  37. 5 3
      app/i18n/install.fr.php
  38. 879 0
      app/install.php
  39. 25 11
      app/layout/aside_configure.phtml
  40. 14 3
      app/layout/aside_feed.phtml
  41. 43 28
      app/layout/aside_flux.phtml
  42. 12 0
      app/layout/aside_stats.phtml
  43. 57 49
      app/layout/header.phtml
  44. 22 13
      app/layout/layout.phtml
  45. 232 154
      app/layout/nav_menu.phtml
  46. 21 0
      app/views/configure/archiving.phtml
  47. 14 6
      app/views/configure/categorize.phtml
  48. 24 110
      app/views/configure/display.phtml
  49. 49 17
      app/views/configure/feed.phtml
  50. 0 40
      app/views/configure/importExport.phtml
  51. 97 0
      app/views/configure/queries.phtml
  52. 158 0
      app/views/configure/reading.phtml
  53. 38 43
      app/views/configure/sharing.phtml
  54. 23 1
      app/views/configure/shortcut.phtml
  55. 43 4
      app/views/configure/users.phtml
  56. 2 11
      app/views/error/index.phtml
  57. 91 0
      app/views/feed/add.phtml
  58. 47 0
      app/views/helpers/export/articles.phtml
  59. 28 0
      app/views/helpers/export/opml.phtml
  60. 14 5
      app/views/helpers/javascript_vars.phtml
  61. 26 15
      app/views/helpers/pagination.phtml
  62. 8 0
      app/views/helpers/view/global_view.phtml
  63. 27 77
      app/views/helpers/view/normal_view.phtml
  64. 11 16
      app/views/helpers/view/reader_view.phtml
  65. 1 1
      app/views/helpers/view/rss_view.phtml
  66. 0 0
      app/views/importExport/export.phtml
  67. 61 0
      app/views/importExport/index.phtml
  68. 23 9
      app/views/index/formLogin.phtml
  69. 33 0
      app/views/index/resetAuth.phtml
  70. 14 13
      app/views/javascript/actualize.phtml
  71. 48 0
      app/views/stats/idle.phtml
  72. 40 38
      app/views/stats/index.phtml
  73. 150 0
      app/views/stats/repartition.phtml
  74. 9 0
      app/views/update/apply.phtml
  75. 36 0
      app/views/update/index.phtml
  76. 8 3
      constants.php
  77. 2 0
      data/.gitignore
  78. 0 0
      data/do-install.txt
  79. 75 0
      data/shares.php
  80. 1 0
      data/tokens/.gitignore
  81. 13 0
      data/tokens/index.html
  82. 1 5
      lib/Minz/ActionController.php
  83. 0 116
      lib/Minz/Cache.php
  84. 79 61
      lib/Minz/Configuration.php
  85. 38 70
      lib/Minz/Dispatcher.php
  86. 24 8
      lib/Minz/Error.php
  87. 33 26
      lib/Minz/FrontController.php
  88. 14 3
      lib/Minz/Helper.php
  89. 17 0
      lib/Minz/Log.php
  90. 39 34
      lib/Minz/ModelPdo.php
  91. 75 52
      lib/Minz/Request.php
  92. 0 60
      lib/Minz/Response.php
  93. 0 16
      lib/Minz/RouteNotFoundException.php
  94. 0 209
      lib/Minz/Router.php
  95. 48 26
      lib/Minz/Session.php
  96. 21 13
      lib/Minz/Translate.php
  97. 4 11
      lib/Minz/Url.php
  98. 21 4
      lib/Minz/View.php
  99. 32 10
      lib/SimplePie/SimplePie.php
  100. 10 2
      lib/SimplePie/SimplePie/File.php

+ 82 - 0
CHANGELOG

@@ -1,5 +1,87 @@
 # Journal des modifications
 
+## 2014-09-xx FreshRSS 0.8.0
+
+* UI
+	* New interface for statistics
+	* Fix filter buttons
+	* Number of articles divided by 2 in reading view
+	* Redesign of bigMarkAsRead
+* Features
+	* New automatic update system
+	* New reset auth system
+* Security
+	* "Mark as read" requires POST requests for several articles
+	* Test HTTP REFERER in install.php
+* Configuration
+	* New "Show all articles" / "Show only unread" / "Adjust viewing" option
+	* New notification timeout option
+* Misc.
+	* Improve coding style + comments
+	* Fix SQLite bug "ON DELETE CASCADE"
+	* Improve performance when importing articles
+
+
+## 2014-08-24 FreshRSS 0.7.4
+
+* UI
+	* Hide categories/feeds with unread articles when showing only unread articles
+	* Dynamic favicon showing the number of unread articles
+	* New theme: Screwdriver by Mister aiR
+* Statistics
+	* New page with article repartition
+	* Improvements
+* Security
+	* Basic protection against XSRF (Cross-Site Request Forgery) based on HTTP Referer (POST requests only)
+* API
+	* Compatible with lighttpd
+* Misc.
+	* Changed lazyload implementation
+	* Support of HTML5 notifications for new upcoming articles
+	* Add option to stay logged in
+* Bux fixes in export function, add/remove users, keyboard shortcuts, etc.
+
+
+## 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

+ 101 - 0
README.fr.md

@@ -0,0 +1,101 @@
+* [English version](README.md)
+
+# 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 <dev@marienfressinaud.fr>
+* Version actuelle : 0.8-dev
+* Date de publication 2014-0x-xx
+* 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 (recommandé), ou nginx, lighttpd (non testé sur les autres)
+* PHP 5.2.1+ (PHP 5.3.7+ recommandé)
+	* Requis : [PDO_MySQL](http://php.net/pdo-mysql) ou [PDO_SQLite](http://php.net/pdo-sqlite), [cURL](http://php.net/curl), [GMP](http://php.net/gmp) (seulement pour accès API sur platformes < 64 bits)
+	* Recommandés : [JSON](http://php.net/json), [mbstring](http://php.net/mbstring), [zlib](http://php.net/zlib), [Zip](http://php.net/zip)
+* MySQL 5.0.3+ (recommandé) ou SQLite 3.7.4+
+* 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/)
+
+## 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)

+ 68 - 59
README.md

@@ -1,80 +1,90 @@
+* [Version française](README.fr.md)
+
 # 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/).
+FreshRSS is a self-hosted RSS feed agregator like [Leed](http://projet.idleman.fr/leed/) or [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.
+It is at the same time light-weight, easy to work with, powerful and customizable.
 
-Il permet de gérer plusieurs utilisateurs, et dispose d’un mode de lecture anonyme.
+It is a multi-user application with an anonymous reading mode.
 
-* Site officiel : http://freshrss.org
-* Démo : http://demo.freshrss.org/
-* Développeur : Marien Fressinaud <dev@marienfressinaud.fr>
-* Version actuelle : 0.7.1
-* Date de publication 2014-02-19
+* Official website: http://freshrss.org
+* Demo: http://demo.freshrss.org/
+* Developer: Marien Fressinaud <dev@marienfressinaud.fr>
+* Current version: 0.8-dev
+* Publication date: 2014-0x-xx
 * 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)
+![FreshRSS logo](http://marienfressinaud.fr/data/images/freshrss/freshrss_title.png)
+
+# Note on branches
+**This application is still in development!** Please use the branch that suits your needs:
+
+* Use [the master branch](https://github.com/marienfressinaud/FreshRSS/tree/master/) if you need a stable version.
+* [The beta branch](https://github.com/marienfressinaud/FreshRSS/tree/beta) is the default branch: new features are added on a monthly basis.
+* For developers and tech savvy persons, [the dev branch](https://github.com/marienfressinaud/FreshRSS/tree/dev) is waiting for you!
 
 # 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)
-* MySQL 5.0.3+ (ou SQLite 3.7.4+ à venir)
-* 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)
+This application was developed to fulfill personal needs not professional needs.
+There is no guarantee neither on its security nor its proper functioning.
+If there is feature requests which I think are good for the project, I'll do my best to include them.
+The best way is to open issues on GitHub
+(https://github.com/marienfressinaud/FreshRSS/issues) or by email (dev@marienfressinaud.fr)
+
+# Requirements
+* Light server running Linux or Windows
+	* It even works on Raspberry Pi with response time under a second (tested with 150 feeds, 22k articles, or 32Mo of compressed data)
+* A web server: Apache2 (recommanded), nginx, lighttpd (not tested on others)
+* PHP 5.2.1+ (PHP 5.3.7+ recommanded)
+	* Required extensions: [PDO_MySQL](http://php.net/pdo-mysql) or [PDO_SQLite](http://php.net/pdo-sqlite), [cURL](http://php.net/curl), [GMP](http://php.net/gmp) (only for API access on platforms under 64 bits)
+	* Recommanded extensions : [JSON](http://php.net/json), [mbstring](http://php.net/mbstring), [zlib](http://php.net/zlib), [Zip](http://php.net/zip)
+* MySQL 5.0.3+ (recommanded) ou SQLite 3.7.4+
+* A recent browser like Firefox 4+, Chrome, Opera, Safari, Internet Explorer 9+
+	* Works on mobile
+
+![FreshRSS screenshot](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 :
-* 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 :
+1. Get FreshRSS with git or [by downloading the archive](https://github.com/marienfressinaud/FreshRSS/archive/master.zip)
+2. Dump the application on your server (expose only the `./p/` folder)
+3. Add write access on `./data/` folder to the webserver user
+4. Access FreshRSS with your browser and follow the installation process
+5. Every thing should be working :) If you encounter any problem, feel free to contact me.
+
+# Access control
+It is needed for the multi-user mode to limit access to FreshRSS. You can:
+* use form authentication (need JavaScript and PHP 5.3.7+, works with some PHP 5.3.3+)
+* use [Mozilla Persona](https://login.persona.org/about) authentication included in FreshRSS
+* use HTTP authentication supported by your web server
+	* See [Apache documentation](http://httpd.apache.org/docs/trunk/howto/auth.html)
+		* In that case, create a `./p/i/.htaccess` file with a matching `.htpasswd` file.
+
+# Automatic feed update
+* You can add a Cron job to launch the update script.
+Check the Cron documentation related to your distribution ([Debian/Ubuntu](https://help.ubuntu.com/community/CronHowto), [Red Hat/Fedora](https://fedoraproject.org/wiki/Administration_Guide_Draft/Cron), [Slackware](http://docs.slackware.com/fr:slackbook:process_control?#cron), [Gentoo](https://wiki.gentoo.org/wiki/Cron), [Arch Linux](https://wiki.archlinux.org/index.php/Cron)…).
+It’s a good idea to use the web server user .
+For example, if you want to run the script every hour:
 
 ```
 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`.
+# Advices
+* For a better security, expose only the `./p/` folder on the web.
+	* Be aware that the `./data/` folder contain all personal data, so it is a bad idea to expose it.
+* The `./constants.php` file define access to application folder. If you want to customize your installation, every thing happens here.
+* If you encounter some problem, logs are accessibles from the interface or manually in `./data/log/*.log` files.
 
-# 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 :
+# Backup
+* You need to keep `./data/config.php`, `./data/*_user.php` and `./data/persona/` files
+* You can export your feed list in OPML format from FreshRSS
+* To save articles, you can use [phpMyAdmin](http://www.phpmyadmin.net) or MySQL tools:
 
 ```bash
-mysqldump -u utilisateur -p --databases freshrss > freshrss.sql
+mysqldump -u user -p --databases freshrss > freshrss.sql
 ```
 
 
-# Bibliothèques incluses
+# Included libraries
 * [SimplePie](http://simplepie.org/)
 * [MINZ](https://github.com/marienfressinaud/MINZ)
 * [php-http-304](http://alexandre.alapetite.fr/doc-alex/php-http-304/)
@@ -82,11 +92,10 @@ mysqldump -u utilisateur -p --databases freshrss > freshrss.sql
 * [keyboard_shortcuts](http://www.openjs.com/scripts/events/keyboard_shortcuts/)
 * [flotr2](http://www.humblesoftware.com/flotr2)
 
-## Uniquement pour certaines options
+## Only for some 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
+## If native functions are not available
 * [Services_JSON](http://pear.php.net/pepr/pepr-proposal-show.php?id=198)
 * [password_compat](https://github.com/ircmaxell/password_compat)

+ 378 - 210
app/Controllers/configureController.php

@@ -1,82 +1,123 @@
 <?php
 
+/**
+ * Controller to handle every configuration options.
+ */
 class FreshRSS_configure_Controller extends Minz_ActionController {
-	public function firstAction () {
+	/**
+	 * This action is called before every other action in that class. It is
+	 * the common boiler plate for every action. It is triggered by the
+	 * underlying framework.
+	 *
+	 * @todo see if the category default configuration is needed here or if
+	 *       we can move it to the categorize action
+	 */
+	public function firstAction() {
 		if (!$this->view->loginOk) {
-			Minz_Error::error (
+			Minz_Error::error(
 				403,
-				array ('error' => array (Minz_Translate::t ('access_denied')))
+				array('error' => array(_t('access_denied')))
 			);
 		}
 
-		$catDAO = new FreshRSS_CategoryDAO ();
-		$catDAO->checkDefault ();
+		$catDAO = new FreshRSS_CategoryDAO();
+		$catDAO->checkDefault();
 	}
 
-	public function categorizeAction () {
-		$feedDAO = new FreshRSS_FeedDAO ();
-		$catDAO = new FreshRSS_CategoryDAO ();
-		$defaultCategory = $catDAO->getDefault ();
-		$defaultId = $defaultCategory->id ();
+	/**
+	 * This action handles the category configuration page
+	 *
+	 * It displays the category configuration page.
+	 * If this action is reached through a POST request, it loops through
+	 * every category to check for modification then add a new category if
+	 * needed then sends a notification to the user.
+	 * If a category name is emptied, the category is deleted and all
+	 * related feeds are moved to the default category. Related user queries
+	 * are deleted too.
+	 * If a category name is changed, it is updated.
+	 */
+	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', ''));
+		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 (),
+				if (strlen($name) > 0) {
+					$cat = new FreshRSS_Category($name);
+					$values = array(
+						'name' => $cat->name(),
 					);
-					$catDAO->updateCategory ($ids[$key], $values);
+					$catDAO->updateCategory($ids[$key], $values);
 				} elseif ($ids[$key] != $defaultId) {
-					$feedDAO->changeCategory ($ids[$key], $defaultId);
-					$catDAO->deleteCategory ($ids[$key]);
+					$feedDAO->changeCategory($ids[$key], $defaultId);
+					$catDAO->deleteCategory($ids[$key]);
+
+					// Remove related queries.
+					$this->view->conf->remove_query_by_get('c_' . $ids[$key]);
+					$this->view->conf->save();
 				}
 			}
 
 			if ($newCat != '') {
-				$cat = new FreshRSS_Category ($newCat);
-				$values = array (
-					'id' => $cat->id (),
-					'name' => $cat->name (),
+				$cat = new FreshRSS_Category($newCat);
+				$values = array(
+					'id' => $cat->id(),
+					'name' => $cat->name(),
 				);
 
-				if ($catDAO->searchByName ($newCat) == false) {
-					$catDAO->addCategory ($values);
+				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);
+			Minz_Request::good(_t('categories_updated'),
+			                   array('c' => 'configure', 'a' => 'categorize'));
 		}
 
-		$this->view->categories = $catDAO->listCategories (false);
-		$this->view->defaultCategory = $catDAO->getDefault ();
-		$this->view->feeds = $feedDAO->listFeeds ();
-		$this->view->flux = false;
+		$this->view->categories = $catDAO->listCategories(false);
+		$this->view->defaultCategory = $catDAO->getDefault();
+		$this->view->feeds = $feedDAO->listFeeds();
 
-		Minz_View::prependTitle (Minz_Translate::t ('categories_management') . ' · ');
+		Minz_View::prependTitle(_t('categories_management') . ' · ');
 	}
 
-	public function feedAction () {
-		$catDAO = new FreshRSS_CategoryDAO ();
-		$this->view->categories = $catDAO->listCategories (false);
-
-		$feedDAO = new FreshRSS_FeedDAO ();
-		$this->view->feeds = $feedDAO->listFeeds ();
-
-		$id = Minz_Request::param ('id');
-		if ($id == false && !empty ($this->view->feeds)) {
-			$id = current ($this->view->feeds)->id ();
+	/**
+	 * This action handles the feed configuration page.
+	 *
+	 * It displays the feed configuration page.
+	 * If this action is reached through a POST request, it stores all new
+	 * configuraiton values then sends a notification to the user.
+	 *
+	 * The options available on the page are:
+	 *   - name
+	 *   - description
+	 *   - website URL
+	 *   - feed URL
+	 *   - category id (default: default category id)
+	 *   - CSS path to article on website
+	 *   - display in main stream (default: 0)
+	 *   - HTTP authentication
+	 *   - number of article to retain (default: -2)
+	 *   - refresh frequency (default: -2)
+	 * Default values are empty strings unless specified.
+	 */
+	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;
@@ -84,14 +125,14 @@ class FreshRSS_configure_Controller extends Minz_ActionController {
 			$this->view->flux = $this->view->feeds[$id];
 
 			if (!$this->view->flux) {
-				Minz_Error::error (
+				Minz_Error::error(
 					404,
-					array ('error' => array (Minz_Translate::t ('page_not_found')))
+					array('error' => array(_t('page_not_found')))
 				);
 			} else {
-				if (Minz_Request::isPost () && $this->view->flux) {
-					$user = Minz_Request::param ('http_user', '');
-					$pass = Minz_Request::param ('http_pass', '');
+				if (Minz_Request::isPost() && $this->view->flux) {
+					$user = Minz_Request::param('http_user', '');
+					$pass = Minz_Request::param('http_pass', '');
 
 					$httpAuth = '';
 					if ($user != '' || $pass != '') {
@@ -100,66 +141,74 @@ class FreshRSS_configure_Controller extends Minz_ActionController {
 
 					$cat = intval(Minz_Request::param('category', 0));
 
-					$values = array (
-						'name' => Minz_Request::param ('name', ''),
+					$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)),
+						'pathEntries' => Minz_Request::param('path_entries', ''),
+						'priority' => intval(Minz_Request::param('priority', 0)),
 						'httpAuth' => $httpAuth,
-						'keep_history' => intval(Minz_Request::param ('keep_history', -2)),
+						'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);
+					if ($feedDAO->updateFeed($id, $values)) {
+						$this->view->flux->_category($cat);
 						$this->view->flux->faviconPrepare();
-						$notif = array (
+						$notif = array(
 							'type' => 'good',
-							'content' => Minz_Translate::t ('feed_updated')
+							'content' => _t('feed_updated')
 						);
 					} else {
-						$notif = array (
+						$notif = array(
 							'type' => 'bad',
-							'content' => Minz_Translate::t ('error_occurred_update')
+							'content' => _t('error_occurred_update')
 						);
 					}
 					invalidateHttpCache();
 
-					Minz_Session::_param ('notification', $notif);
-					Minz_Request::forward (array ('c' => 'configure', 'a' => 'feed', 'params' => array ('id' => $id)), true);
+					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 () . ' · ');
+				Minz_View::prependTitle(_t('rss_feed_management') . ' — ' . $this->view->flux->name() . ' · ');
 			}
 		} else {
-			Minz_View::prependTitle (Minz_Translate::t ('rss_feed_management') . ' · ');
+			Minz_View::prependTitle(_t('rss_feed_management') . ' · ');
 		}
 	}
 
-	public function displayAction () {
+	/**
+	 * This action handles the display configuration page.
+	 *
+	 * It displays the display configuration page.
+	 * If this action is reached through a POST request, it stores all new
+	 * configuration values then sends a notification to the user.
+	 *
+	 * The options available on the page are:
+	 *   - language (default: en)
+	 *   - theme (default: Origin)
+	 *   - content width (default: thin)
+	 *   - display of read action in header
+	 *   - display of favorite action in header
+	 *   - display of date in header
+	 *   - display of open action in header
+	 *   - display of read action in footer
+	 *   - display of favorite action in footer
+	 *   - display of sharing action in footer
+	 *   - display of tags in footer
+	 *   - display of date in footer
+	 *   - display of open action in footer
+	 *   - html5 notification timeout (default: 0)
+	 * Default values are false unless specified.
+	 */
+	public function displayAction() {
 		if (Minz_Request::isPost()) {
 			$this->view->conf->_language(Minz_Request::param('language', 'en'));
-			$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 (Minz_Request::param('default_view', 'a'));
-			$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->_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),
-			));
-			$themeId = Minz_Request::param('theme', '');
-			if ($themeId == '') {
-				$themeId = FreshRSS_Themes::defaultTheme;
-			}
-			$this->view->conf->_theme($themeId);
+			$this->view->conf->_theme(Minz_Request::param('theme', FreshRSS_Themes::$defaultTheme));
+			$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));
@@ -170,131 +219,127 @@ class FreshRSS_configure_Controller extends Minz_ActionController {
 			$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->_html5_notif_timeout(Minz_Request::param('html5_notif_timeout', 0));
 			$this->view->conf->save();
 
-			Minz_Session::_param ('language', $this->view->conf->language);
-			Minz_Translate::reset ();
+			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);
+			Minz_Request::good(_t('configuration_updated'),
+			                   array('c' => 'configure', 'a' => 'display'));
 		}
 
 		$this->view->themes = FreshRSS_Themes::get();
 
-		Minz_View::prependTitle (Minz_Translate::t ('reading_configuration') . ' · ');
+		Minz_View::prependTitle(_t('display_configuration') . ' · ');
 	}
 
-	public function sharingAction () {
-		if (Minz_Request::isPost ()) {
-			$this->view->conf->_sharing (array(
-				'shaarli' => Minz_Request::param ('shaarli', false),
-				'wallabag' => Minz_Request::param ('wallabag', false),
-				'diaspora' => Minz_Request::param ('diaspora', false),
-				'twitter' => Minz_Request::param ('twitter', false),
-				'g+' => Minz_Request::param ('g+', false),
-				'facebook' => Minz_Request::param ('facebook', false),
-				'email' => Minz_Request::param ('email', false),
-				'print' => Minz_Request::param ('print', false),
+	/**
+	 * This action handles the reading configuration page.
+	 *
+	 * It displays the reading configuration page.
+	 * If this action is reached through a POST request, it stores all new
+	 * configuration values then sends a notification to the user.
+	 *
+	 * The options available on the page are:
+	 *   - number of posts per page (default: 10)
+	 *   - view mode (default: normal)
+	 *   - default article view (default: all)
+	 *   - load automatically articles
+	 *   - display expanded articles
+	 *   - display expanded categories
+	 *   - hide categories and feeds without unread articles
+	 *   - jump on next category or feed when marked as read
+	 *   - image lazy loading
+	 *   - stick open articles to the top
+	 *   - display a confirmation when reading all articles
+	 *   - article order (default: DESC)
+	 *   - mark articles as read when:
+	 *       - displayed
+	 *       - opened on site
+	 *       - scrolled
+	 *       - received
+	 * Default values are false unless specified.
+	 */
+	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->_display_categories(Minz_Request::param('display_categories', false));
+			$this->view->conf->_hide_read_feeds(Minz_Request::param('hide_read_feeds', 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();
-			invalidateHttpCache();
 
-			$notif = array (
-				'type' => 'good',
-				'content' => Minz_Translate::t ('configuration_updated')
-			);
-			Minz_Session::_param ('notification', $notif);
+			Minz_Session::_param('language', $this->view->conf->language);
+			Minz_Translate::reset();
+			invalidateHttpCache();
 
-			Minz_Request::forward (array ('c' => 'configure', 'a' => 'sharing'), true);
+			Minz_Request::good(_t('configuration_updated'),
+			                   array('c' => 'configure', 'a' => 'reading'));
 		}
 
-		Minz_View::prependTitle (Minz_Translate::t ('sharing') . ' · ');
+		Minz_View::prependTitle(_t('reading_configuration') . ' · ');
 	}
 
-	public function importExportAction () {
-		require_once(LIB_PATH . '/lib_opml.php');
-		$catDAO = new FreshRSS_CategoryDAO ();
-		$this->view->categories = $catDAO->listCategories ();
-
-		$this->view->req = Minz_Request::param ('q');
-
-		if ($this->view->req == 'export') {
-			Minz_View::_title ('freshrss_feeds.opml');
-
-			$this->view->_useLayout (false);
-			header('Content-Type: application/xml; charset=utf-8');
-			header('Content-disposition: attachment; filename=freshrss_feeds.opml');
-
-			$feedDAO = new FreshRSS_FeedDAO ();
-			$catDAO = new FreshRSS_CategoryDAO ();
-
-			$list = array ();
-			foreach ($catDAO->listCategories () as $key => $cat) {
-				$list[$key]['name'] = $cat->name ();
-				$list[$key]['feeds'] = $feedDAO->listByCategory ($cat->id ());
-			}
-
-			$this->view->categories = $list;
-		} elseif ($this->view->req == 'import' && Minz_Request::isPost ()) {
-			if ($_FILES['file']['error'] == 0) {
-				invalidateHttpCache();
-				// on parse le fichier OPML pour récupérer les catégories et les flux associés
-				try {
-					list ($categories, $feeds) = opml_import (
-						file_get_contents ($_FILES['file']['tmp_name'])
-					);
-
-					// On redirige vers le controller feed qui va se charger d'insérer les flux en BDD
-					// les flux sont mis au préalable dans des variables de Request
-					Minz_Request::_param ('q', 'null');
-					Minz_Request::_param ('categories', $categories);
-					Minz_Request::_param ('feeds', $feeds);
-					Minz_Request::forward (array ('c' => 'feed', 'a' => 'massiveImport'));
-				} catch (FreshRSS_Opml_Exception $e) {
-					Minz_Log::record ($e->getMessage (), Minz_Log::WARNING);
-
-					$notif = array (
-						'type' => 'bad',
-						'content' => Minz_Translate::t ('bad_opml_file')
-					);
-					Minz_Session::_param ('notification', $notif);
+	/**
+	 * This action handles the sharing configuration page.
+	 *
+	 * It displays the sharing configuration page.
+	 * If this action is reached through a POST request, it stores all
+	 * configuration values then sends a notification to the user.
+	 */
+	public function sharingAction() {
+		if (Minz_Request::isPost()) {
+			$params = Minz_Request::params();
+			$this->view->conf->_sharing($params['share']);
+			$this->view->conf->save();
+			invalidateHttpCache();
 
-					Minz_Request::forward (array (
-						'c' => 'configure',
-						'a' => 'importExport'
-					), true);
-				}
-			}
+			Minz_Request::good(_t('configuration_updated'),
+			                   array('c' => 'configure', 'a' => 'sharing'));
 		}
 
-		$feedDAO = new FreshRSS_FeedDAO ();
-		$this->view->feeds = $feedDAO->listFeeds ();
-
-		// au niveau de la vue, permet de ne pas voir un flux sélectionné dans la liste
-		$this->view->flux = false;
-
-		Minz_View::prependTitle (Minz_Translate::t ('import_export_opml') . ' · ');
+		Minz_View::prependTitle(_t('sharing') . ' · ');
 	}
 
-	public function shortcutAction () {
-		$list_keys = array ('a', 'b', 'backspace', 'c', 'd', 'delete', 'down', 'e', 'end', 'enter',
+	/**
+	 * This action handles the shortcut configuration page.
+	 *
+	 * It displays the shortcut configuration page.
+	 * If this action is reached through a POST request, it stores all new
+	 * configuration values then sends a notification to the user.
+	 *
+	 * The authorized values for shortcuts are letters (a to z), numbers (0
+	 * to 9), function keys (f1 to f12), backspace, delete, down, end, enter,
+	 * escape, home, insert, left, page down, page up, return, right, space,
+	 * tab and up.
+	 */
+	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',
+		                    'z', '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 ();
+		if (Minz_Request::isPost()) {
+			$shortcuts = Minz_Request::param('shortcuts');
+			$shortcuts_ok = array();
 
 			foreach ($shortcuts as $key => $value) {
 				if (in_array($value, $list_keys)) {
@@ -302,48 +347,56 @@ class FreshRSS_configure_Controller extends Minz_ActionController {
 				}
 			}
 
-			$this->view->conf->_shortcuts ($shortcuts_ok);
+			$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_Request::good(_t('shortcuts_updated'),
+			                   array('c' => 'configure', 'a' => 'shortcut'));
 		}
 
-		Minz_View::prependTitle (Minz_Translate::t ('shortcuts') . ' · ');
+		Minz_View::prependTitle(_t('shortcuts') . ' · ');
 	}
 
+	/**
+	 * This action display the user configuration page
+	 *
+	 * @todo move that action in the user controller
+	 */
 	public function usersAction() {
-		Minz_View::prependTitle(Minz_Translate::t ('users') . ' · ');
+		Minz_View::prependTitle(_t('users') . ' · ');
 	}
 
-	public function archivingAction () {
+	/**
+	 * This action handles the archive configuration page.
+	 *
+	 * It displays the archive configuration page.
+	 * If this action is reached through a POST request, it stores all new
+	 * configuration values then sends a notification to the user.
+	 *
+	 * The options available on that page are:
+	 *   - duration to retain old article (default: 3)
+	 *   - number of article to retain per feed (default: 0)
+	 *   - refresh frequency (default: -2)
+	 *
+	 * @todo explain why the default value is -2 but this value does not
+	 *       exist in the drop-down list
+	 */
+	public function archivingAction() {
 		if (Minz_Request::isPost()) {
-			$old = Minz_Request::param('old_entries', 3);
-			$keepHistoryDefault = Minz_Request::param('keep_history_default', 0);
-
-			$this->view->conf->_old_entries($old);
-			$this->view->conf->_keep_history_default($keepHistoryDefault);
+			$this->view->conf->_old_entries(Minz_Request::param('old_entries', 3));
+			$this->view->conf->_keep_history_default(Minz_Request::param('keep_history_default', 0));
+			$this->view->conf->_ttl_default(Minz_Request::param('ttl_default', -2));
 			$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_Request::good(_t('configuration_updated'),
+			                   array('c' => 'configure', 'a' => 'archiving'));
 		}
 
-		Minz_View::prependTitle(Minz_Translate::t('archiving_configuration') . ' · ');
+		Minz_View::prependTitle(_t('archiving_configuration') . ' · ');
 
-		$entryDAO = new FreshRSS_EntryDAO();
+		$entryDAO = FreshRSS_Factory::createEntryDao();
 		$this->view->nb_total = $entryDAO->count();
 		$this->view->size_user = $entryDAO->size();
 
@@ -351,4 +404,119 @@ class FreshRSS_configure_Controller extends Minz_ActionController {
 			$this->view->size_total = $entryDAO->size(true);
 		}
 	}
+
+	/**
+	 * This action handles the user queries configuration page.
+	 *
+	 * If this action is reached through a POST request, it stores all new
+	 * configuration values then sends a notification to the user then
+	 * redirect to the same page.
+	 * If this action is not reached through a POST request, it displays the
+	 * configuration page and verifies that every user query is runable by
+	 * checking if categories and feeds are still in use.
+	 */
+	public function queriesAction() {
+		if (Minz_Request::isPost()) {
+			$queries = Minz_Request::param('queries', array());
+
+			foreach ($queries as $key => $query) {
+				if (!$query['name']) {
+					$query['name'] = _t('query_number', $key + 1);
+				}
+			}
+			$this->view->conf->_queries($queries);
+			$this->view->conf->save();
+
+			Minz_Request::good(_t('configuration_updated'),
+			                   array('c' => 'configure', 'a' => 'queries'));
+		} else {
+			$this->view->query_get = array();
+			$cat_dao = new FreshRSS_CategoryDAO();
+			$feed_dao = FreshRSS_Factory::createFeedDao();
+			foreach ($this->view->conf->queries as $key => $query) {
+				if (!isset($query['get'])) {
+					continue;
+				}
+
+				switch ($query['get'][0]) {
+				case 'c':
+					$category = $cat_dao->searchById(substr($query['get'], 2));
+
+					$deprecated = true;
+					$cat_name = '';
+					if ($category) {
+						$cat_name = $category->name();
+						$deprecated = false;
+					}
+
+					$this->view->query_get[$key] = array(
+						'type' => 'category',
+						'name' => $cat_name,
+						'deprecated' => $deprecated,
+					);
+					break;
+				case 'f':
+					$feed = $feed_dao->searchById(substr($query['get'], 2));
+
+					$deprecated = true;
+					$feed_name = '';
+					if ($feed) {
+						$feed_name = $feed->name();
+						$deprecated = false;
+					}
+
+					$this->view->query_get[$key] = array(
+						'type' => 'feed',
+						'name' => $feed_name,
+						'deprecated' => $deprecated,
+					);
+					break;
+				case 's':
+					$this->view->query_get[$key] = array(
+						'type' => 'favorite',
+						'name' => 'favorite',
+						'deprecated' => false,
+					);
+					break;
+				case 'a':
+					$this->view->query_get[$key] = array(
+						'type' => 'all',
+						'name' => 'all',
+						'deprecated' => false,
+					);
+					break;
+				}
+			}
+		}
+
+		Minz_View::prependTitle(_t('queries') . ' · ');
+	}
+
+	/**
+	 * This action handles the creation of a user query.
+	 *
+	 * It gets the GET parameters and stores them in the configuration query
+	 * storage. Before it is saved, the unwanted parameters are unset to keep
+	 * lean data.
+	 */
+	public function addQueryAction() {
+		$whitelist = array('get', 'order', 'name', 'search', 'state');
+		$queries = $this->view->conf->queries;
+		$query = Minz_Request::params();
+		$query['name'] = _t('query_number', count($queries) + 1);
+		foreach ($query as $key => $value) {
+			if (!in_array($key, $whitelist)) {
+				unset($query[$key]);
+			}
+		}
+		if (!empty($query['state']) && $query['state'] & FreshRSS_Entry::STATE_STRICT) {
+			$query['state'] -= FreshRSS_Entry::STATE_STRICT;
+		}
+		$queries[] = $query;
+		$this->view->conf->_queries($queries);
+		$this->view->conf->save();
+
+		Minz_Request::good(_t('query_created', $query['name']),
+		                   array('c' => 'configure', 'a' => 'queries'));
+	}
 }

+ 15 - 6
app/Controllers/entryController.php

@@ -43,8 +43,12 @@ class FreshRSS_entry_Controller extends Minz_ActionController {
 		$nextGet = Minz_Request::param ('nextGet', $get); 
 		$idMax = Minz_Request::param ('idMax', 0);
 
-		$entryDAO = new FreshRSS_EntryDAO ();
+		$entryDAO = FreshRSS_Factory::createEntryDao();
 		if ($id == false) {
+			if (!Minz_Request::isPost()) {
+				return;
+			}
+
 			if (!$get) {
 				$entryDAO->markReadEntries ($idMax);
 			} else {
@@ -85,7 +89,7 @@ class FreshRSS_entry_Controller extends Minz_ActionController {
 
 		$id = Minz_Request::param ('id');
 		if ($id) {
-			$entryDAO = new FreshRSS_EntryDAO ();
+			$entryDAO = FreshRSS_Factory::createEntryDao();
 			$entryDAO->markFavorite ($id, (bool)(Minz_Request::param ('is_favorite', true)));
 		}
 	}
@@ -97,9 +101,12 @@ class FreshRSS_entry_Controller extends Minz_ActionController {
 			// 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 = new FreshRSS_EntryDAO();
+			$entryDAO = FreshRSS_Factory::createEntryDao();
 			$entryDAO->optimizeTable();
 
+			$feedDAO = FreshRSS_Factory::createFeedDao();
+			$feedDAO->updateCachedValues();
+
 			invalidateHttpCache();
 
 			$notif = array (
@@ -121,8 +128,8 @@ class FreshRSS_entry_Controller extends Minz_ActionController {
 		$nb_month_old = max($this->view->conf->old_entries, 1);
 		$date_min = time() - (3600 * 24 * 30 * $nb_month_old);
 
-		$feedDAO = new FreshRSS_FeedDAO();
-		$feeds = $feedDAO->listFeedsOrderUpdate();
+		$feedDAO = FreshRSS_Factory::createFeedDao();
+		$feeds = $feedDAO->listFeeds();
 		$nbTotal = 0;
 
 		invalidateHttpCache();
@@ -137,11 +144,13 @@ class FreshRSS_entry_Controller extends Minz_ActionController {
 				if ($nb > 0) {
 					$nbTotal += $nb;
 					Minz_Log::record($nb . ' old entries cleaned in feed [' . $feed->url() . ']', Minz_Log::DEBUG);
-					$feedDAO->updateLastUpdate($feed->id());
+					//$feedDAO->updateLastUpdate($feed->id());
 				}
 			}
 		}
 
+		$feedDAO->updateCachedValues();
+
 		invalidateHttpCache();
 
 		$notif = array(

+ 32 - 20
app/Controllers/errorController.php

@@ -1,26 +1,38 @@
 <?php
 
 class FreshRSS_error_Controller extends Minz_ActionController {
-	public function indexAction () {
-		switch (Minz_Request::param ('code')) {
-		case 403:
-			$this->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';
+	public function indexAction() {
+		switch (Minz_Request::param('code')) {
+			case 403:
+				$this->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 . ' · ');
+
+		$errors = Minz_Request::param('logs', array());
+		$this->view->errorMessage = trim(implode($errors));
+		if ($this->view->errorMessage == '') {
+			switch(Minz_Request::param('code')) {
+				case 403:
+					$this->view->errorMessage = Minz_Translate::t('forbidden_access');
+					break;
+				case 404:
+				default:
+					$this->view->errorMessage = Minz_Translate::t('page_not_found');
+					break;
+			}
+		}
+
+		Minz_View::prependTitle($this->view->code . ' · ');
 	}
 }

+ 102 - 115
app/Controllers/feedController.php

@@ -22,14 +22,32 @@ class FreshRSS_feed_Controller extends Minz_ActionController {
 	}
 
 	public function addAction () {
-		@set_time_limit(300);
+		$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);
 
-		if (Minz_Request::isPost ()) {
-			$this->catDAO = new FreshRSS_CategoryDAO ();
-			$this->catDAO->checkDefault ();
 
-			$url = Minz_Request::param ('url_rss');
 			$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 ();
@@ -52,7 +70,6 @@ class FreshRSS_feed_Controller extends Minz_ActionController {
 
 				$feed->load(true);
 
-				$feedDAO = new FreshRSS_FeedDAO ();
 				$values = array (
 					'url' => $feed->url (),
 					'category' => $feed->category (),
@@ -85,25 +102,30 @@ class FreshRSS_feed_Controller extends Minz_ActionController {
 
 						$is_read = $this->view->conf->mark_when['reception'] ? 1 : 0;
 
-						$entryDAO = new FreshRSS_EntryDAO ();
+						$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 ();
+						$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 = $entry->toArray();
+							$values['id_feed'] = $feed->id();
+							$values['id'] = min(time(), $entry->date(true)) . uSecString();
 							$values['is_read'] = $is_read;
-							$entryDAO->addEntry ($values);
+							$entryDAO->addEntry($values, $preparedStatement);
+						}
+						$feedDAO->updateLastUpdate($feed->id());
+						if ($transactionStarted) {
+							$feedDAO->commit();
 						}
-						$feedDAO->updateLastUpdate ($feed->id ());
-						$feedDAO->commit ();
 						$transactionStarted = false;
 
 						// ok, ajout terminé
@@ -128,7 +150,7 @@ class FreshRSS_feed_Controller extends Minz_ActionController {
 				Minz_Log::record ($e->getMessage (), Minz_Log::WARNING);
 				$notif = array (
 					'type' => 'bad',
-					'content' => Minz_Translate::t ('internal_problem_feed')
+					'content' => Minz_Translate::t ('internal_problem_feed', Minz_Url::display(array('a' => 'logs')))
 				);
 				Minz_Session::_param ('notification', $notif);
 			} catch (Minz_FileNotExistException $e) {
@@ -136,7 +158,7 @@ class FreshRSS_feed_Controller extends Minz_ActionController {
 				Minz_Log::record ($e->getMessage (), Minz_Log::ERROR);
 				$notif = array (
 					'type' => 'bad',
-					'content' => Minz_Translate::t ('internal_problem_feed')
+					'content' => Minz_Translate::t ('internal_problem_feed', Minz_Url::display(array('a' => 'logs')))
 				);
 				Minz_Session::_param ('notification', $notif);
 			}
@@ -145,13 +167,46 @@ class FreshRSS_feed_Controller extends Minz_ActionController {
 			}
 
 			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 = new FreshRSS_FeedDAO ();
+			$feedDAO = FreshRSS_Factory::createFeedDao();
 			$n = $feedDAO->truncate($id);
 			$notif = array(
 				'type' => $n === false ? 'bad' : 'good',
@@ -166,8 +221,8 @@ class FreshRSS_feed_Controller extends Minz_ActionController {
 	public function actualizeAction () {
 		@set_time_limit(300);
 
-		$feedDAO = new FreshRSS_FeedDAO ();
-		$entryDAO = new FreshRSS_EntryDAO ();
+		$feedDAO = FreshRSS_Factory::createFeedDao();
+		$entryDAO = FreshRSS_Factory::createEntryDao();
 
 		Minz_Session::_param('actualize_feeds', false);
 		$id = Minz_Request::param ('id');
@@ -183,7 +238,7 @@ class FreshRSS_feed_Controller extends Minz_ActionController {
 				$feeds = array ($feed);
 			}
 		} else {
-			$feeds = $feedDAO->listFeedsOrderUpdate ();
+			$feeds = $feedDAO->listFeedsOrderUpdate($this->view->conf->ttl_default);
 		}
 
 		// on calcule la date des articles les plus anciens qu'on accepte
@@ -215,22 +270,23 @@ class FreshRSS_feed_Controller extends Minz_ActionController {
 						$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 ()])) &&
+						$eDate = $entry->date(true);
+						if ((!isset($existingGuids[$entry->guid()])) &&
 							(($feedHistory != 0) || ($eDate  >= $date_min))) {
-							$values = $entry->toArray ();
+							$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);
+							$entryDAO->addEntry($values, $preparedStatement);
 						}
 					}
 				}
@@ -251,7 +307,8 @@ class FreshRSS_feed_Controller extends Minz_ActionController {
 					$feedDAO->commit();
 				}
 				$flux_update++;
-				if ($feed->url() !== $url) {	//URL has changed (auto-discovery)
+				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) {
@@ -319,88 +376,23 @@ class FreshRSS_feed_Controller extends Minz_ActionController {
 		}
 	}
 
-	public function massiveImportAction () {
-		@set_time_limit(300);
-
-		$this->catDAO = new FreshRSS_CategoryDAO ();
-		$this->catDAO->checkDefault ();
-
-		$entryDAO = new FreshRSS_EntryDAO ();
-		$feedDAO = new FreshRSS_FeedDAO ();
-
-		$categories = Minz_Request::param ('categories', array (), true);
-		$feeds = Minz_Request::param ('feeds', array (), true);
-
-		// on ajoute les catégories en masse dans une fonction à part
-		$this->addCategories ($categories);
-
-		// 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);
-
-		// la variable $error permet de savoir si une erreur est survenue
-		// Le but est de ne pas arrêter l'import même en cas d'erreur
-		// L'utilisateur sera mis au courant s'il y a eu des erreurs, mais
-		// ne connaîtra pas les détails. Ceux-ci seront toutefois logguées
-		$error = false;
-		$i = 0;
-		foreach ($feeds as $feed) {
-			try {
-				$values = array (
-					'id' => $feed->id (),
-					'url' => $feed->url (),
-					'category' => $feed->category (),
-					'name' => $feed->name (),
-					'website' => $feed->website (),
-					'description' => $feed->description (),
-					'lastUpdate' => 0,
-					'httpAuth' => $feed->httpAuth ()
-				);
-
-				// ajout du flux que s'il n'est pas déjà en BDD
-				if (!$feedDAO->searchByUrl ($values['url'])) {
-					$id = $feedDAO->addFeed ($values);
-					if ($id) {
-						$feed->_id ($id);
-						$feed->faviconPrepare();
-					} else {
-						$error = true;
-					}
-				}
-			} catch (FreshRSS_Feed_Exception $e) {
-				$error = true;
-				Minz_Log::record ($e->getMessage (), Minz_Log::WARNING);
-			}
-		}
-
-		if ($error) {
-			$res = Minz_Translate::t ('feeds_imported_with_errors');
-		} else {
-			$res = Minz_Translate::t ('feeds_imported');
-		}
-
-		$notif = array (
-			'type' => 'good',
-			'content' => $res
-		);
-		Minz_Session::_param ('notification', $notif);
-		Minz_Session::_param ('actualize_feeds', true);
-
-		// et on redirige vers la page d'accueil
-		Minz_Request::forward (array (
-			'c' => 'index',
-			'a' => 'index'
-		), true);
-	}
-
 	public function deleteAction () {
 		if (Minz_Request::isPost ()) {
 			$type = Minz_Request::param ('type', 'feed');
 			$id = Minz_Request::param ('id');
 
-			$feedDAO = new FreshRSS_FeedDAO ();
+			$feedDAO = FreshRSS_Factory::createFeedDao();
 			if ($type == 'category') {
+				// List feeds to remove then related user queries.
+				$feeds = $feedDAO->listByCategory($id);
+
 				if ($feedDAO->deleteFeedByCategory ($id)) {
+					// Remove related queries
+					foreach ($feeds as $feed) {
+						$this->view->conf->remove_query_by_get('f_' . $feed->id());
+					}
+					$this->view->conf->save();
+
 					$notif = array (
 						'type' => 'good',
 						'content' => Minz_Translate::t ('category_emptied')
@@ -414,6 +406,10 @@ class FreshRSS_feed_Controller extends Minz_ActionController {
 				}
 			} else {
 				if ($feedDAO->deleteFeed ($id)) {
+					// Remove related queries
+					$this->view->conf->remove_query_by_get('f_' . $id);
+					$this->view->conf->save();
+
 					$notif = array (
 						'type' => 'good',
 						'content' => Minz_Translate::t ('feed_deleted')
@@ -429,22 +425,13 @@ class FreshRSS_feed_Controller extends Minz_ActionController {
 
 			Minz_Session::_param ('notification', $notif);
 
-			if ($type == 'category') {
-				Minz_Request::forward (array ('c' => 'configure', 'a' => 'categorize'), true);
+			$redirect_url = Minz_Request::param('r', false, true);
+			if ($redirect_url) {
+				Minz_Request::forward($redirect_url);
+			} elseif ($type == 'category') {
+				Minz_Request::forward(array ('c' => 'configure', 'a' => 'categorize'), true);
 			} else {
-				Minz_Request::forward (array ('c' => 'configure', 'a' => 'feed'), true);
-			}
-		}
-	}
-
-	private function addCategories ($categories) {
-		foreach ($categories as $cat) {
-			if (!$this->catDAO->searchByName ($cat->name ())) {
-				$values = array (
-					'id' => $cat->id (),
-					'name' => $cat->name (),
-				);
-				$catDAO->addCategory ($values);
+				Minz_Request::forward(array ('c' => 'configure', 'a' => 'feed'), true);
 			}
 		}
 	}

+ 447 - 0
app/Controllers/importExportController.php

@@ -0,0 +1,447 @@
+<?php
+
+class FreshRSS_importExport_Controller extends Minz_ActionController {
+	public function firstAction() {
+		if (!$this->view->loginOk) {
+			Minz_Error::error(
+				403,
+				array('error' => array(_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(_t('import_export') . ' · ');
+	}
+
+	public function importAction() {
+		if (!Minz_Request::isPost()) {
+			Minz_Request::forward(array('c' => 'importExport', 'a' => 'index'), true);
+		}
+
+		$file = $_FILES['file'];
+		$status_file = $file['error'];
+
+		if ($status_file !== 0) {
+			Minz_Log::error('File cannot be uploaded. Error code: ' . $status_file);
+			Minz_Request::bad(_t('file_cannot_be_uploaded'),
+			                  array('c' => 'importExport', 'a' => 'index'));
+		}
+
+		@set_time_limit(300);
+
+		$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
+		$list = array();
+		if ($type_file === 'zip' && extension_loaded('zip')) {
+			$zip = zip_open($file['tmp_name']);
+
+			if (!is_resource($zip)) {
+				// zip_open cannot open file: something is wrong
+				Minz_Log::error('Zip archive cannot be imported. Error code: ' . $zip);
+				Minz_Request::bad(_t('zip_error'),
+				                  array('c' => 'importExport', 'a' => 'index'));
+			}
+
+			while (($zipfile = zip_read($zip)) !== false) {
+				if (!is_resource($zipfile)) {
+					// zip_entry() can also return an error code!
+					Minz_Log::error('Zip file cannot be imported. Error code: ' . $zipfile);
+				} else {
+					$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 === 'zip') {
+			// Zip extension is not loaded
+			Minz_Request::bad(_t('no_zip_extension'),
+			                  array('c' => 'importExport', 'a' => 'index'));
+		} elseif ($type_file !== 'unknown') {
+			$list_files[$type_file][] = file_get_contents($file['tmp_name']);
+		}
+
+		// Import file contents.
+		// 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
+		Minz_Session::_param('actualize_feeds', true);
+		$content_notif = $error === true ? _t('feeds_imported_with_errors') :
+		                                   _t('feeds_imported');
+		Minz_Request::good($content_notif);
+	}
+
+	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.
+
+		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 (substr_compare($filename, '.json', -5) === 0 &&
+		          strpos($filename, 'starred') !== false) {
+			return 'json_starred';
+		} elseif (substr_compare($filename, '.json', -5) === 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 = Minz_Helper::htmlspecialchars_utf8($feed_elt['xmlUrl']);
+		$name = Minz_Helper::htmlspecialchars_utf8($feed_elt['text']);
+		$website = '';
+		if (isset($feed_elt['htmlUrl'])) {
+			$website = Minz_Helper::htmlspecialchars_utf8($feed_elt['htmlUrl']);
+		}
+		$description = '';
+		if (isset($feed_elt['description'])) {
+			$description = Minz_Helper::htmlspecialchars_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(Minz_Helper::htmlspecialchars_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;
+		$article_to_feed = array();
+
+		// First, we check feeds of articles are in DB (and add them if needed).
+		foreach ($article_object['items'] as $item) {
+			$feed = $this->addFeedArticles($item['origin'], $google_compliant);
+			if (is_null($feed)) {
+				$error = true;
+			} else {
+				$article_to_feed[$item['id']] = $feed->id();
+			}
+		}
+
+		// Then, articles are imported.
+		$prepared_statement = $this->entryDAO->addEntryPrepare();
+		$this->entryDAO->beginTransaction();
+		foreach ($article_object['items'] as $item) {
+			if (!isset($article_to_feed[$item['id']])) {
+				continue;
+			}
+
+			$feed_id = $article_to_feed[$item['id']];
+			$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->_id(min(time(), $entry->date(true)) . uSecString());
+			$entry->_tags($tags);
+
+			$values = $entry->toArray();
+			$id = $this->entryDAO->addEntry($values, $prepared_statement);
+
+			if (!$error && ($id === false)) {
+				$error = true;
+			}
+		}
+		$this->entryDAO->commit();
+
+		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'];
+
+		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()) {
+			Minz_Request::forward(array('c' => 'importExport', 'a' => 'index'), true);
+		}
+
+		$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', array());
+
+		$export_files = array();
+		if ($export_opml) {
+			$export_files['feeds.opml'] = $this->generateOpml();
+		}
+
+		if ($export_starred) {
+			$export_files['starred.json'] = $this->generateArticles('starred');
+		}
+
+		foreach ($export_feeds as $feed_id) {
+			$feed = $this->feedDAO->searchById($feed_id);
+			if ($feed) {
+				$filename = 'feed_' . $feed->category() . '_'
+				          . $feed->id() . '.json';
+				$export_files[$filename] = $this->generateArticles(
+					'feed', $feed
+				);
+			}
+		}
+
+		$nb_files = count($export_files);
+		if ($nb_files > 1) {
+			// If there are more than 1 file to export, we need a zip archive.
+			try {
+				$this->exportZip($export_files);
+			} catch (Exception $e) {
+				# Oops, there is no Zip extension!
+				Minz_Request::bad(_t('export_no_zip_extension'),
+				                  array('c' => 'importExport', 'a' => 'index'));
+			}
+		} elseif ($nb_files === 1) {
+			// Only one file? Guess its type and export it.
+			$filename = key($export_files);
+			$type = $this->guessFileType($filename);
+			$this->exportFile('freshrss_' . $filename, $export_files[$filename], $type);
+		} else {
+			Minz_Request::forward(array('c' => 'importExport', 'a' => 'index'), true);
+		}
+	}
+
+	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 = _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 = _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');
+	}
+
+	private function exportZip($files) {
+		if (!extension_loaded('zip')) {
+			throw new Exception();
+		}
+
+		// From https://stackoverflow.com/questions/1061710/php-zip-files-on-the-fly
+		$zip_file = tempnam('tmp', 'zip');
+		$zip = new ZipArchive();
+		$zip->open($zip_file, ZipArchive::OVERWRITE);
+
+		foreach ($files as $filename => $content) {
+			$zip->addFromString($filename, $content);
+		}
+
+		// Close and send to user
+		$zip->close();
+		header('Content-Type: application/zip');
+		header('Content-Length: ' . filesize($zip_file));
+		header('Content-Disposition: attachment; filename="freshrss_export.zip"');
+		readfile($zip_file);
+		unlink($zip_file);
+	}
+
+	private function exportFile($filename, $content, $type) {
+		if ($type === 'unknown') {
+			return;
+		}
+
+		$content_type = '';
+		if ($type === 'opml') {
+			$content_type = "text/opml";
+		} elseif ($type === 'json_feed' || $type === 'json_starred') {
+			$content_type = "text/json";
+		}
+
+		header('Content-Type: ' . $content_type . '; charset=utf-8');
+		header('Content-disposition: attachment; filename=' . $filename);
+		print($content);
+	}
+}

+ 171 - 44
app/Controllers/indexController.php

@@ -25,16 +25,12 @@ class FreshRSS_index_Controller extends Minz_ActionController {
 			}
 		}
 
-		// construction of RSS url of this feed
 		$params = Minz_Request::params ();
-		$params['output'] = 'rss';
 		if (isset ($params['search'])) {
 			$params['search'] = urlencode ($params['search']);
 		}
-		if (!Minz_Configuration::allowAnonymous()) {
-			$params['token'] = $token;
-		}
-		$this->view->rss_url = array (
+
+		$this->view->url = array (
 			'c' => 'index',
 			'a' => 'index',
 			'params' => $params
@@ -49,7 +45,7 @@ class FreshRSS_index_Controller extends Minz_ActionController {
 		}
 
 		$catDAO = new FreshRSS_CategoryDAO();
-		$entryDAO = new FreshRSS_EntryDAO();
+		$entryDAO = FreshRSS_Factory::createEntryDao();
 
 		$this->view->cat_aside = $catDAO->listCategories ();
 		$this->view->nb_favorites = $entryDAO->countUnreadReadFavorites ();
@@ -73,31 +69,32 @@ class FreshRSS_index_Controller extends Minz_ActionController {
 
 		// mise à jour des titres
 		$this->view->rss_title = $this->view->currentName . ' | ' . Minz_View::title();
-		if ($this->view->nb_not_read > 0) {
-			Minz_View::appendTitle (' (' . formatNumber($this->view->nb_not_read) . ')');
-		}
-		Minz_View::prependTitle (
+		Minz_View::prependTitle(
+			($this->nb_not_read_cat > 0 ? '(' . formatNumber($this->nb_not_read_cat) . ') ' : '') .
 			$this->view->currentName .
-			($this->nb_not_read_cat > 0 ? ' (' . formatNumber($this->nb_not_read_cat) . ')' : '') .
 			' · '
 		);
 
 		// On récupère les différents éléments de filtrage
-		$this->view->state = $state = Minz_Request::param ('state', $this->view->conf->default_view);
+		$this->view->state = Minz_Request::param('state', $this->view->conf->default_view);
+		$state_param = Minz_Request::param ('state', null);
 		$filter = Minz_Request::param ('search', '');
-		if (!empty($filter)) {
-			$state = 'all';	//Search always in read and unread articles
-		}
 		$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 === 'not_read') {	//Any unread article in this category at all?
+		$ajax_request = Minz_Request::param('ajax', false);
+		if ($output === 'reader') {
+			$nb = max(1, round($nb / 2));
+		}
+
+		if ($this->view->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':
@@ -111,8 +108,8 @@ class FreshRSS_index_Controller extends Minz_ActionController {
 					$hasUnread = true;
 					break;
 			}
-			if (!$hasUnread) {
-				$this->view->state = $state = 'all';
+			if (!$hasUnread && ($state_param === null)) {
+				$this->view->state = FreshRSS_Entry::STATE_ALL;
 			}
 		}
 
@@ -125,15 +122,22 @@ class FreshRSS_index_Controller extends Minz_ActionController {
 		$keepHistoryDefault = $this->view->conf->keep_history_default;
 
 		try {
-			$entries = $entryDAO->listWhere($getType, $getId, $state, $order, $nb + 1, $first, $filter, $date_min, $keepHistoryDefault);
+			$entries = $entryDAO->listWhere($getType, $getId, $this->view->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 === 'not_read' && empty($entries)) {
-				Minz_Log::record ('Conflicting information about nbNotRead!', Minz_Log::DEBUG);
-				$this->view->state = 'all';
-				$entries = $entryDAO->listWhere($getType, $getId, 'all', $order, $nb, $first, $filter, $date_min, $keepHistoryDefault);
+			if ($this->view->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);
 			}
+			Minz_Request::_param('state', $this->view->state);
 
 			if (count($entries) <= $nb) {
 				$this->view->nextId  = '';
@@ -186,7 +190,7 @@ class FreshRSS_index_Controller extends Minz_ActionController {
 			case 'f':
 				$feed = FreshRSS_CategoryDAO::findFeed($this->view->cat_aside, $getId);
 				if (empty($feed)) {
-					$feedDAO = new FreshRSS_FeedDAO();
+					$feedDAO = FreshRSS_Factory::createFeedDao();
 					$feed = $feedDAO->searchById($getId);
 				}
 				if ($feed) {
@@ -203,25 +207,6 @@ class FreshRSS_index_Controller extends Minz_ActionController {
 		}
 	}
 	
-	public function statsAction () {
-		if (!$this->view->loginOk) {
-			Minz_Error::error (
-				403,
-				array ('error' => array (Minz_Translate::t ('access_denied')))
-			);
-		}
-
-		Minz_View::prependTitle (Minz_Translate::t ('stats') . ' · ');
-
-		$statsDAO = new FreshRSS_StatsDAO ();
-		Minz_View::appendScript (Minz_Url::display ('/scripts/flotr2.min.js?' . @filemtime(PUBLIC_PATH . '/scripts/flotr2.min.js')));
-		$this->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 aboutAction () {
 		Minz_View::prependTitle (Minz_Translate::t ('about') . ' · ');
 	}
@@ -316,7 +301,46 @@ class FreshRSS_index_Controller extends Minz_ActionController {
 		Minz_Session::_param('passwordHash');
 	}
 
+	private static function makeLongTermCookie($username, $passwordHash) {
+		do {
+			$token = sha1(Minz_Configuration::salt() . $username . uniqid(mt_rand(), true));
+			$tokenFile = DATA_PATH . '/tokens/' . $token . '.txt';
+		} while (file_exists($tokenFile));
+		if (@file_put_contents($tokenFile, $username . "\t" . $passwordHash) === false) {
+			return false;
+		}
+		$expire = time() + 2629744;	//1 month	//TODO: Use a configuration instead
+		Minz_Session::setLongTermCookie('FreshRSS_login', $token, $expire);
+		Minz_Session::_param('token', $token);
+		return $token;
+	}
+
+	private static function deleteLongTermCookie() {
+		Minz_Session::deleteLongTermCookie('FreshRSS_login');
+		$token = Minz_Session::param('token', null);
+		if (ctype_alnum($token)) {
+			@unlink(DATA_PATH . '/tokens/' . $token . '.txt');
+		}
+		Minz_Session::_param('token');
+		if (rand(0, 10) === 1) {
+			self::purgeTokens();
+		}
+	}
+
+	private static function purgeTokens() {
+		$oldest = time() - 2629744;	//1 month	//TODO: Use a configuration instead
+		foreach (new DirectoryIterator(DATA_PATH . '/tokens/') as $fileInfo) {
+			if ($fileInfo->getExtension() === 'txt' && $fileInfo->getMTime() < $oldest) {
+				@unlink($fileInfo->getPathname());
+			}
+		}
+	}
+
 	public function formLoginAction () {
+		if ($this->view->loginOk) {
+			Minz_Request::forward(array('c' => 'index', 'a' => 'index'), true);
+		}
+
 		if (Minz_Request::isPost()) {
 			$ok = false;
 			$nonce = Minz_Session::param('nonce');
@@ -333,6 +357,11 @@ class FreshRSS_index_Controller extends Minz_ActionController {
 					if ($ok) {
 						Minz_Session::_param('currentUser', $username);
 						Minz_Session::_param('passwordHash', $s);
+						if (Minz_Request::param('keep_logged_in', false)) {
+							self::makeLongTermCookie($username, $s);
+						} else {
+							self::deleteLongTermCookie();
+						}
 					} else {
 						Minz_Log::record('Password mismatch for user ' . $username . ', nonce=' . $nonce . ', c=' . $c, Minz_Log::WARNING);
 					}
@@ -351,6 +380,32 @@ class FreshRSS_index_Controller extends Minz_ActionController {
 			}
 			$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,
@@ -366,6 +421,78 @@ class FreshRSS_index_Controller extends Minz_ActionController {
 		Minz_Session::_param('currentUser');
 		Minz_Session::_param('mail');
 		Minz_Session::_param('passwordHash');
+		self::deleteLongTermCookie();
 		Minz_Request::forward(array('c' => 'index', 'a' => 'index'), true);
 	}
+
+	public function resetAuthAction() {
+		Minz_View::prependTitle(_t('auth_reset') . ' · ');
+		Minz_View::appendScript(Minz_Url::display(
+			'/scripts/bcrypt.min.js?' . @filemtime(PUBLIC_PATH . '/scripts/bcrypt.min.js')
+		));
+
+		$this->view->no_form = false;
+		// Enable changement of auth only if Persona!
+		if (Minz_Configuration::authType() != 'persona') {
+			$this->view->message = array(
+				'status' => 'bad',
+				'title' => _t('damn'),
+				'body' => _t('auth_not_persona')
+			);
+			$this->view->no_form = true;
+			return;
+		}
+
+		$conf = new FreshRSS_Configuration(Minz_Configuration::defaultUser());
+		// Admin user must have set its master password.
+		if (!$conf->passwordHash) {
+			$this->view->message = array(
+				'status' => 'bad',
+				'title' => _t('damn'),
+				'body' => _t('auth_no_password_set')
+			);
+			$this->view->no_form = true;
+			return;
+		}
+
+		invalidateHttpCache();
+
+		if (Minz_Request::isPost()) {
+			$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))) {
+				Minz_Log::debug('Invalid credential parameters:' .
+				                ' user=' . $username .
+				                ' challenge=' . $c .
+				                ' nonce=' . $nonce);
+				Minz_Request::bad(_t('invalid_login'),
+				                  array('c' => 'index', 'a' => 'resetAuth'));
+			}
+
+			if (!function_exists('password_verify')) {
+				include_once(LIB_PATH . '/password_compat.php');
+			}
+
+			$s = $conf->passwordHash;
+			$ok = password_verify($nonce . $s, $c);
+			if ($ok) {
+				Minz_Configuration::_authType('form');
+				$ok = Minz_Configuration::writeFile();
+
+				if ($ok) {
+					Minz_Request::good(_t('auth_form_set'));
+				} else {
+					Minz_Request::bad(_t('auth_form_not_set'),
+				                      array('c' => 'index', 'a' => 'resetAuth'));
+				}
+			} else {
+				Minz_Log::debug('Password mismatch for user ' . $username .
+				                ', nonce=' . $nonce . ', c=' . $c);
+
+				Minz_Request::bad(_t('invalid_login'),
+				                  array('c' => 'index', 'a' => 'resetAuth'));
+			}
+		}
+	}
 }

+ 2 - 2
app/Controllers/javascriptController.php

@@ -7,8 +7,8 @@ class FreshRSS_javascript_Controller extends Minz_ActionController {
 
 	public function actualizeAction () {
 		header('Content-Type: text/javascript; charset=UTF-8');
-		$feedDAO = new FreshRSS_FeedDAO ();
-		$this->view->feeds = $feedDAO->listFeedsOrderUpdate();
+		$feedDAO = FreshRSS_Factory::createFeedDao();
+		$this->view->feeds = $feedDAO->listFeedsOrderUpdate($this->view->conf->ttl_default);
 	}
 
 	public function nbUnreadsPerFeedAction() {

+ 129 - 0
app/Controllers/statsController.php

@@ -0,0 +1,129 @@
+<?php
+
+/**
+ * Controller to handle application statistics.
+ */
+class FreshRSS_stats_Controller extends Minz_ActionController {
+
+	/**
+	 * This action handles the statistic main page.
+	 *
+	 * It displays the statistic main page.
+	 * The values computed to display the page are:
+	 *   - repartition of read/unread/favorite/not favorite
+	 *   - number of article per day
+	 *   - number of feed by category
+	 *   - number of article by category
+	 *   - list of most prolific feed
+	 */
+	public function indexAction() {
+		$statsDAO = FreshRSS_Factory::createStatsDAO();
+		Minz_View::appendScript(Minz_Url::display('/scripts/flotr2.min.js?' . @filemtime(PUBLIC_PATH . '/scripts/flotr2.min.js')));
+		$this->view->repartition = $statsDAO->calculateEntryRepartition();
+		$this->view->count = $statsDAO->calculateEntryCount();
+		$this->view->feedByCategory = $statsDAO->calculateFeedByCategory();
+		$this->view->entryByCategory = $statsDAO->calculateEntryByCategory();
+		$this->view->topFeed = $statsDAO->calculateTopFeed();
+	}
+
+	/**
+	 * This action handles the idle feed statistic page.
+	 *
+	 * It displays the list of idle feed for different period. The supported
+	 * periods are:
+	 *   - last year
+	 *   - last 6 months
+	 *   - last 3 months
+	 *   - last month
+	 *   - last week
+	 */
+	public function idleAction() {
+		$statsDAO = FreshRSS_Factory::createStatsDAO();
+		$feeds = $statsDAO->calculateFeedLastDate();
+		$idleFeeds = array(
+			'last_year' => array(),
+			'last_6_month' => array(),
+			'last_3_month' => array(),
+			'last_month' => array(),
+			'last_week' => 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 < $lastYear) {
+				$idleFeeds['last_year'][] = $feed;
+			} elseif ($feedDate < $last6Month) {
+				$idleFeeds['last_6_month'][] = $feed;
+			} elseif ($feedDate < $last3Month) {
+				$idleFeeds['last_3_month'][] = $feed;
+			} elseif ($feedDate < $lastMonth) {
+				$idleFeeds['last_month'][] = $feed;
+			} elseif ($feedDate < $lastWeek) {
+				$idleFeeds['last_week'][] = $feed;
+			}
+		}
+
+		$this->view->idleFeeds = $idleFeeds;
+	}
+
+	/**
+	 * This action handles the article repartition statistic page.
+	 *
+	 * It displays the number of article and the average of article for the
+	 * following periods:
+	 *   - hour of the day
+	 *   - day of the week
+	 *   - month
+	 *
+	 * @todo verify that the metrics used here make some sense. Especially
+	 *       for the average.
+	 */
+	public function repartitionAction() {
+		$statsDAO = FreshRSS_Factory::createStatsDAO();
+		$categoryDAO = new FreshRSS_CategoryDAO();
+		$feedDAO = FreshRSS_Factory::createFeedDao();
+		Minz_View::appendScript(Minz_Url::display('/scripts/flotr2.min.js?' . @filemtime(PUBLIC_PATH . '/scripts/flotr2.min.js')));
+		$id = Minz_Request::param ('id', null);
+		$this->view->categories = $categoryDAO->listCategories();
+		$this->view->feed = $feedDAO->searchById($id);
+		$this->view->days = $statsDAO->getDays();
+		$this->view->months = $statsDAO->getMonths();
+		$this->view->repartitionHour = $statsDAO->calculateEntryRepartitionPerFeedPerHour($id);
+		$this->view->averageHour = $statsDAO->calculateEntryAveragePerFeedPerHour($id);
+		$this->view->repartitionDayOfWeek = $statsDAO->calculateEntryRepartitionPerFeedPerDayOfWeek($id);
+		$this->view->averageDayOfWeek = $statsDAO->calculateEntryAveragePerFeedPerDayOfWeek($id);
+		$this->view->repartitionMonth = $statsDAO->calculateEntryRepartitionPerFeedPerMonth($id);
+		$this->view->averageMonth = $statsDAO->calculateEntryAveragePerFeedPerMonth($id);
+	}
+
+	/**
+	 * This action is called before every other action in that class. It is
+	 * the common boiler plate for every action. It is triggered by the
+	 * underlying framework.
+	 */
+	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') . ' · ');
+	}
+
+}

+ 129 - 0
app/Controllers/updateController.php

@@ -0,0 +1,129 @@
+<?php
+
+class FreshRSS_update_Controller extends Minz_ActionController {
+	public function firstAction() {
+		$current_user = Minz_Session::param('currentUser', '');
+		if (!$this->view->loginOk && Minz_Configuration::isAdmin($current_user)) {
+			Minz_Error::error(
+				403,
+				array('error' => array(_t('access_denied')))
+			);
+		}
+
+		invalidateHttpCache();
+
+		Minz_View::prependTitle(_t('update_system') . ' · ');
+		$this->view->update_to_apply = false;
+		$this->view->last_update_time = 'unknown';
+		$this->view->check_last_hour = false;
+		$timestamp = (int)@file_get_contents(DATA_PATH . '/last_update.txt');
+		if (is_numeric($timestamp) && $timestamp > 0) {
+			$this->view->last_update_time = timestamptodate($timestamp);
+			$this->view->check_last_hour = (time() - 3600) <= $timestamp;
+		}
+	}
+
+	public function indexAction() {
+		if (file_exists(UPDATE_FILENAME) && !is_writable(FRESHRSS_PATH)) {
+			$this->view->message = array(
+				'status' => 'bad',
+				'title' => _t('damn'),
+				'body' => _t('file_is_nok', FRESHRSS_PATH)
+			);
+		} elseif (file_exists(UPDATE_FILENAME)) {
+			// There is an update file to apply!
+			$this->view->update_to_apply = true;
+			$this->view->message = array(
+				'status' => 'good',
+				'title' => _t('ok'),
+				'body' => _t('update_can_apply')
+			);
+		}
+	}
+
+	public function checkAction() {
+		$this->view->change_view('update', 'index');
+
+		if (file_exists(UPDATE_FILENAME) || $this->view->check_last_hour) {
+			// There is already an update file to apply: we don't need to check
+			// the webserver!
+			// Or if already check during the last hour, do nothing.
+			Minz_Request::forward(array('c' => 'update'));
+
+			return;
+		}
+
+		$c = curl_init(FRESHRSS_UPDATE_WEBSITE);
+		curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
+		curl_setopt($c, CURLOPT_SSL_VERIFYPEER, true);
+		curl_setopt($c, CURLOPT_SSL_VERIFYHOST, 2);
+		$result = curl_exec($c);
+		$c_status = curl_getinfo($c, CURLINFO_HTTP_CODE);
+		$c_error = curl_error($c);
+		curl_close($c);
+
+		if ($c_status !== 200) {
+			Minz_Log::error(
+				'Error during update (HTTP code ' . $c_status . '): ' . $c_error
+			);
+
+			$this->view->message = array(
+				'status' => 'bad',
+				'title' => _t('damn'),
+				'body' => _t('update_server_not_found', FRESHRSS_UPDATE_WEBSITE)
+			);
+			return;
+		}
+
+		$res_array = explode("\n", $result, 2);
+		$status = $res_array[0];
+		if (strpos($status, 'UPDATE') !== 0) {
+			$this->view->message = array(
+				'status' => 'bad',
+				'title' => _t('damn'),
+				'body' => _t('no_update')
+			);
+
+			@file_put_contents(DATA_PATH . '/last_update.txt', time());
+
+			return;
+		}
+
+		$script = $res_array[1];
+		if (file_put_contents(UPDATE_FILENAME, $script) !== false) {
+			Minz_Request::forward(array('c' => 'update'));
+		} else {
+			$this->view->message = array(
+				'status' => 'bad',
+				'title' => _t('damn'),
+				'body' => _t('update_problem', 'Cannot save the update script')
+			);
+		}
+	}
+
+	public function applyAction() {
+		if (!file_exists(UPDATE_FILENAME) || !is_writable(FRESHRSS_PATH)) {
+			Minz_Request::forward(array('c' => 'update'), true);
+		}
+
+		require(UPDATE_FILENAME);
+
+		if (Minz_Request::isPost()) {
+			save_info_update();
+		}
+
+		if (!need_info_update()) {
+			$res = apply_update();
+
+			if ($res === true) {
+				@unlink(UPDATE_FILENAME);
+				@file_put_contents(DATA_PATH . '/last_update.txt', time());
+
+				Minz_Request::good(_t('update_finished'));
+			} else {
+				Minz_Request::bad(_t('update_problem', $res),
+				                  array('c' => 'update', 'a' => 'index'));
+			}
+		}
+	}
+}

+ 26 - 6
app/Controllers/usersController.php

@@ -17,7 +17,7 @@ class FreshRSS_users_Controller extends Minz_ActionController {
 		if (Minz_Request::isPost()) {
 			$ok = true;
 
-			$passwordPlain = Minz_Request::param('passwordPlain', false);
+			$passwordPlain = Minz_Request::param('passwordPlain', '', true);
 			if ($passwordPlain != '') {
 				Minz_Request::_param('passwordPlain');	//Discard plain-text password ASAP
 				$_POST['passwordPlain'] = '';
@@ -32,8 +32,20 @@ class FreshRSS_users_Controller extends Minz_ActionController {
 			}
 			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', false));
+				$this->view->conf->_mail_login(Minz_Request::param('mail_login', '', true));
 			}
 			$email = $this->view->conf->mail_login;
 			Minz_Session::_param('mail', $email);
@@ -57,13 +69,19 @@ class FreshRSS_users_Controller extends Minz_ActionController {
 				$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()) {
+					$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();
 				}
 			}
@@ -81,7 +99,8 @@ class FreshRSS_users_Controller extends Minz_ActionController {
 
 	public function createAction() {
 		if (Minz_Request::isPost() && Minz_Configuration::isAdmin(Minz_Session::param('currentUser', '_'))) {
-			require_once(APP_PATH . '/sql.php');
+			$db = Minz_Configuration::dataBase();
+			require_once(APP_PATH . '/SQL/install.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())) {
@@ -101,7 +120,7 @@ class FreshRSS_users_Controller extends Minz_ActionController {
 			}
 			if ($ok) {
 			
-				$passwordPlain = Minz_Request::param('new_user_passwordPlain', false);
+				$passwordPlain = Minz_Request::param('new_user_passwordPlain', '', true);
 				$passwordHash = '';
 				if ($passwordPlain != '') {
 					Minz_Request::_param('new_user_passwordPlain');	//Discard plain-text password ASAP
@@ -152,7 +171,8 @@ class FreshRSS_users_Controller extends Minz_ActionController {
 
 	public function deleteAction() {
 		if (Minz_Request::isPost() && Minz_Configuration::isAdmin(Minz_Session::param('currentUser', '_'))) {
-			require_once(APP_PATH . '/sql.php');
+			$db = Minz_Configuration::dataBase();
+			require_once(APP_PATH . '/SQL/install.sql.' . $db['type'] . '.php');
 
 			$username = Minz_Request::param('username');
 			$ok = ctype_alnum($username);

+ 0 - 6
app/Exceptions/OpmlException.php

@@ -1,6 +0,0 @@
-<?php
-class FreshRSS_Opml_Exception extends FreshRSS_Feed_Exception {
-	public function __construct ($name_file) {
-		parent::__construct ('OPML file is invalid');
-	}
-}

+ 49 - 13
app/FreshRSS.php

@@ -6,17 +6,48 @@ class FreshRSS extends Minz_FrontController {
 		}
 		$loginOk = $this->accessControl(Minz_Session::param('currentUser', ''));
 		$this->loadParamsView();
+		if (Minz_Request::isPost() && !is_referer_from_same_domain()) {
+			$loginOk = false;	//Basic protection against XSRF attacks
+			Minz_Error::error(
+				403,
+				array('error' => array(Minz_Translate::t('access_denied') . ' [HTTP_REFERER=' .
+					htmlspecialchars(empty($_SERVER['HTTP_REFERER']) ? '' : $_SERVER['HTTP_REFERER']) . ']'))
+			);
+		}
+		Minz_View::_param('loginOk', $loginOk);
 		$this->loadStylesAndScripts($loginOk);	//TODO: Do not load that when not needed, e.g. some Ajax requests
 		$this->loadNotifications();
 	}
 
+	private static function getCredentialsFromLongTermCookie() {
+		$token = Minz_Session::getLongTermCookie('FreshRSS_login');
+		if (!ctype_alnum($token)) {
+			return array();
+		}
+		$tokenFile = DATA_PATH . '/tokens/' . $token . '.txt';
+		$mtime = @filemtime($tokenFile);
+		if ($mtime + 2629744 < time()) {	//1 month	//TODO: Use a configuration instead
+			@unlink($tokenFile);
+			return array(); 	//Expired or token does not exist
+		}
+		$credentials = @file_get_contents($tokenFile);
+		return $credentials === false ? array() : explode("\t", $credentials, 2);
+	}
+
 	private function accessControl($currentUser) {
 		if ($currentUser == '') {
 			switch (Minz_Configuration::authType()) {
 				case 'form':
-					$currentUser = Minz_Configuration::defaultUser();
-					Minz_Session::_param('passwordHash');
-					$loginOk = false;
+					$credentials = self::getCredentialsFromLongTermCookie();
+					if (isset($credentials[1])) {
+						$currentUser = trim($credentials[0]);
+						Minz_Session::_param('passwordHash', trim($credentials[1]));
+					}
+					$loginOk = $currentUser != '';
+					if (!$loginOk) {
+						$currentUser = Minz_Configuration::defaultUser();
+						Minz_Session::_param('passwordHash');
+					}
 					break;
 				case 'http_auth':
 					$currentUser = httpAuthUser();
@@ -95,7 +126,6 @@ class FreshRSS extends Minz_FrontController {
 					break;
 			}
 		}
-		Minz_View::_param ('loginOk', $loginOk);
 		return $loginOk;
 	}
 
@@ -109,11 +139,21 @@ class FreshRSS extends Minz_FrontController {
 		}
 	}
 
-	private function loadStylesAndScripts ($loginOk) {
+	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)));
+				if ($file[0] === '_') {
+					$theme_id = 'base-theme';
+					$filename = substr($file, 1);
+				} else {
+					$theme_id = $theme['id'];
+					$filename = $file;
+				}
+				$filetime = @filemtime(PUBLIC_PATH . '/themes/' . $theme_id . '/' . $filename);
+				Minz_View::appendStyle(Minz_Url::display(
+					'/themes/' . $theme_id . '/' . $filename . '?' . $filetime
+				));
 			}
 		}
 
@@ -127,13 +167,9 @@ class FreshRSS extends Minz_FrontController {
 				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')));
+		Minz_View::appendScript(Minz_Url::display('/scripts/jquery.min.js?' . @filemtime(PUBLIC_PATH . '/scripts/jquery.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 () {

+ 1 - 1
app/Models/Category.php

@@ -44,7 +44,7 @@ class FreshRSS_Category extends Minz_Model {
 	}
 	public function feeds () {
 		if ($this->feeds === null) {
-			$feedDAO = new FreshRSS_FeedDAO ();
+			$feedDAO = FreshRSS_Factory::createFeedDao();
 			$this->feeds = $feedDAO->listByCategory ($this->id ());
 			$this->nbFeed = 0;
 			$this->nbNotRead = 0;

+ 24 - 11
app/Models/CategoryDAO.php

@@ -12,12 +12,25 @@ class FreshRSS_CategoryDAO extends Minz_ModelPdo {
 		if ($stm && $stm->execute ($values)) {
 			return $this->bd->lastInsertId();
 		} else {
-			$info = $stm->errorInfo();
-			Minz_Log::record ('SQL error : ' . $info[2], Minz_Log::ERROR);
+			$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);
@@ -30,8 +43,8 @@ class FreshRSS_CategoryDAO extends Minz_ModelPdo {
 		if ($stm && $stm->execute ($values)) {
 			return $stm->rowCount();
 		} else {
-			$info = $stm->errorInfo();
-			Minz_Log::record ('SQL error : ' . $info[2], Minz_Log::ERROR);
+			$info = $stm == null ? array(2 => 'syntax error') : $stm->errorInfo();
+			Minz_Log::record('SQL error updateCategory: ' . $info[2], Minz_Log::ERROR);
 			return false;
 		}
 	}
@@ -45,8 +58,8 @@ class FreshRSS_CategoryDAO extends Minz_ModelPdo {
 		if ($stm && $stm->execute ($values)) {
 			return $stm->rowCount();
 		} else {
-			$info = $stm->errorInfo();
-			Minz_Log::record ('SQL error : ' . $info[2], Minz_Log::ERROR);
+			$info = $stm == null ? array(2 => 'syntax error') : $stm->errorInfo();
+			Minz_Log::record('SQL error deleteCategory: ' . $info[2], Minz_Log::ERROR);
 			return false;
 		}
 	}
@@ -64,7 +77,7 @@ class FreshRSS_CategoryDAO extends Minz_ModelPdo {
 		if (isset ($cat[0])) {
 			return $cat[0];
 		} else {
-			return false;
+			return null;
 		}
 	}
 	public function searchByName ($name) {
@@ -80,7 +93,7 @@ class FreshRSS_CategoryDAO extends Minz_ModelPdo {
 		if (isset ($cat[0])) {
 			return $cat[0];
 		} else {
-			return false;
+			return null;
 		}
 	}
 
@@ -89,7 +102,7 @@ class FreshRSS_CategoryDAO extends Minz_ModelPdo {
 			$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 '
+			     . '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);
@@ -120,7 +133,7 @@ class FreshRSS_CategoryDAO extends Minz_ModelPdo {
 	public function checkDefault () {
 		$def_cat = $this->searchById (1);
 
-		if ($def_cat === false) {
+		if ($def_cat == null) {
 			$cat = new FreshRSS_Category (Minz_Translate::t ('default_category'));
 			$cat->_id (1);
 
@@ -153,7 +166,7 @@ class FreshRSS_CategoryDAO extends Minz_ModelPdo {
 	}
 
 	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';
+		$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);

+ 119 - 33
app/Models/Configuration.php

@@ -7,16 +7,22 @@ class FreshRSS_Configuration {
 		'language' => 'en',
 		'old_entries' => 3,
 		'keep_history_default' => 0,
+		'ttl_default' => 3600,
 		'mail_login' => '',
 		'token' => '',
 		'passwordHash' => '',	//CRYPT_BLOWFISH
+		'apiPasswordHash' => '',	//CRYPT_BLOWFISH
 		'posts_per_page' => 20,
 		'view_mode' => 'normal',
-		'default_view' => 'not_read',
+		'default_view' => FreshRSS_Entry::STATE_NOT_READ,
 		'auto_load_more' => true,
 		'display_posts' => false,
+		'display_categories' => false,
+		'hide_read_feeds' => true,
 		'onread_jump_next' => true,
 		'lazyload' => true,
+		'sticky_post' => true,
+		'reading_confirm' => false,
 		'sort_order' => 'DESC',
 		'anon_access' => false,
 		'mark_when' => array(
@@ -26,6 +32,7 @@ class FreshRSS_Configuration {
 			'reception' => false,
 		),
 		'theme' => 'Origine',
+		'content_width' => 'thin',
 		'shortcuts' => array(
 			'mark_read' => 'r',
 			'mark_favorite' => 'f',
@@ -37,6 +44,9 @@ class FreshRSS_Configuration {
 			'collapse_entry' => 'c',
 			'load_more' => 'm',
 			'auto_share' => 's',
+			'focus_search' => 'a',
+			'user_filter' => 'u',
+			'help' => 'f1',
 		),
 		'topline_read' => true,
 		'topline_favorite' => true,
@@ -48,16 +58,9 @@ class FreshRSS_Configuration {
 		'bottomline_tags' => true,
 		'bottomline_date' => true,
 		'bottomline_link' => true,
-		'sharing' => array(
-			'shaarli' => '',
-			'wallabag' => '',
-			'diaspora' => '',
-			'twitter' => true,
-			'g+' => true,
-			'facebook' => true,
-			'email' => true,
-			'print' => true,
-		),
+		'sharing' => array(),
+		'queries' => array(),
+		'html5_notif_timeout' => 0,
 	);
 
 	private $available_languages = array(
@@ -65,8 +68,10 @@ class FreshRSS_Configuration {
 		'fr' => 'Français',
 	);
 
-	public function __construct ($user) {
-		$this->filename = DATA_PATH . '/' . $user . '_user.php';
+	private $shares;
+
+	public function __construct($user) {
+		$this->filename = DATA_PATH . DIRECTORY_SEPARATOR . $user . '_user.php';
 
 		$data = @include($this->filename);
 		if (!is_array($data)) {
@@ -80,10 +85,20 @@ class FreshRSS_Configuration {
 			}
 		}
 		$this->data['user'] = $user;
+
+		$this->shares = DATA_PATH . DIRECTORY_SEPARATOR . 'shares.php';
+
+		$shares = @include($this->shares);
+		if (!is_array($shares)) {
+			throw new Minz_PermissionDeniedException($this->shares);
+		}
+
+		$this->data['shares'] = $shares;
 	}
 
 	public function save() {
 		@rename($this->filename, $this->filename . '.bak.php');
+		unset($this->data['shares']); // Remove shares because it is not intended to be stored in user configuration
 		if (file_put_contents($this->filename, "<?php\n return " . var_export($this->data, true) . ';', LOCK_EX) === false) {
 			throw new Minz_PermissionDeniedException($this->filename);
 		}
@@ -104,20 +119,20 @@ class FreshRSS_Configuration {
 		}
 	}
 
-	public function sharing($key = false) {
-		if ($key === false) {
-			return $this->data['sharing'];
-		}
-		if (isset($this->data['sharing'][$key])) {
-			return $this->data['sharing'][$key];
-		}
-		return false;
-	}
-
 	public function availableLanguages() {
 		return $this->available_languages;
 	}
 
+	public function remove_query_by_get($get) {
+		$final_queries = array();
+		foreach ($this->queries as $key => $query) {
+			if (empty($query['get']) || $query['get'] !== $get) {
+				$final_queries[$key] = $query;
+			}
+		}
+		$this->_queries($final_queries);
+	}
+
 	public function _language($value) {
 		if (!isset($this->available_languages[$value])) {
 			$value = 'en';
@@ -136,17 +151,40 @@ class FreshRSS_Configuration {
 		}
 	}
 	public function _default_view ($value) {
-		$this->data['default_view'] = $value === 'all' ? 'all' : 'not_read';
+		switch ($value) {
+		case FreshRSS_Entry::STATE_ALL:
+			// left blank on purpose
+		case FreshRSS_Entry::STATE_NOT_READ:
+			// left blank on purpose
+		case FreshRSS_Entry::STATE_STRICT + FreshRSS_Entry::STATE_NOT_READ:
+			$this->data['default_view'] = $value;
+			break;
+		default:
+			$this->data['default_view'] = FreshRSS_Entry::STATE_ALL;
+			break;
+		}
 	}
 	public function _display_posts ($value) {
 		$this->data['display_posts'] = ((bool)$value) && $value !== 'no';
 	}
+	public function _display_categories ($value) {
+		$this->data['display_categories'] = ((bool)$value) && $value !== 'no';
+	}
+	public function _hide_read_feeds($value) {
+		$this->data['hide_read_feeds'] = (bool)$value;
+	}
 	public function _onread_jump_next ($value) {
 		$this->data['onread_jump_next'] = ((bool)$value) && $value !== 'no';
 	}
 	public function _lazyload ($value) {
 		$this->data['lazyload'] = ((bool)$value) && $value !== 'no';
 	}
+	public function _sticky_post($value) {
+		$this->data['sticky_post'] = ((bool)$value) && $value !== 'no';
+	}
+	public function _reading_confirm($value) {
+		$this->data['reading_confirm'] = ((bool)$value) && $value !== 'no';
+	}
 	public function _sort_order ($value) {
 		$this->data['sort_order'] = $value === 'ASC' ? 'ASC' : 'DESC';
 	}
@@ -158,6 +196,10 @@ class FreshRSS_Configuration {
 		$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])) {
@@ -168,6 +210,9 @@ class FreshRSS_Configuration {
 	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) {
@@ -187,29 +232,70 @@ class FreshRSS_Configuration {
 		}
 	}
 	public function _sharing ($values) {
-		$are_url = array ('shaarli', 'wallabag', 'diaspora');
-		foreach ($values as $key => $value) {
-			if (in_array($key, $are_url)) {
+		$this->data['sharing'] = array();
+		$unique = array();
+		foreach ($values as $value) {
+			if (!is_array($value)) {
+				continue;
+			}
+
+			// Verify URL and add default value when needed
+			if (isset($value['url'])) {
 				$is_url = (
-					filter_var ($value, FILTER_VALIDATE_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) {
-					$value = '';
+					continue;
 				}
-			} elseif (!is_bool($value)) {
-				$value = true;
+			} else {
+				$value['url'] = null;
+			}
+
+			// Add a default name
+			if (empty($value['name'])) {
+				$value['name'] = $value['type'];
 			}
 
-			$this->data['sharing'][$key] = $value;
+			$json_value = json_encode($value);
+			if (!in_array($json_value, $unique)) {
+				$unique[] = $json_value;
+				$this->data['sharing'][] = $value;
+			}
+		}
+	}
+	public function _queries ($values) {
+		$this->data['queries'] = array();
+		foreach ($values as $value) {
+			$value = array_filter($value);
+			$params = $value;
+			unset($params['name']);
+			unset($params['url']);
+			$value['url'] = Minz_Url::display(array('params' => $params));
+
+			$this->data['queries'][] = $value;
 		}
 	}
 	public function _theme($value) {
 		$this->data['theme'] = $value;
 	}
+	public function _content_width($value) {
+		if ($value === 'medium' ||
+				$value === 'large' ||
+				$value === 'no_limit') {
+			$this->data['content_width'] = $value;
+		} else {
+			$this->data['content_width'] = 'thin';
+		}
+	}
+	
+	public function _html5_notif_timeout ($value) {
+		$value = intval($value);
+		$this->data['html5_notif_timeout'] = $value >= 0 ? $value : 0;
+	}
+	
 	public function _token($value) {
 		$this->data['token'] = $value;
 	}

+ 8 - 2
app/Models/Entry.php

@@ -1,6 +1,12 @@
 <?php
 
 class FreshRSS_Entry extends Minz_Model {
+	const STATE_ALL = 0;
+	const STATE_READ = 1;
+	const STATE_NOT_READ = 2;
+	const STATE_FAVORITE = 4;
+	const STATE_NOT_FAVORITE = 8;
+	const STATE_STRICT = 16;
 
 	private $id = 0;
 	private $guid;
@@ -69,7 +75,7 @@ class FreshRSS_Entry extends Minz_Model {
 	}
 	public function feed ($object = false) {
 		if ($object) {
-			$feedDAO = new FreshRSS_FeedDAO ();
+			$feedDAO = FreshRSS_Factory::createFeedDao();
 			return $feedDAO->searchById ($this->feed);
 		} else {
 			return $this->feed;
@@ -149,7 +155,7 @@ class FreshRSS_Entry extends Minz_Model {
 		// Gestion du contenu
 		// On cherche à récupérer les articles en entier... même si le flux ne le propose pas
 		if ($pathEntries) {
-			$entryDAO = new FreshRSS_EntryDAO();
+			$entryDAO = FreshRSS_Factory::createEntryDao();
 			$entry = $entryDAO->searchByGuid($this->feed, $this->guid);
 
 			if($entry) {

+ 392 - 298
app/Models/EntryDAO.php

@@ -1,12 +1,27 @@
 <?php
 
 class FreshRSS_EntryDAO extends Minz_ModelPdo {
-	public function addEntry ($valuesTmp) {
-		$sql = 'INSERT INTO `' . $this->prefix . 'entry`(id, guid, title, author, content_bin, link, date, is_read, is_favorite, id_feed, tags) '
-		     . 'VALUES(?, ?, ?, ?, COMPRESS(?), ?, ?, ?, ?, ?, ?)';
-		$stm = $this->bd->prepare ($sql);
 
-		$values = array (
+	public function isCompressed() {
+		return parent::$sharedDbType !== 'sqlite';
+	}
+
+	public function addEntryPrepare() {
+		$sql = 'INSERT INTO `' . $this->prefix . 'entry`(id, guid, title, author, '
+		     . ($this->isCompressed() ? 'content_bin' : 'content')
+		     . ', link, date, is_read, is_favorite, id_feed, tags) '
+		     . 'VALUES(?, ?, ?, ?, '
+		     . ($this->isCompressed() ? 'COMPRESS(?)' : '?')
+		     . ', ?, ?, ?, ?, ?, ?)';
+		return $this->bd->prepare($sql);
+	}
+
+	public function addEntry($valuesTmp, $preparedStatement = null) {
+		$stm = $preparedStatement === null ?
+				FreshRSS_EntryDAO::addEntryPrepare() :
+				$preparedStatement;
+
+		$values = array(
 			$valuesTmp['id'],
 			substr($valuesTmp['guid'], 0, 760),
 			substr($valuesTmp['title'], 0, 255),
@@ -20,12 +35,12 @@ class FreshRSS_EntryDAO extends Minz_ModelPdo {
 			substr($valuesTmp['tags'], 0, 1023),
 		);
 
-		if ($stm && $stm->execute ($values)) {
+		if ($stm && $stm->execute($values)) {
 			return $this->bd->lastInsertId();
 		} else {
-			$info = $stm->errorInfo();
+			$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 ' . $info[0] . ': ' . $info[1] . ' ' . $info[2]
+				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]
@@ -35,232 +50,259 @@ class FreshRSS_EntryDAO extends Minz_ModelPdo {
 		}
 	}
 
-	public function markFavorite ($id, $is_favorite = true) {
-		$sql = 'UPDATE `' . $this->prefix . 'entry` e '
-		     . 'SET e.is_favorite = ? '
-		     . 'WHERE e.id=?';
-		$values = array ($is_favorite ? 1 : 0, $id);
-		$stm = $this->bd->prepare ($sql);
-		if ($stm && $stm->execute ($values)) {
+	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 || $entry->isFavorite())) {
+			$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->errorInfo();
-			Minz_Log::record ('SQL error : ' . $info[2], Minz_Log::ERROR);
+			$info = $stm == null ? array(2 => 'syntax error') : $stm->errorInfo();
+			Minz_Log::record('SQL error markFavorite: ' . $info[2], Minz_Log::ERROR);
 			return false;
 		}
 	}
-	public function markRead ($id, $is_read = true) {
-		$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=?';
-		$values = array ($is_read ? 1 : 0, $id);
-		$stm = $this->bd->prepare ($sql);
-		if ($stm && $stm->execute ($values)) {
-			return $stm->rowCount();
+
+	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->errorInfo();
-			Minz_Log::record ('SQL error : ' . $info[2], Minz_Log::ERROR);
+			$info = $stm == null ? array(2 => 'syntax error') : $stm->errorInfo();
+			Minz_Log::record('SQL error updateCacheUnreads: ' . $info[2], Minz_Log::ERROR);
 			return false;
 		}
 	}
-	public function markReadEntries ($idMax = 0, $favorites = false) {
-		if ($idMax === 0) {
-			$sql = 'UPDATE `' . $this->prefix . 'entry` e INNER JOIN `' . $this->prefix . 'feed` f ON e.id_feed = f.id '
-			     . 'SET e.is_read = 1, f.cache_nbUnreads=0 '
-			     . 'WHERE e.is_read = 0 AND ';
-			if ($favorites) {
-				$sql .= 'e.is_favorite = 1';
-			} else {
-				$sql .= 'f.priority > 0';
-			}
-			$stm = $this->bd->prepare ($sql);
-			if ($stm && $stm->execute ()) {
-				return $stm->rowCount();
-			} else {
-				$info = $stm->errorInfo();
-				Minz_Log::record ('SQL error : ' . $info[2], Minz_Log::ERROR);
-				return false;
-			}
-		} else {
-			$this->bd->beginTransaction ();
 
-			$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 <= ? AND ';
-			if ($favorites) {
-				$sql .= 'e.is_favorite = 1';
-			} else {
-				$sql .= 'f.priority > 0';
+	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;
 			}
-			$values = array ($idMax);
-			$stm = $this->bd->prepare ($sql);
-			if (!($stm && $stm->execute ($values))) {
-				$info = $stm->errorInfo();
-				Minz_Log::record ('SQL error : ' . $info[2], Minz_Log::ERROR);
-				$this->bd->rollBack ();
+
+			$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) {
-				$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)';
-				$stm = $this->bd->prepare ($sql);
-				if (!($stm && $stm->execute ())) {
-					$info = $stm->errorInfo();
-					Minz_Log::record ('SQL error : ' . $info[2], Minz_Log::ERROR);
-					$this->bd->rollBack ();
-					return false;
-				}
+			if (($affected > 0) && (!$this->updateCacheUnreads(false, false))) {
+				return false;
 			}
-
-			$this->bd->commit ();
 			return $affected;
-		}
-	}
-	public function markReadCat ($id, $idMax = 0) {
-		if ($idMax === 0) {
-			$sql = 'UPDATE `' . $this->prefix . 'entry` e INNER JOIN `' . $this->prefix . 'feed` f ON e.id_feed = f.id '
-			     . 'SET e.is_read = 1, f.cache_nbUnreads=0 '
-			     . 'WHERE f.category = ? AND e.is_read = 0';
-			$values = array ($id);
-			$stm = $this->bd->prepare ($sql);
-			if ($stm && $stm->execute ($values)) {
+		} 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->errorInfo();
-				Minz_Log::record ('SQL error : ' . $info[2], Minz_Log::ERROR);
+				$info = $stm == null ? array(2 => 'syntax error') : $stm->errorInfo();
+				Minz_Log::record('SQL error markRead: ' . $info[2], Minz_Log::ERROR);
 				return false;
 			}
-		} else {
-			$this->bd->beginTransaction ();
-
-			$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->errorInfo();
-				Minz_Log::record ('SQL error : ' . $info[2], Minz_Log::ERROR);
-				$this->bd->rollBack ();
-				return false;
-			}
-			$affected = $stm->rowCount();
+		}
+	}
 
-			if ($affected > 0) {
-				$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 f.category = ?';
-				$values = array ($id);
-				$stm = $this->bd->prepare ($sql);
-				if (!($stm && $stm->execute ($values))) {
-					$info = $stm->errorInfo();
-					Minz_Log::record ('SQL error : ' . $info[2], Minz_Log::ERROR);
-					$this->bd->rollBack ();
-					return false;
-				}
-			}
+	public function markReadEntries($idMax = 0, $onlyFavorites = false, $priorityMin = 0) {
+		if ($idMax == 0) {
+			$idMax = time() . '000000';
+			Minz_Log::record('Calling markReadEntries(0) is deprecated!', Minz_Log::DEBUG);
+		}
 
-			$this->bd->commit ();
-			return $affected;
+		$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 markReadFeed ($id, $idMax = 0) {
-		if ($idMax === 0) {
-			$sql = 'UPDATE `' . $this->prefix . 'entry` e INNER JOIN `' . $this->prefix . 'feed` f ON e.id_feed = f.id '
-			     . 'SET e.is_read = 1, f.cache_nbUnreads=0 '
-			     . 'WHERE f.id=? AND e.is_read = 0';
-			$values = array ($id);
-			$stm = $this->bd->prepare ($sql);
-			if ($stm && $stm->execute ($values)) {
-				return $stm->rowCount();
-			} else {
-				$info = $stm->errorInfo();
-				Minz_Log::record ('SQL error : ' . $info[2], Minz_Log::ERROR);
-				return false;
-			}
-		} else {
-			$this->bd->beginTransaction ();
-
-			$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.id=? AND e.is_read = 0 AND e.id <= ?';
-			$values = array ($id, $idMax);
-			$stm = $this->bd->prepare ($sql);
-			if (!($stm && $stm->execute ($values))) {
-				$info = $stm->errorInfo();
-				Minz_Log::record ('SQL error : ' . $info[2], Minz_Log::ERROR);
-				$this->bd->rollBack ();
-				return false;
-			}
-			$affected = $stm->rowCount();
 
-			if ($affected > 0) {
-				$sql = 'UPDATE `' . $this->prefix . 'feed` f '
-				     . 'SET f.cache_nbUnreads=f.cache_nbUnreads-' . $affected
-				     . ' WHERE f.id=?';
-				$values = array ($id);
-				$stm = $this->bd->prepare ($sql);
-				if (!($stm && $stm->execute ($values))) {
-					$info = $stm->errorInfo();
-					Minz_Log::record ('SQL error : ' . $info[2], Minz_Log::ERROR);
-					$this->bd->rollBack ();
-					return false;
-				}
-			}
+	public function markReadCat($id, $idMax = 0) {
+		if ($idMax == 0) {
+			$idMax = time() . '000000';
+			Minz_Log::record('Calling markReadCat(0) is deprecated!', Minz_Log::DEBUG);
+		}
 
-			$this->bd->commit ();
-			return $affected;
+		$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('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) {
+	public function searchByGuid($feed_id, $id) {
 		// un guid est unique pour un flux donné
-		$sql = 'SELECT id, guid, title, author, UNCOMPRESS(content_bin) AS content, link, date, is_read, is_favorite, id_feed, tags '
+		$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);
+		$stm = $this->bd->prepare($sql);
 
-		$values = array (
+		$values = array(
 			$feed_id,
 			$id
 		);
 
-		$stm->execute ($values);
-		$res = $stm->fetchAll (PDO::FETCH_ASSOC);
-		$entries = self::daoToEntry ($res);
-		return isset ($entries[0]) ? $entries[0] : false;
+		$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, UNCOMPRESS(content_bin) AS content, link, date, is_read, is_favorite, id_feed, tags '
+	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);
+		$stm = $this->bd->prepare($sql);
+
+		$values = array($id);
 
-		$values = array ($id);
+		$stm->execute($values);
+		$res = $stm->fetchAll(PDO::FETCH_ASSOC);
+		$entries = self::daoToEntry($res);
+		return isset($entries[0]) ? $entries[0] : null;
+	}
 
-		$stm->execute ($values);
-		$res = $stm->fetchAll (PDO::FETCH_ASSOC);
-		$entries = self::daoToEntry ($res);
-		return isset ($entries[0]) ? $entries[0] : false;
+	protected function sqlConcat($s1, $s2) {
+		return 'CONCAT(' . $s1 . ',' . $s2 . ')';	//MySQL
 	}
 
-	public function listWhere($type = 'a', $id = '', $state = 'all', $order = 'DESC', $limit = 1, $firstId = '', $filter = '', $date_min = 0, $keepHistoryDefault = 0) {
+	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();
@@ -269,185 +311,237 @@ class FreshRSS_EntryDAO extends Minz_ModelPdo {
 				$where .= 'f.priority > 0 ';
 				$joinFeed = true;
 				break;
-			case 's':
-				$where .= 'e1.is_favorite = 1 ';
+			case 's':	//Deprecated: use $state instead
+				$where .= 'e1.is_favorite=1 ';
 				break;
 			case 'c':
-				$where .= 'f.category = ? ';
+				$where .= 'f.category=? ';
 				$values[] = intval($id);
 				$joinFeed = true;
 				break;
 			case 'f':
-				$where .= 'e1.id_feed = ? ';
+				$where .= 'e1.id_feed=? ';
 				$values[] = intval($id);
 				break;
-			default:
-				throw new FreshRSS_EntriesGetter_Exception ('Bad type in Entry->listByType: [' . $type . ']!');
-		}
-		switch ($state) {
-			case 'all':
-				break;
-			case 'not_read':
-				$where .= 'AND e1.is_read = 0 ';
-				break;
-			case 'read':
-				$where .= 'AND e1.is_read = 1 ';
-				break;
-			case 'favorite':
-				$where .= 'AND e1.is_favorite = 1 ';
+			case 'A':
+				$where .= '1 ';
 				break;
 			default:
-				throw new FreshRSS_EntriesGetter_Exception ('Bad state in Entry->listByType: [' . $state . ']!');
+				throw new FreshRSS_EntriesGetter_Exception('Bad type in Entry->listByType: [' . $type . ']!');
+		}
+
+		if ($state & FreshRSS_Entry::STATE_NOT_READ) {
+			if (!($state & FreshRSS_Entry::STATE_READ)) {
+				$where .= 'AND e1.is_read=0 ';
+			} elseif ($state & FreshRSS_Entry::STATE_STRICT) {
+				$where .= 'AND e1.is_read=0 ';
+			}
+		}
+		elseif ($state & FreshRSS_Entry::STATE_READ) {
+			$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 . ']!');
+				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 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 .= '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 .= ')) ';
+			$where .= ') ';
 			$joinFeed = true;
 		}
 		$search = '';
 		if ($filter !== '') {
+			require_once(LIB_PATH . '/lib_date.php');
 			$filter = trim($filter);
 			$filter = addcslashes($filter, '\\%_');
-			if (stripos($filter, 'intitle:') === 0) {
-				$filter = substr($filter, strlen('intitle:'));
-				$intitle = true;
-			} else {
-				$intitle = false;
-			}
-			if (stripos($filter, 'inurl:') === 0) {
-				$filter = substr($filter, strlen('inurl:'));
-				$inurl = true;
-			} else {
-				$inurl = false;
-			}
-			if (stripos($filter, 'author:') === 0) {
-				$filter = substr($filter, strlen('author:'));
-				$author = true;
-			} else {
-				$author = false;
-			}
 			$terms = array_unique(explode(' ', $filter));
-			sort($terms);	//Put #tags first
+			//sort($terms);	//Put #tags first	//TODO: Put the cheapest filters first
 			foreach ($terms as $word) {
 				$word = trim($word);
-				if (strlen($word) > 0) {
-					if ($intitle) {
-						$search .= 'AND e1.title LIKE ? ';
-						$values[] = '%' . $word .'%';
-					} elseif ($inurl) {
-						$search .= 'AND CONCAT(e1.link, e1.guid) LIKE ? ';
-						$values[] = '%' . $word .'%';
-					} elseif ($author) {
-						$search .= 'AND e1.author LIKE ? ';
+				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 {
-						if ($word[0] === '#' && isset($word[1])) {
-							$search .= 'AND e1.tags LIKE ? ';
-							$values[] = '%' . $word .'%';
-						} else {
-							$search .= 'AND CONCAT(e1.title, UNCOMPRESS(e1.content_bin)) LIKE ? ';
-							$values[] = '%' . $word .'%';
-						}
+						$search .= 'AND ' . $this->sqlconcat('e1.title', $this->isCompressed() ? 'UNCOMPRESS(content_bin)' : 'content') . ' LIKE ? ';
+						$values[] = '%' . $word .'%';
 					}
 				}
 			}
 		}
 
-		$sql = 'SELECT e.id, e.guid, e.title, e.author, UNCOMPRESS(e.content_bin) AS content, e.link, e.date, e.is_read, e.is_favorite, e.id_feed, e.tags '
+		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 (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/
-		     . ') e2 ON e2.id = e.id '
+		     . 'INNER JOIN ('
+		     . $sql
+		     . ') e2 ON e2.id=e.id '
 		     . 'ORDER BY e.id ' . $order;
 
-		$stm = $this->bd->prepare ($sql);
-		$stm->execute ($values);
+		$stm = $this->bd->prepare($sql);
+		$stm->execute($values);
 
-		return self::daoToEntry ($stm->fetchAll (PDO::FETCH_ASSOC));
+		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);
+		$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);
+	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';
+	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);
+		$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';
+	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);
+		$stm = $this->bd->prepare($sql);
+		$stm->execute();
+		$res = $stm->fetchAll(PDO::FETCH_COLUMN, 0);
 		return $res[0];
 	}
 
-	public function countUnreadReadFavorites () {
-		$sql = 'SELECT COUNT(id) FROM `' . $this->prefix . 'entry` WHERE is_favorite=1'
-		     . ' UNION SELECT COUNT(id) FROM `' . $this->prefix . 'entry` WHERE is_favorite=1 AND is_read = 0';
-		$stm = $this->bd->prepare ($sql);
-		$stm->execute ();
-		$res = $stm->fetchAll (PDO::FETCH_COLUMN, 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`';
-		$stm = $this->bd->prepare ($sql);
-		$stm->execute ();
+		$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 ();
+	public static function daoToEntry($listDAO) {
+		$list = array();
 
-		if (!is_array ($listDAO)) {
-			$listDAO = array ($listDAO);
+		if (!is_array($listDAO)) {
+			$listDAO = array($listDAO);
 		}
 
 		foreach ($listDAO as $key => $dao) {
-			$entry = new FreshRSS_Entry (
+			$entry = new FreshRSS_Entry(
 				$dao['id_feed'],
 				$dao['guid'],
 				$dao['title'],
@@ -459,13 +553,13 @@ class FreshRSS_EntryDAO extends Minz_ModelPdo {
 				$dao['is_favorite'],
 				$dao['tags']
 			);
-			if (isset ($dao['id'])) {
-				$entry->_id ($dao['id']);
+			if (isset($dao['id'])) {
+				$entry->_id($dao['id']);
 			}
 			$list[] = $entry;
 		}
 
-		unset ($listDAO);
+		unset($listDAO);
 
 		return $list;
 	}

+ 129 - 0
app/Models/EntryDAOSQLite.php

@@ -0,0 +1,129 @@
+<?php
+
+class FreshRSS_EntryDAOSQLite extends FreshRSS_EntryDAO {
+
+	protected function sqlConcat($s1, $s2) {
+		return $s1 . '||' . $s2;
+	}
+
+	protected function updateCacheUnreads($catId = false, $feedId = false) {
+		$sql = 'UPDATE `' . $this->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('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('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');
+	}
+}

+ 32 - 0
app/Models/Factory.php

@@ -0,0 +1,32 @@
+<?php
+
+class FreshRSS_Factory {
+
+	public static function createFeedDao() {
+		$db = Minz_Configuration::dataBase();
+		if ($db['type'] === 'sqlite') {
+			return new FreshRSS_FeedDAOSQLite();
+		} else {
+			return new FreshRSS_FeedDAO();
+		}
+	}
+
+	public static function createEntryDao() {
+		$db = Minz_Configuration::dataBase();
+		if ($db['type'] === 'sqlite') {
+			return new FreshRSS_EntryDAOSQLite();
+		} else {
+			return new FreshRSS_EntryDAO();
+		}
+	}
+
+	public static function createStatsDAO() {
+		$db = Minz_Configuration::dataBase();
+		if ($db['type'] === 'sqlite') {
+			return new FreshRSS_StatsDAOSQLite();
+		} else {
+			return new FreshRSS_StatsDAO();
+		}
+	}
+
+}

+ 123 - 94
app/Models/Feed.php

@@ -16,17 +16,25 @@ class FreshRSS_Feed extends Minz_Model {
 	private $httpAuth = '';
 	private $error = false;
 	private $keep_history = -2;
+	private $ttl = -2;
 	private $hash = null;
+	private $lockPath = '';
 
-	public function __construct ($url, $validate=true) {
+	public function __construct($url, $validate=true) {
 		if ($validate) {
-			$this->_url ($url);
+			$this->_url($url);
 		} else {
 			$this->url = $url;
 		}
 	}
 
-	public function id () {
+	public static function example() {
+		$f = new FreshRSS_Feed('http://example.net/', false);
+		$f->faviconPrepare();
+		return $f;
+	}
+
+	public function id() {
 		return $this->id;
 	}
 
@@ -37,74 +45,77 @@ class FreshRSS_Feed extends Minz_Model {
 		return $this->hash;
 	}
 
-	public function url () {
+	public function url() {
 		return $this->url;
 	}
-	public function category () {
+	public function category() {
 		return $this->category;
 	}
-	public function entries () {
+	public function entries() {
 		return $this->entries === null ? array() : $this->entries;
 	}
-	public function name () {
+	public function name() {
 		return $this->name;
 	}
-	public function website () {
+	public function website() {
 		return $this->website;
 	}
-	public function description () {
+	public function description() {
 		return $this->description;
 	}
-	public function lastUpdate () {
+	public function lastUpdate() {
 		return $this->lastUpdate;
 	}
-	public function priority () {
+	public function priority() {
 		return $this->priority;
 	}
-	public function pathEntries () {
+	public function pathEntries() {
 		return $this->pathEntries;
 	}
-	public function httpAuth ($raw = true) {
+	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);
+			$pos_colon = strpos($this->httpAuth, ':');
+			$user = substr($this->httpAuth, 0, $pos_colon);
+			$pass = substr($this->httpAuth, $pos_colon + 1);
 
-			return array (
+			return array(
 				'username' => $user,
 				'password' => $pass
 			);
 		}
 	}
-	public function inError () {
+	public function inError() {
 		return $this->error;
 	}
-	public function keepHistory () {
+	public function keepHistory() {
 		return $this->keep_history;
 	}
-	public function nbEntries () {
+	public function ttl() {
+		return $this->ttl;
+	}
+	public function nbEntries() {
 		if ($this->nbEntries < 0) {
-			$feedDAO = new FreshRSS_FeedDAO ();
-			$this->nbEntries = $feedDAO->countEntries ($this->id ());
+			$feedDAO = FreshRSS_Factory::createFeedDao();
+			$this->nbEntries = $feedDAO->countEntries($this->id());
 		}
 
 		return $this->nbEntries;
 	}
-	public function nbNotRead () {
+	public function nbNotRead() {
 		if ($this->nbNotRead < 0) {
-			$feedDAO = new FreshRSS_FeedDAO ();
-			$this->nbNotRead = $feedDAO->countNotRead ($this->id ());
+			$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)) {
+		if (!file_exists($file)) {
 			$t = $this->website;
-			if (empty($t)) {
+			if ($t == '') {
 				$t = $this->url;
 			}
 			file_put_contents($file, $t);
@@ -115,109 +126,123 @@ class FreshRSS_Feed extends Minz_Model {
 		@unlink($path . '.ico');
 		@unlink($path . '.txt');
 	}
-	public function favicon () {
-		return Minz_Url::display ('/f.php?' . $this->hash());
+	public function favicon() {
+		return Minz_Url::display('/f.php?' . $this->hash());
 	}
 
-	public function _id ($value) {
+	public function _id($value) {
 		$this->id = $value;
 	}
-	public function _url ($value, $validate=true) {
+	public function _url($value, $validate=true) {
+		$this->hash = null;
 		if ($validate) {
 			$value = checkUrl($value);
 		}
-		if (empty ($value)) {
-			throw new FreshRSS_BadUrl_Exception ($value);
+		if (empty($value)) {
+			throw new FreshRSS_BadUrl_Exception($value);
 		}
 		$this->url = $value;
 	}
-	public function _category ($value) {
+	public function _category($value) {
 		$value = intval($value);
 		$this->category = $value >= 0 ? $value : 0;
 	}
-	public function _name ($value) {
+	public function _name($value) {
 		$this->name = $value === null ? '' : $value;
 	}
-	public function _website ($value, $validate=true) {
+	public function _website($value, $validate=true) {
 		if ($validate) {
 			$value = checkUrl($value);
 		}
-		if (empty ($value)) {
+		if (empty($value)) {
 			$value = '';
 		}
 		$this->website = $value;
 	}
-	public function _description ($value) {
+	public function _description($value) {
 		$this->description = $value === null ? '' : $value;
 	}
-	public function _lastUpdate ($value) {
+	public function _lastUpdate($value) {
 		$this->lastUpdate = $value;
 	}
-	public function _priority ($value) {
+	public function _priority($value) {
 		$value = intval($value);
 		$this->priority = $value >= 0 ? $value : 10;
 	}
-	public function _pathEntries ($value) {
+	public function _pathEntries($value) {
 		$this->pathEntries = $value;
 	}
-	public function _httpAuth ($value) {
+	public function _httpAuth($value) {
 		$this->httpAuth = $value;
 	}
-	public function _error ($value) {
+	public function _error($value) {
 		$this->error = (bool)$value;
 	}
-	public function _keepHistory ($value) {
+	public function _keepHistory($value) {
 		$value = intval($value);
 		$value = min($value, 1000000);
 		$value = max($value, -2);
 		$this->keep_history = $value;
 	}
-	public function _nbNotRead ($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) {
+	public function _nbEntries($value) {
 		$this->nbEntries = intval($value);
 	}
 
-	public function load ($loadDetails = false) {
+	public function load($loadDetails = false) {
 		if ($this->url !== null) {
 			if (CACHE_PATH === false) {
-				throw new Minz_FileNotExistException (
+				throw new Minz_FileNotExistException(
 					'CACHE_PATH',
 					Minz_Exception::ERROR
 				);
 			} else {
-				$url = htmlspecialchars_decode ($this->url, ENT_QUOTES);
+				$url = htmlspecialchars_decode($this->url, ENT_QUOTES);
 				if ($this->httpAuth != '') {
-					$url = preg_replace ('#((.+)://)(.+)#', '${1}' . $this->httpAuth . '@${3}', $url);
+					$url = preg_replace('#((.+)://)(.+)#', '${1}' . $this->httpAuth . '@${3}', $url);
 				}
 				$feed = customSimplePie();
-				$feed->set_feed_url ($url);
+				$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 . ']');
-				}
-
-				// si on a utilisé l'auto-discover, notre url va avoir changé
-				$subscribe_url = $feed->subscribe_url ();
-				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);
+					throw new FreshRSS_Feed_Exception($feed->error() . ' [' . $url . ']');
 				}
 
 				if ($loadDetails) {
-					$title = htmlspecialchars(html_only_entity_decode($feed->get_title()), ENT_COMPAT, 'UTF-8');
-					$this->_name ($title === null ? $this->url : $title);
+					// si on a utilisé l'auto-discover, notre url va avoir changé
+					$subscribe_url = $feed->subscribe_url(false);
+
+					$title = strtr(html_only_entity_decode($feed->get_title()), array('<' => '&lt;', '>' => '&gt;', '"' => '&quot;'));	//HTML to HTML-PRE	//ENT_COMPAT except &
+					$this->_name($title == '' ? $this->url : $title);
 
 					$this->_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 (($mtime === true) || ($mtime > $this->lastUpdate)) {
+				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 {
@@ -231,47 +256,52 @@ class FreshRSS_Feed extends Minz_Model {
 		}
 	}
 
-	private function loadEntries ($feed) {
-		$entries = array ();
+	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 ());
+		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 ();
+			$tags_tmp = $item->get_categories();
+			$tags = array();
 			if ($tags_tmp !== null) {
 				foreach ($tags_tmp as $tag) {
-					$tags[] = html_only_entity_decode ($tag->get_label ());
+					$tags[] = html_only_entity_decode($tag->get_label());
 				}
 			}
 
-			$content = html_only_entity_decode ($item->get_content ());
+			$content = html_only_entity_decode($item->get_content());
 
 			$elinks = array();
 			foreach ($item->get_enclosures() as $enclosure) {
 				$elink = $enclosure->get_link();
-				if (array_key_exists($elink, $elinks)) continue;
-				$elinks[$elink] = '1';
-				$mime = strtolower($enclosure->get_type());
-				if (strpos($mime, 'image/') === 0) {
-					$content .= '<br /><img src="' . $elink . '" alt="" />';
+				if (empty($elinks[$elink])) {
+					$elinks[$elink] = '1';
+					$mime = strtolower($enclosure->get_type());
+					if (strpos($mime, 'image/') === 0) {
+						$content .= '<br /><img lazyload="" postpone="" src="' . $elink . '" alt="" />';
+					} elseif (strpos($mime, 'audio/') === 0) {
+						$content .= '<br /><audio lazyload="" postpone="" preload="none" src="' . $elink . '" controls="controls" />';
+					} elseif (strpos($mime, 'video/') === 0) {
+						$content .= '<br /><video lazyload="" postpone="" preload="none" src="' . $elink . '" controls="controls" />';
+					}
 				}
 			}
 
-			$entry = new FreshRSS_Entry (
-				$this->id (),
-				$item->get_id (),
+			$entry = new FreshRSS_Entry(
+				$this->id(),
+				$item->get_id(),
 				$title === null ? '' : $title,
-				$author === null ? '' : html_only_entity_decode ($author->name),
+				$author === null ? '' : html_only_entity_decode($author->name),
 				$content === null ? '' : $content,
 				$link === null ? '' : $link,
-				$date ? $date : time ()
+				$date ? $date : time()
 			);
-			$entry->_tags ($tags);
+			$entry->_tags($tags);
 			// permet de récupérer le contenu des flux tronqués
 			$entry->loadCompleteContent($this->pathEntries());
 
@@ -283,20 +313,19 @@ class FreshRSS_Feed extends Minz_Model {
 	}
 
 	function lock() {
-		$lock = TMP_PATH . '/' . md5(Minz_Configuration::salt() . $this->url) . '.freshrss.lock';
-		if (file_exists($lock) && ((time() - @filemtime($lock)) > 3600)) {
-			@unlink($lock);
+		$this->lockPath = TMP_PATH . '/' . $this->hash() . '.freshrss.lock';
+		if (file_exists($this->lockPath) && ((time() - @filemtime($this->lockPath)) > 3600)) {
+			@unlink($this->lockPath);
 		}
-		if (($handle = @fopen($lock, 'x')) === false) {
+		if (($handle = @fopen($this->lockPath, 'x')) === false) {
 			return false;
 		}
-		//register_shutdown_function('unlink', $lock);
+		//register_shutdown_function('unlink', $this->lockPath);
 		@fclose($handle);
 		return true;
 	}
 
 	function unlock() {
-		$lock = TMP_PATH . '/' . md5(Minz_Configuration::salt() . $this->url) . '.freshrss.lock';
-		@unlink($lock);
+		@unlink($this->lockPath);
 	}
 }

+ 190 - 156
app/Models/FeedDAO.php

@@ -1,244 +1,279 @@
 <?php
 
 class FreshRSS_FeedDAO extends Minz_ModelPdo {
-	public function addFeed ($valuesTmp) {
-		$sql = 'INSERT INTO `' . $this->prefix . 'feed` (url, category, name, website, description, lastUpdate, priority, httpAuth, error, keep_history) VALUES(?, ?, ?, ?, ?, ?, 10, ?, 0, -2)';
-		$stm = $this->bd->prepare ($sql);
+	public function addFeed($valuesTmp) {
+		$sql = 'INSERT INTO `' . $this->prefix . 'feed` (url, category, name, website, description, lastUpdate, priority, httpAuth, error, keep_history, ttl) VALUES(?, ?, ?, ?, ?, ?, 10, ?, 0, -2, -2)';
+		$stm = $this->bd->prepare($sql);
 
-		$values = array (
+		$values = array(
 			substr($valuesTmp['url'], 0, 511),
 			$valuesTmp['category'],
 			substr($valuesTmp['name'], 0, 255),
 			substr($valuesTmp['website'], 0, 255),
 			substr($valuesTmp['description'], 0, 1023),
 			$valuesTmp['lastUpdate'],
-			base64_encode ($valuesTmp['httpAuth']),
+			base64_encode($valuesTmp['httpAuth']),
 		);
 
-		if ($stm && $stm->execute ($values)) {
+		if ($stm && $stm->execute($values)) {
 			return $this->bd->lastInsertId();
 		} else {
-			$info = $stm->errorInfo();
-			Minz_Log::record ('SQL error : ' . $info[2], Minz_Log::ERROR);
+			$info = $stm == null ? array(2 => 'syntax error') : $stm->errorInfo();
+			Minz_Log::record('SQL error addFeed: ' . $info[2], Minz_Log::ERROR);
 			return false;
 		}
 	}
 
-	public function updateFeed ($id, $valuesTmp) {
+	public function addFeedObject($feed) {
+		// TODO: not sure if we should write this method in DAO since DAO
+		// should not be aware about feed class
+
+		// Add feed only if we don't find it in DB
+		$feed_search = $this->searchByUrl($feed->url());
+		if (!$feed_search) {
+			$values = array(
+				'id' => $feed->id(),
+				'url' => $feed->url(),
+				'category' => $feed->category(),
+				'name' => $feed->name(),
+				'website' => $feed->website(),
+				'description' => $feed->description(),
+				'lastUpdate' => 0,
+				'httpAuth' => $feed->httpAuth()
+			);
+
+			$id = $this->addFeed($values);
+			if ($id) {
+				$feed->_id($id);
+				$feed->faviconPrepare();
+			}
+
+			return $id;
+		}
+
+		return $feed_search->id();
+	}
+
+	public function updateFeed($id, $valuesTmp) {
 		$set = '';
 		foreach ($valuesTmp as $key => $v) {
 			$set .= $key . '=?, ';
 
 			if ($key == 'httpAuth') {
-				$valuesTmp[$key] = base64_encode ($v);
+				$valuesTmp[$key] = base64_encode($v);
 			}
 		}
-		$set = substr ($set, 0, -2);
+		$set = substr($set, 0, -2);
 
 		$sql = 'UPDATE `' . $this->prefix . 'feed` SET ' . $set . ' WHERE id=?';
-		$stm = $this->bd->prepare ($sql);
+		$stm = $this->bd->prepare($sql);
 
 		foreach ($valuesTmp as $v) {
 			$values[] = $v;
 		}
 		$values[] = $id;
 
-		if ($stm && $stm->execute ($values)) {
+		if ($stm && $stm->execute($values)) {
 			return $stm->rowCount();
 		} else {
-			$info = $stm->errorInfo();
-			Minz_Log::record ('SQL error : ' . $info[2], Minz_Log::ERROR);
+			$info = $stm == null ? array(2 => 'syntax error') : $stm->errorInfo();
+			Minz_Log::record('SQL error updateFeed: ' . $info[2], Minz_Log::ERROR);
 			return false;
 		}
 	}
 
-	public function updateLastUpdate ($id, $inError = 0, $updateCache = true) {
+	public function updateLastUpdate($id, $inError = 0, $updateCache = true) {
 		if ($updateCache) {
-			$sql = 'UPDATE `' . $this->prefix . 'feed` f '	//2 sub-requests with FOREIGN KEY(e.id_feed), INDEX(e.is_read) faster than 1 request with GROUP BY or CASE
-			     . 'SET f.cache_nbEntries=(SELECT COUNT(e1.id) FROM `' . $this->prefix . 'entry` e1 WHERE e1.id_feed=f.id),'
-			     . 'f.cache_nbUnreads=(SELECT COUNT(e2.id) FROM `' . $this->prefix . 'entry` e2 WHERE e2.id_feed=f.id AND e2.is_read=0),'
+			$sql = 'UPDATE `' . $this->prefix . 'feed` '	//2 sub-requests with FOREIGN KEY(e.id_feed), INDEX(e.is_read) faster than 1 request with GROUP BY or CASE
+			     . 'SET cache_nbEntries=(SELECT COUNT(e1.id) FROM `' . $this->prefix . 'entry` e1 WHERE e1.id_feed=`' . $this->prefix . 'feed`.id),'
+			     . 'cache_nbUnreads=(SELECT COUNT(e2.id) FROM `' . $this->prefix . 'entry` e2 WHERE e2.id_feed=`' . $this->prefix . 'feed`.id AND e2.is_read=0),'
 			     . 'lastUpdate=?, error=? '
-			     . 'WHERE f.id=?';
+			     . 'WHERE id=?';
 		} else {
-			$sql = 'UPDATE `' . $this->prefix . 'feed` f '
+			$sql = 'UPDATE `' . $this->prefix . 'feed` '
 			     . 'SET lastUpdate=?, error=? '
-			     . 'WHERE f.id=?';
+			     . 'WHERE id=?';
 		}
 
-		$values = array (
+		$values = array(
 			time(),
 			$inError,
 			$id,
 		);
 
-		$stm = $this->bd->prepare ($sql);
+		$stm = $this->bd->prepare($sql);
 
-		if ($stm && $stm->execute ($values)) {
+		if ($stm && $stm->execute($values)) {
 			return $stm->rowCount();
 		} else {
-			$info = $stm->errorInfo();
-			Minz_Log::record ('SQL error : ' . $info[2], Minz_Log::ERROR);
+			$info = $stm == null ? array(2 => 'syntax error') : $stm->errorInfo();
+			Minz_Log::record('SQL error updateLastUpdate: ' . $info[2], Minz_Log::ERROR);
 			return false;
 		}
 	}
 
-	public function changeCategory ($idOldCat, $idNewCat) {
-		$catDAO = new FreshRSS_CategoryDAO ();
-		$newCat = $catDAO->searchById ($idNewCat);
+	public function changeCategory($idOldCat, $idNewCat) {
+		$catDAO = new FreshRSS_CategoryDAO();
+		$newCat = $catDAO->searchById($idNewCat);
 		if (!$newCat) {
-			$newCat = $catDAO->getDefault ();
+			$newCat = $catDAO->getDefault();
 		}
 
 		$sql = 'UPDATE `' . $this->prefix . 'feed` SET category=? WHERE category=?';
-		$stm = $this->bd->prepare ($sql);
+		$stm = $this->bd->prepare($sql);
 
-		$values = array (
-			$newCat->id (),
+		$values = array(
+			$newCat->id(),
 			$idOldCat
 		);
 
-		if ($stm && $stm->execute ($values)) {
+		if ($stm && $stm->execute($values)) {
 			return $stm->rowCount();
 		} else {
-			$info = $stm->errorInfo();
-			Minz_Log::record ('SQL error : ' . $info[2], Minz_Log::ERROR);
+			$info = $stm == null ? array(2 => 'syntax error') : $stm->errorInfo();
+			Minz_Log::record('SQL error changeCategory: ' . $info[2], Minz_Log::ERROR);
 			return false;
 		}
 	}
 
-	public function deleteFeed ($id) {
-		/*//For MYISAM (MySQL 5.5-) without FOREIGN KEY
-		$sql = 'DELETE FROM `' . $this->prefix . 'entry` WHERE id_feed=?';
-		$stm = $this->bd->prepare ($sql);
-		$values = array ($id);
-		if (!($stm && $stm->execute ($values))) {
-			$info = $stm->errorInfo();
-			Minz_Log::record ('SQL error : ' . $info[2], Minz_Log::ERROR);
-			return false;
-		}*/
-
+	public function deleteFeed($id) {
 		$sql = 'DELETE FROM `' . $this->prefix . 'feed` WHERE id=?';
-		$stm = $this->bd->prepare ($sql);
+		$stm = $this->bd->prepare($sql);
 
-		$values = array ($id);
+		$values = array($id);
 
-		if ($stm && $stm->execute ($values)) {
+		if ($stm && $stm->execute($values)) {
 			return $stm->rowCount();
 		} else {
-			$info = $stm->errorInfo();
-			Minz_Log::record ('SQL error : ' . $info[2], Minz_Log::ERROR);
+			$info = $stm == null ? array(2 => 'syntax error') : $stm->errorInfo();
+			Minz_Log::record('SQL error deleteFeed: ' . $info[2], Minz_Log::ERROR);
 			return false;
 		}
 	}
-	public function deleteFeedByCategory ($id) {
-		/*//For MYISAM (MySQL 5.5-) without FOREIGN KEY
-		$sql = 'DELETE FROM `' . $this->prefix . 'entry` e '
-		     . 'INNER JOIN `' . $this->prefix . 'feed` f ON e.id_feed = f.id '
-		     . 'WHERE f.category=?';
-		$stm = $this->bd->prepare ($sql);
-		$values = array ($id);
-		if (!($stm && $stm->execute ($values))) {
-			$info = $stm->errorInfo();
-			Minz_Log::record ('SQL error : ' . $info[2], Minz_Log::ERROR);
-			return false;
-		}*/
-
+	public function deleteFeedByCategory($id) {
 		$sql = 'DELETE FROM `' . $this->prefix . 'feed` WHERE category=?';
-		$stm = $this->bd->prepare ($sql);
+		$stm = $this->bd->prepare($sql);
 
-		$values = array ($id);
+		$values = array($id);
 
-		if ($stm && $stm->execute ($values)) {
+		if ($stm && $stm->execute($values)) {
 			return $stm->rowCount();
 		} else {
-			$info = $stm->errorInfo();
-			Minz_Log::record ('SQL error : ' . $info[2], Minz_Log::ERROR);
+			$info = $stm == null ? array(2 => 'syntax error') : $stm->errorInfo();
+			Minz_Log::record('SQL error deleteFeedByCategory: ' . $info[2], Minz_Log::ERROR);
 			return false;
 		}
 	}
 
-	public function searchById ($id) {
+	public function searchById($id) {
 		$sql = 'SELECT * FROM `' . $this->prefix . 'feed` WHERE id=?';
-		$stm = $this->bd->prepare ($sql);
+		$stm = $this->bd->prepare($sql);
 
-		$values = array ($id);
+		$values = array($id);
 
-		$stm->execute ($values);
-		$res = $stm->fetchAll (PDO::FETCH_ASSOC);
-		$feed = self::daoToFeed ($res);
+		$stm->execute($values);
+		$res = $stm->fetchAll(PDO::FETCH_ASSOC);
+		$feed = self::daoToFeed($res);
 
-		if (isset ($feed[$id])) {
+		if (isset($feed[$id])) {
 			return $feed[$id];
 		} else {
-			return false;
+			return null;
 		}
 	}
-	public function searchByUrl ($url) {
+	public function searchByUrl($url) {
 		$sql = 'SELECT * FROM `' . $this->prefix . 'feed` WHERE url=?';
-		$stm = $this->bd->prepare ($sql);
+		$stm = $this->bd->prepare($sql);
 
-		$values = array ($url);
+		$values = array($url);
 
-		$stm->execute ($values);
-		$res = $stm->fetchAll (PDO::FETCH_ASSOC);
-		$feed = current (self::daoToFeed ($res));
+		$stm->execute($values);
+		$res = $stm->fetchAll(PDO::FETCH_ASSOC);
+		$feed = current(self::daoToFeed($res));
 
-		if (isset ($feed)) {
+		if (isset($feed)) {
 			return $feed;
 		} else {
-			return false;
+			return null;
 		}
 	}
 
-	public function listFeeds () {
+	public function listFeeds() {
 		$sql = 'SELECT * FROM `' . $this->prefix . 'feed` ORDER BY name';
-		$stm = $this->bd->prepare ($sql);
-		$stm->execute ();
+		$stm = $this->bd->prepare($sql);
+		$stm->execute();
 
-		return self::daoToFeed ($stm->fetchAll (PDO::FETCH_ASSOC));
+		return self::daoToFeed($stm->fetchAll(PDO::FETCH_ASSOC));
 	}
 
-	public function listFeedsOrderUpdate ($cacheDuration = 1500) {
-		$sql = 'SELECT id, name, url, lastUpdate, pathEntries, httpAuth, keep_history '
+	public function arrayFeedCategoryNames() {	//For API
+		$sql = 'SELECT f.id, f.name, c.name as c_name FROM `' . $this->prefix . 'feed` f '
+		     . 'INNER JOIN `' . $this->prefix . 'category` c ON c.id = f.category';
+		$stm = $this->bd->prepare($sql);
+		$stm->execute();
+		$res = $stm->fetchAll(PDO::FETCH_ASSOC);
+		$feedCategoryNames = array();
+		foreach ($res as $line) {
+			$feedCategoryNames[$line['id']] = array(
+				'name' => $line['name'],
+				'c_name' => $line['c_name'],
+			);
+		}
+		return $feedCategoryNames;
+	}
+
+	public function listFeedsOrderUpdate($defaultCacheDuration = 3600) {
+		if ($defaultCacheDuration < 0) {
+			$defaultCacheDuration = 2147483647;
+		}
+		$sql = 'SELECT id, url, name, website, lastUpdate, pathEntries, httpAuth, keep_history, ttl '
 		     . 'FROM `' . $this->prefix . 'feed` '
-		     . 'WHERE lastUpdate < ' . (time() - intval($cacheDuration))
-		     . ' ORDER BY lastUpdate';
-		$stm = $this->bd->prepare ($sql);
-		$stm->execute ();
+		     . 'WHERE ttl <> -1 AND lastUpdate < (' . (time() + 60) . '-(CASE WHEN ttl=-2 THEN ' . intval($defaultCacheDuration) . ' ELSE ttl END)) '
+		     . 'ORDER BY lastUpdate';
+		$stm = $this->bd->prepare($sql);
+		if (!($stm && $stm->execute())) {
+			$sql2 = 'ALTER TABLE `' . $this->prefix . 'feed` ADD COLUMN ttl INT NOT NULL DEFAULT -2';	//v0.7.3
+			$stm = $this->bd->prepare($sql2);
+			$stm->execute();
+			$stm = $this->bd->prepare($sql);
+			$stm->execute();
+		}
 
-		return self::daoToFeed ($stm->fetchAll (PDO::FETCH_ASSOC));
+		return self::daoToFeed($stm->fetchAll(PDO::FETCH_ASSOC));
 	}
 
-	public function listByCategory ($cat) {
+	public function listByCategory($cat) {
 		$sql = 'SELECT * FROM `' . $this->prefix . 'feed` WHERE category=? ORDER BY name';
-		$stm = $this->bd->prepare ($sql);
+		$stm = $this->bd->prepare($sql);
 
-		$values = array ($cat);
+		$values = array($cat);
 
-		$stm->execute ($values);
+		$stm->execute($values);
 
-		return self::daoToFeed ($stm->fetchAll (PDO::FETCH_ASSOC));
+		return self::daoToFeed($stm->fetchAll(PDO::FETCH_ASSOC));
 	}
 
-	public function countEntries ($id) {
+	public function countEntries($id) {
 		$sql = 'SELECT COUNT(*) AS count FROM `' . $this->prefix . 'entry` WHERE id_feed=?';
-		$stm = $this->bd->prepare ($sql);
-		$values = array ($id);
-		$stm->execute ($values);
-		$res = $stm->fetchAll (PDO::FETCH_ASSOC);
+		$stm = $this->bd->prepare($sql);
+		$values = array($id);
+		$stm->execute($values);
+		$res = $stm->fetchAll(PDO::FETCH_ASSOC);
 
 		return $res[0]['count'];
 	}
-	public function countNotRead ($id) {
+
+	public function countNotRead($id) {
 		$sql = 'SELECT COUNT(*) AS count FROM `' . $this->prefix . 'entry` WHERE id_feed=? AND is_read=0';
-		$stm = $this->bd->prepare ($sql);
-		$values = array ($id);
-		$stm->execute ($values);
-		$res = $stm->fetchAll (PDO::FETCH_ASSOC);
+		$stm = $this->bd->prepare($sql);
+		$values = array($id);
+		$stm->execute($values);
+		$res = $stm->fetchAll(PDO::FETCH_ASSOC);
 
 		return $res[0]['count'];
 	}
-	public function updateCachedValues () {	//For one single feed, call updateLastUpdate($id)
+
+	public function updateCachedValues() {	//For one single feed, call updateLastUpdate($id)
 		$sql = 'UPDATE `' . $this->prefix . 'feed` f '
 		     . 'INNER JOIN ('
 		     .	'SELECT e.id_feed, '
@@ -248,80 +283,78 @@ class FreshRSS_FeedDAO extends Minz_ModelPdo {
 		     .	'GROUP BY e.id_feed'
 		     . ') x ON x.id_feed=f.id '
 		     . 'SET f.cache_nbEntries=x.nbEntries, f.cache_nbUnreads=x.nbUnreads';
-		$stm = $this->bd->prepare ($sql);
-
-		$values = array ($feed_id);
+		$stm = $this->bd->prepare($sql);
 
-		if ($stm && $stm->execute ($values)) {
+		if ($stm && $stm->execute()) {
 			return $stm->rowCount();
 		} else {
-			$info = $stm->errorInfo();
-			Minz_Log::record ('SQL error : ' . $info[2], Minz_Log::ERROR);
+			$info = $stm == null ? array(2 => 'syntax error') : $stm->errorInfo();
+			Minz_Log::record('SQL error updateCachedValues: ' . $info[2], Minz_Log::ERROR);
 			return false;
 		}
 	}
 
-	public function truncate ($id) {
-		$sql = 'DELETE e.* FROM `' . $this->prefix . 'entry` e WHERE e.id_feed=?';
+	public function truncate($id) {
+		$sql = 'DELETE FROM `' . $this->prefix . 'entry` WHERE id_feed=?';
 		$stm = $this->bd->prepare($sql);
 		$values = array($id);
-		$this->bd->beginTransaction ();
-		if (!($stm && $stm->execute ($values))) {
-				$info = $stm->errorInfo();
-				Minz_Log::record ('SQL error : ' . $info[2], Minz_Log::ERROR);
-				$this->bd->rollBack ();
-				return false;
-			}
+		$this->bd->beginTransaction();
+		if (!($stm && $stm->execute($values))) {
+			$info = $stm == null ? array(2 => 'syntax error') : $stm->errorInfo();
+			Minz_Log::record('SQL error truncate: ' . $info[2], Minz_Log::ERROR);
+			$this->bd->rollBack();
+			return false;
+		}
 		$affected = $stm->rowCount();
 
-		$sql = 'UPDATE `' . $this->prefix . 'feed` f '
-			 . 'SET f.cache_nbEntries=0, f.cache_nbUnreads=0 WHERE f.id=?';
-		$values = array ($id);
-		$stm = $this->bd->prepare ($sql);
-		if (!($stm && $stm->execute ($values))) {
-			$info = $stm->errorInfo();
-			Minz_Log::record ('SQL error : ' . $info[2], Minz_Log::ERROR);
-			$this->bd->rollBack ();
+		$sql = 'UPDATE `' . $this->prefix . 'feed` '
+			 . 'SET cache_nbEntries=0, cache_nbUnreads=0 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 truncate: ' . $info[2], Minz_Log::ERROR);
+			$this->bd->rollBack();
 			return false;
 		}
 
-		$this->bd->commit ();
+		$this->bd->commit();
 		return $affected;
 	}
 
-	public function cleanOldEntries ($id, $date_min, $keep = 15) {	//Remember to call updateLastUpdate($id) just after
-		$sql = 'DELETE e.* FROM `' . $this->prefix . 'entry` e '
-		     . 'WHERE e.id_feed = :id_feed AND e.id <= :id_max AND e.is_favorite = 0 AND e.id NOT IN '
-		     . '(SELECT id FROM (SELECT e2.id FROM `' . $this->prefix . 'entry` e2 WHERE e2.id_feed = :id_feed ORDER BY id DESC LIMIT :keep) keep)';	//Double select because of: MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery'
-		$stm = $this->bd->prepare ($sql);
+	public function cleanOldEntries($id, $date_min, $keep = 15) {	//Remember to call updateLastUpdate($id) just after
+		$sql = 'DELETE FROM `' . $this->prefix . 'entry` '
+		     . 'WHERE id_feed = :id_feed AND id <= :id_max AND is_favorite=0 AND id NOT IN '
+		     . '(SELECT id FROM (SELECT e2.id FROM `' . $this->prefix . 'entry` e2 WHERE e2.id_feed = :id_feed ORDER BY id DESC LIMIT :keep) keep)';	//Double select MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery'
+		$stm = $this->bd->prepare($sql);
 
 		$id_max = intval($date_min) . '000000';
 
 		$stm->bindParam(':id_feed', $id, PDO::PARAM_INT);
-		$stm->bindParam(':id_max', $id_max, PDO::PARAM_INT);
+		$stm->bindParam(':id_max', $id_max, PDO::PARAM_STR);
 		$stm->bindParam(':keep', $keep, PDO::PARAM_INT);
 
-		if ($stm && $stm->execute ()) {
+		if ($stm && $stm->execute()) {
 			return $stm->rowCount();
 		} else {
-			$info = $stm->errorInfo();
-			Minz_Log::record ('SQL error : ' . $info[2], Minz_Log::ERROR);
+			$info = $stm == null ? array(2 => 'syntax error') : $stm->errorInfo();
+			Minz_Log::record('SQL error cleanOldEntries: ' . $info[2], Minz_Log::ERROR);
 			return false;
 		}
 	}
 
-	public static function daoToFeed ($listDAO, $catID = null) {
-		$list = array ();
+	public static function daoToFeed($listDAO, $catID = null) {
+		$list = array();
 
-		if (!is_array ($listDAO)) {
-			$listDAO = array ($listDAO);
+		if (!is_array($listDAO)) {
+			$listDAO = array($listDAO);
 		}
 
 		foreach ($listDAO as $key => $dao) {
-			if (!isset ($dao['name'])) {
+			if (!isset($dao['name'])) {
 				continue;
 			}
-			if (isset ($dao['id'])) {
+			if (isset($dao['id'])) {
 				$key = $dao['id'];
 			}
 			if ($catID === null) {
@@ -338,13 +371,14 @@ class FreshRSS_FeedDAO extends Minz_ModelPdo {
 			$myFeed->_lastUpdate(isset($dao['lastUpdate']) ? $dao['lastUpdate'] : 0);
 			$myFeed->_priority(isset($dao['priority']) ? $dao['priority'] : 10);
 			$myFeed->_pathEntries(isset($dao['pathEntries']) ? $dao['pathEntries'] : '');
-			$myFeed->_httpAuth(isset($dao['httpAuth']) ? base64_decode ($dao['httpAuth']) : '');
+			$myFeed->_httpAuth(isset($dao['httpAuth']) ? base64_decode($dao['httpAuth']) : '');
 			$myFeed->_error(isset($dao['error']) ? $dao['error'] : 0);
 			$myFeed->_keepHistory(isset($dao['keep_history']) ? $dao['keep_history'] : -2);
+			$myFeed->_ttl(isset($dao['ttl']) ? $dao['ttl'] : -2);
 			$myFeed->_nbNotRead(isset($dao['cache_nbUnreads']) ? $dao['cache_nbUnreads'] : 0);
 			$myFeed->_nbEntries(isset($dao['cache_nbEntries']) ? $dao['cache_nbEntries'] : 0);
-			if (isset ($dao['id'])) {
-				$myFeed->_id ($dao['id']);
+			if (isset($dao['id'])) {
+				$myFeed->_id($dao['id']);
 			}
 			$list[$key] = $myFeed;
 		}

+ 19 - 0
app/Models/FeedDAOSQLite.php

@@ -0,0 +1,19 @@
+<?php
+
+class FreshRSS_FeedDAOSQLite extends FreshRSS_FeedDAO {
+
+	public function updateCachedValues() {	//For one single feed, call updateLastUpdate($id)
+		$sql = 'UPDATE `' . $this->prefix . 'feed` '
+		     . 'SET cache_nbEntries=(SELECT COUNT(e1.id) FROM `' . $this->prefix . 'entry` e1 WHERE e1.id_feed=`' . $this->prefix . 'feed`.id),'
+		     . 'cache_nbUnreads=(SELECT COUNT(e2.id) FROM `' . $this->prefix . 'entry` e2 WHERE e2.id_feed=`' . $this->prefix . 'feed`.id AND e2.is_read=0)';
+		$stm = $this->bd->prepare($sql);
+		if ($stm && $stm->execute()) {
+			return $stm->rowCount();
+		} else {
+			$info = $stm == null ? array(2 => 'syntax error') : $stm->errorInfo();
+			Minz_Log::record('SQL error updateCachedValues: ' . $info[2], Minz_Log::ERROR);
+			return false;
+		}
+	}
+
+}

+ 44 - 0
app/Models/Share.php

@@ -0,0 +1,44 @@
+<?php
+
+class FreshRSS_Share {
+
+	static public function generateUrl($options, $selected, $link, $title) {
+		$share = $options[$selected['type']];
+		$matches = array(
+			'~URL~',
+			'~TITLE~',
+			'~LINK~',
+		);
+		$replaces = array(
+			$selected['url'],
+			self::transformData($title, self::getTransform($share, 'title')),
+			self::transformData($link, self::getTransform($share, 'link')),
+		);
+		$url = str_replace($matches, $replaces, $share['url']);
+		return $url;
+	}
+
+	static private function transformData($data, $transform) {
+		if (!is_array($transform)) {
+			return $data;
+		}
+		if (count($transform) === 0) {
+			return $data;
+		}
+		foreach ($transform as $action) {
+			$data = call_user_func($action, $data);
+		}
+		return $data;
+	}
+
+	static private function getTransform($options, $type) {
+		$transform = $options['transform'];
+
+		if (array_key_exists($type, $transform)) {
+			return $transform[$type];
+		}
+
+		return $transform;
+	}
+
+}

+ 240 - 41
app/Models/StatsDAO.php

@@ -2,6 +2,8 @@
 
 class FreshRSS_StatsDAO extends Minz_ModelPdo {
 
+	const ENTRY_COUNT_PERIOD = 30;
+
 	/**
 	 * Calculates entry repartition for all feeds and for main stream.
 	 * The repartition includes:
@@ -9,7 +11,7 @@ class FreshRSS_StatsDAO extends Minz_ModelPdo {
 	 *   - read entries
 	 *   - unread entries
 	 *   - favorite entries
-	 * 
+	 *
 	 * @return type
 	 */
 	public function calculateEntryRepartition() {
@@ -50,68 +52,190 @@ SQL;
 	/**
 	 * Calculates entry count per day on a 30 days period.
 	 * Returns the result as a JSON string.
-	 * 
+	 *
 	 * @return string
 	 */
 	public function calculateEntryCount() {
-		$count = array();
+		$count = $this->initEntryCountArray();
+		$period = self::ENTRY_COUNT_PERIOD;
 
-		// Generates a list of 30 last day to be sure we always have 30 days.
-		// If we do not do that kind of thing, we'll end up with holes in the
-		// days if the user do not have a lot of feeds.
+		// Get stats per day for the last 30 days
 		$sql = <<<SQL
-SELECT - (tens.val + units.val + 1) AS day
-FROM (
-    SELECT 0 AS val
-    UNION ALL SELECT 1
-    UNION ALL SELECT 2
-    UNION ALL SELECT 3
-    UNION ALL SELECT 4
-    UNION ALL SELECT 5
-    UNION ALL SELECT 6
-    UNION ALL SELECT 7
-    UNION ALL SELECT 8
-    UNION ALL SELECT 9
-) AS units
-CROSS JOIN (
-    SELECT 0 AS val
-    UNION ALL SELECT 10
-    UNION ALL SELECT 20
-) AS tens
+SELECT DATEDIFF(FROM_UNIXTIME(e.date), NOW()) AS day,
+COUNT(1) AS count
+FROM {$this->prefix}entry AS e
+WHERE FROM_UNIXTIME(e.date, '%Y%m%d') BETWEEN DATE_FORMAT(DATE_ADD(NOW(), INTERVAL -{$period} DAY), '%Y%m%d') AND DATE_FORMAT(DATE_ADD(NOW(), INTERVAL -1 DAY), '%Y%m%d')
+GROUP BY day
 ORDER BY day ASC
 SQL;
 		$stm = $this->bd->prepare($sql);
 		$stm->execute();
 		$res = $stm->fetchAll(PDO::FETCH_ASSOC);
+
 		foreach ($res as $value) {
-			$count[$value['day']] = 0;
+			$count[$value['day']] = (int) $value['count'];
 		}
 
-		// Get stats per day for the last 30 days and applies the result on 
-		// the array created with the last query.
+		return $this->convertToSerie($count);
+	}
+
+	/**
+	 * Initialize an array for the entry count.
+	 *
+	 * @return array
+	 */
+	protected function initEntryCountArray() {
+		return $this->initStatsArray(-self::ENTRY_COUNT_PERIOD, -1);
+	}
+
+	/**
+	 * Calculates the number of article per hour of the day per feed
+	 *
+	 * @param integer $feed id
+	 * @return string
+	 */
+	public function calculateEntryRepartitionPerFeedPerHour($feed = null) {
+		return $this->calculateEntryRepartitionPerFeedPerPeriod('%H', $feed);
+	}
+
+	/**
+	 * Calculates the number of article per day of week per feed
+	 *
+	 * @param integer $feed id
+	 * @return string
+	 */
+	public function calculateEntryRepartitionPerFeedPerDayOfWeek($feed = null) {
+		return $this->calculateEntryRepartitionPerFeedPerPeriod('%w', $feed);
+	}
+
+	/**
+	 * Calculates the number of article per month per feed
+	 *
+	 * @param integer $feed
+	 * @return string
+	 */
+	public function calculateEntryRepartitionPerFeedPerMonth($feed = null) {
+		return $this->calculateEntryRepartitionPerFeedPerPeriod('%m', $feed);
+	}
+
+	/**
+	 * Calculates the number of article per period per feed
+	 *
+	 * @param string $period format string to use for grouping
+	 * @param integer $feed id
+	 * @return string
+	 */
+	protected function calculateEntryRepartitionPerFeedPerPeriod($period, $feed = null) {
+		if ($feed) {
+			$restrict = "WHERE e.id_feed = {$feed}";
+		} else {
+			$restrict = '';
+		}
 		$sql = <<<SQL
-SELECT DATEDIFF(FROM_UNIXTIME(e.date), NOW()) AS day,
-COUNT(1) AS count
+SELECT DATE_FORMAT(FROM_UNIXTIME(e.date), '{$period}') AS period
+, COUNT(1) AS count
 FROM {$this->prefix}entry AS e
-WHERE FROM_UNIXTIME(e.date, '%Y%m%d') BETWEEN DATE_FORMAT(DATE_ADD(NOW(), INTERVAL -30 DAY), '%Y%m%d') AND DATE_FORMAT(DATE_ADD(NOW(), INTERVAL -1 DAY), '%Y%m%d')
-GROUP BY day
-ORDER BY day ASC
+{$restrict}
+GROUP BY period
+ORDER BY period ASC
 SQL;
+
 		$stm = $this->bd->prepare($sql);
 		$stm->execute();
-		$res = $stm->fetchAll(PDO::FETCH_ASSOC);
+		$res = $stm->fetchAll(PDO::FETCH_NAMED);
 
 		foreach ($res as $value) {
-			$count[$value['day']] = (int) $value['count'];
+			$repartition[(int) $value['period']] = (int) $value['count'];
 		}
 
-		return $this->convertToSerie($count);
+		return $this->convertToSerie($repartition);
+	}
+
+	/**
+	 * Calculates the average number of article per hour per feed
+	 *
+	 * @param integer $feed id
+	 * @return integer
+	 */
+	public function calculateEntryAveragePerFeedPerHour($feed = null) {
+		return $this->calculateEntryAveragePerFeedPerPeriod(1/24, $feed);
+	}
+	
+	/**
+	 * Calculates the average number of article per day of week per feed
+	 *
+	 * @param integer $feed id
+	 * @return integer
+	 */
+	public function calculateEntryAveragePerFeedPerDayOfWeek($feed = null) {
+		return $this->calculateEntryAveragePerFeedPerPeriod(7, $feed);
+	}
+
+	/**
+	 * Calculates the average number of article per month per feed
+	 *
+	 * @param integer $feed id
+	 * @return integer
+	 */
+	public function calculateEntryAveragePerFeedPerMonth($feed = null) {
+		return $this->calculateEntryAveragePerFeedPerPeriod(30, $feed);
+	}
+	
+	/**
+	 * Calculates the average number of article per feed
+	 * 
+	 * @param float $period number used to divide the number of day in the period
+	 * @param integer $feed id
+	 * @return integer
+	 */
+	protected function calculateEntryAveragePerFeedPerPeriod($period, $feed = null) {
+		if ($feed) {
+			$restrict = "WHERE e.id_feed = {$feed}";
+		} else {
+			$restrict = '';
+		}
+		$sql = <<<SQL
+SELECT COUNT(1) AS count
+, MIN(date) AS date_min
+, MAX(date) AS date_max
+FROM {$this->prefix}entry AS e
+{$restrict}
+SQL;
+		$stm = $this->bd->prepare($sql);
+		$stm->execute();
+		$res = $stm->fetch(PDO::FETCH_NAMED);
+		$date_min = new \DateTime();
+		$date_min->setTimestamp($res['date_min']);
+		$date_max = new \DateTime();
+		$date_max->setTimestamp($res['date_max']);
+		$interval = $date_max->diff($date_min, true);
+		$interval_in_days = $interval->format('%a');
+		if ($interval_in_days <= 0) {
+			// Surely only one article.
+			// We will return count / (period/period) == count.
+			$interval_in_days = $period;
+		}
+
+		return round($res['count'] / ($interval_in_days / $period), 2);
+	}
+
+	/**
+	 * Initialize an array for statistics depending on a range
+	 *
+	 * @param integer $min
+	 * @param integer $max
+	 * @return array
+	 */
+	protected function initStatsArray($min, $max) {
+		return array_map(function () {
+			return 0;
+		}, array_flip(range($min, $max)));
 	}
 
 	/**
 	 * Calculates feed count per category.
 	 * Returns the result as a JSON string.
-	 * 
+	 *
 	 * @return string
 	 */
 	public function calculateFeedByCategory() {
@@ -134,7 +258,7 @@ SQL;
 	/**
 	 * Calculates entry count per category.
 	 * Returns the result as a JSON string.
-	 * 
+	 *
 	 * @return string
 	 */
 	public function calculateEntryByCategory() {
@@ -158,7 +282,7 @@ SQL;
 
 	/**
 	 * Calculates the 10 top feeds based on their number of entries
-	 * 
+	 *
 	 * @return array
 	 */
 	public function calculateTopFeed() {
@@ -172,7 +296,7 @@ FROM {$this->prefix}category AS c,
 {$this->prefix}entry AS e
 WHERE c.id = f.category
 AND f.id = e.id_feed
-GROUP BY id
+GROUP BY f.id
 ORDER BY count DESC
 LIMIT 10
 SQL;
@@ -181,7 +305,29 @@ SQL;
 		return $stm->fetchAll(PDO::FETCH_ASSOC);
 	}
 
-	private function convertToSerie($data) {
+	/**
+	 * Calculates the last publication date for each feed
+	 *
+	 * @return array
+	 */
+	public function calculateFeedLastDate() {
+		$sql = <<<SQL
+SELECT MAX(f.id) as id
+, MAX(f.name) AS name
+, MAX(date) AS last_date
+, COUNT(*) AS nb_articles
+FROM {$this->prefix}feed AS f,
+{$this->prefix}entry AS e
+WHERE f.id = e.id_feed
+GROUP BY f.id
+ORDER BY name
+SQL;
+		$stm = $this->bd->prepare($sql);
+		$stm->execute();
+		return $stm->fetchAll(PDO::FETCH_ASSOC);
+	}
+
+	protected function convertToSerie($data) {
 		$serie = array();
 
 		foreach ($data as $key => $value) {
@@ -191,7 +337,7 @@ SQL;
 		return json_encode($serie);
 	}
 
-	private function convertToPieSerie($data) {
+	protected function convertToPieSerie($data) {
 		$serie = array();
 
 		foreach ($data as $value) {
@@ -202,4 +348,57 @@ SQL;
 		return json_encode($serie);
 	}
 
+	/**
+	 * Gets days ready for graphs
+	 *
+	 * @return string
+	 */
+	public function getDays() {
+		return $this->convertToTranslatedJson(array(
+			'sun',
+			'mon',
+			'tue',
+			'wed',
+			'thu',
+			'fri',
+			'sat',
+		));
+	}
+
+	/**
+	 * Gets months ready for graphs
+	 *
+	 * @return string
+	 */
+	public function getMonths() {
+		return $this->convertToTranslatedJson(array(
+			'jan',
+			'feb',
+			'mar',
+			'apr',
+			'may',
+			'jun',
+			'jul',
+			'aug',
+			'sep',
+			'oct',
+			'nov',
+			'dec',
+		));
+	}
+
+	/**
+	 * Translates array content and encode it as JSON
+	 *
+	 * @param array $data
+	 * @return string
+	 */
+	private function convertToTranslatedJson($data = array()) {
+		$translated = array_map(function ($a) {
+			return Minz_Translate::t($a);
+		}, $data);
+
+		return json_encode($translated);
+	}
+
 }

+ 64 - 0
app/Models/StatsDAOSQLite.php

@@ -0,0 +1,64 @@
+<?php
+
+class FreshRSS_StatsDAOSQLite extends FreshRSS_StatsDAO {
+
+	/**
+	 * Calculates entry count per day on a 30 days period.
+	 * Returns the result as a JSON string.
+	 *
+	 * @return string
+	 */
+	public function calculateEntryCount() {
+		$count = $this->initEntryCountArray();
+		$period = parent::ENTRY_COUNT_PERIOD;
+
+		// Get stats per day for the last 30 days
+		$sql = <<<SQL
+SELECT round(julianday(e.date, 'unixepoch') - julianday('now')) AS day,
+COUNT(1) AS count
+FROM {$this->prefix}entry AS e
+WHERE strftime('%Y%m%d', e.date, 'unixepoch')
+	BETWEEN strftime('%Y%m%d', 'now', '-{$period} days')
+	AND strftime('%Y%m%d', 'now', '-1 day')
+GROUP BY day
+ORDER BY day ASC
+SQL;
+		$stm = $this->bd->prepare($sql);
+		$stm->execute();
+		$res = $stm->fetchAll(PDO::FETCH_ASSOC);
+
+		foreach ($res as $value) {
+			$count[(int) $value['day']] = (int) $value['count'];
+		}
+
+		return $this->convertToSerie($count);
+	}
+
+	protected function calculateEntryRepartitionPerFeedPerPeriod($period, $feed = null) {
+		if ($feed) {
+			$restrict = "WHERE e.id_feed = {$feed}";
+		} else {
+			$restrict = '';
+		}
+		$sql = <<<SQL
+SELECT strftime('{$period}', e.date, 'unixepoch') AS period
+, COUNT(1) AS count
+FROM {$this->prefix}entry AS e
+{$restrict}
+GROUP BY period
+ORDER BY period ASC
+SQL;
+
+		$stm = $this->bd->prepare($sql);
+		$stm->execute();
+		$res = $stm->fetchAll(PDO::FETCH_NAMED);
+
+		$repartition = array();
+		foreach ($res as $value) {
+			$repartition[(int) $value['period']] = (int) $value['count'];
+		}
+
+		return $this->convertToSerie($repartition);
+	}
+
+}

+ 16 - 1
app/Models/Themes.php

@@ -31,7 +31,10 @@ class FreshRSS_Themes extends Minz_Model {
 			if (file_exists($json_filename)) {
 				$content = file_get_contents($json_filename);
 				$res = json_decode($content, true);
-				if ($res && isset($res['files']) && is_array($res['files'])) {
+				if ($res &&
+						!empty($res['name']) &&
+						isset($res['files']) &&
+						is_array($res['files'])) {
 					$res['id'] = $theme_id;
 					return $res;
 				}
@@ -70,6 +73,7 @@ class FreshRSS_Themes extends Minz_Model {
 			'add' => '✚',
 			'all' => '☰',
 			'bookmark' => '★',
+			'bookmark-add' => '✚',
 			'category' => '☷',
 			'category-white' => '☷',
 			'close' => '❌',
@@ -77,6 +81,8 @@ class FreshRSS_Themes extends Minz_Model {
 			'down' => '▽',
 			'favorite' => '★',
 			'help' => 'ⓘ',
+			'icon' => '⊚',
+			'key' => '⚿',
 			'link' => '↗',
 			'login' => '🔒',
 			'logout' => '🔓',
@@ -84,13 +90,18 @@ class FreshRSS_Themes extends Minz_Model {
 			'non-starred' => '☆',
 			'prev' => '⏪',
 			'read' => '☑',
+			'rss' => '☄',
 			'unread' => '☐',
 			'refresh' => '🔃',	//↻
 			'search' => '🔍',
 			'share' => '♺',
 			'starred' => '★',
+			'stats' => '%',
 			'tag' => '⚐',
 			'up' => '△',
+			'view-normal' => '☰',
+			'view-global' => '☷',
+			'view-reader' => '☕',
 		);
 		if (!isset($alts[$name])) {
 			return '';
@@ -104,3 +115,7 @@ class FreshRSS_Themes extends Minz_Model {
 			'<img class="icon" src="' . Minz_Url::display($url) . '" alt="' . $alts[$name] . '" />';
 	}
 }
+
+function _i($icon, $url_only = false) {
+	return FreshRSS_Themes::icon($icon, $url_only);
+}

+ 36 - 16
app/Models/UserDAO.php

@@ -2,35 +2,55 @@
 
 class FreshRSS_UserDAO extends Minz_ModelPdo {
 	public function createUser($username) {
-		require_once(APP_PATH . '/sql.php');
 		$db = Minz_Configuration::dataBase();
+		require_once(APP_PATH . '/SQL/install.sql.' . $db['type'] . '.php');
 
-		$sql = sprintf(SQL_CREATE_TABLES, $db['prefix'] . $username . '_');
-		$stm = $this->bd->prepare($sql, array(PDO::ATTR_EMULATE_PREPARES => true));
-		$values = array(
-			'catName' => Minz_Translate::t('default_category'),
-		);
-		if ($stm && $stm->execute($values)) {
+		$userPDO = new Minz_ModelPdo($username);
+
+		$ok = false;
+		if (defined('SQL_CREATE_TABLES')) {	//E.g. MySQL
+			$sql = sprintf(SQL_CREATE_TABLES, $db['prefix'] . $username . '_', Minz_Translate::t('default_category'));
+			$stm = $userPDO->bd->prepare($sql);
+			$ok = $stm && $stm->execute();
+		} else {	//E.g. SQLite
+			global $SQL_CREATE_TABLES;
+			if (is_array($SQL_CREATE_TABLES)) {
+				$ok = true;
+				foreach ($SQL_CREATE_TABLES as $instruction) {
+					$sql = sprintf($instruction, '', Minz_Translate::t('default_category'));
+					$stm = $userPDO->bd->prepare($sql);
+					$ok &= ($stm && $stm->execute());
+				}
+			}
+		}
+
+		if ($ok) {
 			return true;
 		} else {
-			$info = $stm->errorInfo();
+			$info = empty($stm) ? array(2 => 'syntax error') : $stm->errorInfo();
 			Minz_Log::record ('SQL error : ' . $info[2], Minz_Log::ERROR);
 			return false;
 		}
 	}
 
 	public function deleteUser($username) {
-		require_once(APP_PATH . '/sql.php');
 		$db = Minz_Configuration::dataBase();
+		require_once(APP_PATH . '/SQL/install.sql.' . $db['type'] . '.php');
 
-		$sql = sprintf(SQL_DROP_TABLES, $db['prefix'] . $username . '_');
-		$stm = $this->bd->prepare($sql);
-		if ($stm && $stm->execute()) {
-			return true;
+		if ($db['type'] === 'sqlite') {
+			return unlink(DATA_PATH . '/' . $username . '.sqlite');
 		} else {
-			$info = $stm->errorInfo();
-			Minz_Log::record ('SQL error : ' . $info[2], Minz_Log::ERROR);
-			return false;
+			$userPDO = new Minz_ModelPdo($username);
+
+			$sql = sprintf(SQL_DROP_TABLES, $db['prefix'] . $username . '_');
+			$stm = $userPDO->bd->prepare($sql);
+			if ($stm && $stm->execute()) {
+				return true;
+			} else {
+				$info = $stm == null ? array(2 => 'syntax error') : $stm->errorInfo();
+				Minz_Log::record ('SQL error : ' . $info[2], Minz_Log::ERROR);
+				return false;
+			}
 		}
 	}
 }

+ 4 - 1
app/sql.php → app/SQL/install.sql.mysql.php

@@ -21,6 +21,7 @@ CREATE TABLE IF NOT EXISTS `%1$sfeed` (
 	`httpAuth` varchar(511) DEFAULT NULL,
 	`error` boolean DEFAULT 0,
 	`keep_history` MEDIUMINT NOT NULL DEFAULT -2,	-- v0.7
+	`ttl` INT NOT NULL DEFAULT -2,	-- v0.7.3
 	`cache_nbEntries` int DEFAULT 0,	-- v0.7
 	`cache_nbUnreads` int DEFAULT 0,	-- v0.7
 	PRIMARY KEY (`id`),
@@ -52,7 +53,9 @@ CREATE TABLE IF NOT EXISTS `%1$sentry` (
 ) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci
 ENGINE = INNODB;
 
-INSERT IGNORE INTO `%1$scategory` (id, name) VALUES(1, :catName);
+INSERT IGNORE INTO `%1$scategory` (id, name) VALUES(1, "%2$s");
 ');
 
 define('SQL_DROP_TABLES', 'DROP TABLES %1$sentry, %1$sfeed, %1$scategory');
+
+define('SQL_SHOW_TABLES', 'SHOW tables;');

+ 59 - 0
app/SQL/install.sql.sqlite.php

@@ -0,0 +1,59 @@
+<?php
+global $SQL_CREATE_TABLES;
+$SQL_CREATE_TABLES = array(
+'CREATE TABLE IF NOT EXISTS `%1$scategory` (
+	`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
+	`name` varchar(255) NOT NULL,
+	UNIQUE (`name`)
+);',
+
+'CREATE TABLE IF NOT EXISTS `%1$sfeed` (
+	`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
+	`url` varchar(511) NOT NULL,
+	`%1$scategory` SMALLINT DEFAULT 0,
+	`name` varchar(255) NOT NULL,
+	`website` varchar(255),
+	`description` text,
+	`lastUpdate` int(11) DEFAULT 0,
+	`priority` tinyint(2) NOT NULL DEFAULT 10,
+	`pathEntries` varchar(511) DEFAULT NULL,
+	`httpAuth` varchar(511) DEFAULT NULL,
+	`error` boolean DEFAULT 0,
+	`keep_history` MEDIUMINT NOT NULL DEFAULT -2,
+	`ttl` INT NOT NULL DEFAULT -2,
+	`cache_nbEntries` int DEFAULT 0,
+	`cache_nbUnreads` int DEFAULT 0,
+	FOREIGN KEY (`%1$scategory`) REFERENCES `%1$scategory`(`id`) ON DELETE SET NULL ON UPDATE CASCADE,
+	UNIQUE (`url`)
+);',
+
+'CREATE INDEX IF NOT EXISTS feed_name_index ON `%1$sfeed`(`name`);',
+'CREATE INDEX IF NOT EXISTS feed_priority_index ON `%1$sfeed`(`priority`);',
+'CREATE INDEX IF NOT EXISTS feed_keep_history_index ON `%1$sfeed`(`keep_history`);',
+
+'CREATE TABLE IF NOT EXISTS `%1$sentry` (
+	`id` bigint NOT NULL,
+	`guid` varchar(760) NOT NULL,
+	`title` varchar(255) NOT NULL,
+	`author` varchar(255),
+	`content` text,
+	`link` varchar(1023) NOT NULL,
+	`date` int(11),
+	`is_read` boolean NOT NULL DEFAULT 0,
+	`is_favorite` boolean NOT NULL DEFAULT 0,
+	`id_feed` SMALLINT,
+	`tags` varchar(1023),
+	PRIMARY KEY (`id`),
+	FOREIGN KEY (`id_feed`) REFERENCES `%1$sfeed`(`id`) ON DELETE CASCADE ON UPDATE CASCADE,
+	UNIQUE (`id_feed`,`guid`)
+);',
+
+'CREATE INDEX IF NOT EXISTS entry_is_favorite_index ON `%1$sentry`(`is_favorite`);',
+'CREATE INDEX IF NOT EXISTS entry_is_read_index ON `%1$sentry`(`is_read`);',
+
+'INSERT OR IGNORE INTO `%1$scategory` (id, name) VALUES(1, "%2$s");',
+);
+
+define('SQL_DROP_TABLES', 'DROP TABLES %1$sentry, %1$sfeed, %1$scategory');
+
+define('SQL_SHOW_TABLES', 'SELECT name FROM sqlite_master WHERE type="table"');

+ 0 - 1
app/actualize_script.php

@@ -28,7 +28,6 @@ foreach ($users as $myUser) {
 	$_SERVER['HTTP_HOST'] = '';
 
 	$freshRSS = new FreshRSS();
-	$freshRSS->_useOb(false);
 
 	Minz_Configuration::_authType('none');
 

+ 155 - 27
app/i18n/en.php

@@ -3,7 +3,9 @@
 return array (
 	// LAYOUT
 	'login'				=> 'Login',
+	'keep_logged_in'		=> 'Keep me logged in <small>(1 month)</small>',
 	'login_with_persona'		=> 'Login with Persona',
+	'login_persona_problem'		=> 'Connection problem with Persona?',
 	'logout'			=> 'Logout',
 	'search'			=> 'Search words or #tags',
 	'search_short'			=> 'Search',
@@ -15,18 +17,62 @@ return array (
 	'feed'				=> 'Feed',
 	'feeds'				=> 'Feeds',
 	'shortcuts'			=> 'Shortcuts',
+	'queries'			=> 'User queries',
+	'query_search'			=> 'Search for "%s"',
+	'query_order_asc'		=> 'Display oldest articles first',
+	'query_order_desc'		=> 'Display newest articles first',
+	'query_get_category'		=> 'Display "%s" category',
+	'query_get_feed'		=> 'Display "%s" feed',
+	'query_get_all'			=> 'Display all articles',
+	'query_get_favorite'		=> 'Display favorite articles',
+	'query_state_0'			=> 'Display all articles',
+	'query_state_1'			=> 'Display read articles',
+	'query_state_2'			=> 'Display unread articles',
+	'query_state_3'			=> 'Display all articles',
+	'query_state_4'			=> 'Display favorite articles',
+	'query_state_5'			=> 'Display read favorite articles',
+	'query_state_6'			=> 'Display unread favorite articles',
+	'query_state_7'			=> 'Display favorite articles',
+	'query_state_8'			=> 'Display not favorite articles',
+	'query_state_9'			=> 'Display read not favorite articles',
+	'query_state_10'		=> 'Display unread not favorite articles',
+	'query_state_11'		=> 'Display not favorite articles',
+	'query_state_12'		=> 'Display all articles',
+	'query_state_13'		=> 'Display read articles',
+	'query_state_14'		=> 'Display unread articles',
+	'query_state_15'		=> 'Display all articles',
+	'query_number'			=> 'Query n°%d',
+	'add_query'			=> 'Add a query',
+	'query_created'			=> 'Query "%s" has been created.',
+	'no_query'			=> 'You haven’t created any user query yet.',
+	'query_filter'			=> 'Filter applied:',
+	'no_query_filter'		=> 'No filter',
+	'query_deprecated'		=> 'This query is no longer valid. The referenced category or feed has been deleted.',
 	'about'				=> 'About',
 	'stats'				=> 'Statistics',
+	'stats_idle'			=> 'Idle feeds',
+	'stats_main'			=> 'Main statistics',
+	'stats_repartition'		=> 'Articles repartition',
+	'stats_entry_per_hour'		=> 'Per hour',
+	'stats_entry_per_day_of_week'	=> 'Per day of week',
+	'stats_entry_per_month'		=> 'Per month',
+    
+	'last_week'			=> 'Last week',
+	'last_month'			=> 'Last month',
+	'last_3_month'			=> 'Last three months',
+	'last_6_month'			=> 'Last six months',
+	'last_year'			=> 'Last year',
 
 	'your_rss_feeds'		=> 'Your RSS feeds',
 	'add_rss_feed'			=> 'Add a RSS feed',
 	'no_rss_feed'			=> 'No RSS feed',
-	'import_export_opml'		=> 'Import / export (OPML)',
+	'import_export'			=> 'Import / export',
+	'bookmark'			=> 'Subscribe (FreshRSS bookmark)',
 
 	'subscription_management'	=> 'Subscriptions management',
 	'main_stream'			=> 'Main stream',
 	'all_feeds'			=> 'All feeds',
-	'favorite_feeds'		=> 'Favourites (%d)',
+	'favorite_feeds'		=> 'Favourites (%s)',
 	'not_read'			=> '%d unread',
 	'not_reads'			=> '%d unread',
 
@@ -49,8 +95,10 @@ return array (
 	'rss_view'			=> 'RSS feed',
 	'show_all_articles'		=> 'Show all articles',
 	'show_not_reads'		=> 'Show only unread',
+	'show_adaptive'			=> 'Adjust showing',
 	'show_read'			=> 'Show only read',
-	'show_favorite'			=> 'Show favorites',
+	'show_favorite'			=> 'Show only favorites',
+	'show_not_favorite'		=> 'Show all but favorites',
 	'older_first'			=> 'Oldest first',
 	'newer_first'			=> 'Newer first',
 
@@ -67,7 +115,7 @@ return array (
 	'access_denied'			=> 'You don’t have permission to access this page',
 	'page_not_found'		=> 'You are looking for a page which doesn’t exist',
 	'error_occurred'		=> 'An error occurred',
-	'error_occurred_update'	=> 'Nothing was changed',
+	'error_occurred_update'		=> 'Nothing was changed',
 
 	'default_category'		=> 'Uncategorized',
 	'categories_updated'		=> 'Categories have been updated',
@@ -78,7 +126,6 @@ return array (
 	'sharing_management'		=> 'Sharing options management',
 	'bad_opml_file'			=> 'Your OPML file is invalid',
 	'shortcuts_updated'		=> 'Shortcuts have been updated',
-	'shortcuts_management'		=> 'Shortcuts management',
 	'shortcuts_navigation'		=> 'Navigation',
 	'shortcuts_navigation_help'	=> 'With the "Shift" modifier, navigation shortcuts apply on feeds.<br/>With the "Alt" modifier, navigation shortcuts apply on categories.',
 	'shortcuts_article_action'	=> 'Article actions',
@@ -89,7 +136,7 @@ return array (
 	'already_subscribed'		=> 'You have already subscribed to <em>%s</em>',
 	'feed_added'			=> 'RSS feed <em>%s</em> has been added',
 	'feed_not_added'		=> '<em>%s</em> could not be added',
-	'internal_problem_feed'		=> 'The RSS feed could not be added. Check FressRSS logs for details.',
+	'internal_problem_feed'		=> 'The RSS feed could not be added. <a href="%s">Check FressRSS logs</a> for details.',
 	'invalid_url'			=> 'URL <em>%s</em> is invalid',
 	'feed_actualized'		=> '<em>%s</em> has been updated',
 	'n_feeds_actualized'		=> '%d feeds have been updated',
@@ -109,10 +156,13 @@ return array (
 	'public'			=> 'Public',
 	'invalid_login'			=> 'Login is invalid',
 
+	'file_is_nok'			=> 'Check permissions on <em>%s</em> directory. HTTP server must have rights to write into.',
+
 	// VIEWS
 	'save'				=> 'Save',
 	'delete'			=> 'Delete',
 	'cancel'			=> 'Cancel',
+	'submit'			=> 'Submit',
 
 	'back_to_rss_feeds'		=> '← Go back to your RSS feeds',
 	'feeds_moved_category_deleted'	=> 'When you delete a category, their feeds are automatically classified under <em>%s</em>.',
@@ -136,24 +186,40 @@ return array (
 	'collapse_article'		=> 'Collapse',
 	'auto_share'			=> 'Share',
 	'auto_share_help'		=> 'If there is only one sharing mode, it is used. Else modes are accessible by their number.',
+	'focus_search'			=> 'Access search box',
+	'user_filter'			=> 'Access user filters',
+	'user_filter_help'		=> 'If there is only one user filter, it is used. Else filters are accessible by their number.',
+	'help'				=> 'Display documentation',
 
-	'file_to_import'		=> 'File to import',
+	'file_to_import'		=> 'File to import<br />(OPML, Json or Zip)',
+	'file_to_import_no_zip'		=> 'File to import<br />(OPML or Json)',
 	'import'			=> 'Import',
+	'file_cannot_be_uploaded'	=> 'File cannot be uploaded!',
+	'zip_error'			=> 'An error occured during Zip import.',
+	'no_zip_extension'		=> 'Zip extension is not present on your server.',
 	'export'			=> 'Export',
+	'export_opml'			=> 'Export list of feeds (OPML)',
+	'export_starred'		=> 'Export your favourites',
+	'export_no_zip_extension'	=> 'Zip extension is not present on your server. Please try to export files one by one.',
+	'starred_list'			=> 'List of favourite articles',
+	'feed_list'			=> 'List of %s articles',
 	'or'				=> 'or',
 
 	'informations'			=> 'Information',
 	'damn'				=> 'Damn!',
+	'ok'				=> 'Ok!',
+	'attention'			=> 'Be careful!',
 	'feed_in_error'			=> 'This feed has encountered a problem. Please verify that it is always reachable then actualize it.',
 	'feed_empty'			=> 'This feed is empty. Please verify that it is still maintained.',
 	'feed_description'		=> 'Description',
 	'website_url'			=> 'Website URL',
 	'feed_url'			=> 'Feed URL',
 	'articles'			=> 'articles',
-	'number_articles'		=> 'Number of articles',
+	'number_articles'		=> '%d articles',
 	'by_feed'			=> 'by feed',
 	'by_default'			=> 'By default',
 	'keep_history'			=> 'Minimum number of articles to keep',
+	'ttl'				=> 'Do not automatically refresh more often than',
 	'categorize'			=> 'Store in a category',
 	'truncate'			=> 'Delete all articles',
 	'advanced'			=> 'Advanced',
@@ -166,19 +232,24 @@ return array (
 	'http_username'			=> 'HTTP username',
 	'http_password'			=> 'HTTP password',
 	'blank_to_disable'		=> 'Leave blank to disable',
+	'share_name'			=> 'Share name to display',
+	'share_url'			=> 'Share URL to use',
 	'not_yet_implemented'		=> 'Not yet implemented',
 	'access_protected_feeds'	=> 'Connection allows to access HTTP protected RSS feeds',
 	'no_selected_feed'		=> 'No feed selected.',
-	'think_to_add'			=> '<a href="./?c=configure&amp;a=feed">You may add some feeds</a>.',
+	'think_to_add'			=> 'You may add some feeds.',
 
 	'current_user'			=> 'Current user',
 	'default_user'			=> 'Username of the default user <small>(maximum 16 alphanumeric characters)</small>',
 	'password_form'			=> 'Password<br /><small>(for the Web-form login method)</small>',
+	'password_api'			=> 'Password API<br /><small>(e.g., for mobile apps)</small>',
 	'persona_connection_email'	=> 'Login mail address<br /><small>(for <a href="https://persona.org/" rel="external">Mozilla Persona</a>)</small>',
 	'allow_anonymous'		=> 'Allow anonymous reading of the articles of the default user (%s)',
 	'allow_anonymous_refresh'	=> 'Allow anonymous refresh of the articles',
+	'unsafe_autologin'		=> 'Allow unsafe automatic login using the format: ',
+	'api_enabled'			=> 'Allow <abbr>API</abbr> access <small>(required for mobile apps)</small>',
 	'auth_token'			=> 'Authentication token',
-	'explain_token'			=> 'Allows to access RSS output of the default user without authentication.<br /><kbd>%s?output=rss&token=%s</kbd>',
+	'explain_token'			=> 'Allows to access RSS output of the default user without authentication.<br /><kbd>%s?output=rss&amp;token=%s</kbd>',
 	'login_configuration'		=> 'Login',
 	'is_admin'			=> 'is administrator',
 	'auth_type'			=> 'Authentication method',
@@ -189,6 +260,7 @@ return array (
 	'users_list'			=> 'List of users',
 	'create_user'			=> 'Create new user',
 	'username'			=> 'Username',
+	'username_admin'		=> 'Administrator username',
 	'password'			=> 'Password',
 	'create'			=> 'Create',
 	'user_created'			=> 'User %s has been created',
@@ -197,26 +269,35 @@ return array (
 	'language'			=> 'Language',
 	'month'				=> 'months',
 	'archiving_configuration'	=> 'Archiving',
-	'delete_articles_every'	=> 'Remove articles after',
+	'delete_articles_every'		=> 'Remove articles after',
 	'purge_now'			=> 'Purge now',
 	'purge_completed'		=> 'Purge completed (%d articles deleted)',
 	'archiving_configuration_help'	=> 'More options are available in the individual stream settings',
 	'reading_configuration'		=> 'Reading',
+	'display_configuration'		=> 'Display',
 	'articles_per_page'		=> 'Number of articles per page',
+	'number_divided_when_reader'	=> 'Divided by 2 in the reading view.',
 	'default_view'			=> 'Default view',
+	'articles_to_display'		=> 'Articles to display',
 	'sort_order'			=> 'Sort order',
 	'auto_load_more'		=> 'Load next articles at the page bottom',
 	'display_articles_unfolded'	=> 'Show articles unfolded by default',
+	'display_categories_unfolded'	=> 'Show categories folded by default',
+	'hide_read_feeds'		=> 'Hide categories &amp; feeds with no unread article (does not work with “Show all articles” configuration)',
 	'after_onread'			=> 'After “mark all as read”,',
 	'jump_next'			=> 'jump to next unread sibling (feed or category)',
-	'reading_icons'			=> 'Reading icons',
+	'article_icons'			=> 'Article icons',
 	'top_line'			=> 'Top line',
 	'bottom_line'			=> 'Bottom line',
+	'html5_notif_timeout'		=> 'HTML5 notification timeout',
+	'seconds_(0_means_no_timeout)'	=> 'seconds (0 means no timeout)',
 	'img_with_lazyload'		=> 'Use "lazy load" mode to load pictures',
+	'sticky_post'			=> 'Stick the article to the top when opened',
+	'reading_confirm'		=> 'Display a confirmation dialog on “mark all as read” actions',
 	'auto_read_when'		=> 'Mark article as read…',
-	'article_selected'		=> 'when article is selected',
+	'article_viewed'		=> 'when article is viewed',
 	'article_open_on_website'	=> 'when article is opened on its original website',
-	'scroll'			=> 'during page scrolls',
+	'scroll'			=> 'while scrolling',
 	'upon_reception'		=> 'upon reception of the article',
 	'your_shaarli'			=> 'Your Shaarli',
 	'your_wallabag'			=> 'Your wallabag',
@@ -227,9 +308,15 @@ return array (
 	'optimize_bdd'			=> 'Optimize database',
 	'optimize_todo_sometimes'	=> 'To do occasionally to reduce the size of the database',
 	'theme'				=> 'Theme',
+	'content_width'			=> 'Content width',
+	'width_thin'			=> 'Thin',
+	'width_medium'			=> 'Medium',
+	'width_large'			=> 'Large',
+	'width_no_limit'		=> 'No limit',
 	'more_information'		=> 'More information',
 	'activate_sharing'		=> 'Activate sharing',
 	'shaarli'			=> 'Shaarli',
+	'blogotext'			=> 'Blogotext',
 	'wallabag'			=> 'wallabag',
 	'diaspora'			=> 'Diaspora*',
 	'twitter'			=> 'Twitter',
@@ -270,7 +357,7 @@ return array (
 	'agpl3'				=> '<a href="https://www.gnu.org/licenses/agpl-3.0.html">AGPL 3</a>',
 	'freshrss_description'		=> 'FreshRSS is a RSS feeds aggregator to self-host like <a href="http://tontof.net/kriss/feed/">Kriss Feed</a> or <a href="http://projet.idleman.fr/leed/">Leed</a>. It is light and easy to take in hand while being powerful and configurable tool.',
 	'credits'			=> 'Credits',
-	'credits_content'		=> 'Some design elements come from <a href="http://twitter.github.io/bootstrap/">Bootstrap</a> although FreshRSS doesn’t use this framework. <a href="https://git.gnome.org/browse/gnome-icon-theme-symbolic">Icons</a> come from <a href="https://www.gnome.org/">GNOME project</a>. <em>Open Sans</em> font police used has been created by <a href="https://www.google.com/webfonts/specimen/Open+Sans">Steve Matteson</a>. Favicons are collected with <a href="https://getfavicon.appspot.com/">getFavicon API</a>. FreshRSS is based on <a href="https://github.com/marienfressinaud/MINZ">Minz</a>, a PHP framework.',
+	'credits_content'		=> 'Some design elements come from <a href="http://twitter.github.io/bootstrap/">Bootstrap</a> although FreshRSS doesn’t use this framework. <a href="https://git.gnome.org/browse/gnome-icon-theme-symbolic">Icons</a> come from <a href="https://www.gnome.org/">GNOME project</a>. <em>Open Sans</em> font police has been created by <a href="https://www.google.com/webfonts/specimen/Open+Sans">Steve Matteson</a>. Favicons are collected with <a href="https://getfavicon.appspot.com/">getFavicon API</a>. FreshRSS is based on <a href="https://github.com/marienfressinaud/MINZ">Minz</a>, a PHP framework.',
 	'version'			=> 'Version',
 
 	'logs'				=> 'Logs',
@@ -281,20 +368,42 @@ return array (
 	'login_required'		=> 'Login required:',
 
 	'confirm_action'		=> 'Are you sure you want to perform this action? It cannot be cancelled!',
+	'confirm_action_feed_cat'	=> 'Are you sure you want to perform this action? You may lost related favorites and user queries. It cannot be cancelled!',
+	'notif_title_new_articles'	=> 'FreshRSS: new articles!',
+	'notif_body_new_articles'	=> 'There are \d new articles to read on FreshRSS.',
 
 	// DATE
-	'january'			=> 'january',
-	'february'			=> 'february',
-	'march'				=> 'march',
-	'april'				=> 'april',
-	'may'				=> 'may',
-	'june'				=> 'june',
-	'july'				=> 'july',
-	'august'			=> 'august',
-	'september'			=> 'september',
-	'october'			=> 'october',
-	'november'			=> 'november',
-	'december'			=> 'december',
+	'january'			=> 'January',
+	'february'			=> 'February',
+	'march'				=> 'March',
+	'april'				=> 'April',
+	'may'				=> 'May',
+	'june'				=> 'June',
+	'july'				=> 'July',
+	'august'			=> 'August',
+	'september'			=> 'September',
+	'october'			=> 'October',
+	'november'			=> 'November',
+	'december'			=> 'December',
+	'january'			=> 'Jan',
+	'february'			=> 'Feb',
+	'march'				=> 'Mar',
+	'april'				=> 'Apr',
+	'may'				=> 'May',
+	'june'				=> 'Jun',
+	'july'				=> 'Jul',
+	'august'			=> 'Aug',
+	'september'			=> 'Sep',
+	'october'			=> 'Oct',
+	'november'			=> 'Nov',
+	'december'			=> 'Dec',
+	'sun'				=> 'Sun',
+	'mon'				=> 'Mon',
+	'tue'				=> 'Tue',
+	'wed'				=> 'Wed',
+	'thu'				=> 'Thu',
+	'fri'				=> 'Fri',
+	'sat'				=> 'Sat',
 	// special format for date() function
 	'Jan'				=> '\J\a\n\u\a\r\y',
 	'Feb'				=> '\F\e\b\r\u\a\r\y',
@@ -323,4 +432,23 @@ return array (
 	'stats_entry_per_category'	=> 'Entries per category',
 	'stats_top_feed'		=> 'Top ten feeds',
 	'stats_entry_count'		=> 'Entry count',
+	'stats_no_idle'			=> 'There is no idle feed!',
+
+	'update'			=> 'Update',
+	'update_system'			=> 'Update system',
+	'update_check'			=> 'Check for new updates',
+	'update_last'			=> 'Last verification: %s',
+	'update_can_apply'		=> 'An update is available.',
+	'update_apply'			=> 'Apply',
+	'update_server_not_found'	=> 'Update server cannot be found. [%s]',
+	'no_update'			=> 'No update to apply',
+	'update_problem'		=> 'The update process has encountered an error: %s',
+	'update_finished'		=> 'Update completed!',
+
+	'auth_reset'			=> 'Authentication reset',
+	'auth_will_reset'		=> 'Authentication system will be reset: a form will be used instead of Persona.',
+	'auth_not_persona'		=> 'Only Persona system can be reset.',
+	'auth_no_password_set'		=> 'Administrator password hasn’t been set. This feature isn’t available.',
+	'auth_form_set'			=> 'Form is now your default authentication system.',
+	'auth_form_not_set'		=> 'A problem occured during authentication system configuration. Please retry later.',
 );

+ 175 - 47
app/i18n/fr.php

@@ -3,7 +3,9 @@
 return array (
 	// LAYOUT
 	'login'				=> 'Connexion',
+	'keep_logged_in'		=> 'Rester connecté <small>(1 mois)</small>',
 	'login_with_persona'		=> 'Connexion avec Persona',
+	'login_persona_problem'		=> 'Problème de connexion à Persona ?',
 	'logout'			=> 'Déconnexion',
 	'search'			=> 'Rechercher des mots ou des #tags',
 	'search_short'			=> 'Rechercher',
@@ -15,24 +17,68 @@ return array (
 	'feed'				=> 'Flux',
 	'feeds'				=> 'Flux',
 	'shortcuts'			=> 'Raccourcis',
+	'queries'			=> 'Filtres utilisateurs',
+	'query_search'			=> 'Recherche de "%s"',
+	'query_order_asc'		=> 'Afficher les articles les plus anciens en premier',
+	'query_order_desc'		=> 'Afficher les articles les plus récents en premier',
+	'query_get_category'		=> 'Afficher la catégorie "%s"',
+	'query_get_feed'		=> 'Afficher le flux "%s"',
+	'query_get_all'			=> 'Afficher tous les articles',
+	'query_get_favorite'		=> 'Afficher les articles favoris',
+	'query_state_0'			=> 'Afficher tous les articles',
+	'query_state_1'			=> 'Afficher les articles lus',
+	'query_state_2'			=> 'Afficher les articles non lus',
+	'query_state_3'			=> 'Afficher tous les articles',
+	'query_state_4'			=> 'Afficher les articles favoris',
+	'query_state_5'			=> 'Afficher les articles lus et favoris',
+	'query_state_6'			=> 'Afficher les articles non lus et favoris',
+	'query_state_7'			=> 'Afficher les articles favoris',
+	'query_state_8'			=> 'Afficher les articles non favoris',
+	'query_state_9'			=> 'Afficher les articles lus et non favoris',
+	'query_state_10'		=> 'Afficher les articles non lus et non favoris',
+	'query_state_11'		=> 'Afficher les articles non favoris',
+	'query_state_12'		=> 'Afficher tous les articles',
+	'query_state_13'		=> 'Afficher les articles lus',
+	'query_state_14'		=> 'Afficher les articles non lus',
+	'query_state_15'		=> 'Afficher tous les articles',
+	'query_number'			=> 'Filtre n°%d',
+	'add_query'			=> 'Créer un filtre',
+	'query_created'			=> 'Le filtre "%s" a bien été créé.',
+	'no_query'			=> 'Vous n’avez pas encore créé de filtre.',
+	'query_filter'			=> 'Filtres appliqués :',
+	'no_query_filter'		=> 'Aucun filtre appliqué',
+	'query_deprecated'		=> 'Ce filtre n’est plus valide. La catégorie ou le flux concerné a été supprimé.',
 	'about'				=> 'À propos',
 	'stats'				=> 'Statistiques',
+	'stats_idle'			=> 'Flux inactifs',
+	'stats_main'			=> 'Statistiques principales',
+	'stats_repartition'		=> 'Répartition des articles',
+	'stats_entry_per_hour'		=> 'Par heure',
+	'stats_entry_per_day_of_week'	=> 'Par jour de la semaine',
+	'stats_entry_per_month'		=> 'Par mois',
+
+	'last_week'			=> 'Depuis la semaine dernière',
+	'last_month'			=> 'Depuis le mois dernier',
+	'last_3_month'			=> 'Depuis les trois derniers mois',
+	'last_6_month'			=> 'Depuis les six derniers mois',
+	'last_year'			=> 'Depuis l’année dernière',
 
 	'your_rss_feeds'		=> 'Vos flux RSS',
 	'add_rss_feed'			=> 'Ajouter un flux RSS',
 	'no_rss_feed'			=> 'Aucun flux RSS',
-	'import_export_opml'		=> 'Importer / exporter (OPML)',
+	'import_export'			=> 'Importer / exporter',
+	'bookmark'			=> 'S’abonner (bookmark FreshRSS)',
 
 	'subscription_management'	=> 'Gestion des abonnements',
 	'main_stream'			=> 'Flux principal',
 	'all_feeds'			=> 'Tous les flux',
-	'favorite_feeds'		=> 'Favoris (%d)',
+	'favorite_feeds'		=> 'Favoris (%s)',
 	'not_read'			=> '%d non lu',
 	'not_reads'			=> '%d non lus',
 
 	'filter'			=> 'Filtrer',
 	'see_website'			=> 'Voir le site',
-	'administration'		=> 'Gestion',
+	'administration'		=> 'Gérer',
 	'actualize'			=> 'Actualiser',
 
 	'mark_read'			=> 'Marquer comme lu',
@@ -49,8 +95,10 @@ return array (
 	'rss_view'			=> 'Flux RSS',
 	'show_all_articles'		=> 'Afficher tous les articles',
 	'show_not_reads'		=> 'Afficher les non lus',
+	'show_adaptive'			=> 'Adapter l’affichage',
 	'show_read'			=> 'Afficher les lus',
 	'show_favorite'			=> 'Afficher les favoris',
+	'show_not_favorite'		=> 'Afficher tout sauf les favoris',
 	'older_first'			=> 'Plus anciens en premier',
 	'newer_first'			=> 'Plus récents en premier',
 
@@ -64,67 +112,69 @@ return array (
 	'article_published_on'		=> 'Article publié initialement sur <a href="%s">%s</a>',
 	'article_published_on_author'	=> 'Article publié initialement sur <a href="%s">%s</a> par %s',
 
-	'access_denied'			=> 'Vous n’avez pas le droit d’accéder à cette page',
-	'page_not_found'		=> 'La page que vous cherchez n’existe pas',
-	'error_occurred'		=> 'Une erreur est survenue',
-	'error_occurred_update'	=> 'Rien n’a été modifié',
+	'access_denied'			=> 'Vous n’avez pas le droit d’accéder à cette page !',
+	'page_not_found'		=> 'La page que vous cherchez n’existe pas !',
+	'error_occurred'		=> 'Une erreur est survenue !',
+	'error_occurred_update'		=> 'Rien n’a été modifié !',
 
 	'default_category'		=> 'Sans catégorie',
-	'categories_updated'		=> 'Les catégories ont été mises à jour',
+	'categories_updated'		=> 'Les catégories ont été mises à jour.',
 	'categories_management'		=> 'Gestion des catégories',
-	'feed_updated'			=> 'Le flux a été mis à jour',
+	'feed_updated'			=> 'Le flux a été mis à jour.',
 	'rss_feed_management'		=> 'Gestion des flux RSS',
-	'configuration_updated'		=> 'La configuration a été mise à jour',
+	'configuration_updated'		=> 'La configuration a été mise à jour.',
 	'sharing_management'		=> 'Gestion des options de partage',
-	'bad_opml_file'			=> 'Votre fichier OPML n’est pas valide',
-	'shortcuts_updated'		=> 'Les raccourcis ont été mis à jour',
-	'shortcuts_management'		=> 'Gestion des raccourcis',
+	'bad_opml_file'			=> 'Votre fichier OPML n’est pas valide.',
+	'shortcuts_updated'		=> 'Les raccourcis ont été mis à jour.',
 	'shortcuts_navigation'		=> 'Navigation',
 	'shortcuts_navigation_help'	=> 'Avec le modificateur "Shift", les raccourcis de navigation s’appliquent aux flux.<br/>Avec le modificateur "Alt", les raccourcis de navigation s’appliquent aux catégories.',
 	'shortcuts_article_action'	=> 'Actions associées à l’article courant',
 	'shortcuts_other_action'	=> 'Autres actions',
-	'feeds_marked_read'		=> 'Les flux ont été marqués comme lus',
-	'updated'			=> 'Modifications enregistrées',
+	'feeds_marked_read'		=> 'Les flux ont été marqués comme lus.',
+	'updated'			=> 'Modifications enregistrées.',
 
 	'already_subscribed'		=> 'Vous êtes déjà abonné à <em>%s</em>',
-	'feed_added'			=> 'Le flux <em>%s</em> a bien été ajouté',
-	'feed_not_added'		=> '<em>%s</em> n’a pas pu être ajouté',
-	'internal_problem_feed'		=> 'Le flux n’a pas pu être ajouté. Consulter les logs de FreshRSS pour plus de détails.',
-	'invalid_url'			=> 'L’url <em>%s</em> est invalide',
-	'feed_actualized'		=> '<em>%s</em> a été mis à jour',
-	'n_feeds_actualized'		=> '%d flux ont été mis à jour',
-	'feeds_actualized'		=> 'Les flux ont été mis à jour',
-	'no_feed_actualized'		=> 'Aucun flux n’a pu être mis à jour',
-	'n_entries_deleted'		=> '%d articles ont été supprimés',
-	'feeds_imported_with_errors'	=> 'Vos flux ont été importés mais des erreurs sont survenues',
-	'feeds_imported'		=> 'Vos flux ont été importés et vont maintenant être actualisés',
-	'category_emptied'		=> 'La catégorie a été vidée',
-	'feed_deleted'			=> 'Le flux a été supprimé',
+	'feed_added'			=> 'Le flux <em>%s</em> a bien été ajouté.',
+	'feed_not_added'		=> '<em>%s</em> n’a pas pu être ajouté.',
+	'internal_problem_feed'		=> 'Le flux ne peut pas être ajouté. <a href="%s">Consulter les logs de FreshRSS</a> pour plus de détails.',
+	'invalid_url'			=> 'L’url <em>%s</em> est invalide.',
+	'feed_actualized'		=> '<em>%s</em> a été mis à jour.',
+	'n_feeds_actualized'		=> '%d flux ont été mis à jour.',
+	'feeds_actualized'		=> 'Les flux ont été mis à jour.',
+	'no_feed_actualized'		=> 'Aucun flux n’a pu être mis à jour.',
+	'n_entries_deleted'		=> '%d articles ont été supprimés.',
+	'feeds_imported_with_errors'	=> 'Vos flux ont été importés mais des erreurs sont survenues.',
+	'feeds_imported'		=> 'Vos flux ont été importés et vont maintenant être actualisés.',
+	'category_emptied'		=> 'La catégorie a été vidée.',
+	'feed_deleted'			=> 'Le flux a été supprimé.',
 	'feed_validator'		=> 'Vérifier la valididé du flux',
 
-	'optimization_complete'		=> 'Optimisation terminée',
+	'optimization_complete'		=> 'Optimisation terminée.',
 
 	'your_rss_feeds'		=> 'Vos flux RSS',
 	'your_favorites'		=> 'Vos favoris',
 	'public'			=> 'Public',
-	'invalid_login'			=> 'L’identifiant est invalide',
+	'invalid_login'			=> 'L’identifiant est invalide !',
+
+	'file_is_nok'			=> 'Veuillez vérifier les droits sur le répertoire <em>%s</em>. Le serveur HTTP doit être capable d’écrire dedans.',
 
 	// VIEWS
 	'save'				=> 'Enregistrer',
 	'delete'			=> 'Supprimer',
 	'cancel'			=> 'Annuler',
+	'submit'			=> 'Valider',
 
 	'back_to_rss_feeds'		=> '← Retour à vos flux RSS',
 	'feeds_moved_category_deleted'	=> 'Lors de la suppression d’une catégorie, ses flux seront automatiquement classés dans <em>%s</em>.',
 	'category_number'		=> 'Catégorie n°%d',
 	'ask_empty'			=> 'Vider ?',
 	'number_feeds'			=> '%d flux',
-	'can_not_be_deleted'		=> 'Ne peut pas être supprimée',
+	'can_not_be_deleted'		=> 'Ne peut pas être supprimée.',
 	'add_category'			=> 'Ajouter une catégorie',
 	'new_category'			=> 'Nouvelle catégorie',
 
-	'javascript_for_shortcuts'	=> 'Le JavaScript doit être activé pour pouvoir profiter des raccourcis',
-	'javascript_should_be_activated'=> 'Le JavaScript doit être activé',
+	'javascript_for_shortcuts'	=> 'Le JavaScript doit être activé pour pouvoir profiter des raccourcis.',
+	'javascript_should_be_activated'=> 'Le JavaScript doit être activé.',
 	'shift_for_all_read'		=> '+ <code>shift</code> pour marquer tous les articles comme lus',
 	'see_on_website'		=> 'Voir sur le site d’origine',
 	'next_article'			=> 'Passer à l’article suivant',
@@ -135,25 +185,41 @@ return array (
 	'previous_page'			=> 'Passer à la page précédente',
 	'collapse_article'		=> 'Refermer',
 	'auto_share'			=> 'Partager',
-	'auto_share_help'		=> 'Si il n’y a qu’un mode de partage, celui ci est utilisé automatiquement. Sinon ils sont accessibles par leur numéro.',
+	'auto_share_help'		=> 'S’il n’y a qu’un mode de partage, celui ci est utilisé automatiquement. Sinon ils sont accessibles par leur numéro.',
+	'focus_search'			=> 'Accéder à la recherche',
+	'user_filter'			=> 'Accéder aux filtres utilisateur',
+	'user_filter_help'		=> 'S’il n’y a qu’un filtre utilisateur, celui ci est utilisé automatiquement. Sinon ils sont accessibles par leur numéro.',
+	'help'				=> 'Afficher la documentation',
 
-	'file_to_import'		=> 'Fichier à importer',
+	'file_to_import'		=> 'Fichier à importer<br />(OPML, Json ou Zip)',
+	'file_to_import_no_zip'		=> 'Fichier à importer<br />(OPML ou Json)',
 	'import'			=> 'Importer',
+	'file_cannot_be_uploaded'	=> 'Le fichier ne peut pas être téléchargé!',
+	'zip_error'			=> 'Une erreur est survenue durant l’import du fichier Zip.',
+	'no_zip_extension'		=> 'L’extension Zip n’est pas présente sur votre serveur.',
 	'export'			=> 'Exporter',
+	'export_opml'			=> 'Exporter la liste des flux (OPML)',
+	'export_starred'		=> 'Exporter les favoris',
+	'export_no_zip_extension'	=> 'L’extension Zip n’est pas présente sur votre serveur. Veuillez essayer d’exporter les fichiers un par un.',
+	'starred_list'			=> 'Liste des articles favoris',
+	'feed_list'			=> 'Liste des articles de %s',
 	'or'				=> 'ou',
 
 	'informations'			=> 'Informations',
 	'damn'				=> 'Arf !',
+	'ok'				=> 'Ok !',
+	'attention'			=> 'Attention !',
 	'feed_in_error'			=> 'Ce flux a rencontré un problème. Veuillez vérifier qu’il est toujours accessible puis actualisez-le.',
 	'feed_empty'			=> 'Ce flux est vide. Veuillez vérifier qu’il est toujours maintenu.',
 	'feed_description'		=> 'Description',
 	'website_url'			=> 'URL du site',
 	'feed_url'			=> 'URL du flux',
 	'articles'			=> 'articles',
-	'number_articles'		=> 'Nombre d’articles',
+	'number_articles'		=> '%d articles',
 	'by_feed'			=> 'par flux',
 	'by_default'			=> 'Par défaut',
 	'keep_history'			=> 'Nombre minimum d’articles à conserver',
+	'ttl'				=> 'Ne pas automatiquement rafraîchir plus souvent que',
 	'categorize'			=> 'Ranger dans une catégorie',
 	'truncate'			=> 'Supprimer tous les articles',
 	'advanced'			=> 'Avancé',
@@ -166,19 +232,24 @@ return array (
 	'http_username'			=> 'Identifiant HTTP',
 	'http_password'			=> 'Mot de passe HTTP',
 	'blank_to_disable'		=> 'Laissez vide pour désactiver',
+	'share_name'			=> 'Nom du partage à afficher',
+	'share_url'			=> 'URL du partage à utiliser',
 	'not_yet_implemented'		=> 'Pas encore implémenté',
-	'access_protected_feeds'	=> 'La connexion permet d’accéder aux flux protégés par une authentification HTTP',
+	'access_protected_feeds'	=> 'La connexion permet d’accéder aux flux protégés par une authentification HTTP.',
 	'no_selected_feed'		=> 'Aucun flux sélectionné.',
-	'think_to_add'			=> '<a href="./?c=configure&amp;a=feed">Vous pouvez ajouter des flux</a>.',
+	'think_to_add'			=> 'Vous pouvez ajouter des flux.',
 
 	'current_user'			=> 'Utilisateur actuel',
 	'password_form'			=> 'Mot de passe<br /><small>(pour connexion par formulaire)</small>',
+	'password_api'			=> 'Mot de passe API<br /><small>(ex. : pour applis mobiles)</small>',
 	'default_user'			=> 'Nom de l’utilisateur par défaut <small>(16 caractères alphanumériques maximum)</small>',
 	'persona_connection_email'	=> 'Adresse courriel de connexion<br /><small>(pour <a href="https://persona.org/" rel="external">Mozilla Persona</a>)</small>',
 	'allow_anonymous'		=> 'Autoriser la lecture anonyme des articles de l’utilisateur par défaut (%s)',
 	'allow_anonymous_refresh'	=> 'Autoriser le rafraîchissement anonyme des flux',
+	'unsafe_autologin'		=> 'Autoriser les connexions automatiques non-sûres au format : ',
+	'api_enabled'			=> 'Autoriser l’accès par <abbr>API</abbr> <small>(nécessaire pour les applis mobiles)</small>',
 	'auth_token'			=> 'Jeton d’identification',
-	'explain_token'			=> 'Permet d’accéder à la sortie RSS de l’utilisateur par défaut sans besoin de s’authentifier.<br /><kbd>%s?output=rss&token=%s</kbd>',
+	'explain_token'			=> 'Permet d’accéder à la sortie RSS de l’utilisateur par défaut sans besoin de s’authentifier.<br /><kbd>%s?output=rss&amp;token=%s</kbd>',
 	'login_configuration'		=> 'Identification',
 	'is_admin'			=> 'est administrateur',
 	'auth_type'			=> 'Méthode d’authentification',
@@ -189,32 +260,42 @@ return array (
 	'users_list'			=> 'Liste des utilisateurs',
 	'create_user'			=> 'Créer un nouvel utilisateur',
 	'username'			=> 'Nom d’utilisateur',
+	'username_admin'		=> 'Nom d’utilisateur administrateur',
 	'password'			=> 'Mot de passe',
 	'create'			=> 'Créer',
-	'user_created'			=> 'L’utilisateur %s a été créé',
-	'user_deleted'			=> 'L’utilisateur %s a été supprimé',
+	'user_created'			=> 'L’utilisateur %s a été créé.',
+	'user_deleted'			=> 'L’utilisateur %s a été supprimé.',
 
 	'language'			=> 'Langue',
 	'month'				=> 'mois',
 	'archiving_configuration'	=> 'Archivage',
-	'delete_articles_every'	=> 'Supprimer les articles après',
+	'delete_articles_every'		=> 'Supprimer les articles après',
 	'purge_now'			=> 'Purger maintenant',
-	'purge_completed'		=> 'Purge effectuée (%d articles supprimés)',
-	'archiving_configuration_help'	=> 'D’autres options sont disponibles dans la configuration individuelle des flux',
+	'purge_completed'		=> 'Purge effectuée (%d articles supprimés).',
+	'archiving_configuration_help'	=> 'D’autres options sont disponibles dans la configuration individuelle des flux.',
 	'reading_configuration'		=> 'Lecture',
+	'display_configuration'		=> 'Affichage',
 	'articles_per_page'		=> 'Nombre d’articles par page',
+	'number_divided_when_reader'	=> 'Divisé par 2 dans la vue de lecture.',
 	'default_view'			=> 'Vue par défaut',
+	'articles_to_display'		=> 'Articles à afficher',
 	'sort_order'			=> 'Ordre de tri',
 	'auto_load_more'		=> 'Charger les articles suivants en bas de page',
 	'display_articles_unfolded'	=> 'Afficher les articles dépliés par défaut',
+	'display_categories_unfolded'	=> 'Afficher les catégories pliées par défaut',
+	'hide_read_feeds'		=> 'Cacher les catégories &amp; flux sans article non-lu (ne fonctionne pas avec la configuration “Afficher tous les articles”)',
 	'after_onread'			=> 'Après “marquer tout comme lu”,',
 	'jump_next'			=> 'sauter au prochain voisin non lu (flux ou catégorie)',
-	'reading_icons'			=> 'Icônes de lecture',
+	'article_icons'			=> 'Icônes d’article',
 	'top_line'			=> 'Ligne du haut',
 	'bottom_line'			=> 'Ligne du bas',
+	'html5_notif_timeout'		=> 'Temps d’affichage de la notification HTML5',
+	'seconds_(0_means_no_timeout)'	=> 'secondes (0 signifie aucun timeout ) ',
 	'img_with_lazyload'		=> 'Utiliser le mode “chargement différé” pour les images',
+	'sticky_post'			=> 'Aligner l’article en haut quand il est ouvert',
+	'reading_confirm'		=> 'Afficher une confirmation lors des actions “marquer tout comme lu”',
 	'auto_read_when'		=> 'Marquer un article comme lu…',
-	'article_selected'		=> 'lorsque l’article est sélectionné',
+	'article_viewed'		=> 'lorsque l’article est affiché',
 	'article_open_on_website'	=> 'lorsque l’article est ouvert sur le site d’origine',
 	'scroll'			=> 'au défilement de la page',
 	'upon_reception'		=> 'dès la réception du nouvel article',
@@ -227,9 +308,15 @@ return array (
 	'optimize_bdd'			=> 'Optimiser la base de données',
 	'optimize_todo_sometimes'	=> 'À faire de temps en temps pour réduire la taille de la BDD',
 	'theme'				=> 'Thème',
+	'content_width'			=> 'Largeur du contenu',
+	'width_thin'			=> 'Fine',
+	'width_medium'			=> 'Moyenne',
+	'width_large'			=> 'Large',
+	'width_no_limit'		=> 'Pas de limite',
 	'more_information'		=> 'Plus d’informations',
 	'activate_sharing'		=> 'Activer le partage',
 	'shaarli'			=> 'Shaarli',
+	'blogotext'			=> 'Blogotext',
 	'wallabag'			=> 'wallabag',
 	'diaspora'			=> 'Diaspora*',
 	'twitter'			=> 'Twitter',
@@ -274,13 +361,16 @@ return array (
 	'version'			=> 'Version',
 
 	'logs'				=> 'Logs',
-	'logs_empty'			=> 'Les logs sont vides',
+	'logs_empty'			=> 'Les logs sont vides.',
 	'clear_logs'			=> 'Effacer les logs',
 
 	'forbidden_access'		=> 'L’accès vous est interdit !',
 	'login_required'		=> 'Accès protégé par mot de passe :',
 
 	'confirm_action'		=> 'Êtes-vous sûr(e) de vouloir continuer ? Cette action ne peut être annulée !',
+	'confirm_action_feed_cat'	=> 'Êtes-vous sûr(e) de vouloir continuer ? Vous pourriez perdre les favoris et les filtres associés. Cette action ne peut être annulée !',
+	'notif_title_new_articles'	=> 'FreshRSS : nouveaux articles !',
+	'notif_body_new_articles'	=> 'Il y a \d nouveaux articles à lire sur FreshRSS.',
 
 	// DATE
 	'january'			=> 'janvier',
@@ -295,6 +385,25 @@ return array (
 	'october'			=> 'octobre',
 	'november'			=> 'novembre',
 	'december'			=> 'décembre',
+	'jan'				=> 'jan.',
+	'feb'				=> 'fév.',
+	'mar'				=> 'mar.',
+	'apr'				=> 'avr.',
+	'may'				=> 'mai.',
+	'jun'				=> 'juin',
+	'jul'				=> 'jui.',
+	'aug'				=> 'août',
+	'sep'				=> 'sep.',
+	'oct'				=> 'oct.',
+	'nov'				=> 'nov.',
+	'dec'				=> 'déc.',
+	'sun'				=> 'dim.',
+	'mon'				=> 'lun.',
+	'tue'				=> 'mar.',
+	'wed'				=> 'mer.',
+	'thu'				=> 'jeu.',
+	'fri'				=> 'ven.',
+	'sat'				=> 'sam.',
 	// format spécial pour la fonction date()
 	'Jan'				=> '\j\a\n\v\i\e\r',
 	'Feb'				=> '\f\é\v\r\i\e\r',
@@ -323,4 +432,23 @@ return array (
 	'stats_entry_per_category'	=> 'Articles par catégorie',
 	'stats_top_feed'		=> 'Les dix plus gros flux',
 	'stats_entry_count'		=> 'Nombre d’articles',
+	'stats_no_idle'			=> 'Il n’y a aucun flux inactif !',
+
+	'update'			=> 'Mise à jour',
+	'update_system'			=> 'Système de mise à jour',
+	'update_check'			=> 'Vérifier les mises à jour',
+	'update_last'			=> 'Dernière vérification : %s',
+	'update_can_apply'		=> 'Une mise à jour est disponible.',
+	'update_apply'			=> 'Appliquer la mise à jour',
+	'update_server_not_found'	=> 'Le serveur de mise à jour n’a pas été trouvé. [%s]',
+	'no_update'			=> 'Aucune mise à jour à appliquer',
+	'update_problem'		=> 'La mise à jour a rencontré un problème : %s',
+	'update_finished'		=> 'La mise à jour est terminée !',
+
+	'auth_reset'			=> 'Réinitialisation de l’authentification',
+	'auth_will_reset'		=> 'Le système d’authentification va être réinitialisé : un formulaire sera utilisé à la place de Persona.',
+	'auth_not_persona'		=> 'Seul le système d’authentification Persona peut être réinitialisé.',
+	'auth_no_password_set'		=> 'Aucun mot de passe administrateur n’a été précisé. Cette fonctionnalité n’est pas disponible.',
+	'auth_form_set'			=> 'Le formulaire est désormais votre système d’authentification.',
+	'auth_form_not_set'		=> 'Un problème est survenu lors de la configuration de votre système d’authentification. Veuillez réessayer plus tard.',
 );

+ 5 - 3
app/i18n/install.en.php

@@ -28,8 +28,8 @@ return array (
 	'minz_is_nok'			=> 'You lack the Minz framework. You should execute <em>build.sh</em> script or <a href="https://github.com/marienfressinaud/MINZ">download it on Github</a> and install in <em>%s</em> directory the content of its <em>/lib</em> directory.',
 	'curl_is_ok'			=> 'You have version %s of cURL',
 	'curl_is_nok'			=> 'You lack cURL (php5-curl package)',
-	'pdomysql_is_ok'		=> 'You have PDO and its driver for MySQL',
-	'pdomysql_is_nok'		=> 'You lack PDO or its driver for MySQL (php5-mysql package)',
+	'pdo_is_ok'			=> 'You have PDO and at least one of the supported drivers (pdo_mysql, pdo_sqlite)',
+	'pdo_is_nok'			=> 'You lack PDO or one of the supported drivers (pdo_mysql, pdo_sqlite)',
 	'dom_is_ok'			=> 'You have the required library to browse the DOM',
 	'dom_is_nok'			=> 'You lack a required library to browse the DOM (php-xml package)',
 	'pcre_is_ok'			=> 'You have the required library for regular expressions (PCRE)',
@@ -42,6 +42,8 @@ return array (
 	'data_is_ok'			=> 'Permissions on data directory are good',
 	'persona_is_ok'			=> 'Permissions on Mozilla Persona directory are good',
 	'file_is_nok'			=> 'Check permissions on <em>%s</em> directory. HTTP server must have rights to write into',
+	'http_referer_is_ok'		=> 'Your HTTP REFERER is known and corresponds to your server.',
+	'http_referer_is_nok'		=> 'Please check that you are not altering your HTTP REFERER.',
 	'fix_errors_before'		=> 'Fix errors before skip to the next step.',
 
 	'general_conf_is_ok'		=> 'General configuration has been saved.',
@@ -61,7 +63,7 @@ return array (
 	'update_end'			=> 'Update process is completed, now you can go to the final step.',
 
 
-	'installation_is_ok'		=> 'The installation process was successful.<br />The final step will now attempt to delete the <kbd>./p/i/install.php</kbd> file and any database backup created during the update process.<br />You may choose to skip this step and delete <kbd>./p/i/install.php</kbd> manually.',
+	'installation_is_ok'		=> 'The installation process was successful.<br />The final step will now attempt to delete any file and database backup created during the update process.<br />You may choose to skip this step by deleting <kbd>./data/do-install.txt</kbd> manually.',
 	'finish_installation'		=> 'Complete installation',
 	'install_not_deleted'		=> 'Something went wrong; you must delete the file <em>%s</em> manually.',
 );

+ 5 - 3
app/i18n/install.fr.php

@@ -28,8 +28,8 @@ return array (
 	'minz_is_nok'			=> 'Vous ne disposez pas de la librairie Minz. Vous devriez exécuter le script <em>build.sh</em> ou bien <a href="https://github.com/marienfressinaud/MINZ">la télécharger sur Github</a> et installer dans le répertoire <em>%s</em> le contenu de son répertoire <em>/lib</em>.',
 	'curl_is_ok'			=> 'Vous disposez de cURL dans sa version %s',
 	'curl_is_nok'			=> 'Vous ne disposez pas de cURL (paquet php5-curl)',
-	'pdomysql_is_ok'		=> 'Vous disposez de PDO et de son driver pour MySQL (paquet php5-mysql)',
-	'pdomysql_is_nok'		=> 'Vous ne disposez pas de PDO ou de son driver pour MySQL',
+	'pdo_is_ok'			=> 'Vous disposez de PDO et d’au moins un des drivers supportés (pdo_mysql, pdo_sqlite)',
+	'pdo_is_nok'			=> 'Vous ne disposez pas de PDO ou d’un des drivers supportés (pdo_mysql, pdo_sqlite)',
 	'dom_is_ok'			=> 'Vous disposez du nécessaire pour parcourir le DOM',
 	'dom_is_nok'			=> 'Il manque une librairie pour parcourir le DOM (paquet php-xml)',
 	'pcre_is_ok'			=> 'Vous disposez du nécessaire pour les expressions régulières (PCRE)',
@@ -42,6 +42,8 @@ return array (
 	'data_is_ok'			=> 'Les droits sur le répertoire de data sont bons',
 	'persona_is_ok'			=> 'Les droits sur le répertoire de Mozilla Persona sont bons',
 	'file_is_nok'			=> 'Veuillez vérifier les droits sur le répertoire <em>%s</em>. Le serveur HTTP doit être capable d’écrire dedans',
+	'http_referer_is_ok'		=> 'Le HTTP REFERER est connu et semble correspondre à votre serveur.',
+	'http_referer_is_nok'		=> 'Veuillez vérifier que vous ne modifiez pas votre HTTP REFERER.',
 	'fix_errors_before'		=> 'Veuillez corriger les erreurs avant de passer à l’étape suivante.',
 
 	'general_conf_is_ok'		=> 'La configuration générale a été enregistrée.',
@@ -60,7 +62,7 @@ return array (
 	'update_long'			=> 'Ce processus peut prendre longtemps, selon la taille de votre base de données. Vous aurez peut-être à attendre que cette page dépasse son temps maximum d’exécution (~5 minutes) puis à la recharger.',
 	'update_end'			=> 'La mise à jour est terminée, vous pouvez maintenant passer à l’étape finale.',
 
-	'installation_is_ok'		=> 'L’installation s’est bien passée.<br />La dernière étape va maintenant tenter de supprimer le fichier <kbd>./p/i/install.php</kbd>, ainsi que d’éventuelles copies de base de données créées durant le processus de mise à jour.<br />Vous pouvez choisir de sauter cette étape et de supprimer <kbd>./p/i/install.php</kbd> manuellement.',
+	'installation_is_ok'		=> 'L’installation s’est bien passée.<br />La dernière étape va maintenant tenter de supprimer les fichiers ainsi que d’éventuelles copies de base de données créés durant le processus de mise à jour.<br />Vous pouvez choisir de sauter cette étape en supprimant <kbd>./data/do-install.txt</kbd> manuellement.',
 	'finish_installation'		=> 'Terminer l’installation',
 	'install_not_deleted'		=> 'Quelque chose s’est mal passé, vous devez supprimer le fichier <em>%s</em> à la main.',
 );

+ 879 - 0
app/install.php

@@ -0,0 +1,879 @@
+<?php
+if (function_exists('opcache_reset')) {
+	opcache_reset();
+}
+
+define('BCRYPT_COST', 9);
+
+session_name('FreshRSS');
+session_set_cookie_params(0, dirname(empty($_SERVER['REQUEST_URI']) ? '/' : dirname($_SERVER['REQUEST_URI'])), null, false, true);
+session_start();
+
+if (isset($_GET['step'])) {
+	define('STEP',(int)$_GET['step']);
+} else {
+	define('STEP', 0);
+}
+
+define('SQL_CREATE_DB', 'CREATE DATABASE IF NOT EXISTS %1$s DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci;');
+
+if (STEP === 3 && isset($_POST['type'])) {
+	$_SESSION['bd_type'] = $_POST['type'];
+}
+
+if (isset($_SESSION['bd_type'])) {
+	switch ($_SESSION['bd_type']) {
+	case 'mysql':
+		include(APP_PATH . '/SQL/install.sql.mysql.php');
+		break;
+	case 'sqlite':
+		include(APP_PATH . '/SQL/install.sql.sqlite.php');
+		break;
+	}
+}
+
+function param($key, $default = false) {
+	if (isset($_POST[$key])) {
+		return $_POST[$key];
+	} else {
+		return $default;
+	}
+}
+
+
+// gestion internationalisation
+$translates = array();
+$actual = 'en';
+function initTranslate() {
+	global $translates;
+	global $actual;
+
+	$actual = isset($_SESSION['language']) ? $_SESSION['language'] : getBetterLanguage('en');
+
+	$file = APP_PATH . '/i18n/' . $actual . '.php';
+	if (file_exists($file)) {
+		$translates = array_merge($translates, include($file));
+	}
+
+	$file = APP_PATH . '/i18n/install.' . $actual . '.php';
+	if (file_exists($file)) {
+		$translates = array_merge($translates, include($file));
+	}
+}
+
+function getBetterLanguage($fallback) {
+	$available = availableLanguages();
+	$accept = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
+	$language = strtolower(substr($accept, 0, 2));
+
+	if (isset($available[$language])) {
+		return $language;
+	} else {
+		return $fallback;
+	}
+}
+
+function availableLanguages() {
+	return array(
+		'en' => 'English',
+		'fr' => 'Français'
+	);
+}
+
+function _t($key) {
+	global $translates;
+	$translate = $key;
+	if (isset($translates[$key])) {
+		$translate = $translates[$key];
+	}
+
+	$args = func_get_args();
+	unset($args[0]);
+
+	return vsprintf($translate, $args);
+}
+
+
+/*** SAUVEGARDES ***/
+function saveLanguage() {
+	if (!empty($_POST)) {
+		if (!isset($_POST['language'])) {
+			return false;
+		}
+
+		$_SESSION['language'] = $_POST['language'];
+
+		header('Location: index.php?step=1');
+	}
+}
+
+function saveStep2() {
+	if (!empty($_POST)) {
+		$_SESSION['title'] = substr(trim(param('title', _t('freshrss'))), 0, 25);
+		$_SESSION['old_entries'] = param('old_entries', 3);
+		$_SESSION['auth_type'] = param('auth_type', 'form');
+		$_SESSION['default_user'] = substr(preg_replace('/[^a-zA-Z0-9]/', '', param('default_user', '')), 0, 16);
+		$_SESSION['mail_login'] = filter_var(param('mail_login', ''), FILTER_VALIDATE_EMAIL);
+
+		$password_plain = param('passwordPlain', false);
+		if ($password_plain !== false) {
+			if (!function_exists('password_hash')) {
+				include_once(LIB_PATH . '/password_compat.php');
+			}
+			$passwordHash = password_hash($password_plain, PASSWORD_BCRYPT, array('cost' => BCRYPT_COST));
+			$passwordHash = preg_replace('/^\$2[xy]\$/', '\$2a\$', $passwordHash);	//Compatibility with bcrypt.js
+			$_SESSION['passwordHash'] = $passwordHash;
+		}
+
+		if (empty($_SESSION['title']) ||
+		    empty($_SESSION['old_entries']) ||
+		    empty($_SESSION['auth_type']) ||
+		    empty($_SESSION['default_user'])) {
+			return false;
+		}
+
+		if (($_SESSION['auth_type'] === 'form' && empty($_SESSION['passwordHash'])) ||
+				($_SESSION['auth_type'] === 'persona' && empty($_SESSION['mail_login']))) {
+			return false;
+		}
+
+		$_SESSION['salt'] = sha1(uniqid(mt_rand(), true).implode('', stat(__FILE__)));
+		if ((!ctype_digit($_SESSION['old_entries'])) ||($_SESSION['old_entries'] < 1)) {
+			$_SESSION['old_entries'] = 3;
+		}
+
+		$token = '';
+		if ($_SESSION['mail_login']) {
+			$token = sha1($_SESSION['salt'] . $_SESSION['mail_login']);
+		}
+
+		$config_array = array(
+			'language' => $_SESSION['language'],
+			'theme' => 'Origine',
+			'old_entries' => $_SESSION['old_entries'],
+			'mail_login' => $_SESSION['mail_login'],
+			'passwordHash' => $_SESSION['passwordHash'],
+			'token' => $token,
+		);
+
+		$configPath = DATA_PATH . '/' . $_SESSION['default_user'] . '_user.php';
+		@unlink($configPath);	//To avoid access-rights problems
+		file_put_contents($configPath, "<?php\n return " . var_export($config_array, true) . ';');
+
+		if ($_SESSION['mail_login'] != '') {
+			$personaFile = DATA_PATH . '/persona/' . $_SESSION['mail_login'] . '.txt';
+			@unlink($personaFile);
+			file_put_contents($personaFile, $_SESSION['default_user']);
+		}
+
+		header('Location: index.php?step=3');
+	}
+}
+
+function saveStep3() {
+	if (!empty($_POST)) {
+		if ($_SESSION['bd_type'] === 'sqlite') {
+			$_SESSION['bd_base'] = $_SESSION['default_user'];
+			$_SESSION['bd_host'] = '';
+			$_SESSION['bd_user'] = '';
+			$_SESSION['bd_password'] = '';
+			$_SESSION['bd_prefix'] = '';
+			$_SESSION['bd_prefix_user'] = '';	//No prefix for SQLite
+		} else {
+			if (empty($_POST['type']) ||
+			    empty($_POST['host']) ||
+			    empty($_POST['user']) ||
+			    empty($_POST['base'])) {
+				$_SESSION['bd_error'] = 'Missing parameters!';
+			}
+			$_SESSION['bd_base'] = substr($_POST['base'], 0, 64);
+			$_SESSION['bd_host'] = $_POST['host'];
+			$_SESSION['bd_user'] = $_POST['user'];
+			$_SESSION['bd_password'] = $_POST['pass'];
+			$_SESSION['bd_prefix'] = substr($_POST['prefix'], 0, 16);
+			$_SESSION['bd_prefix_user'] = $_SESSION['bd_prefix'] .(empty($_SESSION['default_user']) ? '' :($_SESSION['default_user'] . '_'));
+		}
+
+		$ini_array = array(
+			'general' => array(
+				'environment' => empty($_SESSION['environment']) ? 'production' : $_SESSION['environment'],
+				'salt' => $_SESSION['salt'],
+				'base_url' => '',
+				'title' => $_SESSION['title'],
+				'default_user' => $_SESSION['default_user'],
+				'allow_anonymous' => isset($_SESSION['allow_anonymous']) ? $_SESSION['allow_anonymous'] : false,
+				'allow_anonymous_refresh' => isset($_SESSION['allow_anonymous_refresh']) ? $_SESSION['allow_anonymous_refresh'] : false,
+				'auth_type' => $_SESSION['auth_type'],
+				'api_enabled' => isset($_SESSION['api_enabled']) ? $_SESSION['api_enabled'] : false,
+				'unsafe_autologin_enabled' => isset($_SESSION['unsafe_autologin_enabled']) ? $_SESSION['unsafe_autologin_enabled'] : false,
+			),
+			'db' => array(
+				'type' => $_SESSION['bd_type'],
+				'host' => $_SESSION['bd_host'],
+				'user' => $_SESSION['bd_user'],
+				'password' => $_SESSION['bd_password'],
+				'base' => $_SESSION['bd_base'],
+				'prefix' => $_SESSION['bd_prefix'],
+			),
+		);
+
+		@unlink(DATA_PATH . '/config.php');	//To avoid access-rights problems
+		file_put_contents(DATA_PATH . '/config.php', "<?php\n return " . var_export($ini_array, true) . ';');
+
+		$res = checkBD();
+
+		if ($res) {
+			$_SESSION['bd_error'] = '';
+			header('Location: index.php?step=4');
+		} elseif (empty($_SESSION['bd_error'])) {
+			$_SESSION['bd_error'] = 'Unknown error!';
+		}
+	}
+	invalidateHttpCache();
+}
+
+function newPdo() {
+	switch ($_SESSION['bd_type']) {
+	case 'mysql':
+		$str = 'mysql:host=' . $_SESSION['bd_host'] . ';dbname=' . $_SESSION['bd_base'];
+		$driver_options = array(
+			PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
+		);
+		break;
+	case 'sqlite':
+		$str = 'sqlite:' . DATA_PATH . '/' . $_SESSION['default_user'] . '.sqlite';
+		$driver_options = array(
+			PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
+		);
+		break;
+	default:
+		return false;
+	}
+	return new PDO($str, $_SESSION['bd_user'], $_SESSION['bd_password'], $driver_options);
+}
+
+function deleteInstall() {
+	$res = unlink(DATA_PATH . '/do-install.txt');
+
+	if (!$res) {
+		return false;
+	}
+
+	header('Location: index.php');
+}
+
+
+/*** VÉRIFICATIONS ***/
+function checkStep() {
+	$s0 = checkStep0();
+	$s1 = checkStep1();
+	$s2 = checkStep2();
+	$s3 = checkStep3();
+	if (STEP > 0 && $s0['all'] != 'ok') {
+		header('Location: index.php?step=0');
+	} elseif (STEP > 1 && $s1['all'] != 'ok') {
+		header('Location: index.php?step=1');
+	} elseif (STEP > 2 && $s2['all'] != 'ok') {
+		header('Location: index.php?step=2');
+	} elseif (STEP > 3 && $s3['all'] != 'ok') {
+		header('Location: index.php?step=3');
+	}
+	$_SESSION['actualize_feeds'] = true;
+}
+
+function checkStep0() {
+	$languages = availableLanguages();
+	$language = isset($_SESSION['language']) &&
+	            isset($languages[$_SESSION['language']]);
+
+	return array(
+		'language' => $language ? 'ok' : 'ko',
+		'all' => $language ? 'ok' : 'ko'
+	);
+}
+
+function checkStep1() {
+	$php = version_compare(PHP_VERSION, '5.2.1') >= 0;
+	$minz = file_exists(LIB_PATH . '/Minz');
+	$curl = extension_loaded('curl');
+	$pdo_mysql = extension_loaded('pdo_mysql');
+	$pdo_sqlite = extension_loaded('pdo_sqlite');
+	$pdo = $pdo_mysql || $pdo_sqlite;
+	$pcre = extension_loaded('pcre');
+	$ctype = extension_loaded('ctype');
+	$dom = class_exists('DOMDocument');
+	$data = DATA_PATH && is_writable(DATA_PATH);
+	$cache = CACHE_PATH && is_writable(CACHE_PATH);
+	$log = LOG_PATH && is_writable(LOG_PATH);
+	$favicons = is_writable(DATA_PATH . '/favicons');
+	$persona = is_writable(DATA_PATH . '/persona');
+	$http_referer = is_referer_from_same_domain();
+
+	return array(
+		'php' => $php ? 'ok' : 'ko',
+		'minz' => $minz ? 'ok' : 'ko',
+		'curl' => $curl ? 'ok' : 'ko',
+		'pdo-mysql' => $pdo_mysql ? 'ok' : 'ko',
+		'pdo-sqlite' => $pdo_sqlite ? 'ok' : 'ko',
+		'pdo' => $pdo ? 'ok' : 'ko',
+		'pcre' => $pcre ? 'ok' : 'ko',
+		'ctype' => $ctype ? 'ok' : 'ko',
+		'dom' => $dom ? 'ok' : 'ko',
+		'data' => $data ? 'ok' : 'ko',
+		'cache' => $cache ? 'ok' : 'ko',
+		'log' => $log ? 'ok' : 'ko',
+		'favicons' => $favicons ? 'ok' : 'ko',
+		'persona' => $persona ? 'ok' : 'ko',
+		'http_referer' => $http_referer ? 'ok' : 'ko',
+		'all' => $php && $minz && $curl && $pdo && $pcre && $ctype && $dom &&
+		         $data && $cache && $log && $favicons && $persona && $http_referer ?
+		         'ok' : 'ko'
+	);
+}
+
+function checkStep2() {
+	$conf = !empty($_SESSION['title']) &&
+	        !empty($_SESSION['old_entries']) &&
+	        isset($_SESSION['mail_login']) &&
+	        !empty($_SESSION['default_user']);
+
+	$form = (
+		isset($_SESSION['auth_type']) &&
+		($_SESSION['auth_type'] != 'form' || !empty($_SESSION['passwordHash']))
+	);
+
+	$persona = (
+		isset($_SESSION['auth_type']) &&
+		($_SESSION['auth_type'] != 'persona' || !empty($_SESSION['mail_login']))
+	);
+
+	$defaultUser = empty($_POST['default_user']) ? null : $_POST['default_user'];
+	if ($defaultUser === null) {
+		$defaultUser = empty($_SESSION['default_user']) ? '' : $_SESSION['default_user'];
+	}
+	$data = is_writable(DATA_PATH . '/' . $defaultUser . '_user.php');
+
+	return array(
+		'conf' => $conf ? 'ok' : 'ko',
+		'form' => $form ? 'ok' : 'ko',
+		'persona' => $persona ? 'ok' : 'ko',
+		'data' => $data ? 'ok' : 'ko',
+		'all' => $conf && $form && $persona && $data ? 'ok' : 'ko'
+	);
+}
+
+function checkStep3() {
+	$conf = is_writable(DATA_PATH . '/config.php');
+
+	$bd = isset($_SESSION['bd_type']) &&
+	      isset($_SESSION['bd_host']) &&
+	      isset($_SESSION['bd_user']) &&
+	      isset($_SESSION['bd_password']) &&
+	      isset($_SESSION['bd_base']) &&
+	      isset($_SESSION['bd_prefix']) &&
+	      isset($_SESSION['bd_error']);
+	$conn = empty($_SESSION['bd_error']);
+
+	return array(
+		'bd' => $bd ? 'ok' : 'ko',
+		'conn' => $conn ? 'ok' : 'ko',
+		'conf' => $conf ? 'ok' : 'ko',
+		'all' => $bd && $conn && $conf ? 'ok' : 'ko'
+	);
+}
+
+function checkBD() {
+	$ok = false;
+
+	try {
+		$str = '';
+		$driver_options = null;
+		switch ($_SESSION['bd_type']) {
+		case 'mysql':
+			$driver_options = array(
+				PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'
+			);
+
+			try {	// on ouvre une connexion juste pour créer la base si elle n'existe pas
+				$str = 'mysql:host=' . $_SESSION['bd_host'] . ';';
+				$c = new PDO($str, $_SESSION['bd_user'], $_SESSION['bd_password'], $driver_options);
+				$sql = sprintf(SQL_CREATE_DB, $_SESSION['bd_base']);
+				$res = $c->query($sql);
+			} catch (PDOException $e) {
+			}
+
+			// on écrase la précédente connexion en sélectionnant la nouvelle BDD
+			$str = 'mysql:host=' . $_SESSION['bd_host'] . ';dbname=' . $_SESSION['bd_base'];
+			break;
+		case 'sqlite':
+			$str = 'sqlite:' . DATA_PATH . '/' . $_SESSION['default_user'] . '.sqlite';
+			$driver_options = array(
+				PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
+			);
+			break;
+		default:
+			return false;
+		}
+
+		$c = new PDO($str, $_SESSION['bd_user'], $_SESSION['bd_password'], $driver_options);
+
+		if (defined('SQL_CREATE_TABLES')) {
+			$sql = sprintf(SQL_CREATE_TABLES, $_SESSION['bd_prefix_user'], _t('default_category'));
+			$stm = $c->prepare($sql);
+			$ok = $stm->execute();
+		} else {
+			global $SQL_CREATE_TABLES;
+			if (is_array($SQL_CREATE_TABLES)) {
+				$ok = true;
+				foreach ($SQL_CREATE_TABLES as $instruction) {
+					$sql = sprintf($instruction, $_SESSION['bd_prefix_user'], _t('default_category'));
+					$stm = $c->prepare($sql);
+					$ok &= $stm->execute();
+				}
+			}
+		}
+	} catch (PDOException $e) {
+		$ok = false;
+		$_SESSION['bd_error'] = $e->getMessage();
+	}
+
+	if (!$ok) {
+		@unlink(DATA_PATH . '/config.php');
+	}
+
+	return $ok;
+}
+
+/*** AFFICHAGE ***/
+function printStep0() {
+	global $actual;
+?>
+	<?php $s0 = checkStep0(); if ($s0['all'] == 'ok') { ?>
+	<p class="alert alert-success"><span class="alert-head"><?php echo _t('ok'); ?></span> <?php echo _t('language_defined'); ?></p>
+	<?php } ?>
+
+	<form action="index.php?step=0" method="post">
+		<legend><?php echo _t('choose_language'); ?></legend>
+		<div class="form-group">
+			<label class="group-name" for="language"><?php echo _t('language'); ?></label>
+			<div class="group-controls">
+				<select name="language" id="language">
+				<?php $languages = availableLanguages(); ?>
+				<?php foreach ($languages as $short => $lib) { ?>
+				<option value="<?php echo $short; ?>"<?php echo $actual == $short ? ' selected="selected"' : ''; ?>><?php echo $lib; ?></option>
+				<?php } ?>
+				</select>
+			</div>
+		</div>
+
+		<div class="form-group form-actions">
+			<div class="group-controls">
+				<button type="submit" class="btn btn-important"><?php echo _t('save'); ?></button>
+				<button type="reset" class="btn"><?php echo _t('cancel'); ?></button>
+				<?php if ($s0['all'] == 'ok') { ?>
+				<a class="btn btn-important next-step" href="?step=1"><?php echo _t('next_step'); ?></a>
+				<?php } ?>
+			</div>
+		</div>
+	</form>
+<?php
+}
+
+function printStep1() {
+	$res = checkStep1();
+?>
+	<noscript><p class="alert alert-warn"><span class="alert-head"><?php echo _t('attention'); ?></span> <?php echo _t('javascript_is_better'); ?></p></noscript>
+
+	<?php if ($res['php'] == 'ok') { ?>
+	<p class="alert alert-success"><span class="alert-head"><?php echo _t('ok'); ?></span> <?php echo _t('php_is_ok', PHP_VERSION); ?></p>
+	<?php } else { ?>
+	<p class="alert alert-error"><span class="alert-head"><?php echo _t('damn'); ?></span> <?php echo _t('php_is_nok', PHP_VERSION, '5.2.1'); ?></p>
+	<?php } ?>
+
+	<?php if ($res['minz'] == 'ok') { ?>
+	<p class="alert alert-success"><span class="alert-head"><?php echo _t('ok'); ?></span> <?php echo _t('minz_is_ok'); ?></p>
+	<?php } else { ?>
+	<p class="alert alert-error"><span class="alert-head"><?php echo _t('damn'); ?></span> <?php echo _t('minz_is_nok', LIB_PATH . '/Minz'); ?></p>
+	<?php } ?>
+
+	<?php if ($res['pdo'] == 'ok') { ?>
+	<p class="alert alert-success"><span class="alert-head"><?php echo _t('ok'); ?></span> <?php echo _t('pdo_is_ok'); ?></p>
+	<?php } else { ?>
+	<p class="alert alert-error"><span class="alert-head"><?php echo _t('damn'); ?></span> <?php echo _t('pdo_is_nok'); ?></p>
+	<?php } ?>
+
+	<?php if ($res['curl'] == 'ok') { ?>
+	<?php $version = curl_version(); ?>
+	<p class="alert alert-success"><span class="alert-head"><?php echo _t('ok'); ?></span> <?php echo _t('curl_is_ok', $version['version']); ?></p>
+	<?php } else { ?>
+	<p class="alert alert-error"><span class="alert-head"><?php echo _t('damn'); ?></span> <?php echo _t('curl_is_nok'); ?></p>
+	<?php } ?>
+
+	<?php if ($res['pcre'] == 'ok') { ?>
+	<p class="alert alert-success"><span class="alert-head"><?php echo _t('ok'); ?></span> <?php echo _t('pcre_is_ok'); ?></p>
+	<?php } else { ?>
+	<p class="alert alert-error"><span class="alert-head"><?php echo _t('damn'); ?></span> <?php echo _t('pcre_is_nok'); ?></p>
+	<?php } ?>
+
+	<?php if ($res['ctype'] == 'ok') { ?>
+	<p class="alert alert-success"><span class="alert-head"><?php echo _t('ok'); ?></span> <?php echo _t('ctype_is_ok'); ?></p>
+	<?php } else { ?>
+	<p class="alert alert-error"><span class="alert-head"><?php echo _t('damn'); ?></span> <?php echo _t('ctype_is_nok'); ?></p>
+	<?php } ?>
+
+	<?php if ($res['dom'] == 'ok') { ?>
+	<p class="alert alert-success"><span class="alert-head"><?php echo _t('ok'); ?></span> <?php echo _t('dom_is_ok'); ?></p>
+	<?php } else { ?>
+	<p class="alert alert-error"><span class="alert-head"><?php echo _t('damn'); ?></span> <?php echo _t('dom_is_nok'); ?></p>
+	<?php } ?>
+
+	<?php if ($res['data'] == 'ok') { ?>
+	<p class="alert alert-success"><span class="alert-head"><?php echo _t('ok'); ?></span> <?php echo _t('data_is_ok'); ?></p>
+	<?php } else { ?>
+	<p class="alert alert-error"><span class="alert-head"><?php echo _t('damn'); ?></span> <?php echo _t('file_is_nok', DATA_PATH); ?></p>
+	<?php } ?>
+
+	<?php if ($res['cache'] == 'ok') { ?>
+	<p class="alert alert-success"><span class="alert-head"><?php echo _t('ok'); ?></span> <?php echo _t('cache_is_ok'); ?></p>
+	<?php } else { ?>
+	<p class="alert alert-error"><span class="alert-head"><?php echo _t('damn'); ?></span> <?php echo _t('file_is_nok', CACHE_PATH); ?></p>
+	<?php } ?>
+
+	<?php if ($res['log'] == 'ok') { ?>
+	<p class="alert alert-success"><span class="alert-head"><?php echo _t('ok'); ?></span> <?php echo _t('log_is_ok'); ?></p>
+	<?php } else { ?>
+	<p class="alert alert-error"><span class="alert-head"><?php echo _t('damn'); ?></span> <?php echo _t('file_is_nok', LOG_PATH); ?></p>
+	<?php } ?>
+
+	<?php if ($res['favicons'] == 'ok') { ?>
+	<p class="alert alert-success"><span class="alert-head"><?php echo _t('ok'); ?></span> <?php echo _t('favicons_is_ok'); ?></p>
+	<?php } else { ?>
+	<p class="alert alert-error"><span class="alert-head"><?php echo _t('damn'); ?></span> <?php echo _t('file_is_nok', DATA_PATH . '/favicons'); ?></p>
+	<?php } ?>
+
+	<?php if ($res['persona'] == 'ok') { ?>
+	<p class="alert alert-success"><span class="alert-head"><?php echo _t('ok'); ?></span> <?php echo _t('persona_is_ok'); ?></p>
+	<?php } else { ?>
+	<p class="alert alert-error"><span class="alert-head"><?php echo _t('damn'); ?></span> <?php echo _t('file_is_nok', DATA_PATH . '/persona'); ?></p>
+	<?php } ?>
+
+	<?php if ($res['http_referer'] == 'ok') { ?>
+	<p class="alert alert-success"><span class="alert-head"><?php echo _t('ok'); ?></span> <?php echo _t('http_referer_is_ok'); ?></p>
+	<?php } else { ?>
+	<p class="alert alert-error"><span class="alert-head"><?php echo _t('damn'); ?></span> <?php echo _t('http_referer_is_nok'); ?></p>
+	<?php } ?>
+
+	<?php if ($res['all'] == 'ok') { ?>
+	<a class="btn btn-important next-step" href="?step=2"><?php echo _t('next_step'); ?></a>
+	<?php } else { ?>
+	<p class="alert alert-error"><?php echo _t('fix_errors_before'); ?></p>
+	<?php } ?>
+<?php
+}
+
+function printStep2() {
+?>
+	<?php $s2 = checkStep2(); if ($s2['all'] == 'ok') { ?>
+	<p class="alert alert-success"><span class="alert-head"><?php echo _t('ok'); ?></span> <?php echo _t('general_conf_is_ok'); ?></p>
+	<?php } elseif (!empty($_POST)) { ?>
+	<p class="alert alert-error"><?php echo _t('fix_errors_before'); ?></p>
+	<?php } ?>
+
+	<form action="index.php?step=2" method="post">
+		<legend><?php echo _t('general_configuration'); ?></legend>
+
+		<div class="form-group">
+			<label class="group-name" for="title"><?php echo _t('title'); ?></label>
+			<div class="group-controls">
+				<input type="text" id="title" name="title" value="<?php echo isset($_SESSION['title']) ? $_SESSION['title'] : _t('freshrss'); ?>" />
+			</div>
+		</div>
+
+		<div class="form-group">
+			<label class="group-name" for="old_entries"><?php echo _t('delete_articles_every'); ?></label>
+			<div class="group-controls">
+				<input type="number" id="old_entries" name="old_entries" required="required" min="1" max="1200" value="<?php echo isset($_SESSION['old_entries']) ? $_SESSION['old_entries'] : '3'; ?>" /> <?php echo _t('month'); ?>
+			</div>
+		</div>
+
+		<div class="form-group">
+			<label class="group-name" for="default_user"><?php echo _t('default_user'); ?></label>
+			<div class="group-controls">
+				<input type="text" id="default_user" name="default_user" required="required" size="16" maxlength="16" pattern="[0-9a-zA-Z]{1,16}" value="<?php echo isset($_SESSION['default_user']) ? $_SESSION['default_user'] : ''; ?>" placeholder="<?php echo httpAuthUser() == '' ? 'user1' : httpAuthUser(); ?>" />
+			</div>
+		</div>
+
+		<div class="form-group">
+			<label class="group-name" for="auth_type"><?php echo _t('auth_type'); ?></label>
+			<div class="group-controls">
+				<select id="auth_type" name="auth_type" required="required" onchange="auth_type_change(true)">
+					<?php
+						function no_auth($auth_type) {
+							return !in_array($auth_type, array('form', 'persona', 'http_auth', 'none'));
+						}
+						$auth_type = isset($_SESSION['auth_type']) ? $_SESSION['auth_type'] : '';
+					?>
+					<option value="form"<?php echo $auth_type === 'form' || no_auth($auth_type) ? ' selected="selected"' : '', cryptAvailable() ? '' : ' disabled="disabled"'; ?>><?php echo _t('auth_form'); ?></option>
+					<option value="persona"<?php echo $auth_type === 'persona' ? ' selected="selected"' : ''; ?>><?php echo _t('auth_persona'); ?></option>
+					<option value="http_auth"<?php echo $auth_type === 'http_auth' ? ' selected="selected"' : '', httpAuthUser() == '' ? ' disabled="disabled"' : ''; ?>><?php echo _t('http_auth'); ?>(REMOTE_USER = '<?php echo httpAuthUser(); ?>')</option>
+					<option value="none"<?php echo $auth_type === 'none' ? ' selected="selected"' : ''; ?>><?php echo _t('auth_none'); ?></option>
+				</select>
+			</div>
+		</div>
+
+		<div class="form-group">
+			<label class="group-name" for="passwordPlain"><?php echo _t('password_form'); ?></label>
+			<div class="group-controls">
+				<div class="stick">
+					<input type="password" id="passwordPlain" name="passwordPlain" pattern=".{7,}" autocomplete="off" <?php echo $auth_type === 'form' ? ' required="required"' : ''; ?> />
+					<a class="btn toggle-password" data-toggle="passwordPlain"><?php echo FreshRSS_Themes::icon('key'); ?></a>
+				</div>
+				<noscript><b><?php echo _t('javascript_should_be_activated'); ?></b></noscript>
+			</div>
+		</div>
+
+		<div class="form-group">
+			<label class="group-name" for="mail_login"><?php echo _t('persona_connection_email'); ?></label>
+			<div class="group-controls">
+				<input type="email" id="mail_login" name="mail_login" value="<?php echo isset($_SESSION['mail_login']) ? $_SESSION['mail_login'] : ''; ?>" placeholder="alice@example.net" <?php echo $auth_type === 'persona' ? ' required="required"' : ''; ?> />
+				<noscript><b><?php echo _t('javascript_should_be_activated'); ?></b></noscript>
+			</div>
+		</div>
+
+		<script>
+			function toggle_password() {
+				var button = this;
+				var passwordField = document.getElementById(button.getAttribute('data-toggle'));
+
+				passwordField.setAttribute('type', 'text');
+				button.className += ' active';
+
+				setTimeout(function() {
+					passwordField.setAttribute('type', 'password');
+					button.className = button.className.replace(/(?:^|\s)active(?!\S)/g , '');
+				}, 2000);
+
+				return false;
+			}
+			toggles = document.getElementsByClassName('toggle-password');
+			for (var i = 0 ; i < toggles.length ; i++) {
+				toggles[i].addEventListener('click', toggle_password);
+			}
+
+			function auth_type_change(focus) {
+				var auth_value = document.getElementById('auth_type').value,
+				    password_input = document.getElementById('passwordPlain'),
+				    mail_input = document.getElementById('mail_login');
+
+				if (auth_value === 'form') {
+					password_input.required = true;
+					mail_input.required = false;
+					if (focus) {
+						password_input.focus();
+					}
+				} else if (auth_value === 'persona') {
+					password_input.required = false;
+					mail_input.required = true;
+					if (focus) {
+						mail_input.focus();
+					}
+				} else {
+					password_input.required = false;
+					mail_input.required = false;
+				}
+			}
+			auth_type_change(false);
+		</script>
+
+		<div class="form-group form-actions">
+			<div class="group-controls">
+				<button type="submit" class="btn btn-important"><?php echo _t('save'); ?></button>
+				<button type="reset" class="btn"><?php echo _t('cancel'); ?></button>
+				<?php if ($s2['all'] == 'ok') { ?>
+				<a class="btn btn-important next-step" href="?step=3"><?php echo _t('next_step'); ?></a>
+				<?php } ?>
+			</div>
+		</div>
+	</form>
+<?php
+}
+
+function printStep3() {
+?>
+	<?php $s3 = checkStep3(); if ($s3['all'] == 'ok') { ?>
+	<p class="alert alert-success"><span class="alert-head"><?php echo _t('ok'); ?></span> <?php echo _t('bdd_conf_is_ok'); ?></p>
+	<?php } elseif ($s3['conn'] == 'ko') { ?>
+	<p class="alert alert-error"><span class="alert-head"><?php echo _t('damn'); ?></span> <?php echo _t('bdd_conf_is_ko'),(empty($_SESSION['bd_error']) ? '' : ' : ' . $_SESSION['bd_error']); ?></p>
+	<?php } ?>
+
+	<form action="index.php?step=3" method="post">
+		<legend><?php echo _t('bdd_configuration'); ?></legend>
+		<div class="form-group">
+			<label class="group-name" for="type"><?php echo _t('bdd_type'); ?></label>
+			<div class="group-controls">
+				<select name="type" id="type" onchange="mySqlShowHide()">
+				<?php if (extension_loaded('pdo_mysql')) {?>
+				<option value="mysql"
+					<?php echo(isset($_SESSION['bd_type']) && $_SESSION['bd_type'] === 'mysql') ? 'selected="selected"' : ''; ?>>
+					MySQL
+				</option>
+				<?php }?>
+				<?php if (extension_loaded('pdo_sqlite')) {?>
+				<option value="sqlite"
+					<?php echo(isset($_SESSION['bd_type']) && $_SESSION['bd_type'] === 'sqlite') ? 'selected="selected"' : ''; ?>>
+					SQLite
+				</option>
+				<?php }?>
+				</select>
+			</div>
+		</div>
+
+		<div id="mysql">
+		<div class="form-group">
+			<label class="group-name" for="host"><?php echo _t('host'); ?></label>
+			<div class="group-controls">
+				<input type="text" id="host" name="host" pattern="[0-9A-Za-z_.-]{1,64}" value="<?php echo isset($_SESSION['bd_host']) ? $_SESSION['bd_host'] : 'localhost'; ?>" />
+			</div>
+		</div>
+
+		<div class="form-group">
+			<label class="group-name" for="user"><?php echo _t('username'); ?></label>
+			<div class="group-controls">
+				<input type="text" id="user" name="user" maxlength="16" pattern="[0-9A-Za-z_.-]{1,16}" value="<?php echo isset($_SESSION['bd_user']) ? $_SESSION['bd_user'] : ''; ?>" />
+			</div>
+		</div>
+
+		<div class="form-group">
+			<label class="group-name" for="pass"><?php echo _t('password'); ?></label>
+			<div class="group-controls">
+				<input type="password" id="pass" name="pass" value="<?php echo isset($_SESSION['bd_password']) ? $_SESSION['bd_password'] : ''; ?>" />
+			</div>
+		</div>
+
+		<div class="form-group">
+			<label class="group-name" for="base"><?php echo _t('bdd'); ?></label>
+			<div class="group-controls">
+				<input type="text" id="base" name="base" maxlength="64" pattern="[0-9A-Za-z_]{1,64}" value="<?php echo isset($_SESSION['bd_base']) ? $_SESSION['bd_base'] : ''; ?>" placeholder="freshrss" />
+			</div>
+		</div>
+
+		<div class="form-group">
+			<label class="group-name" for="prefix"><?php echo _t('prefix'); ?></label>
+			<div class="group-controls">
+				<input type="text" id="prefix" name="prefix" maxlength="16" pattern="[0-9A-Za-z_]{1,16}" value="<?php echo isset($_SESSION['bd_prefix']) ? $_SESSION['bd_prefix'] : 'freshrss_'; ?>" />
+			</div>
+		</div>
+		</div>
+		<script>
+			function mySqlShowHide() {
+				document.getElementById('mysql').style.display = document.getElementById('type').value === 'mysql' ? 'block' : 'none';
+			}
+			mySqlShowHide();
+		</script>
+
+		<div class="form-group form-actions">
+			<div class="group-controls">
+				<button type="submit" class="btn btn-important"><?php echo _t('save'); ?></button>
+				<button type="reset" class="btn"><?php echo _t('cancel'); ?></button>
+				<?php if ($s3['all'] == 'ok') { ?>
+				<a class="btn btn-important next-step" href="?step=4"><?php echo _t('next_step'); ?></a>
+				<?php } ?>
+			</div>
+		</div>
+	</form>
+<?php
+}
+
+function printStep4() {
+?>
+	<p class="alert alert-success"><span class="alert-head"><?php echo _t('congratulations'); ?></span> <?php echo _t('installation_is_ok'); ?></p>
+	<a class="btn btn-important next-step" href="?step=5"><?php echo _t('finish_installation'); ?></a>
+<?php
+}
+
+function printStep5() {
+?>
+	<p class="alert alert-error"><span class="alert-head"><?php echo _t('oops'); ?></span> <?php echo _t('install_not_deleted', DATA_PATH . '/do-install.txt'); ?></p>
+<?php
+}
+
+checkStep();
+
+initTranslate();
+
+switch (STEP) {
+case 0:
+default:
+	saveLanguage();
+	break;
+case 1:
+	break;
+case 2:
+	saveStep2();
+	break;
+case 3:
+	saveStep3();
+	break;
+case 4:
+	break;
+case 5:
+	deleteInstall();
+	break;
+}
+?>
+<!DOCTYPE html>
+<html lang="fr">
+	<head>
+		<meta charset="utf-8">
+		<meta name="viewport" content="initial-scale=1.0">
+		<title><?php echo _t('freshrss_installation'); ?></title>
+		<link rel="stylesheet" type="text/css" media="all" href="../themes/base-theme/template.css" />
+		<link rel="stylesheet" type="text/css" media="all" href="../themes/Origine/origine.css" />
+	</head>
+	<body>
+
+<div class="header">
+	<div class="item title">
+		<h1><a href="index.php"><?php echo _t('freshrss'); ?></a></h1>
+		<h2><?php echo _t('installation_step', STEP); ?></h2>
+	</div>
+</div>
+
+<div id="global">
+	<ul class="nav nav-list aside">
+		<li class="nav-header"><?php echo _t('steps'); ?></li>
+		<li class="item<?php echo STEP == 0 ? ' active' : ''; ?>"><a href="?step=0"><?php echo _t('language'); ?></a></li>
+		<li class="item<?php echo STEP == 1 ? ' active' : ''; ?>"><a href="?step=1"><?php echo _t('checks'); ?></a></li>
+		<li class="item<?php echo STEP == 2 ? ' active' : ''; ?>"><a href="?step=2"><?php echo _t('general_configuration'); ?></a></li>
+		<li class="item<?php echo STEP == 3 ? ' active' : ''; ?>"><a href="?step=3"><?php echo _t('bdd_configuration'); ?></a></li>
+		<li class="item<?php echo STEP == 4 ? ' active' : ''; ?>"><a href="?step=5"><?php echo _t('this_is_the_end'); ?></a></li>
+	</ul>
+
+	<div class="post">
+		<?php
+		switch (STEP) {
+		case 0:
+		default:
+			printStep0();
+			break;
+		case 1:
+			printStep1();
+			break;
+		case 2:
+			printStep2();
+			break;
+		case 3:
+			printStep3();
+			break;
+		case 4:
+			printStep4();
+			break;
+		case 5:
+			printStep5();
+			break;
+		}
+		?>
+	</div>
+</div>
+	</body>
+</html>

+ 25 - 11
app/layout/aside_configure.phtml

@@ -1,19 +1,33 @@
 <ul class="nav nav-list aside">
-	<li class="nav-header"><?php echo Minz_Translate::t ('configuration'); ?></li>
-	<li class="item<?php echo Minz_Request::actionName () == 'display' ? ' active' : ''; ?>">
-		<a href="<?php echo _url ('configure', 'display'); ?>"><?php echo Minz_Translate::t ('reading_configuration'); ?></a>
+	<li class="nav-header"><?php echo _t('configuration'); ?></li>
+	<li class="item<?php echo Minz_Request::actionName() === 'display' ? ' active' : ''; ?>">
+		<a href="<?php echo _url('configure', 'display'); ?>"><?php echo _t('display_configuration'); ?></a>
 	</li>
-	<li class="item<?php echo Minz_Request::actionName () == 'archiving' ? ' active' : ''; ?>">
-		<a href="<?php echo _url ('configure', 'archiving'); ?>"><?php echo Minz_Translate::t ('archiving_configuration'); ?></a>
+	<li class="item<?php echo Minz_Request::actionName() === 'reading' ? ' active' : ''; ?>">
+		<a href="<?php echo _url('configure', 'reading'); ?>"><?php echo _t('reading_configuration'); ?></a>
 	</li>
-	<li class="item<?php echo Minz_Request::actionName () == 'sharing' ? ' active' : ''; ?>">
-		<a href="<?php echo _url ('configure', 'sharing'); ?>"><?php echo Minz_Translate::t ('sharing'); ?></a>
+	<li class="item<?php echo Minz_Request::actionName() === 'archiving' ? ' active' : ''; ?>">
+		<a href="<?php echo _url('configure', 'archiving'); ?>"><?php echo _t('archiving_configuration'); ?></a>
 	</li>
-	<li class="item<?php echo Minz_Request::actionName () == 'shortcut' ? ' active' : ''; ?>">
-		<a href="<?php echo _url ('configure', 'shortcut'); ?>"><?php echo Minz_Translate::t ('shortcuts'); ?></a>
+	<li class="item<?php echo Minz_Request::actionName() === 'sharing' ? ' active' : ''; ?>">
+		<a href="<?php echo _url('configure', 'sharing'); ?>"><?php echo _t('sharing'); ?></a>
+	</li>
+	<li class="item<?php echo Minz_Request::actionName() === 'shortcut' ? ' active' : ''; ?>">
+		<a href="<?php echo _url('configure', 'shortcut'); ?>"><?php echo _t('shortcuts'); ?></a>
+	</li>
+	<li class="item<?php echo Minz_Request::actionName() === 'queries' ? ' active' : ''; ?>">
+		<a href="<?php echo _url('configure', 'queries'); ?>"><?php echo _t('queries'); ?></a>
 	</li>
 	<li class="separator"></li>
-	<li class="item<?php echo Minz_Request::actionName () == 'users' ? ' active' : ''; ?>">
-		<a href="<?php echo _url ('configure', 'users'); ?>"><?php echo Minz_Translate::t ('users'); ?></a>
+	<li class="item<?php echo Minz_Request::actionName() === 'users' ? ' active' : ''; ?>">
+		<a href="<?php echo _url('configure', 'users'); ?>"><?php echo _t('users'); ?></a>
+	</li>
+	<?php
+		$current_user = Minz_Session::param('currentUser', '');
+		if (Minz_Configuration::isAdmin($current_user)) {
+	?>
+	<li class="item<?php echo Minz_Request::controllerName() === 'update' ? ' active' : ''; ?>">
+		<a href="<?php echo _url('update', 'index'); ?>"><?php echo _t('update'); ?></a>
 	</li>
+	<?php } ?>
 </ul>

+ 14 - 3
app/layout/aside_feed.phtml

@@ -20,9 +20,14 @@
 							<?php echo $cat->name (); ?>
 						</option>
 						<?php } ?>
+						<option value="nc"><?php echo Minz_Translate::t ('new_category'); ?></option>
 						</select>
 					</li>
 
+					<li class="input" style="display:none">
+						<input type="text" name="new_category[name]" id="new_category_name" autocomplete="off" placeholder="<?php echo Minz_Translate::t ('new_category'); ?>" />
+					</li>
+
 					<li class="separator"></li>
 
 					<li class="dropdown-header"><?php echo Minz_Translate::t ('http_authentication'); ?></li>
@@ -38,8 +43,14 @@
 		</div>
 	</form></li>
 
-	<li class="item<?php echo Minz_Request::actionName () == 'importExport' ? ' active' : ''; ?>">
-		<a href="<?php echo _url ('configure', 'importExport'); ?>"><?php echo Minz_Translate::t ('import_export_opml'); ?></a>
+	<li class="item">
+		<a onclick="return false;" href="javascript:(function(){var%20url%20=%20location.href;window.open('<?php echo Minz_Url::display(array('c' => 'feed', 'a' => 'add'), 'html', true); ?>&amp;url_rss='+encodeURIComponent(url), '_blank');})();">
+			<?php echo Minz_Translate::t('bookmark'); ?>
+		</a>
+	</li>
+
+	<li class="item<?php echo Minz_Request::controllerName () == 'importExport' ? ' active' : ''; ?>">
+		<a href="<?php echo _url ('importExport', 'index'); ?>"><?php echo Minz_Translate::t ('import_export'); ?></a>
 	</li>
 
 	<li class="item<?php echo Minz_Request::actionName () == 'categorize' ? ' active' : ''; ?>">
@@ -51,7 +62,7 @@
 	<?php if (!empty ($this->feeds)) { ?>
 	<?php foreach ($this->feeds as $feed) { ?>
 	<?php $nbEntries = $feed->nbEntries (); ?>
-	<li class="item<?php echo ($this->flux && $this->flux->id () == $feed->id ()) ? ' active' : ''; ?><?php echo $feed->inError () ? ' error' : ''; ?><?php echo $nbEntries == 0 ? ' empty' : ''; ?>">
+	<li class="item<?php echo (isset($this->flux) && $this->flux->id () == $feed->id ()) ? ' active' : ''; ?><?php echo $feed->inError () ? ' error' : ''; ?><?php echo $nbEntries == 0 ? ' empty' : ''; ?>">
 		<a href="<?php echo _url ('configure', 'feed', 'id', $feed->id ()); ?>">
 			<img class="favicon" src="<?php echo $feed->favicon (); ?>" alt="✇" />
 			<?php echo $feed->name (); ?>

+ 43 - 28
app/layout/aside_flux.phtml

@@ -1,16 +1,18 @@
-<div class="aside aside_flux" id="aside_flux">
-	<a class="toggle_aside" href="#close"><?php echo FreshRSS_Themes::icon('close'); ?></a>
+<div class="aside aside_flux<?php if ($this->conf->hide_read_feeds && ($this->state & FreshRSS_Entry::STATE_NOT_READ) && !($this->state & FreshRSS_Entry::STATE_READ)) echo ' state_unread'; ?>" id="aside_flux">
+	<a class="toggle_aside" href="#close"><?php echo _i('close'); ?></a>
 
 	<ul class="categories">
 		<?php if ($this->loginOk) { ?>
+		<form id="mark-read-aside" method="post" style="display: none"></form>
+
 		<li>
-			<div class="stick">
-				<a class="btn btn-important" href="<?php echo _url ('configure', 'feed'); ?>"><?php echo Minz_Translate::t ('subscription_management'); ?></a>
-				<a class="btn btn-important" href="<?php echo _url ('configure', 'categorize'); ?>" title="<?php echo Minz_Translate::t ('categories_management'); ?>"><?php echo FreshRSS_Themes::icon('category-white'); ?></a>
+			<div class="stick configure-feeds">
+				<a class="btn btn-important" href="<?php echo _url('configure', 'feed'); ?>"><?php echo _t('subscription_management'); ?></a>
+				<a class="btn btn-important" href="<?php echo _url('configure', 'categorize'); ?>" title="<?php echo _t('categories_management'); ?>"><?php echo _i('category-white'); ?></a>
 			</div>
 		</li>
 		<?php } elseif (Minz_Configuration::needsLogin()) { ?>
-		<li><a href="<?php echo _url ('index', 'about'); ?>"><?php echo Minz_Translate::t ('about_freshrss'); ?></a></li>
+		<li><a href="<?php echo _url('index', 'about'); ?>"><?php echo _t('about_freshrss'); ?></a></li>
 		<?php } ?>
 
 		<?php
@@ -22,8 +24,8 @@
 		<li>
 			<div class="category all<?php echo $this->get_c == 'a' ? ' active' : ''; ?>">
 				<a data-unread="<?php echo formatNumber($this->nb_not_read); ?>" class="btn<?php echo $this->get_c == 'a' ? ' active' : ''; ?>" href="<?php echo Minz_Url::display($arUrl); ?>">
-					<?php echo FreshRSS_Themes::icon('all'); ?>
-					<?php echo Minz_Translate::t ('main_stream'); ?>
+					<?php echo _i('all'); ?>
+					<?php echo _t('main_stream'); ?>
 				</a>
 			</div>
 		</li>
@@ -31,38 +33,42 @@
 		<li>
 			<div class="category favorites<?php echo $this->get_c == 's' ? ' active' : ''; ?>">
 				<a data-unread="<?php echo formatNumber($this->nb_favorites['unread']); ?>" class="btn<?php echo $this->get_c == 's' ? ' active' : ''; ?>" href="<?php $arUrl['params']['get'] = 's'; echo Minz_Url::display($arUrl); ?>">
-					<?php echo FreshRSS_Themes::icon('bookmark'); ?>
-					<?php echo Minz_Translate::t('favorite_feeds', formatNumber($this->nb_favorites['all'])); ?>
+					<?php echo _i('bookmark'); ?>
+					<?php echo _t('favorite_feeds', formatNumber($this->nb_favorites['all'])); ?>
 				</a>
 			</div>
 		</li>
 
 		<?php
 		foreach ($this->cat_aside as $cat) {
-			$feeds = $cat->feeds ();
-			if (!empty ($feeds)) {
-				?><li><?php
+			$feeds = $cat->feeds();
+			if (!empty($feeds)) {
 				$c_active = false;
-				if ($this->get_c == $cat->id ()) {
+				$c_show = false;
+				if ($this->get_c == $cat->id()) {
 					$c_active = true;
+					if (!$this->conf->display_categories || $this->get_f) {
+						$c_show = true;
+					}
 				}
+				?><li data-unread="<?php echo $cat->nbNotRead(); ?>"<?php if ($c_active) echo ' class="active"'; ?>><?php
 				?><div class="category stick<?php echo $c_active ? ' active' : ''; ?>"><?php
-					?><a data-unread="<?php echo formatNumber($cat->nbNotRead()); ?>" class="btn<?php echo $c_active ? ' active' : ''; ?>" href="<?php $arUrl['params']['get'] = 'c_' . $cat->id(); echo Minz_Url::display($arUrl); ?>"><?php echo $cat->name (); ?></a><?php
-					?><a class="btn dropdown-toggle" href="#"><?php echo FreshRSS_Themes::icon($c_active ? 'up' : 'down'); ?></a><?php
+					?><a data-unread="<?php echo formatNumber($cat->nbNotRead()); ?>" class="btn<?php echo $c_active ? ' active' : ''; ?>" href="<?php $arUrl['params']['get'] = 'c_' . $cat->id(); echo Minz_Url::display($arUrl); ?>"><?php echo $cat->name(); ?></a><?php
+					?><a class="btn dropdown-toggle" href="#"><?php echo _i($c_show ? 'up' : 'down'); ?></a><?php
 				?></div><?php
-				?><ul class="feeds<?php echo $c_active ? ' active' : ''; ?>"><?php
+				?><ul class="feeds<?php echo $c_show ? ' active' : ''; ?>"><?php
 				foreach ($feeds as $feed) {
-					$feed_id = $feed->id ();
-					$nbEntries = $feed->nbEntries ();
+					$feed_id = $feed->id();
+					$nbEntries = $feed->nbEntries();
 					$f_active = ($this->get_f == $feed_id);
-					?><li id="f_<?php echo $feed_id; ?>" class="item<?php echo $f_active ? ' active' : ''; ?><?php echo $feed->inError () ? ' error' : ''; ?><?php echo $nbEntries == 0 ? ' empty' : ''; ?>"><?php
+					?><li id="f_<?php echo $feed_id; ?>" class="item<?php echo $f_active ? ' active' : ''; ?><?php echo $feed->inError() ? ' error' : ''; ?><?php echo $nbEntries == 0 ? ' empty' : ''; ?>" data-unread="<?php echo $feed->nbNotRead(); ?>"><?php
 						?><div class="dropdown"><?php
 							?><div class="dropdown-target"></div><?php
-							?><a class="dropdown-toggle" data-fweb="<?php echo $feed->website (); ?>"><?php echo FreshRSS_Themes::icon('configure'); ?></a><?php
+							?><a class="dropdown-toggle" data-fweb="<?php echo $feed->website(); ?>"><?php echo _i('configure'); ?></a><?php
 							/* feed_config_template */
 						?></div><?php
-						?> <img class="favicon" src="<?php echo $feed->favicon (); ?>" alt="✇" /> <?php
-						?><a class="feed" data-unread="<?php echo formatNumber($feed->nbNotRead()); ?>" data-priority="<?php echo $feed->priority (); ?>" href="<?php $arUrl['params']['get'] = 'f_' . $feed_id; echo Minz_Url::display($arUrl); ?>"><?php echo $feed->name(); ?></a><?php
+						?> <img class="favicon" src="<?php echo $feed->favicon(); ?>" alt="✇" /> <?php
+						?><a class="feed" data-unread="<?php echo formatNumber($feed->nbNotRead()); ?>" data-priority="<?php echo $feed->priority(); ?>" href="<?php $arUrl['params']['get'] = 'f_' . $feed_id; echo Minz_Url::display($arUrl); ?>"><?php echo $feed->name(); ?></a><?php
 					?></li><?php
 				}
 				?></ul><?php
@@ -76,13 +82,22 @@
 <script id="feed_config_template" type="text/html">
 	<ul class="dropdown-menu">
 		<li class="dropdown-close"><a href="#close">❌</a></li>
-		<li class="item"><a href="<?php echo _url ('index', 'index', 'get', 'f_!!!!!!'); ?>"><?php echo Minz_Translate::t ('filter'); ?></a></li>
-		<li class="item"><a target="_blank" href="http://example.net/"><?php echo Minz_Translate::t ('see_website'); ?></a></li>
+		<li class="item"><a href="<?php echo _url('index', 'index', 'get', 'f_!!!!!!'); ?>"><?php echo _t('filter'); ?></a></li>
+		<?php if ($this->loginOk) { ?>
+		<li class="item"><a href="<?php echo _url('stats', 'repartition', 'id', '!!!!!!'); ?>"><?php echo _t('stats'); ?></a></li>
+		<?php } ?>
+		<li class="item"><a target="_blank" href="http://example.net/"><?php echo _t('see_website'); ?></a></li>
 		<?php if ($this->loginOk) { ?>
 		<li class="separator"></li>
-		<li class="item"><a href="<?php echo _url ('configure', 'feed', 'id', '!!!!!!'); ?>"><?php echo Minz_Translate::t ('administration'); ?></a></li>
-		<li class="item"><a href="<?php echo _url ('feed', 'actualize', 'id', '!!!!!!'); ?>"><?php echo Minz_Translate::t ('actualize'); ?></a></li>
-		<li class="item"><a href="<?php echo _url ('entry', 'read', 'get', 'f_!!!!!!'); ?>"><?php echo Minz_Translate::t ('mark_read'); ?></a></li>
+		<li class="item"><a href="<?php echo _url('configure', 'feed', 'id', '!!!!!!'); ?>"><?php echo _t('administration'); ?></a></li>
+		<li class="item"><a href="<?php echo _url('feed', 'actualize', 'id', '!!!!!!'); ?>"><?php echo _t('actualize'); ?></a></li>
+		<li class="item">
+			<?php $confirm = $this->conf->reading_confirm ? 'confirm' : ''; ?>
+			<button class="read_all as-link <?php echo $confirm; ?>"
+			        form="mark-read-aside"
+			        formaction="<?php echo _url('entry', 'read', 'get', 'f_!!!!!!'); ?>"
+			        type="submit"><?php echo _t('mark_read'); ?></button>
+		</li>
 		<?php } ?>
 	</ul>
 </script>

+ 12 - 0
app/layout/aside_stats.phtml

@@ -0,0 +1,12 @@
+<ul class="nav nav-list aside">
+	<li class="nav-header"><?php echo Minz_Translate::t ('stats'); ?></li>
+	<li class="item<?php echo Minz_Request::actionName () == 'index' ? ' active' : ''; ?>">
+		<a href="<?php echo _url ('stats', 'index'); ?>"><?php echo Minz_Translate::t ('stats_main'); ?></a>
+	</li>
+	<li class="item<?php echo Minz_Request::actionName () == 'idle' ? ' active' : ''; ?>">
+		<a href="<?php echo _url ('stats', 'idle'); ?>"><?php echo Minz_Translate::t ('stats_idle'); ?></a>
+	</li>
+	<li class="item<?php echo Minz_Request::actionName () == 'repartition' ? ' active' : ''; ?>">
+		<a href="<?php echo _url ('stats', 'repartition'); ?>"><?php echo Minz_Translate::t ('stats_repartition'); ?></a>
+	</li>
+</ul>

+ 57 - 49
app/layout/header.phtml

@@ -2,20 +2,20 @@
 if (Minz_Configuration::canLogIn()) {
 	?><ul class="nav nav-head nav-login"><?php
 	switch (Minz_Configuration::authType()) {
-		case 'form':
-			if ($this->loginOk) {
-				?><li class="item"><?php echo FreshRSS_Themes::icon('logout'); ?> <a class="signout" href="<?php echo _url ('index', 'formLogout'); ?>"><?php echo Minz_Translate::t ('logout'); ?></a></li><?php
-			} else {
-				?><li class="item"><?php echo FreshRSS_Themes::icon('login'); ?> <a class="signin" href="<?php echo _url ('index', 'formLogin'); ?>"><?php echo Minz_Translate::t ('login'); ?></a></li><?php
-			}
-			break;
-		case 'persona':
-			if ($this->loginOk) {
-				?><li class="item"><?php echo FreshRSS_Themes::icon('logout'); ?> <a class="signout" href="#"><?php echo Minz_Translate::t ('logout'); ?></a></li><?php
-			} else {
-				?><li class="item"><?php echo FreshRSS_Themes::icon('login'); ?> <a class="signin" href="#"><?php echo Minz_Translate::t ('login'); ?></a></li><?php
-			}
-			break;
+	case 'form':
+		if ($this->loginOk) {
+			?><li class="item"><?php echo _i('logout'); ?> <a class="signout" href="<?php echo _url('index', 'formLogout'); ?>"><?php echo _t('logout'); ?></a></li><?php
+		} else {
+			?><li class="item"><?php echo _i('login'); ?> <a class="signin" href="<?php echo _url('index', 'formLogin'); ?>"><?php echo _t('login'); ?></a></li><?php
+		}
+		break;
+	case 'persona':
+		if ($this->loginOk) {
+			?><li class="item"><?php echo _i('logout'); ?> <a class="signout" href="#"><?php echo _t('logout'); ?></a></li><?php
+		} else {
+			?><li class="item"><?php echo _i('login'); ?> <a class="signin" href="#"><?php echo _t('login'); ?></a></li><?php
+		}
+		break;
 	}
 	?></ul><?php
 }
@@ -24,36 +24,36 @@ if (Minz_Configuration::canLogIn()) {
 <div class="header">
 	<div class="item title">
 		<h1>
-			<a href="<?php echo _url ('index', 'index'); ?>">
-				<img class="logo" src="<?php echo Minz_Url::display ('/themes/icons/icon.svg'); ?>" alt="⊚" />
-				<?php echo Minz_Configuration::title (); ?>
+			<a href="<?php echo _url('index', 'index'); ?>">
+				<img class="logo" src="<?php echo _i('icon', true); ?>" alt="⊚" />
+				<?php echo Minz_Configuration::title(); ?>
 			</a>
 		</h1>
 	</div>
 
 	<div class="item search">
 		<?php if ($this->loginOk || Minz_Configuration::allowAnonymous()) { ?>
-		<form action="<?php echo _url ('index', 'index'); ?>" method="get">
+		<form action="<?php echo _url('index', 'index'); ?>" method="get">
 			<div class="stick">
-				<?php $search = Minz_Request::param ('search', ''); ?>
-				<input type="search" name="search" id="search" class="extend" value="<?php echo $search; ?>" placeholder="<?php echo Minz_Translate::t ('search'); ?>" />
+				<?php $search = Minz_Request::param('search', ''); ?>
+				<input type="search" name="search" id="search" class="extend" value="<?php echo $search; ?>" placeholder="<?php echo _t('search'); ?>" />
 
-				<?php $get = Minz_Request::param ('get', ''); ?>
-				<?php if($get != '') { ?>
+				<?php $get = Minz_Request::param('get', ''); ?>
+				<?php if ($get != '') { ?>
 				<input type="hidden" name="get" value="<?php echo $get; ?>" />
 				<?php } ?>
 
-				<?php $order = Minz_Request::param ('order', ''); ?>
-				<?php if($order != '') { ?>
+				<?php $order = Minz_Request::param('order', ''); ?>
+				<?php if ($order != '') { ?>
 				<input type="hidden" name="order" value="<?php echo $order; ?>" />
 				<?php } ?>
 
-				<?php $state = Minz_Request::param ('state', ''); ?>
-				<?php if($state != '') { ?>
+				<?php $state = Minz_Request::param('state', ''); ?>
+				<?php if ($state != '') { ?>
 				<input type="hidden" name="state" value="<?php echo $state; ?>" />
 				<?php } ?>
 
-				<button class="btn" type="submit"><?php echo FreshRSS_Themes::icon('search'); ?></button>
+				<button class="btn" type="submit"><?php echo _i('search'); ?></button>
 			</div>
 		</form>
 		<?php } ?>
@@ -63,30 +63,38 @@ if (Minz_Configuration::canLogIn()) {
 	<div class="item configure">
 		<div class="dropdown">
 			<div id="dropdown-configure" class="dropdown-target"></div>
-			<a class="btn dropdown-toggle" href="#dropdown-configure"><?php echo FreshRSS_Themes::icon('configure'); ?></a>
+			<a class="btn dropdown-toggle" href="#dropdown-configure"><?php echo _i('configure'); ?></a>
 			<ul class="dropdown-menu">
 				<li class="dropdown-close"><a href="#close">❌</a></li>
-				<li class="dropdown-header"><?php echo Minz_Translate::t ('configuration'); ?></li>
-				<li class="item"><a href="<?php echo _url ('configure', 'display'); ?>"><?php echo Minz_Translate::t ('reading_configuration'); ?></a></li>
-				<li class="item"><a href="<?php echo _url ('configure', 'archiving'); ?>"><?php echo Minz_Translate::t ('archiving_configuration'); ?></a></li>
-				<li class="item"><a href="<?php echo _url ('configure', 'sharing'); ?>"><?php echo Minz_Translate::t ('sharing'); ?></a></li>
-				<li class="item"><a href="<?php echo _url ('configure', 'shortcut'); ?>"><?php echo Minz_Translate::t ('shortcuts'); ?></a></li>
+				<li class="dropdown-header"><?php echo _t('configuration'); ?></li>
+				<li class="item"><a href="<?php echo _url('configure', 'display'); ?>"><?php echo _t('display_configuration'); ?></a></li>
+				<li class="item"><a href="<?php echo _url('configure', 'reading'); ?>"><?php echo _t('reading_configuration'); ?></a></li>
+				<li class="item"><a href="<?php echo _url('configure', 'archiving'); ?>"><?php echo _t('archiving_configuration'); ?></a></li>
+				<li class="item"><a href="<?php echo _url('configure', 'sharing'); ?>"><?php echo _t('sharing'); ?></a></li>
+				<li class="item"><a href="<?php echo _url('configure', 'shortcut'); ?>"><?php echo _t('shortcuts'); ?></a></li>
+				<li class="item"><a href="<?php echo _url('configure', 'queries'); ?>"><?php echo _t('queries'); ?></a></li>
 				<li class="separator"></li>
-				<li class="item"><a href="<?php echo _url ('configure', 'users'); ?>"><?php echo Minz_Translate::t ('users'); ?></a></li>
+				<li class="item"><a href="<?php echo _url('configure', 'users'); ?>"><?php echo _t('users'); ?></a></li>
+				<?php
+					$current_user = Minz_Session::param('currentUser', '');
+					if (Minz_Configuration::isAdmin($current_user)) {
+				?>
+				<li class="item"><a href="<?php echo _url('update', 'index'); ?>"><?php echo _t('update'); ?></a></li>
+				<?php } ?>
 				<li class="separator"></li>
-				<li class="item"><a href="<?php echo _url ('index', 'stats'); ?>"><?php echo Minz_Translate::t ('stats'); ?></a></li>
-				<li class="item"><a href="<?php echo _url ('index', 'logs'); ?>"><?php echo Minz_Translate::t ('logs'); ?></a></li>
-				<li class="item"><a href="<?php echo _url ('index', 'about'); ?>"><?php echo Minz_Translate::t ('about'); ?></a></li>
+				<li class="item"><a href="<?php echo _url('stats', 'index'); ?>"><?php echo _t('stats'); ?></a></li>
+				<li class="item"><a href="<?php echo _url('index', 'logs'); ?>"><?php echo _t('logs'); ?></a></li>
+				<li class="item"><a href="<?php echo _url('index', 'about'); ?>"><?php echo _t('about'); ?></a></li>
 				<?php
 				if (Minz_Configuration::canLogIn()) {
 					?><li class="separator"></li><?php
 					switch (Minz_Configuration::authType()) {
-						case 'form':
-							?><li class="item"><a class="signout" href="<?php echo _url ('index', 'formLogout'); ?>"><?php echo FreshRSS_Themes::icon('logout'), ' ', Minz_Translate::t ('logout'); ?></a></li><?php
-							break;
-						case 'persona':
-							?><li class="item"><a class="signout" href="#"><?php echo FreshRSS_Themes::icon('logout'), ' ', Minz_Translate::t ('logout'); ?></a></li><?php
-							break;
+					case 'form':
+						?><li class="item"><a class="signout" href="<?php echo _url('index', 'formLogout'); ?>"><?php echo _i('logout'), ' ', _t('logout'); ?></a></li><?php
+						break;
+					case 'persona':
+						?><li class="item"><a class="signout" href="#"><?php echo _i('logout'), ' ', _t('logout'); ?></a></li><?php
+						break;
 					}
 				} ?>
 			</ul>
@@ -95,12 +103,12 @@ if (Minz_Configuration::canLogIn()) {
 	<?php } elseif (Minz_Configuration::canLogIn()) {
 		?><div class="item configure"><?php
 		switch (Minz_Configuration::authType()) {
-			case 'form':
-				echo FreshRSS_Themes::icon('login'); ?><a class="signin" href="<?php echo _url ('index', 'formLogin'); ?>"><?php echo Minz_Translate::t ('login'); ?></a></li><?php
-				break;
-			case 'persona':
-				echo FreshRSS_Themes::icon('login'); ?><a class="signin" href="#"><?php echo Minz_Translate::t ('login'); ?></a></li><?php
-				break;
+		case 'form':
+			echo _i('login'); ?><a class="signin" href="<?php echo _url('index', 'formLogin'); ?>"><?php echo _t('login'); ?></a></li><?php
+			break;
+		case 'persona':
+			echo _i('login'); ?><a class="signin" href="#"><?php echo _t('login'); ?></a></li><?php
+			break;
 		}
 		?></div><?php
 	} ?>

+ 22 - 13
app/layout/layout.phtml

@@ -3,49 +3,58 @@
 	<head>
 		<meta charset="UTF-8" />
 		<meta name="viewport" content="initial-scale=1.0" />
-		<?php echo self::headTitle (); ?>
-		<?php echo self::headStyle (); ?>
-		<?php echo self::headScript (); ?>
+		<?php echo self::headTitle(); ?>
+		<?php echo self::headStyle(); ?>
+		<?php echo self::headScript(); ?>
 		<script>//<![CDATA[
-<?php $this->renderHelper ('javascript_vars'); ?>
+<?php $this->renderHelper('javascript_vars'); ?>
 		//]]></script>
 <?php
 	if (!empty($this->nextId)) {
-		$params = Minz_Request::params ();
+		$params = Minz_Request::params();
 		$params['next'] = $this->nextId;
+		$params['ajax'] = 1;
 ?>
-		<link id="prefetch" rel="next prefetch" href="<?php echo Minz_Url::display (array ('c' => Minz_Request::controllerName (), 'a' => Minz_Request::actionName (), 'params' => $params)); ?>" />
+		<link id="prefetch" rel="next prefetch" href="<?php echo Minz_Url::display(array('c' => Minz_Request::controllerName(), 'a' => Minz_Request::actionName(), 'params' => $params)); ?>" />
 <?php } ?>
-		<link rel="shortcut icon" type="image/x-icon" sizes="16x16 64x64" href="<?php echo Minz_Url::display('/favicon.ico'); ?>" />
+		<link rel="shortcut icon" id="favicon" type="image/x-icon" sizes="16x16 64x64" href="<?php echo Minz_Url::display('/favicon.ico'); ?>" />
 		<link rel="icon msapplication-TileImage apple-touch-icon" type="image/png" sizes="256x256" href="<?php echo Minz_Url::display('/themes/icons/favicon-256.png'); ?>" />
-<?php if (isset ($this->rss_url)) { ?>
-		<link rel="alternate" type="application/rss+xml" title="<?php echo $this->rss_title; ?>" href="<?php echo Minz_Url::display ($this->rss_url); ?>" />
+<?php
+	if (isset($this->url)) {
+		$rss_url = $this->url;
+		$rss_url['params']['output'] = 'rss';
+?>
+		<link rel="alternate" type="application/rss+xml" title="<?php echo $this->rss_title; ?>" href="<?php echo Minz_Url::display($rss_url); ?>" />
 <?php } ?>
 		<link rel="prefetch" href="<?php echo FreshRSS_Themes::icon('starred', true); ?>">
 		<link rel="prefetch" href="<?php echo FreshRSS_Themes::icon('non-starred', true); ?>">
 		<link rel="prefetch" href="<?php echo FreshRSS_Themes::icon('read', true); ?>">
 		<link rel="prefetch" href="<?php echo FreshRSS_Themes::icon('unread', true); ?>">
+		<link rel="apple-touch-icon" href="<?php echo Minz_Url::display('/themes/icons/apple-touch-icon.png'); ?>">
+		<meta name="apple-mobile-web-app-capable" content="yes" />
+		<meta name="apple-mobile-web-app-status-bar-style" content="black" />
+		<meta name="apple-mobile-web-app-title" content="<?php echo Minz_Configuration::title(); ?>">
 		<meta name="msapplication-TileColor" content="#FFF" />
 		<meta name="robots" content="noindex,nofollow" />
 	</head>
 	<body class="<?php echo Minz_Request::param('output', 'normal'); ?>">
-<?php $this->partial ('header'); ?>
+<?php $this->partial('header'); ?>
 
 <div id="global">
-	<?php $this->render (); ?>
+	<?php $this->render(); ?>
 </div>
 
 <?php
 	$msg = '';
 	$status = 'closed';
-	if (isset ($this->notification)) {
+	if (isset($this->notification)) {
 		$msg = $this->notification['content'];
 		$status = $this->notification['type'];
 
 		invalidateHttpCache();
 	}
 ?>
-<div id="notification" class="<?php echo $status; ?>">
+<div id="notification" class="notification <?php echo $status; ?>">
 	<span class="msg"><?php echo $msg; ?></span>
 	<a class="close" href=""><?php echo FreshRSS_Themes::icon('close'); ?></a>
 </div>

+ 232 - 154
app/layout/nav_menu.phtml

@@ -3,226 +3,304 @@
 ?>
 <div class="nav_menu">
 	<?php if ($actual_view === 'normal') { ?>
-	<a class="btn toggle_aside" href="#aside_flux"><?php echo FreshRSS_Themes::icon('category'); ?></a>
-	<?php } ?>
-
-	<?php if ($this->loginOk || Minz_Configuration::allowAnonymousRefresh()) { ?>
-	<a id="actualize" class="btn" href="<?php echo _url ('feed', 'actualize'); ?>"><?php echo FreshRSS_Themes::icon('refresh'); ?></a>
+	<a class="btn toggle_aside" href="#aside_flux"><?php echo _i('category'); ?></a>
 	<?php } ?>
 
 	<?php if ($this->loginOk) { ?>
+	<div id="nav_menu_actions" class="stick">
+		<?php
+			$url_state = $this->url;
+
+			if ($this->state & FreshRSS_Entry::STATE_READ) {
+				$url_state['params']['state'] = $this->state & ~FreshRSS_Entry::STATE_READ;
+				$checked = 'true';
+				$class = 'active';
+			} else {
+				$url_state['params']['state'] = $this->state | FreshRSS_Entry::STATE_READ;
+				$checked = 'false';
+				$class = '';
+			}
+		?>
+		<a id="toggle-read"
+		   class="btn <?php echo $class; ?>"
+		   aria-checked="<?php echo $checked; ?>"
+		   href="<?php echo Minz_Url::display($url_state); ?>"
+		   title="<?php echo _t('show_read'); ?>">
+			<?php echo _i('read'); ?>
+		</a>
+
+		<?php
+			if ($this->state & FreshRSS_Entry::STATE_NOT_READ) {
+				$url_state['params']['state'] = $this->state & ~FreshRSS_Entry::STATE_NOT_READ;
+				$checked = 'true';
+				$class = 'active';
+			} else {
+				$url_state['params']['state'] = $this->state | FreshRSS_Entry::STATE_NOT_READ;
+				$checked = 'false';
+				$class = '';
+			}
+		?>
+		<a id="toggle-unread"
+		   class="btn <?php echo $class; ?>"
+		   aria-checked="<?php echo $checked; ?>"
+		   href="<?php echo Minz_Url::display($url_state); ?>"
+		   title="<?php echo _t('show_not_reads'); ?>">
+			<?php echo _i('unread'); ?>
+		</a>
+
+		<?php
+			if ($this->state & FreshRSS_Entry::STATE_FAVORITE || $this->get_c == 's') {
+				$url_state['params']['state'] = $this->state & ~FreshRSS_Entry::STATE_FAVORITE;
+				$checked = 'true';
+				$class = 'active';
+			} else {
+				$url_state['params']['state'] = $this->state | FreshRSS_Entry::STATE_FAVORITE;
+				$checked = 'false';
+				$class = '';
+			}
+		?>
+		<a id="toggle-favorite"
+		   class="btn <?php echo $class; ?>"
+		   aria-checked="<?php echo $checked; ?>"
+		   href="<?php echo Minz_Url::display($url_state); ?>"
+		   title="<?php echo _t('show_favorite'); ?>">
+			<?php echo _i('starred'); ?>
+		</a>
+
+		<?php
+			if ($this->state & FreshRSS_Entry::STATE_NOT_FAVORITE) {
+				$url_state['params']['state'] = $this->state & ~FreshRSS_Entry::STATE_NOT_FAVORITE;
+				$checked = 'true';
+				$class = 'active';
+			} else {
+				$url_state['params']['state'] = $this->state | FreshRSS_Entry::STATE_NOT_FAVORITE;
+				$checked = 'false';
+				$class = '';
+			}
+		?>
+		<a id="toggle-not-favorite"
+		   class="btn <?php echo $class; ?>"
+		   aria-checked="<?php echo $checked; ?>"
+		   href="<?php echo Minz_Url::display($url_state); ?>"
+		   title="<?php echo _t('show_not_favorite'); ?>">
+			<?php echo _i('non-starred'); ?>
+		</a>
+
+		<div class="dropdown">
+			<div id="dropdown-query" class="dropdown-target"></div>
+
+			<a class="dropdown-toggle btn" href="#dropdown-query"><?php echo _i('down'); ?></a>
+			<ul class="dropdown-menu">
+				<li class="dropdown-close"><a href="#close">❌</a></li>
+
+				<li class="dropdown-header">
+					<?php echo _t('queries'); ?>
+					<a class="no-mobile" href="<?php echo _url('configure', 'queries'); ?>"><?php echo _i('configure'); ?></a>
+				</li>
+
+				<?php foreach ($this->conf->queries as $query) { ?>
+				<li class="item query">
+					<a href="<?php echo $query['url']; ?>"><?php echo $query['name']; ?></a>
+				</li>
+				<?php } ?>
+
+				<?php if (count($this->conf->queries) > 0) { ?>
+				<li class="separator no-mobile"></li>
+				<?php } ?>
+
+				<?php
+					$url_query = $this->url;
+					$url_query['c'] = 'configure';
+					$url_query['a'] = 'addQuery';
+				?>
+				<li class="item no-mobile"><a href="<?php echo Minz_Url::display($url_query); ?>"><?php echo _i('bookmark-add'); ?> <?php echo _t('add_query'); ?></a></li>
+			</ul>
+		</div>
+	</div>
 	<?php
 		$get = false;
-		$string_mark = Minz_Translate::t ('mark_all_read');
+		$string_mark = _t('mark_all_read');
 		if ($this->get_f) {
 			$get = 'f_' . $this->get_f;
-			$string_mark = Minz_Translate::t ('mark_feed_read');
+			$string_mark = _t('mark_feed_read');
 		} elseif ($this->get_c && $this->get_c != 'a') {
 			if ($this->get_c === 's') {
 				$get = 's';
 			} else {
 				$get = 'c_' . $this->get_c;
 			}
-			$string_mark = Minz_Translate::t ('mark_cat_read');
+			$string_mark = _t('mark_cat_read');
 		}
 		$nextGet = $get;
-		if ($this->conf->onread_jump_next && (strlen ($get) > 2)) {
+		if ($this->conf->onread_jump_next && strlen($get) > 2) {
 			$anotherUnreadId = '';
 			$foundCurrent = false;
 			switch ($get[0]) {
-				case 'c':
-					foreach ($this->cat_aside as $cat) {
-						if ($cat->id () == $this->get_c) {
-							$foundCurrent = true;
-							continue;
-						}
-						if ($cat->nbNotRead () <= 0) continue;
-						$anotherUnreadId = $cat->id ();
-						if ($foundCurrent) break;
+			case 'c':
+				foreach ($this->cat_aside as $cat) {
+					if ($cat->id() == $this->get_c) {
+						$foundCurrent = true;
+						continue;
 					}
-					$nextGet = empty ($anotherUnreadId) ? 'a' : 'c_' . $anotherUnreadId;
-					break;
-				case 'f':
-					foreach ($this->cat_aside as $cat) {
-						if ($cat->id () == $this->get_c) {
-							foreach ($cat->feeds () as $feed) {
-								if ($feed->id () == $this->get_f) {
-									$foundCurrent = true;
-									continue;
-								}
-								if ($feed->nbNotRead () <= 0) continue;
-								$anotherUnreadId = $feed->id ();
-								if ($foundCurrent) break;
+					if ($cat->nbNotRead() <= 0) continue;
+					$anotherUnreadId = $cat->id();
+					if ($foundCurrent) break;
+				}
+				$nextGet = empty($anotherUnreadId) ? 'a' : 'c_' . $anotherUnreadId;
+				break;
+			case 'f':
+				foreach ($this->cat_aside as $cat) {
+					if ($cat->id() == $this->get_c) {
+						foreach ($cat->feeds() as $feed) {
+							if ($feed->id() == $this->get_f) {
+								$foundCurrent = true;
+								continue;
 							}
-							break;
+							if ($feed->nbNotRead() <= 0) continue;
+							$anotherUnreadId = $feed->id();
+							if ($foundCurrent) break;
 						}
+						break;
 					}
-					$nextGet = empty ($anotherUnreadId) ? 'c_' . $this->get_c : 'f_' . $anotherUnreadId;
-					break;
+				}
+				$nextGet = empty($anotherUnreadId) ? 'c_' . $this->get_c : 'f_' . $anotherUnreadId;
+				break;
 			}
 		}
+
 		$p = isset($this->entries[0]) ? $this->entries[0] : null;
-		$idMax = $p === null ? '0' : $p->id();
+		$idMax = $p === null ? (time() - 1) . '000000' : $p->id();
+
+		if ($this->order === 'ASC') {	//In this case we do not know but we guess idMax
+			$idMax2 = (time() - 1) . '000000';
+			if (strcmp($idMax2, $idMax) > 0) {
+				$idMax = $idMax2;
+			}
+		}
 
 		$arUrl = array('c' => 'entry', 'a' => 'read', 'params' => array('get' => $get, 'nextGet' => $nextGet, 'idMax' => $idMax));
 		$output = Minz_Request::param('output', '');
-		if (($output != '') && ($this->conf->view_mode !== $output)) {
+		if ($output != '' && $this->conf->view_mode !== $output) {
 			$arUrl['params']['output'] = $output;
 		}
 		$markReadUrl = Minz_Url::display($arUrl);
-		Minz_Session::_param ('markReadUrl', $markReadUrl);
+		Minz_Session::_param('markReadUrl', $markReadUrl);
 	?>
 
+	<form id="mark-read-menu" method="post" style="display: none"></form>
+
 	<div class="stick" id="nav_menu_read_all">
-		<a class="read_all btn" href="<?php echo $markReadUrl; ?>"><?php echo Minz_Translate::t ('mark_read'); ?></a>
+		<?php $confirm = $this->conf->reading_confirm ? 'confirm' : ''; ?>
+		<button class="read_all btn <?php echo $confirm; ?>"
+		        form="mark-read-menu"
+		        formaction="<?php echo $markReadUrl; ?>"
+		        type="submit"><?php echo _t('mark_read'); ?></button>
+
 		<div class="dropdown">
 			<div id="dropdown-read" class="dropdown-target"></div>
 
-			<a class="dropdown-toggle btn" href="#dropdown-read"><?php echo FreshRSS_Themes::icon('down'); ?></a>
+			<a class="dropdown-toggle btn" href="#dropdown-read"><?php echo _i('down'); ?></a>
 			<ul class="dropdown-menu">
 				<li class="dropdown-close"><a href="#close">❌</a></li>
 
-				<li class="item"><a href="<?php echo $markReadUrl; ?>"><?php echo $string_mark; ?></a></li> 
+				<li class="item">
+					<button class="as-link <?php echo $confirm; ?>"
+					        form="mark-read-menu"
+					        formaction="<?php echo $markReadUrl; ?>"
+					        type="submit"><?php echo $string_mark; ?></button>
+				</li>
 				<li class="separator"></li>
 <?php
-	$today = $this->today;
-	$one_week = $today - 604800;
+	$mark_before_today = $arUrl;
+	$mark_before_today['params']['idMax'] = $this->today . '000000';
+	$mark_before_one_week = $arUrl;
+	$mark_before_one_week['params']['idMax'] = ($this->today - 604800) . '000000';
 ?>
-				<li class="item"><a href="<?php echo _url ('entry', 'read', 'is_read', 1, 'get', $get, 'idMax', $today . '000000'); ?>"><?php echo Minz_Translate::t ('before_one_day'); ?></a></li>
-				<li class="item"><a href="<?php echo _url ('entry', 'read', 'is_read', 1, 'get', $get, 'idMax', $one_week . '000000'); ?>"><?php echo Minz_Translate::t ('before_one_week'); ?></a></li>
+				<li class="item">
+					<button class="as-link <?php echo $confirm; ?>"
+					        form="mark-read-menu"
+					        formaction="<?php echo Minz_Url::display($mark_before_today); ?>"
+					        type="submit"><?php echo _t('before_one_day'); ?></button>
+				</li>
+				<li class="item">
+					<button class="as-link <?php echo $confirm; ?>"
+					        form="mark-read-menu"
+					        formaction="<?php echo Minz_Url::display($mark_before_one_week); ?>"
+					        type="submit"><?php echo _t('before_one_week'); ?></button>
+				</li>
 			</ul>
 		</div>
 	</div>
 	<?php } ?>
 
-	<?php
-		$params = Minz_Request::params ();
-		if (isset ($params['search'])) {
-			$params['search'] = urlencode ($params['search']);
-		}
-		$url = array (
-			'c' => 'index',
-			'a' => 'index',
-			'params' => $params
-		);
-	?>
-	<div class="dropdown" id="nav_menu_views">
-		<div id="dropdown-views" class="dropdown-target"></div>
-		<a class="dropdown-toggle btn" href="#dropdown-views"><?php echo Minz_Translate::t ('display'); ?> <?php echo FreshRSS_Themes::icon('down'); ?></a>
-		<ul class="dropdown-menu">
-			<li class="dropdown-close"><a href="#close">❌</a></li>
-
-			<?php
-				$url_output = $url;
-				if ($actual_view !== 'normal') { ?>
-			<li class="item">
-				<?php $url_output['params']['output'] = 'normal'; ?>
-				<a class="view_normal" href="<?php echo Minz_Url::display ($url_output); ?>">
-					<?php echo Minz_Translate::t ('normal_view'); ?>
-				</a>
-			</li>
-			<?php } if($actual_view !== 'reader') { ?>
-			<li class="item">
-				<?php $url_output['params']['output'] = 'reader'; ?>
-				<a class="view_normal" href="<?php echo Minz_Url::display ($url_output); ?>">
-					<?php echo Minz_Translate::t ('reader_view'); ?>
-				</a>
-			</li>
-			<?php } if($actual_view !== 'global') { ?>
-			<li class="item">
-				<?php $url_output['params']['output'] = 'global'; ?>
-				<a class="view_normal" href="<?php echo Minz_Url::display ($url_output); ?>">
-					<?php echo Minz_Translate::t ('global_view'); ?>
-				</a>
-			</li>
-			<?php } ?>
+	<?php $url_output = $this->url; ?>
+	<div class="stick" id="nav_menu_views">
+		<?php $url_output['params']['output'] = 'normal'; ?>
+		<a class="view_normal btn <?php echo $actual_view == 'normal'? 'active' : ''; ?>" title="<?php echo _t('normal_view'); ?>" href="<?php echo Minz_Url::display($url_output); ?>">
+			<?php echo _i("view-normal"); ?>
+		</a>
 
-			<li class="separator"></li>
-
-			<?php
-				$url_state = $url;
-				$url_state['params']['state'] = 'all';
-			?>
-			<li class="item" role="checkbox" aria-checked="<?php echo ($this->state === 'all') ? 'true' :'false'; ?>">
-				<a class="print_all" href="<?php echo Minz_Url::display ($url_state); ?>">
-					<?php echo Minz_Translate::t ('show_all_articles'); ?>
-				</a>
-			</li>
-			<?php
-				$url_state['params']['state'] = 'not_read';
-			?>
-			<li class="item" role="checkbox" aria-checked="<?php echo ($this->state === 'not_read') ? 'true' :'false'; ?>">
-				<a class="print_non_read" href="<?php echo Minz_Url::display ($url_state); ?>">
-					<?php echo Minz_Translate::t ('show_not_reads'); ?>
-				</a>
-			</li>
-			<?php
-				$url_state['params']['state'] = 'read';
-			?>
-			<li class="item" role="checkbox" aria-checked="<?php echo ($this->state === 'read') ? 'true' :'false'; ?>">
-				<a class="print_read" href="<?php echo Minz_Url::display ($url_state); ?>">
-					<?php echo Minz_Translate::t ('show_read'); ?>
-				</a>
-			</li>
-			<?php
-				$url_state['params']['state'] = 'favorite';
-			?>
-			<li class="item" role="checkbox" aria-checked="<?php echo ($this->state === 'favorite') ? 'true' :'false'; ?>">
-				<a class="print_favorite" href="<?php echo Minz_Url::display ($url_state); ?>">
-					<?php echo Minz_Translate::t ('show_favorite'); ?>
-				</a>
-			</li>
-
-			<li class="separator"></li>
-
-			<li class="item">
-				<?php
-					$url_order = $url;
-					if ($this->order === 'DESC') {
-						$url_order['params']['order'] = 'ASC';
-				?>
-				<a href="<?php echo Minz_Url::display ($url_order); ?>">
-					<?php echo Minz_Translate::t ('older_first'); ?>
-				</a>
-				<?php
-					} else {
-						$url_order['params']['order'] = 'DESC';
-				?>
-				<a href="<?php echo Minz_Url::display ($url_order); ?>">
-					<?php echo Minz_Translate::t ('newer_first'); ?>
-				</a>
-				<?php } ?>
-			</li>
+		<?php $url_output['params']['output'] = 'global'; ?>
+		<a class="view_global btn <?php echo $actual_view == 'global'? 'active' : ''; ?>" title="<?php echo _t('global_view'); ?>" href="<?php echo Minz_Url::display($url_output); ?>">
+			<?php echo _i("view-global"); ?>
+		</a>
 
-			<li class="separator"></li>
+		<?php $url_output['params']['output'] = 'reader'; ?>
+		<a class="view_reader btn <?php echo $actual_view == 'reader'? 'active' : ''; ?>" title="<?php echo _t('reader_view'); ?>" href="<?php echo Minz_Url::display($url_output); ?>">
+			<?php echo _i("view-reader"); ?>
+		</a>
 
-			<li class="item">
-				<a class="view_rss" target="_blank" href="<?php echo Minz_Url::display ($this->rss_url); ?>">
-					<?php echo Minz_Translate::t ('rss_view'); ?>
-				</a>
-			</li>
-		</ul>
+		<?php
+			$url_output['params']['output'] = 'rss';
+			if ($this->conf->token) {
+				$url_output['params']['token'] = $this->conf->token;
+			}
+		?>
+		<a class="view_rss btn" target="_blank" title="<?php echo _t('rss_view'); ?>" href="<?php echo Minz_Url::display($url_output); ?>">
+			<?php echo _i('rss'); ?>
+		</a>
 	</div>
 
 	<div class="item search">
-		<form action="<?php echo _url ('index', 'index'); ?>" method="get">
-			<?php $search = Minz_Request::param ('search', ''); ?>
-			<input type="search" name="search" class="extend" value="<?php echo $search; ?>" placeholder="<?php echo Minz_Translate::t ('search_short'); ?>" />
+		<form action="<?php echo _url('index', 'index'); ?>" method="get">
+			<?php $search = Minz_Request::param('search', ''); ?>
+			<input type="search" name="search" class="extend" value="<?php echo $search; ?>" placeholder="<?php echo _t('search_short'); ?>" />
 
-			<?php $get = Minz_Request::param ('get', ''); ?>
+			<?php $get = Minz_Request::param('get', ''); ?>
 			<?php if($get != '') { ?>
 			<input type="hidden" name="get" value="<?php echo $get; ?>" />
 			<?php } ?>
 
-			<?php $order = Minz_Request::param ('order', ''); ?>
+			<?php $order = Minz_Request::param('order', ''); ?>
 			<?php if($order != '') { ?>
 			<input type="hidden" name="order" value="<?php echo $order; ?>" />
 			<?php } ?>
 
-			<?php $state = Minz_Request::param ('state', ''); ?>
+			<?php $state = Minz_Request::param('state', ''); ?>
 			<?php if($state != '') { ?>
 			<input type="hidden" name="state" value="<?php echo $state; ?>" />
 			<?php } ?>
 		</form>
 	</div>
+	
+	<?php
+		if ($this->order === 'DESC') {
+			$order = 'ASC';
+			$icon = 'up';
+			$title = 'older_first';
+		} else {
+			$order = 'DESC';
+			$icon = 'down';
+			$title = 'newer_first';
+		}
+		$url_order = $this->url;
+		$url_order['params']['order'] = $order;
+	?>
+	<a id="toggle-order" class="btn" href="<?php echo Minz_Url::display($url_order); ?>" title="<?php echo _t($title); ?>">
+		<?php echo _i($icon); ?>
+	</a>
+	
+	<?php if ($this->loginOk || Minz_Configuration::allowAnonymousRefresh()) { ?>
+	<a id="actualize" class="btn" href="<?php echo _url('feed', 'actualize'); ?>"><?php echo _i('refresh'); ?></a>
+	<?php } ?>
 </div>

+ 21 - 0
app/views/configure/archiving.phtml

@@ -24,6 +24,27 @@
 				?></select> (<?php echo Minz_Translate::t('by_default'); ?>)
 			</div>
 		</div>
+		<div class="form-group">
+			<label class="group-name" for="ttl_default"><?php echo Minz_Translate::t('ttl'); ?></label>
+			<div class="group-controls">
+				<select class="number" name="ttl_default" id="ttl_default" required="required"><?php
+					$found = false;
+					foreach (array(1200 => '20min', 1500 => '25min', 1800 => '30min', 2700 => '45min',
+					                3600 => '1h', 5400 => '1.5h', 7200 => '2h', 10800 => '3h', 14400 => '4h', 18800 => '5h', 21600 => '6h', 25200 => '7h', 28800 => '8h',
+					                36000 => '10h', 43200 => '12h', 64800 => '18h',
+					                86400 => '1d', 129600 => '1.5d', 172800 => '2d', 259200 => '3d', 345600 => '4d', 432000 => '5d', 518400 => '6d',
+					                604800 => '1wk', -1 => '∞') as $v => $t) {
+						echo '<option value="' . $v . ($this->conf->ttl_default == $v ? '" selected="selected' : '') . '">' . $t . '</option>';
+						if ($this->conf->ttl_default == $v) {
+							$found = true;
+						}
+					}
+					if (!$found) {
+						echo '<option value="' . intval($this->conf->ttl_default) . '" selected="selected">' . intval($this->conf->ttl_default) . 's</option>';
+					}
+				?></select> (<?php echo Minz_Translate::t('by_default'); ?>)
+			</div>
+		</div>
 
 		<div class="form-group form-actions">
 			<div class="group-controls">

+ 14 - 6
app/views/configure/categorize.phtml

@@ -14,14 +14,22 @@
 				<?php echo Minz_Translate::t ('category_number', $i); ?>
 			</label>
 			<div class="group-controls">
-				<input type="text" id="cat_<?php echo $cat->id (); ?>" name="categories[]" value="<?php echo $cat->name (); ?>" />
-
-				<?php if ($cat->nbFeed () > 0) { ?>
-				<a class="confirm" href="<?php echo _url ('feed', 'delete', 'id', $cat->id (), 'type', 'category'); ?>"><?php echo Minz_Translate::t ('ask_empty'); ?></a>
-				<?php } ?>
+				<div class="stick">
+					<input type="text" id="cat_<?php echo $cat->id (); ?>" name="categories[]" value="<?php echo $cat->name (); ?>" />
+
+					<?php if ($cat->nbFeed () > 0) { ?>
+					<a class="btn" href="<?php echo _url('index', 'index', 'get', 'c_' . $cat->id ()); ?>">
+						<?php echo _i('link'); ?>
+					</a>
+					<button formaction="<?php echo _url('feed', 'delete', 'id', $cat->id (), 'type', 'category'); ?>"
+					        class="btn btn-attention confirm"
+					        data-str-confirm="<?php echo _t('confirm_action_feed_cat'); ?>"
+					        type="submit"><?php echo _t('ask_empty'); ?></button>
+					<?php } ?>
+				</div>
 				(<?php echo Minz_Translate::t ('number_feeds', $cat->nbFeed ()); ?>)
 
-				<?php if ($cat->id () == $this->defaultCategory->id ()) { ?>
+				<?php if ($cat->id () === $this->defaultCategory->id ()) { ?>
 				<?php echo FreshRSS_Themes::icon('help'); ?> <?php echo Minz_Translate::t ('can_not_be_deleted'); ?>
 				<?php } ?>
 

+ 24 - 110
app/views/configure/display.phtml

@@ -4,7 +4,7 @@
 	<a href="<?php echo _url ('index', 'index'); ?>"><?php echo Minz_Translate::t ('back_to_rss_feeds'); ?></a>
 
 	<form method="post" action="<?php echo _url ('configure', 'display'); ?>">
-		<legend><?php echo Minz_Translate::t ('theme'); ?></legend>
+		<legend><?php echo Minz_Translate::t ('display_configuration'); ?></legend>
 
 		<div class="form-group">
 			<label class="group-name" for="language"><?php echo Minz_Translate::t ('language'); ?></label>
@@ -35,122 +35,29 @@
 			</div>
 		</div>
 
-		<div class="form-group form-actions">
-			<div class="group-controls">
-				<button type="submit" class="btn btn-important"><?php echo Minz_Translate::t ('save'); ?></button>
-				<button type="reset" class="btn"><?php echo Minz_Translate::t ('cancel'); ?></button>
-			</div>
-		</div>
-
-		<legend><?php echo Minz_Translate::t ('reading_configuration'); ?></legend>
-
-		<div class="form-group">
-			<label class="group-name" for="posts_per_page"><?php echo Minz_Translate::t ('articles_per_page'); ?></label>
-			<div class="group-controls">
-				<input type="number" id="posts_per_page" name="posts_per_page" value="<?php echo $this->conf->posts_per_page; ?>" />
-			</div>
-		</div>
-
-		<div class="form-group">
-			<label class="group-name" for="sort_order"><?php echo Minz_Translate::t ('sort_order'); ?></label>
-			<div class="group-controls">
-				<select name="sort_order" id="sort_order">
-					<option value="DESC"<?php echo $this->conf->sort_order === 'DESC' ? ' selected="selected"' : ''; ?>><?php echo Minz_Translate::t ('newer_first'); ?></option>
-					<option value="ASC"<?php echo $this->conf->sort_order === 'ASC' ? ' selected="selected"' : ''; ?>><?php echo Minz_Translate::t ('older_first'); ?></option>
-				</select>
-			</div>
-		</div>
-
+		<?php $width = $this->conf->content_width; ?>
 		<div class="form-group">
-			<label class="group-name" for="view_mode"><?php echo Minz_Translate::t ('default_view'); ?></label>
+			<label class="group-name" for="content_width"><?php echo Minz_Translate::t('content_width'); ?></label>
 			<div class="group-controls">
-				<select name="view_mode" id="view_mode">
-					<option value="normal"<?php echo $this->conf->view_mode === 'normal' ? ' selected="selected"' : ''; ?>><?php echo Minz_Translate::t ('normal_view'); ?></option>
-					<option value="reader"<?php echo $this->conf->view_mode === 'reader' ? ' selected="selected"' : ''; ?>><?php echo Minz_Translate::t ('reader_view'); ?></option>
-					<option value="global"<?php echo $this->conf->view_mode === 'global' ? ' selected="selected"' : ''; ?>><?php echo Minz_Translate::t ('global_view'); ?></option>
+				<select name="content_width" id="content_width" required="">
+					<option value="thin" <?php echo $width === 'thin'? 'selected="selected"' : ''; ?>>
+						<?php echo Minz_Translate::t('width_thin'); ?>
+					</option>
+					<option value="medium" <?php echo $width === 'medium'? 'selected="selected"' : ''; ?>>
+						<?php echo Minz_Translate::t('width_medium'); ?>
+					</option>
+					<option value="large" <?php echo $width === 'large'? 'selected="selected"' : ''; ?>>
+						<?php echo Minz_Translate::t('width_large'); ?>
+					</option>
+					<option value="no_limit" <?php echo $width === 'no_limit'? 'selected="selected"' : ''; ?>>
+						<?php echo Minz_Translate::t('width_no_limit'); ?>
+					</option>
 				</select>
-				<label class="radio" for="radio_all">
-					<input type="radio" name="default_view" id="radio_all" value="all"<?php echo $this->conf->default_view === 'all' ? ' checked="checked"' : ''; ?> />
-					<?php echo Minz_Translate::t ('show_all_articles'); ?>
-				</label>
-				<label class="radio" for="radio_not_read">
-					<input type="radio" name="default_view" id="radio_not_read" value="not_read"<?php echo $this->conf->default_view === 'not_read' ? ' checked="checked"' : ''; ?> />
-					<?php echo Minz_Translate::t ('show_not_reads'); ?>
-				</label>
-			</div>
-		</div>
-
-		<div class="form-group">
-			<div class="group-controls">
-				<label class="checkbox" for="auto_load_more">
-					<input type="checkbox" name="auto_load_more" id="auto_load_more" value="1"<?php echo $this->conf->auto_load_more ? ' checked="checked"' : ''; ?> />
-					<?php echo Minz_Translate::t ('auto_load_more'); ?>
-					<noscript> — <strong><?php echo Minz_Translate::t ('javascript_should_be_activated'); ?></strong></noscript>
-				</label>
 			</div>
 		</div>
 
 		<div class="form-group">
-			<div class="group-controls">
-				<label class="checkbox" for="display_posts">
-					<input type="checkbox" name="display_posts" id="display_posts" value="1"<?php echo $this->conf->display_posts ? ' checked="checked"' : ''; ?> />
-					<?php echo Minz_Translate::t ('display_articles_unfolded'); ?>
-					<noscript> — <strong><?php echo Minz_Translate::t ('javascript_should_be_activated'); ?></strong></noscript>
-				</label>
-			</div>
-		</div>
-
-		<div class="form-group">
-			<div class="group-controls">
-				<label class="checkbox" for="lazyload">
-					<input type="checkbox" name="lazyload" id="lazyload" value="1"<?php echo $this->conf->lazyload ? ' checked="checked"' : ''; ?> />
-					<?php echo Minz_Translate::t ('img_with_lazyload'); ?>
-					<noscript> — <strong><?php echo Minz_Translate::t ('javascript_should_be_activated'); ?></strong></noscript>
-				</label>
-			</div>
-		</div>
-
-		<div class="form-group">
-			<label class="group-name"><?php echo Minz_Translate::t ('auto_read_when'); ?></label>
-			<div class="group-controls">
-				<label class="checkbox" for="check_open_article">
-					<input type="checkbox" name="mark_open_article" id="check_open_article" value="1"<?php echo $this->conf->mark_when['article'] ? ' checked="checked"' : ''; ?> />
-					<?php echo Minz_Translate::t ('article_selected'); ?>
-				</label>
-				<label class="checkbox" for="check_open_site">
-					<input type="checkbox" name="mark_open_site" id="check_open_site" value="1"<?php echo $this->conf->mark_when['site'] ? ' checked="checked"' : ''; ?> />
-					<?php echo Minz_Translate::t ('article_open_on_website'); ?>
-				</label>
-				<label class="checkbox" for="check_scroll">
-					<input type="checkbox" name="mark_scroll" id="check_scroll" value="1"<?php echo $this->conf->mark_when['scroll'] ? ' checked="checked"' : ''; ?> />
-					<?php echo Minz_Translate::t ('scroll'); ?>
-				</label>
-				<label class="checkbox" for="check_reception">
-					<input type="checkbox" name="mark_upon_reception" id="check_reception" value="1"<?php echo $this->conf->mark_when['reception'] ? ' checked="checked"' : ''; ?> />
-					<?php echo Minz_Translate::t ('upon_reception'); ?>
-				</label>
-			</div>
-		</div>
-
-		<div class="form-group">
-			<label class="group-name"><?php echo Minz_Translate::t ('after_onread'); ?></label>
-			<div class="group-controls">
-				<label class="checkbox" for="onread_jump_next">
-					<input type="checkbox" name="onread_jump_next" id="onread_jump_next" value="1"<?php echo $this->conf->onread_jump_next ? ' checked="checked"' : ''; ?> />
-					<?php echo Minz_Translate::t ('jump_next'); ?>
-				</label>
-			</div>
-		</div>
-
-		<div class="form-group form-actions">
-			<div class="group-controls">
-				<button type="submit" class="btn btn-important"><?php echo Minz_Translate::t ('save'); ?></button>
-				<button type="reset" class="btn"><?php echo Minz_Translate::t ('cancel'); ?></button>
-			</div>
-		</div>
-
-		<legend><?php echo Minz_Translate::t ('reading_icons'); ?></legend>
-		<div class="form-group">
+			<label class="group-name" for="theme"><?php echo Minz_Translate::t ('article_icons'); ?></label>
 			<table>
 				<thead>
 					<tr>
@@ -184,6 +91,13 @@
 				</tbody>
 			</table><br />
 		</div>
+		
+		<div class="form-group">
+			<label class="group-name" for="posts_per_page"><?php echo Minz_Translate::t ('html5_notif_timeout'); ?></label>
+			<div class="group-controls">
+				<input type="number" id="html5_notif_timeout" name="html5_notif_timeout" value="<?php echo $this->conf->html5_notif_timeout; ?>" /> <?php echo Minz_Translate::t ('seconds_(0_means_no_timeout)'); ?>
+			</div>
+		</div>
 
 		<div class="form-group form-actions">
 			<div class="group-controls">

+ 49 - 17
app/views/configure/feed.phtml

@@ -32,16 +32,21 @@
 		<div class="form-group">
 			<label class="group-name" for="website"><?php echo Minz_Translate::t ('website_url'); ?></label>
 			<div class="group-controls">
-				<input type="text" name="website" id="website" class="extend" value="<?php echo $this->flux->website (); ?>" />
-				<a target="_blank" href="<?php echo $this->flux->website (); ?>"><?php echo FreshRSS_Themes::icon('link'); ?></a>
+				<div class="stick">
+					<input type="text" name="website" id="website" class="extend" value="<?php echo $this->flux->website (); ?>" />
+					<a class="btn" target="_blank" href="<?php echo $this->flux->website (); ?>"><?php echo FreshRSS_Themes::icon('link'); ?></a>
+				</div>
 			</div>
 		</div>
 		<div class="form-group">
 			<label class="group-name" for="url"><?php echo Minz_Translate::t ('feed_url'); ?></label>
 			<div class="group-controls">
-				<input type="text" name="url" id="url" class="extend" value="<?php echo $this->flux->url (); ?>" />
-				<a target="_blank" href="<?php echo $this->flux->url (); ?>"><?php echo FreshRSS_Themes::icon('link'); ?></a>
-				  <a class="btn" target="_blank" href="http://validator.w3.org/feed/check.cgi?url=<?php echo $this->flux->url (); ?>"><?php echo Minz_Translate::t ('feed_validator'); ?></a>
+				<div class="stick">
+					<input type="text" name="url" id="url" class="extend" value="<?php echo $this->flux->url (); ?>" />
+					<a class="btn" target="_blank" href="<?php echo $this->flux->url (); ?>"><?php echo FreshRSS_Themes::icon('link'); ?></a>
+				</div>
+
+				<a class="btn" target="_blank" href="http://validator.w3.org/feed/check.cgi?url=<?php echo $this->flux->url (); ?>"><?php echo Minz_Translate::t ('feed_validator'); ?></a>
 			</div>
 		</div>
 		<div class="form-group">
@@ -65,27 +70,33 @@
 				</label>
 			</div>
 		</div>
+		<div class="form-group">
+			<div class="group-controls">
+				<a href="<?php echo _url('stats', 'repartition', 'id', $this->flux->id()); ?>">
+					<?php echo _i('stats'); ?> <?php echo _t('stats'); ?>
+				</a>
+			</div>
+		</div>
 		<div class="form-group form-actions">
 			<div class="group-controls">
-				<button class="btn btn-important"><?php echo Minz_Translate::t ('save'); ?></button>
-				<button class="btn btn-attention confirm" formmethod="post" formaction="<?php echo Minz_Url::display (array ('c' => 'feed', 'a' => 'delete', 'params' => array ('id' => $this->flux->id ()))); ?>"><?php echo Minz_Translate::t ('delete'); ?></button>
+				<button class="btn btn-important"><?php echo _t('save'); ?></button>
+				<button class="btn btn-attention confirm"
+				        data-str-confirm="<?php echo _t('confirm_action_feed_cat'); ?>"
+				        formaction="<?php echo _url('feed', 'delete', 'id', $this->flux->id ()); ?>"
+				        formmethod="post"><?php echo _t('delete'); ?></button>
 			</div>
 		</div>
 
 		<legend><?php echo Minz_Translate::t ('archiving_configuration'); ?></legend>
 
 		<div class="form-group">
-			<label class="group-name"></label>
-			<div class="group-controls">
-				<a class="btn" href="<?php echo _url ('feed', 'actualize', 'id', $this->flux->id ()); ?>">
-					<?php echo FreshRSS_Themes::icon('refresh'); ?> <?php echo Minz_Translate::t('actualize'); ?>
-				</a>
-			</div>
-		</div>
-		<div class="form-group">
-			<label class="group-name"><?php echo Minz_Translate::t ('number_articles'); ?></label>
 			<div class="group-controls">
-				<span class="control"><?php echo $nbEntries; ?></span>
+				<div class="stick">
+					<input type="text" value="<?php echo _t('number_articles', $nbEntries); ?>" disabled="disabled" />
+					<a class="btn" href="<?php echo _url('feed', 'actualize', 'id', $this->flux->id ()); ?>">
+						<?php echo _i('refresh'); ?> <?php echo _t('actualize'); ?>
+					</a>
+				</div>
 			</div>
 		</div>
 		<div class="form-group">
@@ -98,6 +109,27 @@
 				?></select>
 			</div>
 		</div>
+		<div class="form-group">
+			<label class="group-name" for="ttl"><?php echo Minz_Translate::t('ttl'); ?></label>
+			<div class="group-controls">
+				<select class="number" name="ttl" id="ttl" required="required"><?php
+					$found = false;
+					foreach (array(-2 => Minz_Translate::t('by_default'), 900 => '15min', 1200 => '20min', 1500 => '25min', 1800 => '30min', 2700 => '45min',
+					                3600 => '1h', 5400 => '1.5h', 7200 => '2h', 10800 => '3h', 14400 => '4h', 18800 => '5h', 21600 => '6h', 25200 => '7h', 28800 => '8h',
+					                36000 => '10h', 43200 => '12h', 64800 => '18h',
+					                86400 => '1d', 129600 => '1.5d', 172800 => '2d', 259200 => '3d', 345600 => '4d', 432000 => '5d', 518400 => '6d',
+					                604800 => '1wk', 1209600 => '2wk', 1814400 => '3wk', 2419200 => '4wk', 2629744 => '1mo', -1 => '∞') as $v => $t) {
+						echo '<option value="' . $v . ($this->flux->ttl() === $v ? '" selected="selected' : '') . '">' . $t . '</option>';
+						if ($this->flux->ttl() == $v) {
+							$found = true;
+						}
+					}
+					if (!$found) {
+						echo '<option value="' . intval($this->flux->ttl()) . '" selected="selected">' . intval($this->flux->ttl()) . 's</option>';
+					}
+				?></select>
+			</div>
+		</div>
 		<div class="form-group form-actions">
 			<div class="group-controls">
 				<button class="btn btn-important"><?php echo Minz_Translate::t ('save'); ?></button>

+ 0 - 40
app/views/configure/importExport.phtml

@@ -1,40 +0,0 @@
-<?php
-require_once(LIB_PATH . '/lib_opml.php');
-if ($this->req == 'export') {
-	echo '<?xml version="1.0" encoding="UTF-8" ?>';
-?>
-<!-- Generated by <?php echo Minz_Configuration::title (); ?> -->
-<opml version="2.0">
-	<head>
-		<title><?php echo Minz_Configuration::title (); ?> OPML Feed</title>
-		<dateCreated><?php echo date('D, d M Y H:i:s'); ?></dateCreated>
-	</head>
-	<body>
-<?php echo opml_export ($this->categories); ?>
-	</body>
-</opml>
-<?php } else { ?>
-<?php $this->partial ('aside_feed'); ?>
-
-<div class="post ">
-	<a href="<?php echo _url ('index', 'index'); ?>"><?php echo Minz_Translate::t ('back_to_rss_feeds'); ?></a>
-
-	<form method="post" action="<?php echo Minz_Url::display (array ('c' => 'configure', 'a' => 'importExport', 'params' => array ('q' => 'import'))); ?>" enctype="multipart/form-data">
-		<legend><?php echo Minz_Translate::t ('import_export_opml'); ?></legend>
-		<div class="form-group">
-			<label class="group-name" for="file"><?php echo Minz_Translate::t ('file_to_import'); ?></label>
-			<div class="group-controls">
-				<input type="file" name="file" id="file" />
-			</div>
-		</div>
-
-		<div class="form-group form-actions">
-			<div class="group-controls">
-				<button type="submit" class="btn btn-important"><?php echo Minz_Translate::t ('import'); ?></button>
-				<?php echo Minz_Translate::t ('or'); ?>
-				<a target="_blank" class="btn btn-important" href="<?php echo _url ('configure', 'importExport', 'q', 'export'); ?>"><?php echo Minz_Translate::t ('export'); ?></a>
-			</div>
-		</div>
-	</form>
-</div>
-<?php } ?>

+ 97 - 0
app/views/configure/queries.phtml

@@ -0,0 +1,97 @@
+<?php $this->partial('aside_configure'); ?>
+
+<div class="post">
+	<a href="<?php echo _url('index', 'index'); ?>"><?php echo _t('back_to_rss_feeds'); ?></a>
+
+	<form method="post" action="<?php echo _url('configure', 'queries'); ?>">
+		<legend><?php echo _t('queries'); ?></legend>
+
+		<?php foreach ($this->conf->queries as $key => $query) { ?>
+		<div class="form-group" id="query-group-<?php echo $key; ?>">
+			<label class="group-name" for="queries_<?php echo $key; ?>_name">
+				<?php echo _t('query_number', $key + 1); ?>
+			</label>
+
+			<div class="group-controls">
+				<input type="hidden" id="queries_<?php echo $key; ?>_search" name="queries[<?php echo $key; ?>][search]" value="<?php echo isset($query['search']) ? $query['search'] : ""; ?>"/>
+				<input type="hidden" id="queries_<?php echo $key; ?>_state" name="queries[<?php echo $key; ?>][state]" value="<?php echo isset($query['state']) ? $query['state'] : ""; ?>"/>
+				<input type="hidden" id="queries_<?php echo $key; ?>_order" name="queries[<?php echo $key; ?>][order]" value="<?php echo isset($query['order']) ? $query['order'] : ""; ?>"/>
+				<input type="hidden" id="queries_<?php echo $key; ?>_get" name="queries[<?php echo $key; ?>][get]" value="<?php echo isset($query['get']) ? $query['get'] : ""; ?>"/>
+
+				<div class="stick">
+					<input class="extend"
+					       type="text"
+					       id="queries_<?php echo $key; ?>_name"
+					       name="queries[<?php echo $key; ?>][name]"
+					       value="<?php echo $query['name']; ?>"
+					/>
+
+					<a class="btn" href="<?php echo $query['url']; ?>">
+						<?php echo _i('link'); ?>
+					</a>
+
+					<a class="btn btn-attention remove" href="#" data-remove="query-group-<?php echo $key; ?>">
+						<?php echo _i('close'); ?>
+					</a>
+				</div>
+
+				<?php
+					$exist = (isset($query['search']) ? 1 : 0)
+						   + (isset($query['state']) ? 1 : 0)
+						   + (isset($query['order']) ? 1 : 0)
+						   + (isset($query['get']) ? 1 : 0);
+					// If the only filter is "all" articles, we consider there is no filter
+					$exist = ($exist === 1 && isset($query['get']) && $query['get'] === 'a') ? 0 : $exist;
+
+					$deprecated = (isset($this->query_get[$key]) &&
+					               $this->query_get[$key]['deprecated']);
+				?>
+
+				<?php if ($exist === 0) { ?>
+				<div class="alert alert-warn">
+					<div class="alert-head"><?php echo _t('no_query_filter'); ?></div>
+				</div>
+				<?php } elseif ($deprecated) { ?>
+				<div class="alert alert-error">
+					<div class="alert-head"><?php echo _t('query_deprecated'); ?></div>
+				</div>
+				<?php } else { ?>
+				<div class="alert alert-success">
+					<div class="alert-head"><?php echo _t('query_filter'); ?></div>
+
+					<ul>
+						<?php if (isset($query['search'])) { ?>
+						<li class="item"><?php echo _t('query_search', $query['search']); ?></li>
+						<?php } ?>
+
+						<?php if (isset($query['state'])) { ?>
+						<li class="item"><?php echo _t('query_state_' . $query['state']); ?></li>
+						<?php } ?>
+
+						<?php if (isset($query['order'])) { ?>
+						<li class="item"><?php echo _t('query_order_' . strtolower($query['order'])); ?></li>
+						<?php } ?>
+
+						<?php if (isset($query['get'])) { ?>
+						<li class="item"><?php echo _t('query_get_' . $this->query_get[$key]['type'], $this->query_get[$key]['name']); ?></li>
+						<?php } ?>
+					</ul>
+				</div>
+				<?php } ?>
+			</div>
+		</div>
+		<?php } ?>
+
+		<?php if (count($this->conf->queries) > 0) { ?>
+		<div class="form-group form-actions">
+			<div class="group-controls">
+				<button type="submit" class="btn btn-important"><?php echo _t('save'); ?></button>
+				<button type="reset" class="btn"><?php echo _t('cancel'); ?></button>
+			</div>
+		</div>
+		<?php } else { ?>
+		<p class="alert alert-warn"><span class="alert-head"><?php echo _t('damn'); ?></span> <?php echo _t('no_query'); ?></p>
+		<?php } ?>
+	</form>
+
+</div>

+ 158 - 0
app/views/configure/reading.phtml

@@ -0,0 +1,158 @@
+<?php $this->partial ('aside_configure'); ?>
+
+<div class="post">
+	<a href="<?php echo _url ('index', 'index'); ?>"><?php echo Minz_Translate::t ('back_to_rss_feeds'); ?></a>
+
+	<form method="post" action="<?php echo _url ('configure', 'reading'); ?>">
+		<legend><?php echo Minz_Translate::t ('reading_configuration'); ?></legend>
+
+		<div class="form-group">
+			<label class="group-name" for="posts_per_page"><?php echo Minz_Translate::t ('articles_per_page'); ?></label>
+			<div class="group-controls">
+				<input type="number" id="posts_per_page" name="posts_per_page" value="<?php echo $this->conf->posts_per_page; ?>" min="5" max="50" />
+				<?php echo _i('help'); ?> <?php echo _t('number_divided_when_reader'); ?>
+			</div>
+		</div>
+
+		<div class="form-group">
+			<label class="group-name" for="sort_order"><?php echo Minz_Translate::t ('sort_order'); ?></label>
+			<div class="group-controls">
+				<select name="sort_order" id="sort_order">
+					<option value="DESC"<?php echo $this->conf->sort_order === 'DESC' ? ' selected="selected"' : ''; ?>><?php echo Minz_Translate::t ('newer_first'); ?></option>
+					<option value="ASC"<?php echo $this->conf->sort_order === 'ASC' ? ' selected="selected"' : ''; ?>><?php echo Minz_Translate::t ('older_first'); ?></option>
+				</select>
+			</div>
+		</div>
+
+		<div class="form-group">
+			<label class="group-name" for="view_mode"><?php echo Minz_Translate::t ('default_view'); ?></label>
+			<div class="group-controls">
+				<select name="view_mode" id="view_mode">
+					<option value="normal"<?php echo $this->conf->view_mode === 'normal' ? ' selected="selected"' : ''; ?>><?php echo Minz_Translate::t ('normal_view'); ?></option>
+					<option value="reader"<?php echo $this->conf->view_mode === 'reader' ? ' selected="selected"' : ''; ?>><?php echo Minz_Translate::t ('reader_view'); ?></option>
+					<option value="global"<?php echo $this->conf->view_mode === 'global' ? ' selected="selected"' : ''; ?>><?php echo Minz_Translate::t ('global_view'); ?></option>
+				</select>
+			</div>
+		</div>
+
+		<div class="form-group">
+			<label class="group-name" for="view_mode"><?php echo _t('articles_to_display'); ?></label>
+			<div class="group-controls">
+				<select name="default_view" id="default_view">
+					<option value="<?php echo FreshRSS_Entry::STATE_NOT_READ; ?>"<?php echo $this->conf->default_view === FreshRSS_Entry::STATE_NOT_READ ? ' selected="selected"' : ''; ?>><?php echo _t('show_adaptive'); ?></option>
+					<option value="<?php echo FreshRSS_Entry::STATE_ALL; ?>"<?php echo $this->conf->default_view === FreshRSS_Entry::STATE_ALL ? ' selected="selected"' : ''; ?>><?php echo _t('show_all_articles'); ?></option>
+					<option value="<?php echo FreshRSS_Entry::STATE_STRICT + FreshRSS_Entry::STATE_NOT_READ; ?>"<?php echo $this->conf->default_view === FreshRSS_Entry::STATE_STRICT + FreshRSS_Entry::STATE_NOT_READ ? ' selected="selected"' : ''; ?>><?php echo _t('show_not_reads'); ?></option>
+				</select>
+			</div>
+		</div>
+
+		<div class="form-group">
+			<div class="group-controls">
+				<label class="checkbox" for="hide_read_feeds">
+					<input type="checkbox" name="hide_read_feeds" id="hide_read_feeds" value="1"<?php echo $this->conf->hide_read_feeds ? ' checked="checked"' : ''; ?> />
+					<?php echo Minz_Translate::t('hide_read_feeds'); ?>
+				</label>
+			</div>
+		</div>
+
+		<div class="form-group">
+			<div class="group-controls">
+				<label class="checkbox" for="display_posts">
+					<input type="checkbox" name="display_posts" id="display_posts" value="1"<?php echo $this->conf->display_posts ? ' checked="checked"' : ''; ?> />
+					<?php echo Minz_Translate::t ('display_articles_unfolded'); ?>
+					<noscript> — <strong><?php echo Minz_Translate::t ('javascript_should_be_activated'); ?></strong></noscript>
+				</label>
+			</div>
+		</div>
+
+		<div class="form-group">
+			<div class="group-controls">
+				<label class="checkbox" for="display_categories">
+					<input type="checkbox" name="display_categories" id="display_categories" value="1"<?php echo $this->conf->display_categories ? ' checked="checked"' : ''; ?> />
+					<?php echo Minz_Translate::t ('display_categories_unfolded'); ?>
+					<noscript> — <strong><?php echo Minz_Translate::t ('javascript_should_be_activated'); ?></strong></noscript>
+				</label>
+			</div>
+		</div>
+
+		<div class="form-group">
+			<div class="group-controls">
+				<label class="checkbox" for="sticky_post">
+					<input type="checkbox" name="sticky_post" id="sticky_post" value="1"<?php echo $this->conf->sticky_post ? ' checked="checked"' : ''; ?> />
+					<?php echo Minz_Translate::t ('sticky_post'); ?>
+					<noscript> — <strong><?php echo Minz_Translate::t ('javascript_should_be_activated'); ?></strong></noscript>
+				</label>
+			</div>
+		</div>
+
+		<div class="form-group">
+			<div class="group-controls">
+				<label class="checkbox" for="auto_load_more">
+					<input type="checkbox" name="auto_load_more" id="auto_load_more" value="1"<?php echo $this->conf->auto_load_more ? ' checked="checked"' : ''; ?> />
+					<?php echo Minz_Translate::t ('auto_load_more'); ?>
+					<noscript> — <strong><?php echo Minz_Translate::t ('javascript_should_be_activated'); ?></strong></noscript>
+				</label>
+			</div>
+		</div>
+
+		<div class="form-group">
+			<div class="group-controls">
+				<label class="checkbox" for="lazyload">
+					<input type="checkbox" name="lazyload" id="lazyload" value="1"<?php echo $this->conf->lazyload ? ' checked="checked"' : ''; ?> />
+					<?php echo Minz_Translate::t ('img_with_lazyload'); ?>
+					<noscript> — <strong><?php echo Minz_Translate::t ('javascript_should_be_activated'); ?></strong></noscript>
+				</label>
+			</div>
+		</div>
+
+		<div class="form-group">
+			<div class="group-controls">
+				<label class="checkbox" for="reading_confirm">
+					<input type="checkbox" name="reading_confirm" id="reading_confirm" value="1"<?php echo $this->conf->reading_confirm ? ' checked="checked"' : ''; ?> />
+					<?php echo Minz_Translate::t ('reading_confirm'); ?>
+					<noscript> — <strong><?php echo Minz_Translate::t ('javascript_should_be_activated'); ?></strong></noscript>
+				</label>
+			</div>
+		</div>
+
+		<div class="form-group">
+			<label class="group-name"><?php echo Minz_Translate::t ('auto_read_when'); ?></label>
+			<div class="group-controls">
+				<label class="checkbox" for="check_open_article">
+					<input type="checkbox" name="mark_open_article" id="check_open_article" value="1"<?php echo $this->conf->mark_when['article'] ? ' checked="checked"' : ''; ?> />
+					<?php echo Minz_Translate::t('article_viewed'); ?>
+				</label>
+				<label class="checkbox" for="check_open_site">
+					<input type="checkbox" name="mark_open_site" id="check_open_site" value="1"<?php echo $this->conf->mark_when['site'] ? ' checked="checked"' : ''; ?> />
+					<?php echo Minz_Translate::t ('article_open_on_website'); ?>
+				</label>
+				<label class="checkbox" for="check_scroll">
+					<input type="checkbox" name="mark_scroll" id="check_scroll" value="1"<?php echo $this->conf->mark_when['scroll'] ? ' checked="checked"' : ''; ?> />
+					<?php echo Minz_Translate::t ('scroll'); ?>
+				</label>
+				<label class="checkbox" for="check_reception">
+					<input type="checkbox" name="mark_upon_reception" id="check_reception" value="1"<?php echo $this->conf->mark_when['reception'] ? ' checked="checked"' : ''; ?> />
+					<?php echo Minz_Translate::t ('upon_reception'); ?>
+				</label>
+			</div>
+		</div>
+
+		<div class="form-group">
+			<label class="group-name"><?php echo Minz_Translate::t ('after_onread'); ?></label>
+			<div class="group-controls">
+				<label class="checkbox" for="onread_jump_next">
+					<input type="checkbox" name="onread_jump_next" id="onread_jump_next" value="1"<?php echo $this->conf->onread_jump_next ? ' checked="checked"' : ''; ?> />
+					<?php echo Minz_Translate::t ('jump_next'); ?>
+				</label>
+			</div>
+		</div>
+
+		<div class="form-group form-actions">
+			<div class="group-controls">
+				<button type="submit" class="btn btn-important"><?php echo Minz_Translate::t ('save'); ?></button>
+				<button type="reset" class="btn"><?php echo Minz_Translate::t ('cancel'); ?></button>
+			</div>
+		</div>
+
+	</form>
+</div>

+ 38 - 43
app/views/configure/sharing.phtml

@@ -3,54 +3,49 @@
 <div class="post">
 	<a href="<?php echo _url ('index', 'index'); ?>"><?php echo Minz_Translate::t ('back_to_rss_feeds'); ?></a>
 
-	<form method="post" action="<?php echo _url ('configure', 'sharing'); ?>">
+	<form method="post" action="<?php echo _url ('configure', 'sharing'); ?>"
+		data-simple='<div class="form-group" id="group-share-##key##"><label class="group-name">##label##</label><div class="group-controls"><a href="#" class="remove btn btn-attention" data-remove="group-share-##key##"><?php echo FreshRSS_Themes::icon('close'); ?></a>
+			<input type="hidden" id="share_##key##_type" name="share[##key##][type]" value="##type##" /></div></div>'
+		data-advanced='<div class="form-group" id="group-share-##key##"><label class="group-name">##label##</label><div class="group-controls">
+			<input type="hidden" id="share_##key##_type" name="share[##key##][type]" value="##type##" />
+			<div class="stick">
+			<input type="text" id="share_##key##_name" name="share[##key##][name]" class="extend" value="" placeholder="<?php echo Minz_Translate::t ('share_name'); ?>" size="64" />
+			<input type="url" id="share_##key##_url" name="share[##key##][url]" class="extend" value="" placeholder="<?php echo Minz_Translate::t ('share_url'); ?>" size="64" />
+			<a href="#" class="remove btn btn-attention" data-remove="group-share-##key##"><?php echo FreshRSS_Themes::icon('close'); ?></a></div>
+			<a target="_blank" class="btn" title="<?php echo Minz_Translate::t('more_information'); ?>" href="##help##"><?php echo FreshRSS_Themes::icon('help'); ?></a>
+			</div></div>'>
 		<legend><?php echo Minz_Translate::t ('sharing'); ?></legend>
-		<div class="form-group">
-			<label class="group-name" for="shaarli">
-				<?php echo Minz_Translate::t ('your_shaarli'); ?>
-			</label>
-			<div class="group-controls">
-				<input type="url" id="shaarli" name="shaarli" class="extend" value="<?php echo $this->conf->sharing ('shaarli'); ?>" placeholder="<?php echo Minz_Translate::t ('blank_to_disable'); ?>" size="64" />
-
-				<?php echo FreshRSS_Themes::icon('help'); ?> <a target="_blank" href="http://sebsauvage.net/wiki/doku.php?id=php:shaarli"><?php echo Minz_Translate::t ('more_information'); ?></a>
-			</div>
-		</div>
-
-		<div class="form-group">
-			<label class="group-name" for="wallabag">
-				<?php echo Minz_Translate::t ('your_wallabag'); ?>
-			</label>
-			<div class="group-controls">
-				<input type="url" id="wallabag" name="wallabag" class="extend" value="<?php echo $this->conf->sharing ('wallabag'); ?>" placeholder="<?php echo Minz_Translate::t ('blank_to_disable'); ?>" size="64" />
-
-				<?php echo FreshRSS_Themes::icon('help'); ?> <a target="_blank" href="http://www.wallabag.org"><?php echo Minz_Translate::t ('more_information'); ?></a>
-			</div>
-		</div>
-
-		<div class="form-group">
-			<label class="group-name" for="diaspora">
-				<?php echo Minz_Translate::t ('your_diaspora_pod'); ?>
-			</label>
-			<div class="group-controls">
-				<input type="url" id="diaspora" name="diaspora" class="extend" value="<?php echo $this->conf->sharing ('diaspora'); ?>" placeholder="<?php echo Minz_Translate::t ('blank_to_disable'); ?>" size="64" />
-
-				<?php echo FreshRSS_Themes::icon('help'); ?> <a target="_blank" href="https://diasporafoundation.org/"><?php echo Minz_Translate::t ('more_information'); ?></a>
+		<?php foreach ($this->conf->sharing as $key => $sharing): ?>
+			<?php $share = $this->conf->shares[$sharing['type']]; ?>
+			<div class="form-group" id="group-share-<?php echo $key; ?>">
+				<label class="group-name">
+					<?php echo Minz_Translate::t ($sharing['type']); ?>
+				</label>
+				<div class="group-controls">
+					<input type='hidden' id='share_<?php echo $key;?>_type' name="share[<?php echo $key;?>][type]" value='<?php echo $sharing['type']?>' />
+					<?php if ($share['form'] === 'advanced') { ?>
+						<div class="stick">
+							<input type="text" id="share_<?php echo $key;?>_name" name="share[<?php echo $key;?>][name]" class="extend" value="<?php echo $sharing['name']?>" placeholder="<?php echo Minz_Translate::t ('share_name'); ?>" size="64" />
+							<input type="url" id="share_<?php echo $key;?>_url" name="share[<?php echo $key;?>][url]" class="extend" value="<?php echo $sharing['url']?>" placeholder="<?php echo Minz_Translate::t ('share_url'); ?>" size="64" />
+							<a href='#' class='remove btn btn-attention' data-remove="group-share-<?php echo $key; ?>"><?php echo FreshRSS_Themes::icon('close'); ?></a>
+						</div>
+
+						<a target="_blank" class="btn" title="<?php echo Minz_Translate::t('more_information'); ?>" href="<?php echo $share['help']?>"><?php echo FreshRSS_Themes::icon('help'); ?></a>
+					<?php } else { ?>
+					<a href='#' class='remove btn btn-attention' data-remove="group-share-<?php echo $key; ?>"><?php echo FreshRSS_Themes::icon('close'); ?></a>
+					<?php } ?>
+				</div>
 			</div>
-		</div>
+		<?php endforeach;?>
 
 		<div class="form-group">
-			<label class="group-name"><?php echo Minz_Translate::t ('activate_sharing'); ?></label>
 			<div class="group-controls">
-				<?php
-					$services = array ('twitter', 'g+', 'facebook', 'email', 'print');
-
-					foreach ($services as $service) {
-				?>
-				<label class="checkbox" for="<?php echo $service; ?>">
-					<input type="checkbox" name="<?php echo $service; ?>" id="<?php echo $service; ?>" value="1"<?php echo $this->conf->sharing($service) ? ' checked="checked"' : ''; ?> />
-					<?php echo Minz_Translate::t ($service); ?>
-				</label>
-				<?php } ?>
+				<select>
+					<?php foreach($this->conf->shares as $key => $params):?>
+						<option value='<?php echo $key?>' data-form='<?php echo $params['form']?>' data-help='<?php if (!empty($params['help'])) {echo $params['help'];}?>'><?php echo Minz_Translate::t($key) ?></option>
+					<?php endforeach; ?>
+				</select>
+				<a href='#' class='share add btn'><?php echo FreshRSS_Themes::icon('add'); ?></a>
 			</div>
 		</div>
 

+ 23 - 1
app/views/configure/shortcut.phtml

@@ -12,7 +12,7 @@
 	<?php $s = $this->conf->shortcuts; ?>
 
 	<form method="post" action="<?php echo _url ('configure', 'shortcut'); ?>">
-		<legend><?php echo Minz_Translate::t ('shortcuts_management'); ?></legend>
+		<legend><?php echo Minz_Translate::t ('shortcuts'); ?></legend>
 
 		<noscript><p class="alert alert-error"><?php echo Minz_Translate::t ('javascript_for_shortcuts'); ?></p></noscript>
 
@@ -96,6 +96,28 @@
 			</div>
 		</div>
 
+		<div class="form-group">
+			<label class="group-name" for="focus_search_shortcut"><?php echo Minz_Translate::t ('focus_search'); ?></label>
+			<div class="group-controls">
+				<input type="text" id="focus_search_shortcut" name="shortcuts[focus_search]" list="keys" value="<?php echo $s['focus_search']; ?>" />
+			</div>
+		</div>
+
+		<div class="form-group">
+			<label class="group-name" for="user_filter_shortcut"><?php echo Minz_Translate::t ('user_filter'); ?></label>
+			<div class="group-controls">
+				<input type="text" id="user_filter_shortcut" name="shortcuts[user_filter]" list="keys" value="<?php echo $s['user_filter']; ?>" />
+				<?php echo Minz_Translate::t ('user_filter_help'); ?>
+			</div>
+		</div>
+
+		<div class="form-group">
+			<label class="group-name" for="help_shortcut"><?php echo Minz_Translate::t ('help'); ?></label>
+			<div class="group-controls">
+				<input type="text" id="help_shortcut" name="shortcuts[help]" list="keys" value="<?php echo $s['help']; ?>" />
+			</div>
+		</div>
+
 		<div class="form-group form-actions">
 			<div class="group-controls">
 				<button type="submit" class="btn btn-important"><?php echo Minz_Translate::t ('save'); ?></button>

+ 43 - 4
app/views/configure/users.phtml

@@ -20,11 +20,26 @@
 		<div class="form-group">
 			<label class="group-name" for="passwordPlain"><?php echo Minz_Translate::t('password_form'); ?></label>
 			<div class="group-controls">
-				<input type="password" id="passwordPlain" name="passwordPlain" autocomplete="off" pattern=".{7,}" />
+				<div class="stick">
+					<input type="password" id="passwordPlain" name="passwordPlain" autocomplete="off" pattern=".{7,}" <?php echo cryptAvailable() ? '' : 'disabled="disabled" '; ?>/>
+					<a class="btn toggle-password"><?php echo FreshRSS_Themes::icon('key'); ?></a>
+				</div>
 				<noscript><b><?php echo Minz_Translate::t('javascript_should_be_activated'); ?></b></noscript>
 			</div>
 		</div>
 
+		<?php if (Minz_Configuration::apiEnabled()) { ?>
+		<div class="form-group">
+			<label class="group-name" for="apiPasswordPlain"><?php echo Minz_Translate::t('password_api'); ?></label>
+			<div class="group-controls">
+				<div class="stick">
+					<input type="password" id="apiPasswordPlain" name="apiPasswordPlain" autocomplete="off" pattern=".{7,}" <?php echo cryptAvailable() ? '' : 'disabled="disabled" '; ?>/>
+					<a class="btn toggle-password"><?php echo FreshRSS_Themes::icon('key'); ?></a>
+				</div>
+			</div>
+		</div>
+		<?php } ?>
+
 		<div class="form-group">
 			<label class="group-name" for="mail_login"><?php echo Minz_Translate::t('persona_connection_email'); ?></label>
 			<?php $mail = $this->conf->mail_login; ?>
@@ -52,7 +67,7 @@
 					<?php if (!in_array(Minz_Configuration::authType(), array('form', 'persona', 'http_auth', 'none'))) { ?>
 						<option selected="selected"></option>
 					<?php } ?>
-					<option value="form"<?php echo Minz_Configuration::authType() === 'form' ? ' selected="selected"' : '', version_compare(PHP_VERSION, '5.3', '<') ? ' disabled="disabled"' : ''; ?>><?php echo Minz_Translate::t('auth_form'); ?></option>
+					<option value="form"<?php echo Minz_Configuration::authType() === 'form' ? ' selected="selected"' : '', cryptAvailable() ? '' : ' disabled="disabled"'; ?>><?php echo Minz_Translate::t('auth_form'); ?></option>
 					<option value="persona"<?php echo Minz_Configuration::authType() === 'persona' ? ' selected="selected"' : '', $this->conf->mail_login == '' ? ' disabled="disabled"' : ''; ?>><?php echo Minz_Translate::t('auth_persona'); ?></option>
 					<option value="http_auth"<?php echo Minz_Configuration::authType() === 'http_auth' ? ' selected="selected"' : '', httpAuthUser() == '' ? ' disabled="disabled"' : ''; ?>><?php echo Minz_Translate::t('http_auth'); ?> (REMOTE_USER = '<?php echo httpAuthUser(); ?>')</option>
 					<option value="none"<?php echo Minz_Configuration::authType() === 'none' ? ' selected="selected"' : ''; ?>><?php echo Minz_Translate::t('auth_none'); ?></option>
@@ -80,18 +95,39 @@
 			</div>
 		</div>
 
+		<div class="form-group">
+			<div class="group-controls">
+				<label class="checkbox" for="unsafe_autologin">
+					<input type="checkbox" name="unsafe_autologin" id="unsafe_autologin" value="1"<?php echo Minz_Configuration::unsafeAutologinEnabled() ? ' checked="checked"' : '',
+						Minz_Configuration::canLogIn() ? '' : ' disabled="disabled"'; ?> />
+					<?php echo Minz_Translate::t('unsafe_autologin'); ?>
+					<kbd>p/i/?a=formLogin&amp;u=Alice&amp;p=1234</kbd>
+				</label>
+			</div>
+		</div>
+
 		<?php if (Minz_Configuration::canLogIn()) { ?>
 		<div class="form-group">
 			<label class="group-name" for="token"><?php echo Minz_Translate::t('auth_token'); ?></label>
 			<?php $token = $this->conf->token; ?>
 			<div class="group-controls">
-				<input type="text" id="token" name="token" value="<?php echo $token; ?>"  placeholder="<?php echo Minz_Translate::t('blank_to_disable'); ?>"<?php
+				<input type="text" id="token" name="token" value="<?php echo $token; ?>" placeholder="<?php echo Minz_Translate::t('blank_to_disable'); ?>"<?php
 					echo Minz_Configuration::canLogIn() ? '' : ' disabled="disabled"'; ?> />
 				<?php echo FreshRSS_Themes::icon('help'); ?> <?php echo Minz_Translate::t('explain_token', Minz_Url::display(null, 'html', true), $token); ?>
 			</div>
 		</div>
 		<?php } ?>
 
+		<div class="form-group">
+			<div class="group-controls">
+				<label class="checkbox" for="api_enabled">
+					<input type="checkbox" name="api_enabled" id="api_enabled" value="1"<?php echo Minz_Configuration::apiEnabled() ? ' checked="checked"' : '',
+						Minz_Configuration::needsLogin() ? '' : ' disabled="disabled"'; ?> />
+					<?php echo Minz_Translate::t('api_enabled'); ?>
+				</label>
+			</div>
+		</div>
+
 		<div class="form-group form-actions">
 			<div class="group-controls">
 				<button type="submit" class="btn btn-important"><?php echo Minz_Translate::t('save'); ?></button>
@@ -146,7 +182,10 @@
 		<div class="form-group">
 			<label class="group-name" for="new_user_passwordPlain"><?php echo Minz_Translate::t('password_form'); ?></label>
 			<div class="group-controls">
-				<input type="password" id="new_user_passwordPlain" name="new_user_passwordPlain" autocomplete="off" pattern=".{7,}" />
+				<div class="stick">
+					<input type="password" id="new_user_passwordPlain" name="new_user_passwordPlain" autocomplete="off" pattern=".{7,}" />
+					<a class="btn toggle-password"><?php echo FreshRSS_Themes::icon('key'); ?></a>
+				</div>
 				<noscript><b><?php echo Minz_Translate::t('javascript_should_be_activated'); ?></b></noscript>
 			</div>
 		</div>

+ 2 - 11
app/views/error/index.phtml

@@ -1,18 +1,9 @@
 <div class="post">
 	<div class="alert alert-error">
 		<h1 class="alert-head"><?php echo $this->code; ?></h1>
-
 		<p>
-			<?php
-			switch(Minz_Request::param ('code')) {
-			case 403:
-				echo Minz_Translate::t ('forbidden_access');
-				break;
-			case 404:
-			default:
-				echo Minz_Translate::t ('page_not_found');
-			} ?><br />
-			<a href="<?php echo _url ('index', 'index'); ?>"><?php echo Minz_Translate::t ('back_to_rss_feeds'); ?></a>
+			<?php echo $this->errorMessage; ?><br />
+			<a href="<?php echo _url('index', 'index'); ?>"><?php echo Minz_Translate::t('back_to_rss_feeds'); ?></a>
 		</p>
 	</div>
 </div>

+ 91 - 0
app/views/feed/add.phtml

@@ -0,0 +1,91 @@
+<?php if ($this->feed) { ?>
+<div class="post">
+	<h1><?php echo Minz_Translate::t ('add_rss_feed'); ?></h1>
+
+	<?php if (!$this->load_ok) { ?>
+	<p class="alert alert-error"><span class="alert-head"><?php echo Minz_Translate::t('damn'); ?></span> <?php echo Minz_Translate::t('internal_problem_feed', _url('index', 'logs')); ?></p>
+	<?php } ?>
+
+	<form method="post" action="<?php echo _url('feed', 'add'); ?>" autocomplete="off">
+		<legend><?php echo Minz_Translate::t('informations'); ?></legend>
+		<?php if ($this->load_ok) { ?>
+		<div class="form-group">
+			<label class="group-name"><?php echo Minz_Translate::t('title'); ?></label>
+			<div class="group-controls">
+				<label><?php echo $this->feed->name() ; ?></label>
+			</div>
+		</div>
+
+		<?php $desc = $this->feed->description(); if ($desc != '') { ?>
+		<div class="form-group">
+			<label class="group-name"><?php echo Minz_Translate::t('feed_description'); ?></label>
+			<div class="group-controls">
+				<label><?php echo htmlspecialchars($desc, ENT_NOQUOTES, 'UTF-8'); ?></label>
+			</div>
+		</div>
+		<?php } ?>
+
+		<div class="form-group">
+			<label class="group-name"><?php echo Minz_Translate::t('website_url'); ?></label>
+			<div class="group-controls">
+				<?php echo $this->feed->website(); ?>
+				<a class="btn" target="_blank" href="<?php echo $this->feed->website(); ?>"><?php echo FreshRSS_Themes::icon('link'); ?></a>
+			</div>
+		</div>
+		<?php } ?>
+
+		<div class="form-group">
+			<label class="group-name" for="url"><?php echo Minz_Translate::t('feed_url'); ?></label>
+			<div class="group-controls">
+				<div class="stick">
+					<input type="text" name="url_rss" id="url" class="extend" value="<?php echo $this->feed->url(); ?>" />
+					<a class="btn" target="_blank" href="<?php echo $this->feed->url(); ?>"><?php echo FreshRSS_Themes::icon('link'); ?></a>
+				</div>
+				<a class="btn" target="_blank" href="http://validator.w3.org/feed/check.cgi?url=<?php echo $this->feed->url(); ?>"><?php echo Minz_Translate::t('feed_validator'); ?></a>
+			</div>
+		</div>
+		<div class="form-group">
+			<label class="group-name" for="category"><?php echo Minz_Translate::t('category'); ?></label>
+			<div class="group-controls">
+				<select name="category" id="category">
+					<?php foreach ($this->categories as $cat) { ?>
+					<option value="<?php echo $cat->id(); ?>"<?php echo $cat->id() == 1 ? ' selected="selected"' : ''; ?>>
+						<?php echo $cat->name(); ?>
+					</option>
+					<?php } ?>
+					<option value="nc"><?php echo Minz_Translate::t('new_category'); ?></option>
+				</select>
+
+				<span style="display: none;">
+					<input type="text" name="new_category[name]" id="new_category_name" autocomplete="off" placeholder="<?php echo Minz_Translate::t('new_category'); ?>" />
+				</span>
+			</div>
+		</div>
+
+		<legend><?php echo Minz_Translate::t('http_authentication'); ?></legend>
+		<?php $auth = $this->feed->httpAuth(false); ?>
+		<div class="form-group">
+			<label class="group-name" for="http_user"><?php echo Minz_Translate::t('http_username'); ?></label>
+			<div class="group-controls">
+				<input type="text" name="http_user" id="http_user" class="extend" value="<?php echo $auth['username']; ?>" autocomplete="off" />
+			</div>
+
+			<label class="group-name" for="http_pass"><?php echo Minz_Translate::t('http_password'); ?></label>
+			<div class="group-controls">
+				<input type="password" name="http_pass" id="http_pass" class="extend" value="<?php echo $auth['password']; ?>" autocomplete="off" />
+			</div>
+
+			<div class="group-controls">
+				<?php echo FreshRSS_Themes::icon('help'); ?> <?php echo Minz_Translate::t('access_protected_feeds'); ?>
+			</div>
+		</div>
+
+		<div class="form-group form-actions">
+			<div class="group-controls">
+				<button type="submit" class="btn btn-important"><?php echo Minz_Translate::t('save'); ?></button>
+				<button type="reset" class="btn"><?php echo Minz_Translate::t('cancel'); ?></button>
+			</div>
+		</div>
+	</form>
+</div>
+<?php } ?>

+ 47 - 0
app/views/helpers/export/articles.phtml

@@ -0,0 +1,47 @@
+<?php
+    $username = Minz_Session::param('currentUser', '_');
+
+    $articles = array(
+        'id' => 'user/' . str_replace('/', '', $username) . '/state/org.freshrss/' . $this->type,
+        'title' => $this->list_title,
+        'author' => $username,
+        'items' => array()
+    );
+
+    foreach ($this->entries as $entry) {
+        if (!isset($this->feed)) {
+            $feed = FreshRSS_CategoryDAO::findFeed($this->categories, $entry->feed ());
+        } else {
+            $feed = $this->feed;
+        }
+
+        $articles['items'][] = array(
+            'id' => $entry->guid(),
+            'categories' => array_values($entry->tags()),
+            'title' => $entry->title(),
+            'author' => $entry->author(),
+            'published' => $entry->date(true),
+            'updated' => $entry->date(true),
+            'alternate' => array(array(
+                'href' => $entry->link(),
+                'type' => 'text/html'
+            )),
+            'content' => array(
+                'content' => $entry->content()
+            ),
+            'origin' => array(
+                'streamId' => $feed->id(),
+                'title' => $feed->name(),
+                'htmlUrl' => $feed->website(),
+                'feedUrl' => $feed->url()
+            )
+        );
+    }
+
+    $options = 0;
+    if (version_compare(PHP_VERSION, '5.4.0') >= 0) {
+        $options = JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE;
+    }
+
+    echo json_encode($articles, $options);
+?>

+ 28 - 0
app/views/helpers/export/opml.phtml

@@ -0,0 +1,28 @@
+<?php
+
+$opml_array = array(
+	'head' => array(
+		'title' => Minz_Configuration::title(),
+		'dateCreated' => date('D, d M Y H:i:s')
+	),
+	'body' => array()
+);
+
+foreach ($this->categories as $key => $cat) {
+	$opml_array['body'][$key] = array(
+		'text' => $cat['name'],
+		'@outlines' => array()
+	);
+
+	foreach ($cat['feeds'] as $feed) {
+		$opml_array['body'][$key]['@outlines'][] = array(
+			'text' => htmlspecialchars_decode($feed->name()),
+			'type' => 'rss',
+			'xmlUrl' => htmlspecialchars_decode($feed->url()),
+			'htmlUrl' => htmlspecialchars_decode($feed->website()),
+			'description' => htmlspecialchars_decode($feed->description()),
+		);
+	}
+}
+
+echo libopml_render($opml_array);

+ 14 - 5
app/views/helpers/javascript_vars.phtml

@@ -4,13 +4,15 @@ echo '"use strict";', "\n";
 
 $mark = $this->conf->mark_when;
 echo 'var ',
-	'hide_posts=', ($this->conf->display_posts || Minz_Request::param('output') === 'reader') ? 'false' : 'true',
+	'help_url="', FRESHRSS_WIKI, '"',
+	',hide_posts=', ($this->conf->display_posts || Minz_Request::param('output') === 'reader') ? 'false' : 'true',
+	',display_order="', Minz_Request::param('order', $this->conf->sort_order), '"',
 	',auto_mark_article=', $mark['article'] ? 'true' : 'false',
 	',auto_mark_site=', $mark['site'] ? 'true' : 'false',
 	',auto_mark_scroll=', $mark['scroll'] ? 'true' : 'false',
 	',auto_load_more=', $this->conf->auto_load_more ? 'true' : 'false',
-	',full_lazyload=', $this->conf->lazyload && ($this->conf->display_posts || Minz_Request::param('output') === 'reader') ? 'true' : 'false',
-	',does_lazyload=', $this->conf->lazyload ? 'true' : 'false';
+	',does_lazyload=', $this->conf->lazyload ? 'true' : 'false',
+	',sticky_post=', $this->conf->sticky_post ? 'true' : 'false';
 
 $s = $this->conf->shortcuts;
 echo ',shortcuts={',
@@ -23,7 +25,10 @@ echo ',shortcuts={',
 	'last_entry:"', $s['last_entry'], '",',
 	'collapse_entry:"', $s['collapse_entry'], '",',
 	'load_more:"', $s['load_more'], '",',
-	'auto_share:"', $s['auto_share'], '"',
+	'auto_share:"', $s['auto_share'], '",',
+	'focus_search:"', $s['focus_search'], '",',
+	'user_filter:"', $s['user_filter'], '",',
+	'help:"', $s['help'], '"',
 "},\n";
 
 if (Minz_Request::param ('output') === 'global') {
@@ -46,7 +51,11 @@ echo 'authType="', $authType, '",',
 	'url_login="', _url ('index', 'login'), '",',
 	'url_logout="', _url ('index', 'logout'), '",';
 
-echo 'str_confirmation="', Minz_Translate::t('confirm_action'), '"', ",\n";
+echo 'str_confirmation_default="', Minz_Translate::t('confirm_action'), '"', ",\n";
+echo 'str_notif_title_articles="', Minz_Translate::t('notif_title_new_articles'), '"', ",\n";
+echo 'str_notif_body_articles="', Minz_Translate::t('notif_body_new_articles'), '"', ",\n";
+echo 'html5_notif_timeout=', $this->conf->html5_notif_timeout,",\n";
+
 
 $autoActualise = Minz_Session::param('actualize_feeds', false);
 echo 'auto_actualize_feeds=', $autoActualise ? 'true' : 'false', ";\n";

+ 26 - 15
app/views/helpers/pagination.phtml

@@ -1,26 +1,37 @@
 <?php
-	$c = Minz_Request::controllerName ();
-	$a = Minz_Request::actionName ();
-	$params = Minz_Request::params ();
-	$markReadUrl = Minz_Session::param ('markReadUrl');
-	Minz_Session::_param ('markReadUrl', false);
+	$c = Minz_Request::controllerName();
+	$a = Minz_Request::actionName();
+	$params = Minz_Request::params();
+	$markReadUrl = Minz_Session::param('markReadUrl');
+	Minz_Session::_param('markReadUrl', false);
 ?>
 
+<form id="mark-read-pagination" method="post" style="display: none"></form>
+
 <ul class="pagination">
 	<li class="item pager-next">
 	<?php if (!empty($this->nextId)) { ?>
-	<?php $params['next'] = $this->nextId; ?>
-	<a id="load_more" href="<?php echo Minz_Url::display (array ('c' => $c, 'a' => $a, 'params' => $params)); ?>"><?php echo Minz_Translate::t ('load_more'); ?></a>
+		<?php
+			$params['next'] = $this->nextId;
+			$params['ajax'] = 1;
+		?>
+		<a id="load_more" href="<?php echo Minz_Url::display(array('c' => $c, 'a' => $a, 'params' => $params)); ?>">
+			<?php echo _t('load_more'); ?>
+		</a>
 	<?php } elseif ($markReadUrl) { ?>
-	<a id="bigMarkAsRead" href="<?php echo $markReadUrl; ?>">
-		<?php echo Minz_Translate::t ('nothing_to_load'); ?><br />
-		<span class="bigTick">✔</span><br />
-		<?php echo Minz_Translate::t ('mark_all_read'); ?>
-	</a>
+		<button id="bigMarkAsRead"
+		        class="as-link <?php echo $this->conf->reading_confirm ? 'confirm' : ''; ?>"
+		        form="mark-read-pagination"
+		        formaction="<?php echo $markReadUrl; ?>"
+		        type="submit">
+			<?php echo _t('nothing_to_load'); ?><br />
+			<span class="bigTick">✓</span><br />
+			<?php echo _t('mark_all_read'); ?>
+		</button>
 	<?php } else { ?>
-	<a id="bigMarkAsRead" href=".">
-		<?php echo Minz_Translate::t ('nothing_to_load'); ?><br />
-	</a>
+		<a id="bigMarkAsRead" href=".">
+			<?php echo _t('nothing_to_load'); ?><br />
+		</a>
 	<?php } ?>
 	</li>
 </ul>

+ 8 - 0
app/views/helpers/view/global_view.phtml

@@ -1,5 +1,6 @@
 <?php $this->partial ('nav_menu'); ?>
 
+<?php if (!empty($this->entries)) { ?>
 <div id="stream" class="global categories">
 <?php
 	$arUrl = array('c' => 'index', 'a' => 'index', 'params' => array());
@@ -43,3 +44,10 @@
 <div id="panel"<?php echo $this->conf->display_posts ? '' : ' class="hide_posts"'; ?>>
 	<a class="close" href="#"><?php echo FreshRSS_Themes::icon('close'); ?></a>
 </div>
+
+<?php } else { ?>
+<div id="stream" class="prompt alert alert-warn global">
+	<h2><?php echo _t('no_feed_to_display'); ?></h2>
+	<a href="<?php echo _url('configure', 'feed'); ?>"><?php echo _t('think_to_add'); ?></a><br /><br />
+</div>
+<?php } ?>

+ 27 - 77
app/views/helpers/view/normal_view.phtml

@@ -8,19 +8,10 @@ if (!empty($this->entries)) {
 	$display_yesterday = true;
 	$display_others = true;
 	if ($this->loginOk) {
-		$shaarli = $this->conf->sharing ('shaarli');
-		$wallabag = $this->conf->sharing ('wallabag');
-		$diaspora = $this->conf->sharing ('diaspora');
+		$sharing = $this->conf->sharing;
 	} else {
-		$shaarli = '';
-		$wallabag = '';
-		$diaspora = '';
+		$sharing = array();
 	}
-	$twitter = $this->conf->sharing ('twitter');
-	$google_plus = $this->conf->sharing ('g+');
-	$facebook = $this->conf->sharing ('facebook');
-	$email = $this->conf->sharing ('email');
-	$print = $this->conf->sharing ('print');
 	$hidePosts = !$this->conf->display_posts;
 	$lazyload = $this->conf->lazyload;
 	$topline_read = $this->conf->topline_read;
@@ -29,17 +20,17 @@ if (!empty($this->entries)) {
 	$topline_link = $this->conf->topline_link;
 	$bottomline_read = $this->conf->bottomline_read;
 	$bottomline_favorite = $this->conf->bottomline_favorite;
-	$bottomline_sharing = $this->conf->bottomline_sharing && (
-		$shaarli || $wallabag || $diaspora || $twitter ||
-		$google_plus || $facebook || $email || $print);
+	$bottomline_sharing = $this->conf->bottomline_sharing && (count($sharing));
 	$bottomline_tags = $this->conf->bottomline_tags;
 	$bottomline_date = $this->conf->bottomline_date;
 	$bottomline_link = $this->conf->bottomline_link;
+
+	$content_width = $this->conf->content_width;
 ?>
 
 <div id="stream" class="normal<?php echo $hidePosts ? ' hide_posts' : ''; ?>"><?php
 	?><div id="new-article">
-		<a href="<?php echo _url('index', 'index'); ?>"><?php echo Minz_Translate::t ('new_article'); ?></a>
+		<a href="<?php echo Minz_Url::display ($this->url); ?>"><?php echo Minz_Translate::t ('new_article'); ?></a>
 	</div><?php
 	foreach ($this->entries as $item) {
 		if ($display_today && $item->isDay (FreshRSS_Days::TODAY, $this->today)) {
@@ -90,7 +81,12 @@ if (!empty($this->entries)) {
 				}
 			}
 			$feed = FreshRSS_CategoryDAO::findFeed($this->cat_aside, $item->feed ());	//We most likely already have the feed object in cache
-			if (empty($feed)) $feed = $item->feed (true);
+			if ($feed == null) {
+				$feed = $item->feed(true);
+				if ($feed == null) {
+					$feed = FreshRSS_Feed::example();
+				}
+			}
 			?><li class="item website"><a href="<?php echo _url ('index', 'index', 'get', 'f_' . $feed->id ()); ?>"><img class="favicon" src="<?php echo $feed->favicon (); ?>" alt="✇" /> <span><?php echo $feed->name(); ?></span></a></li>
 			<li class="item title"><a target="_blank" href="<?php echo $item->link (); ?>"><?php echo $item->title (); ?></a></li>
 			<?php if ($topline_date) { ?><li class="item date"><?php echo $item->date (); ?> </li><?php } ?>
@@ -98,16 +94,12 @@ if (!empty($this->entries)) {
 		</ul>
 
 		<div class="flux_content">
-			<div class="content">
-				<h1 class="title"><?php echo $item->title (); ?></h1>
+			<div class="content <?php echo $content_width; ?>">
+				<h1 class="title"><a target="_blank" href="<?php echo $item->link (); ?>"><?php echo $item->title (); ?></a></h1>
 				<?php
-					$author = $item->author ();
-					echo $author != '' ? '<div class="author">' . Minz_Translate::t ('by_author', $author) . '</div>' : '';
-					if ($lazyload) {
-						echo $hidePosts ? lazyIframe(lazyimg($item->content())) : lazyimg($item->content());
-					} else {
-						echo $item->content();
-					}
+					$author = $item->author();
+					echo $author != '' ? '<div class="author">' . Minz_Translate::t('by_author', $author) . '</div>' : '',
+						$lazyload && $hidePosts ? lazyimg($item->content()) : $item->content();
 				?>
 			</div>
 			<ul class="horizontal-list bottom"><?php
@@ -146,55 +138,13 @@ if (!empty($this->entries)) {
 
 						<ul class="dropdown-menu">
 							<li class="dropdown-close"><a href="#close">❌</a></li>
-							<?php if ($shaarli) { ?>
-							<li class="item share">
-								<a target="_blank" href="<?php echo $shaarli . '?post=' . $link . '&amp;title=' . $title . '&amp;source=FreshRSS'; ?>">
-									<?php echo Minz_Translate::t ('shaarli'); ?>
-								</a>
-							</li>
-							<?php } if ($wallabag) { ?>
-							<li class="item share">
-								<a target="_blank" href="<?php echo $wallabag . '?action=add&amp;url=' . base64_encode (urldecode($link)); ?>">
-									<?php echo Minz_Translate::t ('wallabag'); ?>
-								</a>
-							</li>
-							<?php } if ($diaspora) { ?>
-							<li class="item share">
-								<a target="_blank" href="<?php echo $diaspora . '/bookmarklet?url=' . $link . '&amp;title=' . $title; ?>">
-									<?php echo Minz_Translate::t ('diaspora'); ?>
-								</a>
-							</li>
-							<?php } if ($twitter) { ?>
-							<li class="item share">
-								<a target="_blank" href="https://twitter.com/share?url=<?php echo $link; ?>&amp;text=<?php echo $title; ?>">
-									<?php echo Minz_Translate::t ('twitter'); ?>
-								</a>
-							</li>
-							<?php } if ($google_plus) { ?>
-							<li class="item share">
-								<a target="_blank" href="https://plus.google.com/share?url=<?php echo $link; ?>">
-									<?php echo Minz_Translate::t ('g+'); ?>
-								</a>
-							</li>
-							<?php } if ($facebook) { ?>
-							<li class="item share">
-								<a target="_blank" href="https://www.facebook.com/sharer.php?u=<?php echo $link; ?>&amp;t=<?php echo $title; ?>">
-									<?php echo Minz_Translate::t ('facebook'); ?>
-								</a>
-							</li>
-							<?php } if ($email) { ?>
-							<li class="item share">
-								<a href="mailto:?subject=<?php echo urldecode($title); ?>&amp;body=<?php echo $link; ?>">
-									<?php echo Minz_Translate::t ('by_email'); ?>
-								</a>
-							</li>
-							<?php } if ($print) { ?>
-							<li class="item share">
-								<a href="#" class="print-article">
-									<?php echo Minz_Translate::t ('print'); ?>
-								</a>
-							</li>
-							<?php } ?>
+							<?php foreach ($sharing as $share) :?>
+								<li class="item share">
+									<a target="_blank" href="<?php echo FreshRSS_Share::generateUrl($this->conf->shares, $share, $item->link(), $item->title() . ' . ' . $feed->name())?>">
+										<?php echo Minz_Translate::t ($share['name']);?>
+									</a>
+								</li>
+							<?php endforeach;?>
 						</ul>
 					</div>
 					<?php } ?>
@@ -233,8 +183,8 @@ if (!empty($this->entries)) {
 <?php $this->partial ('nav_entries'); ?>
 
 <?php } else { ?>
-<div id="stream" class="alert alert-warn normal">
-	<span class="alert-head"><?php echo Minz_Translate::t ('no_feed_to_display'); ?></span>
-	<?php echo Minz_Translate::t ('think_to_add'); ?>
+<div id="stream" class="prompt alert alert-warn normal">
+	<h2><?php echo _t('no_feed_to_display'); ?></h2>
+	<a href="<?php echo _url('configure', 'feed'); ?>"><?php echo _t('think_to_add'); ?></a><br /><br />
 </div>
 <?php } ?>

+ 11 - 16
app/views/helpers/view/reader_view.phtml

@@ -3,6 +3,7 @@ $this->partial ('nav_menu');
 
 if (!empty($this->entries)) {
 	$lazyload = $this->conf->lazyload;
+	$content_width = $this->conf->content_width;
 ?>
 
 <div id="stream" class="reader">
@@ -10,7 +11,7 @@ if (!empty($this->entries)) {
 
 	<div class="flux<?php echo !$item->isRead () ? ' not_read' : ''; ?><?php echo $item->isFavorite () ? ' favorite' : ''; ?>" id="flux_<?php echo $item->id (); ?>">
 		<div class="flux_content">
-			<div class="content">
+			<div class="content <?php echo $content_width; ?>">
 				<?php
 					$feed = FreshRSS_CategoryDAO::findFeed($this->cat_aside, $item->feed ());	//We most likely already have the feed object in cache
 					if (empty($feed)) $feed = $item->feed (true);
@@ -20,19 +21,13 @@ if (!empty($this->entries)) {
 				</a>
 				<h1 class="title"><?php echo $item->title (); ?></h1>
 
-				<div class="author">
-					<?php $author = $item->author (); ?>
-					<?php echo $author != '' ? Minz_Translate::t ('by_author', $author) . ' — ' : ''; ?>
-					<?php echo $item->date (); ?>
-				</div>
+				<div class="author"><?php
+					$author = $item->author();
+					echo $author != '' ? Minz_Translate::t('by_author', $author) . ' — ' : '',
+						$item->date();
+				?></div>
 
-				<?php
-					if ($lazyload) {
-						echo lazyimg($item->content ());
-					} else {
-						echo $item->content();
-					}
-				?>
+				<?php echo $item->content(); ?>
 			</div>
 		</div>
 	</div>
@@ -42,8 +37,8 @@ if (!empty($this->entries)) {
 </div>
 
 <?php } else { ?>
-<div id="stream" class="alert alert-warn reader">
-	<span class="alert-head"><?php echo Minz_Translate::t ('no_feed_to_display'); ?></span>
-	<?php echo Minz_Translate::t ('think_to_add'); ?>
+<div id="stream" class="prompt alert alert-warn reader">
+	<h2><?php echo _t('no_feed_to_display'); ?></h2>
+	<a href="<?php echo _url('configure', 'feed'); ?>"><?php echo _t('think_to_add'); ?></a><br /><br />
 </div>
 <?php } ?>

+ 1 - 1
app/views/helpers/view/rss_view.phtml

@@ -6,7 +6,7 @@
 		<description><?php echo Minz_Translate::t ('rss_feeds_of', $this->rss_title); ?></description>
 		<pubDate><?php echo date('D, d M Y H:i:s O'); ?></pubDate>
 		<lastBuildDate><?php echo gmdate('D, d M Y H:i:s'); ?> GMT</lastBuildDate>
-		<atom:link href="<?php echo Minz_Url::display ($this->rss_url, 'html', true); ?>" rel="self" type="application/rss+xml" />
+		<atom:link href="<?php echo Minz_Url::display ($this->url, 'html', true); ?>" rel="self" type="application/rss+xml" />
 <?php
 foreach ($this->entries as $item) {
 ?>

+ 0 - 0
app/views/importExport/export.phtml


+ 61 - 0
app/views/importExport/index.phtml

@@ -0,0 +1,61 @@
+<?php $this->partial('aside_feed'); ?>
+
+<div class="post ">
+	<a href="<?php echo _url('index', 'index'); ?>"><?php echo _t('back_to_rss_feeds'); ?></a>
+
+	<form method="post" action="<?php echo _url('importExport', 'import'); ?>" enctype="multipart/form-data">
+		<legend><?php echo _t('import'); ?></legend>
+		<div class="form-group">
+			<label class="group-name" for="file">
+				<?php echo extension_loaded('zip') ? _t('file_to_import') : _t('file_to_import_no_zip'); ?>
+			</label>
+			<div class="group-controls">
+				<input type="file" name="file" id="file" />
+			</div>
+		</div>
+
+		<div class="form-group form-actions">
+			<div class="group-controls">
+				<button type="submit" class="btn btn-important"><?php echo _t('import'); ?></button>
+			</div>
+		</div>
+	</form>
+
+	<?php if (count($this->feeds) > 0) { ?>
+	<form method="post" action="<?php echo _url('importExport', 'export'); ?>">
+		<legend><?php echo _t('export'); ?></legend>
+		<div class="form-group">
+			<div class="group-controls">
+				<label class="checkbox" for="export_opml">
+					<input type="checkbox" name="export_opml" id="export_opml" value="1" checked="checked" />
+					<?php echo _t('export_opml'); ?>
+				</label>
+
+				<label class="checkbox" for="export_starred">
+					<input type="checkbox" name="export_starred" id="export_starred" value="1" <?php echo extension_loaded('zip') ? 'checked="checked"' : ''; ?> />
+					<?php echo _t('export_starred'); ?>
+				</label>
+
+				<?php
+					$select_args = '';
+					if (extension_loaded('zip')) {
+						$select_args = ' size="' . min(10, count($this->feeds)) .'" multiple="multiple"';
+					}
+				?>
+				<select name="export_feeds[]"<?php echo $select_args; ?>>
+					<?php echo extension_loaded('zip') ? '' : '<option></option>'; ?>
+					<?php foreach ($this->feeds as $feed) { ?>
+					<option value="<?php echo $feed->id(); ?>"><?php echo $feed->name(); ?></option>
+					<?php } ?>
+				</select>
+			</div>
+		</div>
+
+		<div class="form-group form-actions">
+			<div class="group-controls">
+				<button type="submit" class="btn btn-important"><?php echo _t('export'); ?></button>
+			</div>
+		</div>
+	</form>
+	<?php } ?>
+</div>

+ 23 - 9
app/views/index/formLogin.phtml

@@ -1,32 +1,46 @@
 <div class="prompt">
-	<h1><?php echo Minz_Translate::t('login'); ?></h1><?php
+	<h1><?php echo _t('login'); ?></h1><?php
 
 	switch (Minz_Configuration::authType()) {
 	case 'form':
-	?><form id="loginForm" method="post" action="<?php echo _url('index', 'formLogin'); ?>">
+	?><form id="crypto-form" method="post" action="<?php echo _url('index', 'formLogin'); ?>">
 		<div>
-			<label for="username"><?php echo Minz_Translate::t('username'); ?></label>
+			<label for="username"><?php echo _t('username'); ?></label>
 			<input type="text" id="username" name="username" size="16" required="required" maxlength="16" pattern="[0-9a-zA-Z]{1,16}" autofocus="autofocus" />
 		</div>
 		<div>
-			<label for="passwordPlain"><?php echo Minz_Translate::t('password'); ?></label>
+			<label for="passwordPlain"><?php echo _t('password'); ?></label>
 				<input type="password" id="passwordPlain" required="required" />
 				<input type="hidden" id="challenge" name="challenge" /><br />
-				<noscript><strong><?php echo Minz_Translate::t('javascript_should_be_activated'); ?></strong></noscript>
+				<noscript><strong><?php echo _t('javascript_should_be_activated'); ?></strong></noscript>
 		</div>
 		<div>
-			<button id="loginButton" type="submit" class="btn btn-important"><?php echo Minz_Translate::t('login'); ?></button>
+			<label class="checkbox" for="keep_logged_in">
+				<input type="checkbox" name="keep_logged_in" id="keep_logged_in" value="1" />
+				<?php echo _t('keep_logged_in'); ?>
+			</label>
+			<br />
+		</div>
+		<div>
+			<button id="loginButton" type="submit" class="btn btn-important"><?php echo _t('login'); ?></button>
 		</div>
 	</form><?php
 		break;
 
 	case 'persona':
 		?><p>
-			<?php echo FreshRSS_Themes::icon('login'); ?>
-			<a class="signin" href="#"><?php echo Minz_Translate::t('login_with_persona'); ?></a>
+			<a class="signin btn btn-important" href="#">
+				<?php echo _i('login'); ?>
+				<?php echo _t('login_with_persona'); ?>
+			</a><br /><br />
+
+			<?php echo _i('help'); ?>
+			<small>
+				<a href="<?php echo _url('index', 'resetAuth'); ?>"><?php echo _t('login_persona_problem'); ?></a>
+			</small>
 		</p><?php
 		break;
 	} ?>
 
-	<p><a href="<?php echo _url('index', 'about'); ?>"><?php echo Minz_Translate::t('about_freshrss'); ?></a></p>
+	<p><a href="<?php echo _url('index', 'about'); ?>"><?php echo _t('about_freshrss'); ?></a></p>
 </div>

+ 33 - 0
app/views/index/resetAuth.phtml

@@ -0,0 +1,33 @@
+<div class="prompt">
+	<h1><?php echo _t('auth_reset'); ?></h1>
+
+	<?php if (!empty($this->message)) { ?>
+	<p class="alert <?php echo $this->message['status'] === 'bad' ? 'alert-error' : 'alert-warn'; ?>">
+		<span class="alert-head"><?php echo $this->message['title']; ?></span><br />
+		<?php echo $this->message['body']; ?>
+	</p>
+	<?php } ?>
+
+	<?php if (!$this->no_form) { ?>
+	<form id="crypto-form" method="post" action="<?php echo _url('index', 'resetAuth'); ?>">
+		<p class="alert alert-warn">
+			<span class="alert-head"><?php echo _t('attention'); ?></span><br />
+			<?php echo _t('auth_will_reset'); ?>
+		</p>
+
+		<div>
+			<label for="username"><?php echo _t('username_admin'); ?></label>
+			<input type="text" id="username" name="username" size="16" required="required" maxlength="16" pattern="[0-9a-zA-Z]{1,16}" autofocus="autofocus" />
+		</div>
+		<div>
+			<label for="passwordPlain"><?php echo _t('password'); ?></label>
+				<input type="password" id="passwordPlain" required="required" />
+				<input type="hidden" id="challenge" name="challenge" /><br />
+				<noscript><strong><?php echo _t('javascript_should_be_activated'); ?></strong></noscript>
+		</div>
+		<div>
+			<button id="loginButton" type="submit" class="btn btn-important"><?php echo _t('submit'); ?></button>
+		</div>
+	</form>
+	<?php } ?>
+</div>

+ 14 - 13
app/views/javascript/actualize.phtml

@@ -1,30 +1,30 @@
 "use strict";
-var feeds = [<?php
-	foreach ($this->feeds as $feed) {
-		echo "'", Minz_Url::display(array('c' => 'feed', 'a' => 'actualize', 'params' => array('id' => $feed->id(), 'ajax' => '1')), 'php'), "',\n";
-	}
-	?>],
+var feeds = [<?php foreach ($this->feeds as $feed) { ?>{<?php
+	?>url: "<?php echo Minz_Url::display(array('c' => 'feed', 'a' => 'actualize', 'params' => array('id' => $feed->id(), 'ajax' => '1')), 'php'); ?>",<?php
+	?>title: "<?php echo $feed->name(); ?>"<?php
+?>},<?php } ?>],
 	feed_processed = 0,
 	feed_count = feeds.length;
 
 function initProgressBar(init) {
 	if (init) {
-		$("body").after("\<div id=\"actualizeProgress\" class=\"actualizeProgress\">\
-			<?php echo Minz_Translate::t ('refresh'); ?> <span class=\"progress\">0 / " + feed_count + "</span><br />\
-			<progress id=\"actualizeProgressBar\" value=\"0\" max=\"" + feed_count + "\"></progress>\
+		$("body").after("\<div id=\"actualizeProgress\" class=\"notification good\">\
+			<?php echo _t('refresh'); ?><br /><span class=\"title\">/</span><br />\
+			<span class=\"progress\">0 / " + feed_count + "</span>\
 		</div>");
 	} else {
 		window.location.reload();
 	}
 }
-function updateProgressBar(i) {
-	$("#actualizeProgressBar").val(i);
+function updateProgressBar(i, title_feed) {
 	$("#actualizeProgress .progress").html(i + " / " + feed_count);
+	$("#actualizeProgress .title").html(title_feed);
 }
 
 function updateFeeds() {
 	if (feed_count === 0) {
-		openNotification("<?php echo Minz_Translate::t ('no_feed_to_refresh'); ?>", "good");
+		openNotification("<?php echo _t('no_feed_to_refresh'); ?>", "good");
+		ajax_loading = false;
 		return;
 	}
 	initProgressBar(true);
@@ -39,12 +39,13 @@ function updateFeed() {
 	if (feed == undefined) {
 		return;
 	}
+
 	$.ajax({
 		type: 'POST',
-		url: feed,
+		url: feed['url'],
 	}).complete(function (data) {
 		feed_processed++;
-		updateProgressBar(feed_processed);
+		updateProgressBar(feed_processed, feed['title']);
 
 		if (feed_processed === feed_count) {
 			initProgressBar(false);

+ 48 - 0
app/views/stats/idle.phtml

@@ -0,0 +1,48 @@
+<?php $this->partial('aside_stats'); ?>
+
+<div class="post">
+	<a href="<?php echo _url('index', 'index'); ?>"><?php echo _t('back_to_rss_feeds'); ?></a>
+
+	<h1><?php echo _t('stats_idle'); ?></h1>
+
+	<?php
+		$current_url = urlencode(Minz_Url::display(
+			array('c' => 'stats', 'a' => 'idle'),
+			'php', true
+		));
+		$nothing = true;
+		foreach ($this->idleFeeds as $period => $feeds) {
+			if (!empty($feeds)) {
+				$nothing = false;
+	?>
+		<div class="stat">
+			<h2><?php echo _t($period); ?></h2>
+
+			<form id="form-delete" method="post" style="display: none"></form>
+
+			<?php foreach ($feeds as $feed) { ?>
+			<ul class="horizontal-list">
+				<li class="item">
+					<div class="stick">
+						<a class="btn" href="<?php echo _url('index', 'index', 'get', 'f_' . $feed['id']); ?>"><?php echo _i('link'); ?> <?php echo _t('filter'); ?></a>
+						<a class="btn" href="<?php echo _url('configure', 'feed', 'id', $feed['id']); ?>"><?php echo _i('configure'); ?> <?php echo _t('administration'); ?></a>
+						<button class="btn btn-attention confirm" form="form-delete" formaction="<?php echo _url('feed', 'delete', 'id', $feed['id'], 'r', $current_url); ?>"><?php echo _t('delete'); ?></button>
+					</div>
+				</li>
+				<li class="item">
+					<span title="<?php echo timestamptodate($feed['last_date'], false); ?>"><?php echo $feed['name']; ?> (<?php echo _t('number_articles', $feed['nb_articles']); ?>)</span>
+				</li>
+			</ul>
+			<?php } ?>
+		</div>
+	<?php
+			}
+		}
+
+		if ($nothing) {
+	?>
+	<p class="alert alert-warn">
+		<span class="alert-head"><?php echo _t('stats_no_idle'); ?></span>
+	</p>
+	<?php } ?>
+</div>

+ 40 - 38
app/views/index/stats.phtml → app/views/stats/index.phtml

@@ -1,74 +1,59 @@
-<div class="post content">
-	<a href="<?php echo _url ('index', 'index'); ?>"><?php echo Minz_Translate::t ('back_to_rss_feeds'); ?></a>
-	
-	<h1><?php echo Minz_Translate::t ('stats'); ?></h1>
-	
-	<div class="stat">
-		<h2><?php echo Minz_Translate::t ('stats_entry_repartition'); ?></h2>
+<?php $this->partial('aside_stats'); ?>
+
+<div class="post">
+	<a href="<?php echo _url ('index', 'index'); ?>"><?php echo _t ('back_to_rss_feeds'); ?></a>
+
+	<h1><?php echo _t ('stats_main'); ?></h1>
+
+	<div class="stat half">
+		<h2><?php echo _t ('stats_entry_repartition'); ?></h2>
 		<table>
 			<thead>
 				<tr>
 					<th> </th>
-					<th><?php echo Minz_Translate::t ('main_stream'); ?></th>
-					<th><?php echo Minz_Translate::t ('all_feeds'); ?></th>
+					<th><?php echo _t ('main_stream'); ?></th>
+					<th><?php echo _t ('all_feeds'); ?></th>
 				</tr>
 			</thead>
 			<tbody>
 				<tr>
-					<th><?php echo Minz_Translate::t ('status_total'); ?></th>
+					<th><?php echo _t ('status_total'); ?></th>
 					<td class="numeric"><?php echo formatNumber($this->repartition['main_stream']['total']); ?></td>
 					<td class="numeric"><?php echo formatNumber($this->repartition['all_feeds']['total']); ?></td>
 				</tr>
 				<tr>
-					<th><?php echo Minz_Translate::t ('status_read'); ?></th>
+					<th><?php echo _t ('status_read'); ?></th>
 					<td class="numeric"><?php echo formatNumber($this->repartition['main_stream']['read']); ?></td>
 					<td class="numeric"><?php echo formatNumber($this->repartition['all_feeds']['read']); ?></td>
 				</tr>
 				<tr>
-					<th><?php echo Minz_Translate::t ('status_unread'); ?></th>
+					<th><?php echo _t ('status_unread'); ?></th>
 					<td class="numeric"><?php echo formatNumber($this->repartition['main_stream']['unread']); ?></td>
 					<td class="numeric"><?php echo formatNumber($this->repartition['all_feeds']['unread']); ?></td>
 				</tr>
 				<tr>
-					<th><?php echo Minz_Translate::t ('status_favorites'); ?></th>
+					<th><?php echo _t ('status_favorites'); ?></th>
 					<td class="numeric"><?php echo formatNumber($this->repartition['main_stream']['favorite']); ?></td>
 					<td class="numeric"><?php echo formatNumber($this->repartition['all_feeds']['favorite']); ?></td>
 				</tr>
 			</tbody>
 		</table>
-	</div>
-	
-	<div class="stat">
-		<h2><?php echo Minz_Translate::t ('stats_entry_per_day'); ?></h2>
-		<div id="statsEntryPerDay" style="height: 300px"></div>
-	</div>
-	
-	<div class="stat">
-		<h2><?php echo Minz_Translate::t ('stats_feed_per_category'); ?></h2>
-		<div id="statsFeedPerCategory" style="height: 300px"></div>
-		<div id="statsFeedPerCategoryLegend"></div>
-	</div>
-	
-	<div class="stat">
-		<h2><?php echo Minz_Translate::t ('stats_entry_per_category'); ?></h2>
-		<div id="statsEntryPerCategory" style="height: 300px"></div>
-		<div id="statsEntryPerCategoryLegend"></div>
-	</div>
-	
-	<div class="stat">
-		<h2><?php echo Minz_Translate::t ('stats_top_feed'); ?></h2>
+	</div><!--
+
+	--><div class="stat half">
+		<h2><?php echo _t ('stats_top_feed'); ?></h2>
 		<table>
 			<thead>
 				<tr>
-					<th><?php echo Minz_Translate::t ('feed'); ?></th>
-					<th><?php echo Minz_Translate::t ('category'); ?></th>
-					<th><?php echo Minz_Translate::t ('stats_entry_count'); ?></th>
+					<th><?php echo _t ('feed'); ?></th>
+					<th><?php echo _t ('category'); ?></th>
+					<th><?php echo _t ('stats_entry_count'); ?></th>
 				</tr>
 			</thead>
 			<tbody>
 				<?php foreach ($this->topFeed as $feed): ?>
 					<tr>
-						<td><?php echo $feed['name']; ?></td>
+						<td><a href="<?php echo _url('stats', 'repartition', 'id', $feed['id']); ?>"><?php echo $feed['name']; ?></a></td>
 						<td><?php echo $feed['category']; ?></td>
 						<td class="numeric"><?php echo formatNumber($feed['count']); ?></td>
 					</tr>
@@ -76,6 +61,23 @@
 			</tbody>
 		</table>
 	</div>
+
+	<div class="stat">
+		<h2><?php echo _t ('stats_entry_per_day'); ?></h2>
+		<div id="statsEntryPerDay" style="height: 300px"></div>
+	</div>
+
+	<div class="stat half">
+		<h2><?php echo _t ('stats_feed_per_category'); ?></h2>
+		<div id="statsFeedPerCategory" style="height: 300px"></div>
+		<div id="statsFeedPerCategoryLegend"></div>
+	</div><!--
+
+	--><div class="stat half">
+		<h2><?php echo _t ('stats_entry_per_category'); ?></h2>
+		<div id="statsEntryPerCategory" style="height: 300px"></div>
+		<div id="statsEntryPerCategoryLegend"></div>
+	</div>
 </div>
 
 <script>

+ 150 - 0
app/views/stats/repartition.phtml

@@ -0,0 +1,150 @@
+<?php $this->partial('aside_stats'); ?>
+
+<div class="post ">
+	<a href="<?php echo _url('index', 'index'); ?>"><?php echo _t('back_to_rss_feeds'); ?></a>
+
+	<h1><?php echo _t('stats_repartition'); ?></h1>
+
+	<select id="feed_select">
+		<option data-url="<?php echo _url('stats', 'repartition')?>"><?php echo _t('all_feeds')?></option>
+	<?php foreach ($this->categories as $category) {
+		$feeds = $category->feeds();
+		if (!empty($feeds)) {
+			echo '<optgroup label="', $category->name(), '">';
+			foreach ($feeds as $feed) {
+				if ($this->feed && $feed->id() == $this->feed->id()){
+					echo '<option value="', $feed->id(), '" selected="selected" data-url="', _url('stats', 'repartition', 'id', $feed->id()), '">', $feed->name(), '</option>';
+				} else {
+					echo '<option value="', $feed->id(), '" data-url="', _url('stats', 'repartition', 'id', $feed->id()), '">', $feed->name(), '</option>';
+				}
+			}
+			echo '</optgroup>';
+		}
+	}?>
+	</select>
+
+	<?php if ($this->feed) {?>
+		<a class="btn" href="<?php echo _url('configure', 'feed', 'id', $this->feed->id()); ?>">
+			<?php echo _i('configure'); ?> <?php echo _t('administration'); ?>
+		</a>
+	<?php }?>
+
+	<div class="stat">
+		<h2><?php echo _t('stats_entry_per_hour'); ?></h2>
+		<div id="statsEntryPerHour" style="height: 300px"></div>
+	</div>
+
+	<div class="stat half">
+		<h2><?php echo _t('stats_entry_per_day_of_week'); ?></h2>
+		<div id="statsEntryPerDayOfWeek" style="height: 300px"></div>
+	</div><!--
+
+	--><div class="stat half">
+		<h2><?php echo _t('stats_entry_per_month'); ?></h2>
+		<div id="statsEntryPerMonth" style="height: 300px"></div>
+	</div>
+</div>
+
+<script>
+"use strict";
+function initStats() {
+	if (!window.Flotr) {
+		if (window.console) {
+			console.log('FreshRSS waiting for Flotr…');
+		}
+		window.setTimeout(initStats, 50);
+		return;
+	}
+	// Entry per hour
+	var avg_h = [];
+	for (var i = -1; i <= 24; i++) {
+		avg_h.push([i, <?php echo $this->averageHour?>]);
+	}
+	Flotr.draw(document.getElementById('statsEntryPerHour'),
+		[{
+			data: <?php echo $this->repartitionHour ?>,
+			bars: {horizontal: false, show: true}
+		}, {
+			data: avg_h,
+			lines: {show: true},
+			label: <?php echo $this->averageHour?>,
+			yaxis: 2
+		}],
+		{
+			grid: {verticalLines: false},
+			xaxis: {noTicks: 23,
+				tickFormatter: function(x) {
+					var x = parseInt(x);
+					return x + 1;
+				},
+				min: -0.9,
+				max: 23.9,
+				tickDecimals: 0},
+			yaxis: {min: 0},
+			y2axis: {showLabels: false},
+			mouse: {relative: true, track: true, trackDecimals: 0, trackFormatter: function(obj) {return numberFormat(obj.y);}}
+		});
+	// Entry per day of week
+	var avg_dow = [];
+	for (var i = -1; i <= 7; i++) {
+		avg_dow.push([i, <?php echo $this->averageDayOfWeek?>]);
+	}
+	Flotr.draw(document.getElementById('statsEntryPerDayOfWeek'),
+		[{
+			data: <?php echo $this->repartitionDayOfWeek ?>,
+			bars: {horizontal: false, show: true}
+		}, {
+			data: avg_dow,
+			lines: {show: true},
+			label: <?php echo $this->averageDayOfWeek?>,
+			yaxis: 2
+		}],
+		{
+			grid: {verticalLines: false},
+			xaxis: {noTicks: 6,
+				tickFormatter: function(x) {
+					var x = parseInt(x),
+					    days = <?php echo $this->days?>;
+					return days[x];
+				},
+				min: -0.9,
+				max: 6.9,
+				tickDecimals: 0},
+			yaxis: {min: 0},
+			y2axis: {showLabels: false},
+			mouse: {relative: true, track: true, trackDecimals: 0, trackFormatter: function(obj) {return numberFormat(obj.y);}}
+		});
+	// Entry per month
+	var avg_m = [];
+	for (var i = 0; i <= 13; i++) {
+		avg_m.push([i, <?php echo $this->averageMonth?>]);
+	}
+	Flotr.draw(document.getElementById('statsEntryPerMonth'),
+		[{
+			data: <?php echo $this->repartitionMonth ?>,
+			bars: {horizontal: false, show: true}
+		}, {
+			data: avg_m,
+			lines: {show: true},
+			label: <?php echo $this->averageMonth?>,
+			yaxis: 2
+		}],
+		{
+			grid: {verticalLines: false},
+			xaxis: {noTicks: 12,
+				tickFormatter: function(x) {
+					var x = parseInt(x),
+					    months = <?php echo $this->months?>;
+					return months[(x - 1)];
+				},
+				min: 0.1,
+				max: 12.9,
+				tickDecimals: 0},
+			yaxis: {min: 0},
+			y2axis: {showLabels: false},
+			mouse: {relative: true, track: true, trackDecimals: 0, trackFormatter: function(obj) {return numberFormat(obj.y);}}
+		});
+
+}
+initStats();
+</script>

+ 9 - 0
app/views/update/apply.phtml

@@ -0,0 +1,9 @@
+<?php $this->partial('aside_configure'); ?>
+
+<div class="post">
+	<a href="<?php echo _url('index', 'index'); ?>"><?php echo _t('back_to_rss_feeds'); ?></a>
+
+	<h1><?php echo _t('update_system'); ?></h1>
+
+	<?php ask_info_update(); ?>
+</div>

+ 36 - 0
app/views/update/index.phtml

@@ -0,0 +1,36 @@
+<?php $this->partial('aside_configure'); ?>
+
+<div class="post">
+	<a href="<?php echo _url('index', 'index'); ?>"><?php echo _t('back_to_rss_feeds'); ?></a>
+
+	<h1><?php echo _t('update_system'); ?></h1>
+
+	<p>
+		<?php echo _i('help'); ?> <?php echo _t('update_last', $this->last_update_time); ?>
+	</p>
+
+	<?php if (!empty($this->message)) { ?>
+	<p class="alert <?php echo $this->message['status'] === 'bad' ? 'alert-error' : 'alert-warn'; ?>">
+		<span class="alert-head"><?php echo $this->message['title']; ?></span>
+		<?php echo $this->message['body']; ?>
+	</p>
+	<?php } elseif ($this->check_last_hour) { ?>
+	<p class="alert alert-warn">
+		<span class="alert-head"><?php echo _t('damn'); ?></span>
+		<?php echo _t('no_update'); ?>
+	</p>
+	<?php } ?>
+
+	<?php
+		if (!$this->check_last_hour &&
+				(empty($this->message) || $this->message['status'] !== 'good')) {
+	?>
+	<p>
+		<a href="<?php echo _url('update', 'check'); ?>" class="btn"><?php echo _t('update_check'); ?></a>
+	</p>
+	<?php } ?>
+
+	<?php if ($this->update_to_apply) { ?>
+	<a class="btn btn-important" href="<?php echo _url('update', 'apply'); ?>"><?php echo _t('update_apply'); ?></a>
+	<?php } ?>
+</div>

+ 8 - 3
constants.php

@@ -1,6 +1,11 @@
 <?php
-define('FRESHRSS_VERSION', '0.7.1');
+define('FRESHRSS_VERSION', '0.8-dev');
 define('FRESHRSS_WEBSITE', 'http://freshrss.org');
+define('FRESHRSS_UPDATE_WEBSITE', 'https://update.freshrss.org?v=' . FRESHRSS_VERSION);
+define('FRESHRSS_WIKI', 'http://doc.freshrss.org');
+
+// PHP text output compression http://php.net/ob_gzhandler (better to do it at Web server level)
+define('PHP_COMPRESSION', false);
 
 // Constantes de chemins
 define('FRESHRSS_PATH', dirname(__FILE__));
@@ -10,11 +15,11 @@ define('FRESHRSS_PATH', dirname(__FILE__));
 		define('PUBLIC_RELATIVE', '..');
 
 	define('DATA_PATH', FRESHRSS_PATH . '/data');
+		define('UPDATE_FILENAME', DATA_PATH . '/update.php');
 		define('LOG_PATH', DATA_PATH . '/log');
 		define('CACHE_PATH', DATA_PATH . '/cache');
 
 	define('LIB_PATH', FRESHRSS_PATH . '/lib');
 		define('APP_PATH', FRESHRSS_PATH . '/app');
 
-//define('TMP_PATH', sys_get_temp_dir());  // need more tests so...
-define('TMP_PATH', DATA_PATH);  // ... we use DATA_PATH for the 0.7.1
+define('TMP_PATH', sys_get_temp_dir());

+ 2 - 0
data/.gitignore

@@ -6,3 +6,5 @@ touch.txt
 no-cache.txt
 *.bak.php
 *.lock.txt
+last_update.txt
+update.php

+ 0 - 0
data/do-install.txt


+ 75 - 0
data/shares.php

@@ -0,0 +1,75 @@
+<?php
+
+/*
+ * This is a configuration file. You shouldn't modify it unless you know what
+ * you are doing. If you want to add a share type, this is where you need to do
+ * it.
+ * 
+ * For each share there is different configuration options. Here is the description
+ * of those options:
+ *   - url is a mandatory option. It is a string representing the share URL. It
+ *     supports 3 different placeholders for custom data. The ~URL~ placeholder
+ *     represents the URL of the system used to share, it is configured by the
+ *     user. The ~LINK~ placeholder represents the link of the shared article.
+ *     The ~TITLE~ placeholder represents the title of the shared article.
+ *   - transform is an array of transformation to apply on links and titles
+ *   - help is a URL to a help page
+ */
+
+return array(
+	'shaarli' => array(
+		'url' => '~URL~?post=~LINK~&amp;title=~TITLE~&amp;source=FreshRSS',
+		'transform' => array('urlencode'),
+		'help' => 'http://sebsauvage.net/wiki/doku.php?id=php:shaarli',
+		'form' => 'advanced',
+	),
+	'blogotext' => array(
+		'url' => '~URL~/admin/links.php?url=~LINK~',
+		'transform' => array(),
+		'help' => 'http://lehollandaisvolant.net/blogotext/fr/',
+		'form' => 'advanced',
+	),
+	'wallabag' => array(
+		'url' => '~URL~?action=add&amp;url=~LINK~',
+		'transform' => array(
+			'link' => array('base64_encode'),
+			'title' => array(),
+		),
+		'help' => 'http://www.wallabag.org/',
+		'form' => 'advanced',
+	),
+	'diaspora' => array(
+		'url' => '~URL~/bookmarklet?url=~LINK~&amp;title=~TITLE~',
+		'transform' => array('urlencode'),
+		'help' => 'https://diasporafoundation.org/',
+		'form' => 'advanced',
+	),
+	'twitter' => array(
+		'url' => 'https://twitter.com/share?url=~LINK~&amp;text=~TITLE~',
+		'transform' => array('urlencode'),
+		'form' => 'simple',
+	),
+	'g+' => array(
+		'url' => 'https://plus.google.com/share?url=~LINK~',
+		'transform' => array('urlencode'),
+		'form' => 'simple',
+	),
+	'facebook' => array(
+		'url' => 'https://www.facebook.com/sharer.php?u=~LINK~&amp;t=~TITLE~',
+		'transform' => array('urlencode'),
+		'form' => 'simple',
+	),
+	'email' => array(
+		'url' => 'mailto:?subject=~TITLE~&amp;body=~LINK~',
+		'transform' => array(
+			'link' => array('urlencode'),
+			'title' => array(),
+		),
+		'form' => 'simple',
+	),
+	'print' => array(
+		'url' => '#',
+		'transform' => array(),
+		'form' => 'simple',
+	),
+);

+ 1 - 0
data/tokens/.gitignore

@@ -0,0 +1 @@
+*.txt

+ 13 - 0
data/tokens/index.html

@@ -0,0 +1,13 @@
+<!DOCTYPE html>
+<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-GB" lang="en-GB">
+<head>
+<meta charset="UTF-8" />
+<meta http-equiv="Refresh" content="0; url=/" />
+<title>Redirection</title>
+<meta name="robots" content="noindex" />
+</head>
+
+<body>
+<p><a href="/">Redirection</a></p>
+</body>
+</html>

+ 1 - 5
lib/Minz/ActionController.php

@@ -8,16 +8,12 @@
  * La classe ActionController représente le contrôleur de l'application
  */
 class Minz_ActionController {
-	protected $router;
 	protected $view;
 
 	/**
 	 * Constructeur
-	 * @param $controller nom du controller
-	 * @param $action nom de l'action à lancer
 	 */
-	public function __construct ($router) {
-		$this->router = $router;
+	public function __construct () {
 		$this->view = new Minz_View ();
 		$this->view->attributeParams ();
 	}

+ 0 - 116
lib/Minz/Cache.php

@@ -1,116 +0,0 @@
-<?php
-/** 
- * MINZ - Copyright 2011 Marien Fressinaud
- * Sous licence AGPL3 <http://www.gnu.org/licenses/>
-*/
-
-/**
- * La classe Cache permet de gérer facilement les pages en cache
- */
-class Minz_Cache {
-	/**
-	 * $expire timestamp auquel expire le cache de $url
-	 */
-	private $expire = 0;
-
-	/**
-	 * $file est le nom du fichier de cache
-	 */
-	private $file = '';
-
-	/**
-	 * $enabled permet de déterminer si le cache est activé
-	 */
-	private static $enabled = true;
-
-	/**
-	 * Constructeur
-	 */
-	public function __construct () {
-		$this->_fileName ();
-		$this->_expire ();
-	}
-
-	/**
-	 * Setteurs
-	 */
-	public function _fileName () {
-		$file = md5 (Minz_Request::getURI ());
-
-		$this->file = CACHE_PATH . '/'.$file;
-	}
-
-	public function _expire () {
-		if ($this->exist ()) {
-			$this->expire = filemtime ($this->file)
-			              + Minz_Configuration::delayCache ();
-		}
-	}
-
-	/**
-	 * Permet de savoir si le cache est activé
-	 * @return true si activé, false sinon
-	 */
-	public static function isEnabled () {
-		return Minz_Configuration::cacheEnabled () && self::$enabled;
-	}
-
-	/**
-	 * Active / désactive le cache
-	 */
-	public static function switchOn () {
-		self::$enabled = true;
-	}
-	public static function switchOff () {
-		self::$enabled = false;
-	}
-
-	/**
-	 * Détermine si le cache de $url a expiré ou non
-	 * @return true si il a expiré, false sinon
-	 */
-	public function expired () {
-		return time () > $this->expire;
-	}
-
-	/**
-	 * Affiche le contenu du cache
-	 * @print le code html du cache
-	 */
-	public function render () {
-		if ($this->exist ()) {
-			include ($this->file);
-		}
-	}
-
-	/**
-	 * Enregistre $html en cache
-	 * @param $html le html à mettre en cache
-	 */
-	public function cache ($html) {
-		file_put_contents ($this->file, $html);
-	}
-
-	/**
-	 * Permet de savoir si le cache existe
-	 * @return true si il existe, false sinon
-	 */
-	public function exist () {
-		return file_exists ($this->file);
-	}
-
-	/**
-	 * Nettoie le cache en supprimant tous les fichiers
-	 */
-	public static function clean () {
-		$files = opendir (CACHE_PATH);
-
-		while ($fic = readdir ($files)) {
-			if ($fic != '.' && $fic != '..') {
-				unlink (CACHE_PATH.'/'.$fic);
-			}
-		}
-
-		closedir ($files);
-	}
-}

+ 79 - 61
lib/Minz/Configuration.php

@@ -30,12 +30,9 @@ class Minz_Configuration {
 	 * définition des variables de configuration
 	 * $salt une chaîne de caractères aléatoires (obligatoire)
 	 * $environment gère le niveau d'affichage pour log et erreurs
-	 * $use_url_rewriting indique si on utilise l'url_rewriting
 	 * $base_url le chemin de base pour accéder à l'application
 	 * $title le nom de l'application
 	 * $language la langue par défaut de l'application
-	 * $cacheEnabled permet de savoir si le cache doit être activé
-	 * $delayCache la limite de cache
 	 * $db paramètres pour la base de données (tableau)
 	 *     - host le serveur de la base
 	 *     - user nom d'utilisateur
@@ -45,15 +42,14 @@ class Minz_Configuration {
 	private static $salt = '';
 	private static $environment = Minz_Configuration::PRODUCTION;
 	private static $base_url = '';
-	private static $use_url_rewriting = false;
 	private static $title = '';
 	private static $language = 'en';
-	private static $cache_enabled = false;
-	private static $delay_cache = 3600;
 	private static $default_user = '';
 	private static $allow_anonymous = false;
 	private static $allow_anonymous_refresh = false;
 	private static $auth_type = 'none';
+	private static $api_enabled = false;
+	private static $unsafe_autologin_enabled = false;
 
 	private static $db = array (
 		'type' => 'mysql',
@@ -92,21 +88,12 @@ class Minz_Configuration {
 	public static function baseUrl () {
 		return self::$base_url;
 	}
-	public static function useUrlRewriting () {
-		return self::$use_url_rewriting;
-	}
 	public static function title () {
 		return self::$title;
 	}
 	public static function language () {
 		return self::$language;
 	}
-	public static function cacheEnabled () {
-		return self::$cache_enabled;
-	}
-	public static function delayCache () {
-		return self::$delay_cache;
-	}
 	public static function dataBase () {
 		return self::$db;
 	}
@@ -131,6 +118,12 @@ class Minz_Configuration {
 	public static function canLogIn() {
 		return self::$auth_type === 'form' || self::$auth_type === 'persona';
 	}
+	public static function apiEnabled() {
+		return self::$api_enabled;
+	}
+	public static function unsafeAutologinEnabled() {
+		return self::$unsafe_autologin_enabled;
+	}
 
 	public static function _allowAnonymous($allow = false) {
 		self::$allow_anonymous = ((bool)$allow) && self::canLogIn();
@@ -151,6 +144,13 @@ class Minz_Configuration {
 		self::_allowAnonymous(self::$allow_anonymous);
 	}
 
+	public static function _enableApi($value = false) {
+		self::$api_enabled = (bool)$value;
+	}
+	public static function _enableAutologin($value = false) {
+		self::$unsafe_autologin_enabled = (bool)$value;
+	}
+
 	/**
 	 * Initialise les variables de configuration
 	 * @exception Minz_FileNotExistException si le CONF_PATH_NAME n'existe pas
@@ -171,7 +171,6 @@ class Minz_Configuration {
 		$ini_array = array(
 			'general' => array(
 				'environment' => self::environment(true),
-				'use_url_rewriting' => self::$use_url_rewriting,
 				'salt' => self::$salt,
 				'base_url' => self::$base_url,
 				'title' => self::$title,
@@ -179,6 +178,8 @@ class Minz_Configuration {
 				'allow_anonymous' => self::$allow_anonymous,
 				'allow_anonymous_refresh' => self::$allow_anonymous_refresh,
 				'auth_type' => self::$auth_type,
+				'api_enabled' => self::$api_enabled,
+				'unsafe_autologin_enabled' => self::$unsafe_autologin_enabled,
 			),
 			'db' => self::$db,
 		);
@@ -255,9 +256,6 @@ class Minz_Configuration {
 		if (isset ($general['base_url'])) {
 			self::$base_url = $general['base_url'];
 		}
-		if (isset ($general['use_url_rewriting'])) {
-			self::$use_url_rewriting = $general['use_url_rewriting'];
-		}
 
 		if (isset ($general['title'])) {
 			self::$title = $general['title'];
@@ -265,18 +263,6 @@ class Minz_Configuration {
 		if (isset ($general['language'])) {
 			self::$language = $general['language'];
 		}
-		if (isset ($general['cache_enabled'])) {
-			self::$cache_enabled = $general['cache_enabled'];
-			if (CACHE_PATH === false && self::$cache_enabled) {
-				throw new FileNotExistException (
-					'CACHE_PATH',
-					Minz_Exception::ERROR
-				);
-			}
-		}
-		if (isset ($general['delay_cache'])) {
-			self::$delay_cache = inval($general['delay_cache']);
-		}
 		if (isset ($general['default_user'])) {
 			self::$default_user = $general['default_user'];
 		}
@@ -295,45 +281,77 @@ class Minz_Configuration {
 				($general['allow_anonymous_refresh'] !== 'no')
 			);
 		}
+		if (isset ($general['api_enabled'])) {
+			self::$api_enabled = (
+				((bool)($general['api_enabled'])) &&
+				($general['api_enabled'] !== 'no')
+			);
+		}
+		if (isset ($general['unsafe_autologin_enabled'])) {
+			self::$unsafe_autologin_enabled = (
+				((bool)($general['unsafe_autologin_enabled'])) &&
+				($general['unsafe_autologin_enabled'] !== 'no')
+			);
+		}
 
 		// Base de données
 		if (isset ($ini_array['db'])) {
 			$db = $ini_array['db'];
-			if (empty($db['host'])) {
+			if (empty($db['type'])) {
 				throw new Minz_BadConfigurationException (
-					'host',
+					'type',
 					Minz_Exception::ERROR
 				);
 			}
-			if (empty($db['user'])) {
-				throw new Minz_BadConfigurationException (
-					'user',
-					Minz_Exception::ERROR
-				);
-			}
-			if (!isset ($db['password'])) {
-				throw new Minz_BadConfigurationException (
-					'password',
-					Minz_Exception::ERROR
-				);
-			}
-			if (empty($db['base'])) {
-				throw new Minz_BadConfigurationException (
-					'base',
-					Minz_Exception::ERROR
-				);
-			}
-
-			if (!empty($db['type'])) {
-				self::$db['type'] = $db['type'];
-			}
-			self::$db['host'] = $db['host'];
-			self::$db['user'] = $db['user'];
-			self::$db['password'] = $db['password'];
-			self::$db['base'] = $db['base'];
-			if (isset($db['prefix'])) {
-				self::$db['prefix'] = $db['prefix'];
+			switch ($db['type']) {
+				case 'mysql':
+					if (empty($db['host'])) {
+						throw new Minz_BadConfigurationException (
+							'host',
+							Minz_Exception::ERROR
+						);
+					}
+					if (empty($db['user'])) {
+						throw new Minz_BadConfigurationException (
+							'user',
+							Minz_Exception::ERROR
+						);
+					}
+					if (!isset($db['password'])) {
+						throw new Minz_BadConfigurationException (
+							'password',
+							Minz_Exception::ERROR
+						);
+					}
+					if (empty($db['base'])) {
+						throw new Minz_BadConfigurationException (
+							'base',
+							Minz_Exception::ERROR
+						);
+					}
+					self::$db['host'] = $db['host'];
+					self::$db['user'] = $db['user'];
+					self::$db['password'] = $db['password'];
+					self::$db['base'] = $db['base'];
+					if (isset($db['prefix'])) {
+						self::$db['prefix'] = $db['prefix'];
+					}
+					break;
+				case 'sqlite':
+					self::$db['host'] = '';
+					self::$db['user'] = '';
+					self::$db['password'] = '';
+					self::$db['base'] = '';
+					self::$db['prefix'] = '';
+					break;
+				default:
+					throw new Minz_BadConfigurationException (
+						'type',
+						Minz_Exception::ERROR
+					);
+					break;
 			}
+			self::$db['type'] = $db['type'];
 		}
 	}
 

+ 38 - 70
lib/Minz/Dispatcher.php

@@ -14,85 +14,55 @@ class Minz_Dispatcher {
 
 	/* singleton */
 	private static $instance = null;
+	private static $needsReset;
 
-	private $router;
 	private $controller;
 
 	/**
 	 * Récupère l'instance du Dispatcher
 	 */
-	public static function getInstance ($router) {
+	public static function getInstance () {
 		if (self::$instance === null) {
-			self::$instance = new Minz_Dispatcher ($router);
+			self::$instance = new Minz_Dispatcher ();
 		}
 		return self::$instance;
 	}
 
-	/**
-	 * Constructeur
-	 */
-	private function __construct ($router) {
-		$this->router = $router;
-	}
-
 	/**
 	 * Lance le controller indiqué dans Request
 	 * Remplit le body de Response à partir de la Vue
 	 * @exception Minz_Exception
 	 */
-	public function run ($ob = true) {
-		$cache = new Minz_Cache();
-		// Le ob_start est dupliqué : sans ça il y a un bug sous Firefox
-		// ici on l'appelle avec 'ob_gzhandler', après sans.
-		// Vraisemblablement la compression fonctionne mais c'est sale
-		// J'ignore les effets de bord :(
-		if ($ob) {
-			ob_start ('ob_gzhandler');
-		}
+	public function run () {
+		do {
+			self::$needsReset = false;
 
-		if (Minz_Cache::isEnabled () && !$cache->expired ()) {
-			if ($ob) {
-				ob_start ();
-			}
-			$cache->render ();
-			if ($ob) {
-				$text = ob_get_clean();
-			}
-		} else {
-			$text = '';	//TODO: Clean this code
-			while (Minz_Request::$reseted) {
-				Minz_Request::$reseted = false;
-
-				try {
-					$this->createController ('FreshRSS_' . Minz_Request::controllerName () . '_Controller');
-					$this->controller->init ();
-					$this->controller->firstAction ();
+			try {
+				$this->createController ('FreshRSS_' . Minz_Request::controllerName () . '_Controller');
+				$this->controller->init ();
+				$this->controller->firstAction ();
+				if (!self::$needsReset) {
 					$this->launchAction (
 						Minz_Request::actionName ()
 						. 'Action'
 					);
-					$this->controller->lastAction ();
-
-					if (!Minz_Request::$reseted) {
-						if ($ob) {
-							ob_start ();
-						}
-						$this->controller->view ()->build ();
-						if ($ob) {
-							$text = ob_get_clean();
-						}
-					}
-				} catch (Minz_Exception $e) {
-					throw $e;
 				}
-			}
+				$this->controller->lastAction ();
 
-			if (Minz_Cache::isEnabled ()) {
-				$cache->cache ($text);
+				if (!self::$needsReset) {
+					$this->controller->view ()->build ();
+				}
+			} catch (Minz_Exception $e) {
+				throw $e;
 			}
-		}
+		} while (self::$needsReset);
+	}
 
-		Minz_Response::setBody ($text);
+	/**
+	 * Informe le contrôleur qu'il doit recommancer car la requête a été modifiée
+	 */
+	public static function reset() {
+		self::$needsReset = true;
 	}
 
 	/**
@@ -112,7 +82,7 @@ class Minz_Dispatcher {
 				Minz_Exception::ERROR
 			);
 		}
-		$this->controller = new $controller_name ($this->router);
+		$this->controller = new $controller_name ();
 
 		if (! ($this->controller instanceof Minz_ActionController)) {
 			throw new Minz_ControllerNotActionControllerException (
@@ -129,21 +99,19 @@ class Minz_Dispatcher {
 	 *  le controller
 	 */
 	private function launchAction ($action_name) {
-		if (!Minz_Request::$reseted) {
-			if (!is_callable (array (
-				$this->controller,
-				$action_name
-			))) {
-				throw new Minz_ActionException (
-					get_class ($this->controller),
-					$action_name,
-					Minz_Exception::ERROR
-				);
-			}
-			call_user_func (array (
-				$this->controller,
-				$action_name
-			));
+		if (!is_callable (array (
+			$this->controller,
+			$action_name
+		))) {
+			throw new Minz_ActionException (
+				get_class ($this->controller),
+				$action_name,
+				Minz_Exception::ERROR
+			);
 		}
+		call_user_func (array (
+			$this->controller,
+			$action_name
+		));
 	}
 }

+ 24 - 8
lib/Minz/Error.php

@@ -23,13 +23,32 @@ class Minz_Error {
 		$logs = self::processLogs ($logs);
 		$error_filename = APP_PATH . '/Controllers/errorController.php';
 
+		switch ($code) {
+			case 200 :
+				header('HTTP/1.1 200 OK');
+				break;
+			case 403 :
+				header('HTTP/1.1 403 Forbidden');
+				break;
+			case 404 :
+				header('HTTP/1.1 404 Not Found');
+				break;
+			case 500 :
+				header('HTTP/1.1 500 Internal Server Error');
+				break;
+			case 503 :
+				header('HTTP/1.1 503 Service Unavailable');
+				break;
+			default :
+				header('HTTP/1.1 500 Internal Server Error');
+		}
+
 		if (file_exists ($error_filename)) {
 			$params = array (
 				'code' => $code,
 				'logs' => $logs
 			);
 
-			Minz_Response::setHeader ($code);
 			if ($redirect) {
 				Minz_Request::forward (array (
 					'c' => 'error'
@@ -41,19 +60,16 @@ class Minz_Error {
 				), false);
 			}
 		} else {
-			$text = '<h1>An error occured</h1>'."\n";
+			echo '<h1>An error occured</h1>' . "\n";
 
 			if (!empty ($logs)) {
-				$text .= '<ul>'."\n";
+				echo '<ul>' . "\n";
 				foreach ($logs as $log) {
-					$text .= '<li>' . $log . '</li>'."\n";
+					echo '<li>' . $log . '</li>' . "\n";
 				}
-				$text .= '</ul>'."\n";
+				echo '</ul>' . "\n";
 			}
 
-			Minz_Response::setHeader ($code);
-			Minz_Response::setBody ($text);
-			Minz_Response::send ();
 			exit ();
 		}
 	}

+ 33 - 26
lib/Minz/FrontController.php

@@ -24,13 +24,10 @@
  */
 class Minz_FrontController {
 	protected $dispatcher;
-	protected $router;
-
-	private $useOb = true;
 
 	/**
 	 * Constructeur
-	 * Initialise le router et le dispatcher
+	 * Initialise le dispatcher, met à jour la Request
 	 */
 	public function __construct () {
 		if (LOG_PATH === false) {
@@ -42,29 +39,50 @@ class Minz_FrontController {
 
 			Minz_Request::init ();
 
-			$this->router = new Minz_Router ();
-			$this->router->init ();
-		} catch (Minz_RouteNotFoundException $e) {
-			Minz_Log::record ($e->getMessage (), Minz_Log::ERROR);
-			Minz_Error::error (
-				404,
-				array ('error' => array ($e->getMessage ()))
+			$url = $this->buildUrl();
+			$url['params'] = array_merge (
+				$url['params'],
+				Minz_Request::fetchPOST ()
 			);
+			Minz_Request::forward ($url);
 		} catch (Minz_Exception $e) {
 			Minz_Log::record ($e->getMessage (), Minz_Log::ERROR);
 			$this->killApp ($e->getMessage ());
 		}
 
-		$this->dispatcher = Minz_Dispatcher::getInstance ($this->router);
+		$this->dispatcher = Minz_Dispatcher::getInstance();
 	}
 
 	/**
-	 * Démarre l'application (lance le dispatcher et renvoie la réponse
+	 * Retourne un tableau représentant l'url passée par la barre d'adresses
+	 * @return tableau représentant l'url
+	 */
+	private function buildUrl() {
+		$url = array ();
+
+		$url['c'] = Minz_Request::fetchGET (
+			'c',
+			Minz_Request::defaultControllerName ()
+		);
+		$url['a'] = Minz_Request::fetchGET (
+			'a',
+			Minz_Request::defaultActionName ()
+		);
+		$url['params'] = Minz_Request::fetchGET ();
+
+		// post-traitement
+		unset ($url['params']['c']);
+		unset ($url['params']['a']);
+
+		return $url;
+	}
+
+	/**
+	 * Démarre l'application (lance le dispatcher et renvoie la réponse)
 	 */
 	public function run () {
 		try {
-			$this->dispatcher->run ($this->useOb);
-			Minz_Response::send ();
+			$this->dispatcher->run();
 		} catch (Minz_Exception $e) {
 			try {
 				Minz_Log::record ($e->getMessage (), Minz_Log::ERROR);
@@ -96,15 +114,4 @@ class Minz_FrontController {
 		}
 		exit ('### Application problem ###<br />'."\n".$txt);
 	}
-
-	public function useOb() {
-		return $this->useOb;
-	}
-
-	/**
-	 * Use ob_start('ob_gzhandler') or not.
-	 */
-	public function _useOb($ob) {
-		return $this->useOb = (bool)$ob;
-	}
 }

+ 14 - 3
lib/Minz/Helper.php

@@ -12,11 +12,22 @@ class Minz_Helper {
 	 * Annule les effets des magic_quotes pour une variable donnée
 	 * @param $var variable à traiter (tableau ou simple variable)
 	 */
-	public static function stripslashes_r ($var) {
-		if (is_array ($var)){
-			return array_map (array ('Helper', 'stripslashes_r'), $var);
+	public static function stripslashes_r($var) {
+		if (is_array($var)){
+			return array_map(array('Minz_Helper', 'stripslashes_r'), $var);
 		} else {
 			return stripslashes($var);
 		}
 	}
+
+	/**
+	 * Wrapper for htmlspecialchars.
+	 * Force UTf-8 value and can be used on array too.
+	 */
+	public static function htmlspecialchars_utf8($var) {
+		if (is_array($var)) {
+			return array_map(array('Minz_Helper', 'htmlspecialchars_utf8'), $var);
+		}
+		return htmlspecialchars($var, ENT_COMPAT, 'UTF-8');
+	}
 }

+ 17 - 0
lib/Minz/Log.php

@@ -80,4 +80,21 @@ class Minz_Log {
 		self::record($msg_get, Minz_Log::DEBUG, $file_name);
 		self::record($msg_post, Minz_Log::DEBUG, $file_name);
 	}
+
+	/**
+	 * Some helpers to Minz_Log::record() method
+	 * Parameters are the same of those of the record() method.
+	 */
+	public static function debug($msg, $file_name = null) {
+		self::record($msg, Minz_Log::DEBUG, $file_name);
+	}
+	public static function notice($msg, $file_name = null) {
+		self::record($msg, Minz_Log::NOTICE, $file_name);
+	}
+	public static function warning($msg, $file_name = null) {
+		self::record($msg, Minz_Log::WARNING, $file_name);
+	}
+	public static function error($msg, $file_name = null) {
+		self::record($msg, Minz_Log::ERROR, $file_name);
+	}
 }

+ 39 - 34
lib/Minz/ModelPdo.php

@@ -16,6 +16,7 @@ class Minz_ModelPdo {
 	public static $useSharedBd = true;
 	private static $sharedBd = null;
 	private static $sharedPrefix;
+	protected static $sharedDbType;
 
 	/**
 	 * $bd variable représentant la base de données
@@ -24,46 +25,64 @@ class Minz_ModelPdo {
 
 	protected $prefix;
 
+	public function dbType() {
+		return self::$sharedDbType;
+	}
+
 	/**
 	 * Créé la connexion à la base de données à l'aide des variables
 	 * HOST, BASE, USER et PASS définies dans le fichier de configuration
 	 */
-	public function __construct () {
-		if (self::$useSharedBd && self::$sharedBd != null) {
+	public function __construct($currentUser = null) {
+		if (self::$useSharedBd && self::$sharedBd != null && $currentUser === null) {
 			$this->bd = self::$sharedBd;
 			$this->prefix = self::$sharedPrefix;
 			return;
 		}
 
-		$db = Minz_Configuration::dataBase ();
-		$driver_options = null;
+		$db = Minz_Configuration::dataBase();
+
+		if ($currentUser === null) {
+			$currentUser = Minz_Session::param('currentUser', '_');
+		}
 
 		try {
 			$type = $db['type'];
-			if($type == 'mysql') {
-				$string = $type
-				        . ':host=' . $db['host']
+			if ($type === 'mysql') {
+				$string = 'mysql:host=' . $db['host']
 				        . ';dbname=' . $db['base']
 				        . ';charset=utf8';
 				$driver_options = array(
-					PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'
+					PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
+				);
+				$this->prefix = $db['prefix'] . $currentUser . '_';
+			} elseif ($type === 'sqlite') {
+				$string = 'sqlite:' . DATA_PATH . '/' . $currentUser . '.sqlite';
+				$driver_options = array(
+					//PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
+				);
+				$this->prefix = '';
+			} else {
+				throw new Minz_PDOConnectionException(
+					'Invalid database type!',
+					$db['user'], Minz_Exception::ERROR
 				);
-			} elseif($type == 'sqlite') {
-				$string = $type . ':/' . DATA_PATH . $db['base'] . '.sqlite';	//TODO: DEBUG UTF-8 http://www.siteduzero.com/forum/sujet/sqlite-connexion-utf-8-18797
 			}
+			self::$sharedDbType = $type;
+			self::$sharedPrefix = $this->prefix;
 
-			$this->bd = new FreshPDO (
+			$this->bd = new MinzPDO(
 				$string,
 				$db['user'],
 				$db['password'],
 				$driver_options
 			);
+			if ($type === 'sqlite') {
+				$this->bd->exec('PRAGMA foreign_keys = ON;');
+			}
 			self::$sharedBd = $this->bd;
-
-			$this->prefix = $db['prefix'] . Minz_Session::param('currentUser', '_') . '_';
-			self::$sharedPrefix = $this->prefix;
 		} catch (Exception $e) {
-			throw new Minz_PDOConnectionException (
+			throw new Minz_PDOConnectionException(
 				$string,
 				$db['user'], Minz_Exception::ERROR
 			);
@@ -80,40 +99,26 @@ class Minz_ModelPdo {
 		$this->bd->rollBack();
 	}
 
-	public function size($all = false) {
-		$db = Minz_Configuration::dataBase ();
-		$sql = 'SELECT SUM(data_length + index_length) FROM information_schema.TABLES WHERE table_schema = ?';
-		$values = array ($db['base']);
-		if (!$all) {
-			$sql .= ' AND table_name LIKE ?';
-			$values[] = $this->prefix . '%';
-		}
-		$stm = $this->bd->prepare ($sql);
-		$stm->execute ($values);
-		$res = $stm->fetchAll(PDO::FETCH_COLUMN, 0);
-		return $res[0];
-	}
-
 	public static function clean() {
 		self::$sharedBd = null;
 		self::$sharedPrefix = '';
 	}
 }
 
-class FreshPDO extends PDO {
+class MinzPDO extends PDO {
 	private static function check($statement) {
 		if (preg_match('/^(?:UPDATE|INSERT|DELETE)/i', $statement)) {
 			invalidateHttpCache();
 		}
 	}
 
-	public function prepare ($statement, $driver_options = array()) {
-		FreshPDO::check($statement);
+	public function prepare($statement, $driver_options = array()) {
+		MinzPDO::check($statement);
 		return parent::prepare($statement, $driver_options);
 	}
 
-	public function exec ($statement) {
-		FreshPDO::check($statement);
+	public function exec($statement) {
+		MinzPDO::check($statement);
 		return parent::exec($statement);
 	}
 }

+ 75 - 52
lib/Minz/Request.php

@@ -10,68 +10,61 @@
 class Minz_Request {
 	private static $controller_name = '';
 	private static $action_name = '';
-	private static $params = array ();
+	private static $params = array();
 
 	private static $default_controller_name = 'index';
 	private static $default_action_name = 'index';
 
-	public static $reseted = true;
-
 	/**
 	 * Getteurs
 	 */
-	public static function controllerName () {
+	public static function controllerName() {
 		return self::$controller_name;
 	}
-	public static function actionName () {
+	public static function actionName() {
 		return self::$action_name;
 	}
-	public static function params () {
+	public static function params() {
 		return self::$params;
 	}
-	static function htmlspecialchars_utf8 ($p) {
-		return htmlspecialchars($p, ENT_COMPAT, 'UTF-8');
-	}
-	public static function param ($key, $default = false, $specialchars = false) {
-		if (isset (self::$params[$key])) {
+	public static function param($key, $default = false, $specialchars = false) {
+		if (isset(self::$params[$key])) {
 			$p = self::$params[$key];
-			if(is_object($p) || $specialchars) {
+			if (is_object($p) || $specialchars) {
 				return $p;
-			} elseif(is_array($p)) {
-				return array_map('self::htmlspecialchars_utf8', $p);
 			} else {
-				return self::htmlspecialchars_utf8($p);
+				return Minz_Helper::htmlspecialchars_utf8($p);
 			}
 		} else {
 			return $default;
 		}
 	}
-	public static function defaultControllerName () {
+	public static function defaultControllerName() {
 		return self::$default_controller_name;
 	}
-	public static function defaultActionName () {
+	public static function defaultActionName() {
 		return self::$default_action_name;
 	}
 
 	/**
 	 * Setteurs
 	 */
-	public static function _controllerName ($controller_name) {
+	public static function _controllerName($controller_name) {
 		self::$controller_name = $controller_name;
 	}
-	public static function _actionName ($action_name) {
+	public static function _actionName($action_name) {
 		self::$action_name = $action_name;
 	}
-	public static function _params ($params) {
+	public static function _params($params) {
 		if (!is_array($params)) {
-			$params = array ($params);
+			$params = array($params);
 		}
 
 		self::$params = $params;
 	}
-	public static function _param ($key, $value = false) {
+	public static function _param($key, $value = false) {
 		if ($value === false) {
-			unset (self::$params[$key]);
+			unset(self::$params[$key]);
 		} else {
 			self::$params[$key] = $value;
 		}
@@ -80,14 +73,14 @@ class Minz_Request {
 	/**
 	 * Initialise la Request
 	 */
-	public static function init () {
-		self::magicQuotesOff ();
+	public static function init() {
+		self::magicQuotesOff();
 	}
 
 	/**
 	 * Retourn le nom de domaine du site
 	 */
-	public static function getDomainName () {
+	public static function getDomainName() {
 		return $_SERVER['HTTP_HOST'];
 	}
 
@@ -95,7 +88,7 @@ class Minz_Request {
 	 * Détermine la base de l'url
 	 * @return la base de l'url
 	 */
-	public static function getBaseUrl () {
+	public static function getBaseUrl() {
 		$defaultBaseUrl = Minz_Configuration::baseUrl();
 		if (!empty($defaultBaseUrl)) {
 			return $defaultBaseUrl;
@@ -110,13 +103,13 @@ class Minz_Request {
 	 * Récupère l'URI de la requête
 	 * @return l'URI
 	 */
-	public static function getURI () {
-		if (isset ($_SERVER['REQUEST_URI'])) {
-			$base_url = self::getBaseUrl ();
+	public static function getURI() {
+		if (isset($_SERVER['REQUEST_URI'])) {
+			$base_url = self::getBaseUrl();
 			$uri = $_SERVER['REQUEST_URI'];
 
-			$len_base_url = strlen ($base_url);
-			$real_uri = substr ($uri, $len_base_url);
+			$len_base_url = strlen($base_url);
+			$real_uri = substr($uri, $len_base_url);
 		} else {
 			$real_uri = '';
 		}
@@ -130,24 +123,53 @@ class Minz_Request {
 	 * @param $redirect si vrai, force la redirection http
 	 *                > sinon, le dispatcher recharge en interne
 	 */
-	public static function forward ($url = array (), $redirect = false) {
-		$url = Minz_Url::checkUrl ($url);
+	public static function forward($url = array(), $redirect = false) {
+		if (!is_array($url)) {
+			header('Location: ' . $url);
+			exit();
+		}
+
+		$url = Minz_Url::checkUrl($url);
 
 		if ($redirect) {
-			header ('Location: ' . Minz_Url::display ($url, 'php'));
-			exit ();
+			header('Location: ' . Minz_Url::display($url, 'php'));
+			exit();
 		} else {
-			self::$reseted = true;
-
-			self::_controllerName ($url['c']);
-			self::_actionName ($url['a']);
-			self::_params (array_merge (
+			self::_controllerName($url['c']);
+			self::_actionName($url['a']);
+			self::_params(array_merge(
 				self::$params,
 				$url['params']
 			));
+			Minz_Dispatcher::reset();
 		}
 	}
 
+
+	/**
+	 * Wrappers good notifications + redirection
+	 * @param $msg notification content
+	 * @param $url url array to where we should be forwarded
+	 */
+	public static function good($msg, $url = array()) {
+		Minz_Session::_param('notification', array(
+			'type' => 'good',
+			'content' => $msg
+		));
+
+		Minz_Request::forward($url, true);
+	}
+
+	public static function bad($msg, $url = array()) {
+		Minz_Session::_param('notification', array(
+			'type' => 'bad',
+			'content' => $msg
+		));
+
+		Minz_Request::forward($url, true);
+	}
+
+
 	/**
 	 * Permet de récupérer une variable de type $_GET
 	 * @param $param nom de la variable
@@ -156,10 +178,10 @@ class Minz_Request {
 	 *         $_GET si $param = false
 	 *         $default si $_GET[$param] n'existe pas
 	 */
-	public static function fetchGET ($param = false, $default = false) {
+	public static function fetchGET($param = false, $default = false) {
 		if ($param === false) {
 			return $_GET;
-		} elseif (isset ($_GET[$param])) {
+		} elseif (isset($_GET[$param])) {
 			return $_GET[$param];
 		} else {
 			return $default;
@@ -174,10 +196,10 @@ class Minz_Request {
 	 *         $_POST si $param = false
 	 *         $default si $_POST[$param] n'existe pas
 	 */
-	public static function fetchPOST ($param = false, $default = false) {
+	public static function fetchPOST($param = false, $default = false) {
 		if ($param === false) {
 			return $_POST;
-		} elseif (isset ($_POST[$param])) {
+		} elseif (isset($_POST[$param])) {
 			return $_POST[$param];
 		} else {
 			return $default;
@@ -190,15 +212,16 @@ class Minz_Request {
 	 *   $_POST
 	 *   $_COOKIE
 	 */
-	private static function magicQuotesOff () {
-		if (get_magic_quotes_gpc ()) {
-			$_GET = Minz_Helper::stripslashes_r ($_GET);
-			$_POST = Minz_Helper::stripslashes_r ($_POST);
-			$_COOKIE = Minz_Helper::stripslashes_r ($_COOKIE);
+	private static function magicQuotesOff() {
+		if (get_magic_quotes_gpc()) {
+			$_GET = Minz_Helper::stripslashes_r($_GET);
+			$_POST = Minz_Helper::stripslashes_r($_POST);
+			$_COOKIE = Minz_Helper::stripslashes_r($_COOKIE);
 		}
 	}
 
-	public static function isPost () {
-		return $_SERVER['REQUEST_METHOD'] === 'POST';
+	public static function isPost() {
+		return isset($_SERVER['REQUEST_METHOD']) &&
+			$_SERVER['REQUEST_METHOD'] === 'POST';
 	}
 }

+ 0 - 60
lib/Minz/Response.php

@@ -1,60 +0,0 @@
-<?php
-/** 
- * MINZ - Copyright 2011 Marien Fressinaud
- * Sous licence AGPL3 <http://www.gnu.org/licenses/>
-*/
-
-/**
- * Response représente la requête http renvoyée à l'utilisateur
- */
-class Minz_Response {
-	private static $header = 'HTTP/1.0 200 OK';
-	private static $body = '';
-	
-	/**
-	 * Mets à jour le body de la Response
-	 * @param $text le texte à incorporer dans le body
-	 */
-	public static function setBody ($text) {
-		self::$body = $text;
-	}
-	
-	/**
-	 * Mets à jour le header de la Response
-	 * @param $code le code HTTP, valeurs possibles
-	 *	- 200 (OK)
-	 *	- 403 (Forbidden)
-	 *	- 404 (Forbidden)
-	 *	- 500 (Forbidden) -> par défaut si $code erroné
-	 *	- 503 (Forbidden)
-	 */
-	public static function setHeader ($code) {
-		switch ($code) {
-		case 200 :
-			self::$header = 'HTTP/1.0 200 OK';
-			break;
-		case 403 :
-			self::$header = 'HTTP/1.0 403 Forbidden';
-			break;
-		case 404 :
-			self::$header = 'HTTP/1.0 404 Not Found';
-			break;
-		case 500 :
-			self::$header = 'HTTP/1.0 500 Internal Server Error';
-			break;
-		case 503 :
-			self::$header = 'HTTP/1.0 503 Service Unavailable';
-			break;
-		default :
-			self::$header = 'HTTP/1.0 500 Internal Server Error';
-		}
-	}
-
-	/**
-	 * Envoie la Response à l'utilisateur
-	 */
-	public static function send () {
-		header (self::$header);
-		echo self::$body;
-	}
-}

+ 0 - 16
lib/Minz/RouteNotFoundException.php

@@ -1,16 +0,0 @@
-<?php
-class Minz_RouteNotFoundException extends Minz_Exception {
-	private $route;
-	
-	public function __construct ($route, $code = self::ERROR) {
-		$this->route = $route;
-		
-		$message = 'Route `' . $route . '` not found';
-		
-		parent::__construct ($message, $code);
-	}
-	
-	public function route () {
-		return $this->route;
-	}
-}

+ 0 - 209
lib/Minz/Router.php

@@ -1,209 +0,0 @@
-<?php
-/** 
- * MINZ - Copyright 2011 Marien Fressinaud
- * Sous licence AGPL3 <http://www.gnu.org/licenses/>
-*/
-
-/**
- * La classe Router gère le routage de l'application
- * Les routes sont définies dans APP_PATH.'/configuration/routes.php'
- */
-class Minz_Router {
-	const ROUTES_PATH_NAME = '/configuration/routes.php';
-
-	private $routes = array ();
-	
-	/**
-	 * Constructeur
-	 * @exception FileNotExistException si ROUTES_PATH_NAME n'existe pas
-	 *            et que l'on utilise l'url rewriting
-	 */
-	public function __construct () {
-		if (Minz_Configuration::useUrlRewriting ()) {
-			if (file_exists (APP_PATH . self::ROUTES_PATH_NAME)) {
-				$routes = include (
-					APP_PATH . self::ROUTES_PATH_NAME
-				);
-		
-				if (!is_array ($routes)) {
-					$routes = array ();
-				}
-				
-				$this->routes = array_map (
-					array ('Url', 'checkUrl'),
-					$routes
-				);
-			} else {
-				throw new Minz_FileNotExistException (
-					self::ROUTES_PATH_NAME,
-					Minz_Exception::ERROR
-				);
-			}
-		}
-	}
-	
-	/**
-	 * Initialise le Router en déterminant le couple Controller / Action
-	 * Mets à jour la Request
-	 * @exception RouteNotFoundException si l'uri n'est pas présente dans
-	 *          > la table de routage
-	 */
-	public function init () {
-		$url = array ();
-		
-		if (Minz_Configuration::useUrlRewriting ()) {
-			try {
-				$url = $this->buildWithRewriting ();
-			} catch (Minz_RouteNotFoundException $e) {
-				throw $e;
-			}
-		} else {
-			$url = $this->buildWithoutRewriting ();
-		}
-		
-		$url['params'] = array_merge (
-			$url['params'],
-			Minz_Request::fetchPOST ()
-		);
-		
-		Minz_Request::forward ($url);
-	}
-	
-	/**
-	 * Retourne un tableau représentant l'url passée par la barre d'adresses
-	 * Ne se base PAS sur la table de routage
-	 * @return tableau représentant l'url
-	 */
-	public function buildWithoutRewriting () {
-		$url = array ();
-		
-		$url['c'] = Minz_Request::fetchGET (
-			'c',
-			Minz_Request::defaultControllerName ()
-		);
-		$url['a'] = Minz_Request::fetchGET (
-			'a',
-			Minz_Request::defaultActionName ()
-		);
-		$url['params'] = Minz_Request::fetchGET ();
-		
-		// post-traitement
-		unset ($url['params']['c']);
-		unset ($url['params']['a']);
-		
-		return $url;
-	}
-	
-	/**
-	 * Retourne un tableau représentant l'url passée par la barre d'adresses
-	 * Se base sur la table de routage
-	 * @return tableau représentant l'url
-	 * @exception RouteNotFoundException si l'uri n'est pas présente dans
-	 *          > la table de routage
-	 */
-	public function buildWithRewriting () {
-		$url = array ();
-		$uri = Minz_Request::getURI ();
-		$find = false;
-		
-		foreach ($this->routes as $route) {
-			$regex = '*^' . $route['route'] . '$*';
-			if (preg_match ($regex, $uri, $matches)) {
-				$url['c'] = $route['controller'];
-				$url['a'] = $route['action'];
-				$url['params'] = $this->getParams (
-					$route['params'],
-					$matches
-				);
-				$find = true;
-				break;
-			}
-		}
-		
-		if (!$find && $uri != '/') {
-			throw new Minz_RouteNotFoundException (
-				$uri,
-				Minz_Exception::ERROR
-			);
-		}
-		
-		// post-traitement
-		$url = Minz_Url::checkUrl ($url);
-		
-		return $url;
-	}
-	
-	/**
-	 * Retourne l'uri d'une url en se basant sur la table de routage
-	 * @param l'url sous forme de tableau
-	 * @return l'uri formatée (string) selon une route trouvée
-	 */
-	public function printUriRewrited ($url) {
-		$route = $this->searchRoute ($url);
-		
-		if ($route !== false) {
-			return $this->replaceParams ($route, $url['params']);
-		}
-		
-		return '';
-	}
-	
-	/**
-	 * Recherche la route correspondante à une url
-	 * @param l'url sous forme de tableau
-	 * @return la route telle que spécifiée dans la table de routage,
-	 *         false si pas trouvée
-	 */
-	public function searchRoute ($url) {
-		foreach ($this->routes as $route) {
-			if ($route['controller'] == $url['c']
-			 && $route['action'] == $url['a']) {
-				// calcule la différence des tableaux de params
-				$params = array_flip ($route['params']);
-				$difference_params = array_diff_key (
-					$params,
-					$url['params']
-				);
-				
-				// vérifie que pas de différence
-				// et le cas où $params est vide et pas $url['params']
-				if (empty ($difference_params)
-				&& (!empty ($params) || empty ($url['params']))) {
-					return $route;
-				}
-			}
-		}
-		
-		return false;
-	}
-	
-	/**
-	 * Récupère un tableau dont
-	 * 	- les clés sont définies dans $params_route
-	 *	- les valeurs sont situées dans $matches
-	 * Le tableau $matches est décalé de +1 par rapport à $params_route
-	 */
-	private function getParams($params_route, $matches) {
-		$params = array ();
-		
-		for ($i = 0; $i < count ($params_route); $i++) {
-			$param = $params_route[$i];
-			$params[$param] = $matches[$i + 1];
-		}
-	
-		return $params;
-	}
-	
-	/**
-	 * Remplace les éléments de la route par les valeurs contenues dans $params
-	 */
-	private function replaceParams ($route, $params_replace) {
-		$uri = $route['route'];
-		$params = array();
-		foreach($route['params'] as $param) {
-			$uri = preg_replace('#\((.+)\)#U', $params_replace[$param], $uri, 1);
-		}
-
-		return stripslashes($uri);
-	 }
-}

+ 48 - 26
lib/Minz/Session.php

@@ -2,28 +2,20 @@
 
 /**
  * La classe Session gère la session utilisateur
- * C'est un singleton
  */
 class Minz_Session {
-	/**
-	 * $session stocke les variables de session
-	 */
-	private static $session = array ();	//TODO: Try to avoid having another local copy
-
 	/**
 	 * Initialise la session, avec un nom
-	 * Le nom de session est utilisé comme nom pour les cookies et les URLs (i.e. PHPSESSID).
+	 * Le nom de session est utilisé comme nom pour les cookies et les URLs(i.e. PHPSESSID).
 	 * Il ne doit contenir que des caractères alphanumériques ; il doit être court et descriptif
 	 */
-	public static function init ($name) {
-		// démarre la session
-		session_name ($name);
-		session_set_cookie_params (0, dirname(empty($_SERVER['REQUEST_URI']) ? '/' : dirname($_SERVER['REQUEST_URI'])), null, false, true);
-		session_start ();
+	public static function init($name) {
+		$cookie = session_get_cookie_params();
+		self::keepCookie($cookie['lifetime']);
 
-		if (isset ($_SESSION)) {
-			self::$session = $_SESSION;
-		}
+		// démarre la session
+		session_name($name);
+		session_start();
 	}
 
 
@@ -32,8 +24,8 @@ class Minz_Session {
 	 * @param $p le paramètre à récupérer
 	 * @return la valeur de la variable de session, false si n'existe pas
 	 */
-	public static function param ($p, $default = false) {
-		return isset(self::$session[$p]) ? self::$session[$p] : $default;
+	public static function param($p, $default = false) {
+		return isset($_SESSION[$p]) ? $_SESSION[$p] : $default;
 	}
 
 
@@ -42,13 +34,11 @@ class Minz_Session {
 	 * @param $p le paramètre à créer ou modifier
 	 * @param $v la valeur à attribuer, false pour supprimer
 	 */
-	public static function _param ($p, $v = false) {
+	public static function _param($p, $v = false) {
 		if ($v === false) {
-			unset ($_SESSION[$p]);
-			unset (self::$session[$p]);
+			unset($_SESSION[$p]);
 		} else {
 			$_SESSION[$p] = $v;
-			self::$session[$p] = $v;
 		}
 	}
 
@@ -57,15 +47,47 @@ class Minz_Session {
 	 * Permet d'effacer une session
 	 * @param $force si à false, n'efface pas le paramètre de langue
 	 */
-	public static function unset_session ($force = false) {
-		$language = self::param ('language');
+	public static function unset_session($force = false) {
+		$language = self::param('language');
 
 		session_destroy();
-		self::$session = array ();
+		$_SESSION = array();
 
 		if (!$force) {
-			self::_param ('language', $language);
-			Minz_Translate::reset ();
+			self::_param('language', $language);
+			Minz_Translate::reset();
 		}
 	}
+
+
+	/**
+	 * Spécifie la durée de vie des cookies
+	 * @param $l la durée de vie
+	 */
+	public static function keepCookie($l) {
+		$cookie_dir = empty($_SERVER['REQUEST_URI']) ? '' : $_SERVER['REQUEST_URI'];
+		session_set_cookie_params($l, $cookie_dir, '', false, true);
+	}
+
+
+	/**
+	 * Régénère un id de session.
+	 * Utile pour appeler session_set_cookie_params après session_start()
+	 */
+	public static function regenerateID() {
+		session_regenerate_id(true);
+	}
+
+	public static function deleteLongTermCookie($name) {
+		setcookie($name, '', 1, '', '', false, true);
+	}
+
+	public static function setLongTermCookie($name, $value, $expire) {
+		setcookie($name, $value, $expire, '', '', false, true);
+	}
+
+	public static function getLongTermCookie($name) {
+		return isset($_COOKIE[$name]) ? $_COOKIE[$name] : null;
+	}
+
 }

+ 21 - 13
lib/Minz/Translate.php

@@ -18,28 +18,28 @@ class Minz_Translate {
 	 * $translates est le tableau de correspondance
 	 * 	$key => $traduction
 	 */
-	private static $translates = array ();
+	private static $translates = array();
 	
 	/**
 	 * Inclus le fichier de langue qui va bien
 	 * l'enregistre dans $translates
 	 */
-	public static function init () {
-		$l = Minz_Configuration::language ();
-		self::$language = Minz_Session::param ('language', $l);
+	public static function init() {
+		$l = Minz_Configuration::language();
+		self::$language = Minz_Session::param('language', $l);
 		
 		$l_path = APP_PATH . '/i18n/' . self::$language . '.php';
 		
-		if (file_exists ($l_path)) {
-			self::$translates = include ($l_path);
+		if (file_exists($l_path)) {
+			self::$translates = include($l_path);
 		}
 	}
 	
 	/**
 	 * Alias de init
 	 */
-	public static function reset () {
-		self::init ();
+	public static function reset() {
+		self::init();
 	}
 	
 	/**
@@ -48,24 +48,32 @@ class Minz_Translate {
 	 * @return la valeur correspondante à la clé
 	 *       > si non présente dans le tableau, on retourne la clé elle-même
 	 */ 
-	public static function t ($key) {
+	public static function t($key) {
 		$translate = $key;
 		
-		if (isset (self::$translates[$key])) {
+		if (isset(self::$translates[$key])) {
 			$translate = self::$translates[$key];
 		}
 
-		$args = func_get_args ();
+		$args = func_get_args();
 		unset($args[0]);
 		
-		return vsprintf ($translate, $args);
+		return vsprintf($translate, $args);
 	}
 	
 	/**
 	 * Retourne la langue utilisée actuellement
 	 * @return la langue
 	 */
-	public static function language () {
+	public static function language() {
 		return self::$language;
 	}
 }
+
+function _t($key) {
+	$args = func_get_args();
+	unset($args[0]);
+	array_unshift($args, $key);
+
+	return call_user_func_array('Minz_Translate::t', $args);
+}

+ 4 - 11
lib/Minz/Url.php

@@ -5,8 +5,7 @@
  */
 class Minz_Url {
 	/**
-	 * Affiche une Url formatée selon que l'on utilise l'url_rewriting ou non
-	 * si oui, on cherche dans la table de routage la correspondance pour formater
+	 * Affiche une Url formatée
 	 * @param $url l'url à formater définie comme un tableau :
 	 *                    $url['c'] = controller
 	 *                    $url['a'] = action
@@ -39,13 +38,7 @@ class Minz_Url {
 		}
 
 		if ($isArray) {
-			$router = new Minz_Router ();
-
-			if (Minz_Configuration::useUrlRewriting ()) {
-				$url_string .= $router->printUriRewrited ($url);
-			} else {
-				$url_string .= self::printUri ($url, $encodage);
-			}
+			$url_string .= self::printUri ($url, $encodage);
 		} else {
 			$url_string .= $url;
 		}
@@ -54,14 +47,14 @@ class Minz_Url {
 	}
 	
 	/**
-	 * Construit l'URI d'une URL sans url rewriting
+	 * Construit l'URI d'une URL
 	 * @param l'url sous forme de tableau
 	 * @param $encodage pour indiquer comment encoder les & (& ou &amp; pour html)
 	 * @return l'uri sous la forme ?key=value&key2=value2
 	 */
 	private static function printUri ($url, $encodage) {
 		$uri = '';
-		$separator = '/?';
+		$separator = '?';
 		
 		if($encodage == 'html') {
 			$and = '&amp;';

+ 21 - 4
lib/Minz/View.php

@@ -26,12 +26,19 @@ class Minz_View {
 	 * Détermine si on utilise un layout ou non
 	 */
 	public function __construct () {
+		$this->change_view(Minz_Request::controllerName(),
+		                   Minz_Request::actionName());
+		self::$title = Minz_Configuration::title ();
+	}
+
+	/**
+	 * Change le fichier de vue en fonction d'un controller / action
+	 */
+	public function change_view($controller_name, $action_name) {
 		$this->view_filename = APP_PATH
 		                     . self::VIEWS_PATH_NAME . '/'
-		                     . Minz_Request::controllerName () . '/'
-		                     . Minz_Request::actionName () . '.phtml';
-
-		self::$title = Minz_Configuration::title ();
+		                     . $controller_name . '/'
+		                     . $action_name . '.phtml';
 	}
 
 	/**
@@ -102,6 +109,16 @@ class Minz_View {
 		}
 	}
 
+	/**
+	 * Retourne renderHelper() dans une chaîne
+	 * @param $helper l'élément à traîter
+	 */
+	public function helperToString($helper) {
+		ob_start();
+		$this->renderHelper($helper);
+		return ob_get_clean();
+	}
+
 	/**
 	 * Permet de choisir si on souhaite utiliser le layout
 	 * @param $use true si on souhaite utiliser le layout, false sinon

+ 32 - 10
lib/SimplePie/SimplePie.php

@@ -445,6 +445,13 @@ class SimplePie
 	 */
 	public $feed_url;
 
+	/**
+	 * @var string Original feed URL, or new feed URL iff HTTP 301 Moved Permanently
+	 * @see SimplePie::subscribe_url()
+	 * @access private
+	 */
+	public $permanent_url = null;	//FreshRSS
+
 	/**
 	 * @var object Instance of SimplePie_File to use as a feed
 	 * @see SimplePie::set_file()
@@ -735,6 +742,7 @@ class SimplePie
 		else
 		{
 			$this->feed_url = $this->registry->call('Misc', 'fix_protocol', array($url, 1));
+			$this->permanent_url = $this->feed_url;	//FreshRSS
 		}
 	}
 
@@ -749,6 +757,7 @@ class SimplePie
 		if ($file instanceof SimplePie_File)
 		{
 			$this->feed_url = $file->url;
+			$this->permanent_url = $this->feed_url;	//FreshRSS
 			$this->file =& $file;
 			return true;
 		}
@@ -1331,7 +1340,7 @@ class SimplePie
 		// First check to see if input has been overridden.
 		if ($this->input_encoding !== false)
 		{
-			$encodings[] = strtoupper($this->input_encoding);	//FreshRSS
+			$encodings[] = strtoupper($this->input_encoding);
 		}
 
 		$application_types = array('application/xml', 'application/xml-dtd', 'application/xml-external-parsed-entity');
@@ -1355,7 +1364,7 @@ class SimplePie
 			{
 				if (isset($headers['content-type']) && preg_match('/;\x20?charset=([^;]*)/i', $headers['content-type'], $charset))
 				{
-					$encodings[] = strtoupper($charset[1]);	//FreshRSS
+					$encodings[] = strtoupper($charset[1]);
 				}
 				else
 				{
@@ -1602,7 +1611,7 @@ class SimplePie
 		}
 
 		$this->raw_data = $file->body;
-
+		$this->permanent_url = $file->permanent_url;	//FreshRSS
 		$headers = $file->headers;
 		$sniffer = $this->registry->create('Content_Type_Sniffer', array(&$file));
 		$sniffed = $sniffer->get_type();
@@ -1788,26 +1797,39 @@ class SimplePie
 
 	/**
 	 * Get the URL for the feed
+	 * 
+	 * When the 'permanent' mode is enabled, returns the original feed URL,
+	 * except in the case of an `HTTP 301 Moved Permanently` status response,
+	 * in which case the location of the first redirection is returned.
 	 *
-	 * May or may not be different from the URL passed to {@see set_feed_url()},
+	 * When the 'permanent' mode is disabled (default),
+	 * may or may not be different from the URL passed to {@see set_feed_url()},
 	 * depending on whether auto-discovery was used.
 	 *
 	 * @since Preview Release (previously called `get_feed_url()` since SimplePie 0.8.)
-	 * @todo If we have a perm redirect we should return the new URL
-	 * @todo When we make the above change, let's support <itunes:new-feed-url> as well
+	 * @todo Support <itunes:new-feed-url>
 	 * @todo Also, |atom:link|@rel=self
+	 * @param bool $permanent Permanent mode to return only the original URL or the first redirection
+	 *  iff it is a 301 redirection
 	 * @return string|null
 	 */
-	public function subscribe_url()
+	public function subscribe_url($permanent = false)
 	{
-		if ($this->feed_url !== null)
+		if ($permanent)	//FreshRSS
 		{
-			return $this->sanitize($this->feed_url, SIMPLEPIE_CONSTRUCT_IRI);
+			if ($this->permanent_url !== null)
+			{
+				return $this->sanitize($this->permanent_url, SIMPLEPIE_CONSTRUCT_IRI);
+			}
 		}
 		else
 		{
-			return null;
+			if ($this->feed_url !== null)
+			{
+				return $this->sanitize($this->feed_url, SIMPLEPIE_CONSTRUCT_IRI);
+			}
 		}
+		return null;
 	}
 
 	/**

+ 10 - 2
lib/SimplePie/SimplePie/File.php

@@ -64,6 +64,7 @@ class SimplePie_File
 	var $redirects = 0;
 	var $error;
 	var $method = SIMPLEPIE_FILE_SOURCE_NONE;
+	var $permanent_url;	//FreshRSS
 
 	public function __construct($url, $timeout = 10, $redirects = 5, $headers = null, $useragent = null, $force_fsockopen = false)
 	{
@@ -74,6 +75,7 @@ class SimplePie_File
 			$url = SimplePie_Misc::compress_parse_url($parsed['scheme'], $idn->encode($parsed['authority']), $parsed['path'], $parsed['query'], $parsed['fragment']);
 		}
 		$this->url = $url;
+		$this->permanent_url = $url;	//FreshRSS
 		$this->useragent = $useragent;
 		if (preg_match('/^http(s)?:\/\//i', $url))
 		{
@@ -142,7 +144,10 @@ class SimplePie_File
 						{
 							$this->redirects++;
 							$location = SimplePie_Misc::absolutize_url($this->headers['location'], $url);
-							return $this->__construct($location, $timeout, $redirects, $headers, $useragent, $force_fsockopen);
+							$previousStatusCode = $this->status_code;
+							$this->__construct($location, $timeout, $redirects, $headers, $useragent, $force_fsockopen);
+							$this->permanent_url = ($previousStatusCode == 301) ? $location : $url;	//FreshRSS
+							return;
 						}
 					}
 				}
@@ -224,7 +229,10 @@ class SimplePie_File
 							{
 								$this->redirects++;
 								$location = SimplePie_Misc::absolutize_url($this->headers['location'], $url);
-								return $this->__construct($location, $timeout, $redirects, $headers, $useragent, $force_fsockopen);
+								$previousStatusCode = $this->status_code;
+								$this->__construct($location, $timeout, $redirects, $headers, $useragent, $force_fsockopen);
+								$this->permanent_url = ($previousStatusCode == 301) ? $location : $url;	//FreshRSS
+								return;
 							}
 							if (isset($this->headers['content-encoding']))
 							{

Some files were not shown because too many files changed in this diff