From 3602405ec0dbc576fce09ff9e865ba2404622080 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicolas=20L=C5=93uillet?= Date: Fri, 11 Jul 2014 16:03:59 +0200 Subject: [PATCH 01/13] WHAT. A. BIG. REFACTOR. + new license (we moved to MIT one) --- COPYING.md | 27 +- CREDITS.md | 3 +- README.md | 5 +- check_setup.php | 14 +- inc/3rdparty/FlattrItem.class.php | 26 +- inc/3rdparty/Session.class.php | 34 +++ inc/poche/Database.class.php | 19 +- inc/poche/Language.class.php | 114 ++++++++ inc/poche/Poche.class.php | 453 ++++-------------------------- inc/poche/Routing.class.php | 149 ++++++++++ inc/poche/Template.class.php | 236 ++++++++++++++++ inc/poche/Tools.class.php | 156 +++++++--- inc/poche/Url.class.php | 2 +- inc/poche/User.class.php | 11 +- inc/poche/config.inc.default.php | 2 +- inc/poche/global.inc.php | 23 +- inc/poche/pochePictures.php | 277 +++++++++--------- index.php | 132 +-------- install/index.php | 9 + wallabag_compatibility_test.php | 9 + 20 files changed, 930 insertions(+), 771 deletions(-) create mode 100644 inc/poche/Language.class.php create mode 100644 inc/poche/Routing.class.php create mode 100644 inc/poche/Template.class.php diff --git a/COPYING.md b/COPYING.md index ee7d6a54e..c43f619a3 100644 --- a/COPYING.md +++ b/COPYING.md @@ -1,14 +1,19 @@ - DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE - Version 2, December 2004 +Copyright (c) 2013-2014 Nicolas Lœuillet - Copyright (C) 2004 Sam Hocevar +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: - Everyone is permitted to copy and distribute verbatim or modified - copies of this license document, and changing it is allowed as long - as the name is changed. - - DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. You just DO WHAT THE FUCK YOU WANT TO. +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. \ No newline at end of file diff --git a/CREDITS.md b/CREDITS.md index c892336dc..7ec3cbb7a 100644 --- a/CREDITS.md +++ b/CREDITS.md @@ -1,7 +1,6 @@ wallabag is based on : * PHP Readability https://bitbucket.org/fivefilters/php-readability * Full Text RSS http://code.fivefilters.org/full-text-rss/src -* Encoding https://github.com/neitanod/forceutf8 * logo by Maylis Agniel https://github.com/wallabag/logo * icons http://icomoon.io * PHP Simple HTML DOM Parser (for Pocket import) http://simplehtmldom.sourceforge.net/ @@ -10,6 +9,6 @@ wallabag is based on : * Flash messages https://github.com/plasticbrain/PHP-Flash-Messages * Pagination https://github.com/daveismyname/pagination -wallabag is developed by Nicolas Lœuillet under the Do What the Fuck You Want to Public License +wallabag is mainly developed by Nicolas Lœuillet under the MIT License Contributors : https://github.com/wallabag/wallabag/graphs/contributors \ No newline at end of file diff --git a/README.md b/README.md index 0b54dff45..38866f7af 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,6 @@ wallabag is a self hostable application allowing you to not miss any content any More informations on our website: [wallabag.org](http://wallabag.org) ## License -Copyright © 2010-2014 Nicolas Lœuillet +Copyright © 2013-2014 Nicolas Lœuillet This work is free. You can redistribute it and/or modify it under the -terms of the Do What The Fuck You Want To Public License, Version 2, -as published by Sam Hocevar. See the COPYING file for more details. +terms of the MIT License. See the COPYING file for more details. diff --git a/check_setup.php b/check_setup.php index 2b84a7440..eee5d24a4 100644 --- a/check_setup.php +++ b/check_setup.php @@ -1,5 +1,4 @@ + * @copyright 2013 + * @license http://opensource.org/licenses/MIT see COPYING file + */ +class FlattrItem +{ public $status; public $urltoflattr; public $flattrItemURL; public $numflattrs; - public function checkItem($urltoflattr,$id) { - $this->cacheflattrfile($urltoflattr, $id); + public function checkItem($urltoflattr, $id) + { + $this->_cacheflattrfile($urltoflattr, $id); $flattrResponse = file_get_contents(CACHE . "/flattr/".$id.".cache"); if($flattrResponse != FALSE) { $result = json_decode($flattrResponse); - if (isset($result->message)){ + if (isset($result->message)) { if ($result->message == "flattrable") { $this->status = FLATTRABLE; } } - elseif (is_object($result) && $result->link) { + elseif (is_object($result) && $result->link) { $this->status = FLATTRED; $this->flattrItemURL = $result->link; $this->numflattrs = $result->flattrs; @@ -33,7 +40,8 @@ class FlattrItem { } } - private function cacheflattrfile($urltoflattr, $id) { + private function _cacheflattrfile($urltoflattr, $id) + { if (!is_dir(CACHE . '/flattr')) { mkdir(CACHE . '/flattr', 0777); } diff --git a/inc/3rdparty/Session.class.php b/inc/3rdparty/Session.class.php index 59dfbe670..b56e4c545 100644 --- a/inc/3rdparty/Session.class.php +++ b/inc/3rdparty/Session.class.php @@ -309,4 +309,38 @@ class Session return true; // User is not banned. } + + + /** + * Tells if a param exists in session + * + * @param $name name of the param to test + * @return bool + */ + public static function isInSession($name) + { + return (isset($_SESSION[$name]) ? : FALSE); + } + + /** + * Returns param in session + * + * @param $name name of the param to return + * @return mixed param or null + */ + public static function getParam($name) + { + return (self::isInSession($name) ? $_SESSION[$name] : NULL); + } + + /** + * Store value in session + * + * @param $name name of the variable to store + * @param $value value to store + */ + public static function setParam($name, $value) + { + $_SESSION[$name] = $value; + } } diff --git a/inc/poche/Database.class.php b/inc/poche/Database.class.php index 11cccb723..9c1c0286b 100755 --- a/inc/poche/Database.class.php +++ b/inc/poche/Database.class.php @@ -5,7 +5,7 @@ * @category wallabag * @author Nicolas Lœuillet * @copyright 2013 - * @license http://www.wtfpl.net/ see COPYING file + * @license http://opensource.org/licenses/MIT see COPYING file */ class Database { @@ -38,6 +38,7 @@ class Database { } $this->handle->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); + $this->_checkTags(); Tools::logm('storage type ' . STORAGE); } @@ -45,21 +46,7 @@ class Database { return $this->handle; } - public function isInstalled() { - $sql = "SELECT username FROM users"; - $query = $this->executeQuery($sql, array()); - if ($query == false) { - die(STORAGE . ' database looks empty. You have to create it (you can find database structure in install folder).'); - } - $hasAdmin = count($query->fetchAll()); - - if ($hasAdmin == 0) - return false; - - return true; - } - - public function checkTags() { + private function _checkTags() { if (STORAGE == 'sqlite') { $sql = ' diff --git a/inc/poche/Language.class.php b/inc/poche/Language.class.php new file mode 100644 index 000000000..790cc197a --- /dev/null +++ b/inc/poche/Language.class.php @@ -0,0 +1,114 @@ + + * @copyright 2013 + * @license http://opensource.org/licenses/MIT see COPYING file + */ + +class Language +{ + protected $wallabag; + + private $currentLanguage; + + private $languageNames = array( + 'cs_CZ.utf8' => 'čeština', + 'de_DE.utf8' => 'German', + 'en_EN.utf8' => 'English', + 'es_ES.utf8' => 'Español', + 'fa_IR.utf8' => 'فارسی', + 'fr_FR.utf8' => 'Français', + 'it_IT.utf8' => 'Italiano', + 'pl_PL.utf8' => 'Polski', + 'pt_BR.utf8' => 'Português (Brasil)', + 'ru_RU.utf8' => 'Pусский', + 'sl_SI.utf8' => 'Slovenščina', + 'uk_UA.utf8' => 'Українська', + ); + + public function __construct(Poche $wallabag) + { + $this->wallabag = $wallabag; + $pocheUser = Session::getParam('poche_user'); + $language = (is_null($pocheUser) ? LANG : $pocheUser->getConfigValue('language')); + + @putenv('LC_ALL=' . $language); + setlocale(LC_ALL, $language); + bindtextdomain($language, LOCALE); + textdomain($language); + + $this->currentLanguage = $language; + } + + public function getLanguage() { + return $this->currentLanguage; + } + + public function getInstalledLanguages() { + $handle = opendir(LOCALE); + $languages = array(); + + while (($language = readdir($handle)) !== false) { + # Languages are stored in a directory, so all directory names are languages + # @todo move language installation data to database + if (! is_dir(LOCALE . '/' . $language) || in_array($language, array('..', '.', 'tools'))) { + continue; + } + + $current = false; + + if ($language === $this->getLanguage()) { + $current = true; + } + + $languages[] = array('name' => (isset($this->languageNames[$language]) ? $this->languageNames[$language] : $language), 'value' => $language, 'current' => $current); + } + + return $languages; + } + + + /** + * Update language for current user + * + * @param $newLanguage + */ + public function updateLanguage($newLanguage) + { + # we are not going to change it to the current language + if ($newLanguage == $this->getLanguage()) { + $this->wallabag->messages->add('w', _('still using the "' . $this->getLanguage() . '" language!')); + Tools::redirect('?view=config'); + } + + $languages = $this->getInstalledLanguages(); + $actualLanguage = false; + + foreach ($languages as $language) { + if ($language['value'] == $newLanguage) { + $actualLanguage = true; + break; + } + } + + if (!$actualLanguage) { + $this->wallabag->messages->add('e', _('that language does not seem to be installed')); + Tools::redirect('?view=config'); + } + + $this->wallabag->store->updateUserConfig($this->wallabag->user->getId(), 'language', $newLanguage); + $this->wallabag->messages->add('s', _('you have changed your language preferences')); + + $currentConfig = $_SESSION['poche_user']->config; + $currentConfig['language'] = $newLanguage; + + $_SESSION['poche_user']->setConfig($currentConfig); + + $this->wallabag->emptyCache(); + + Tools::redirect('?view=config'); + } +} \ No newline at end of file diff --git a/inc/poche/Poche.class.php b/inc/poche/Poche.class.php index 09a9f5ff8..bc4320b83 100755 --- a/inc/poche/Poche.class.php +++ b/inc/poche/Poche.class.php @@ -5,244 +5,77 @@ * @category wallabag * @author Nicolas Lœuillet * @copyright 2013 - * @license http://www.wtfpl.net/ see COPYING file + * @license http://opensource.org/licenses/MIT see COPYING file */ class Poche { - public static $canRenderTemplates = true; - public static $configFileAvailable = true; - + /** + * @var User + */ public $user; + /** + * @var Database + */ public $store; + /** + * @var Template + */ public $tpl; + /** + * @var Language + */ + public $language; + /** + * @var Routing + */ + public $routing; + /** + * @var Messages + */ public $messages; + /** + * @var Paginator + */ public $pagination; - private $currentTheme = ''; - private $currentLanguage = ''; - private $notInstalledMessage = array(); - - private $language_names = array( - 'cs_CZ.utf8' => 'čeština', - 'de_DE.utf8' => 'German', - 'en_EN.utf8' => 'English', - 'es_ES.utf8' => 'Español', - 'fa_IR.utf8' => 'فارسی', - 'fr_FR.utf8' => 'Français', - 'it_IT.utf8' => 'Italiano', - 'pl_PL.utf8' => 'Polski', - 'pt_BR.utf8' => 'Português (Brasil)', - 'ru_RU.utf8' => 'Pусский', - 'sl_SI.utf8' => 'Slovenščina', - 'uk_UA.utf8' => 'Українська', - ); public function __construct() { - if ($this->configFileIsAvailable()) { - $this->init(); - } - - if ($this->themeIsInstalled()) { - $this->initTpl(); - } - - if ($this->systemIsInstalled()) { - $this->store = new Database(); - $this->messages = new Messages(); - # installation - if (! $this->store->isInstalled()) { - $this->install(); - } - $this->store->checkTags(); - } + $this->init(); } private function init() { Tools::initPhp(); - if (isset($_SESSION['poche_user']) && $_SESSION['poche_user'] != array()) { - $this->user = $_SESSION['poche_user']; + $pocheUser = Session::getParam('poche_user'); + + if ($pocheUser && $pocheUser != array()) { + $this->user = $pocheUser; } else { - # fake user, just for install & login screens + // fake user, just for install & login screens $this->user = new User(); $this->user->setConfig($this->getDefaultConfig()); } - # l10n - $language = $this->user->getConfigValue('language'); - @putenv('LC_ALL=' . $language); - setlocale(LC_ALL, $language); - bindtextdomain($language, LOCALE); - textdomain($language); - - # Pagination - $this->pagination = new Paginator($this->user->getConfigValue('pager'), 'p'); - - # Set up theme - $themeDirectory = $this->user->getConfigValue('theme'); - - if ($themeDirectory === false) { - $themeDirectory = DEFAULT_THEME; - } - - $this->currentTheme = $themeDirectory; - - # Set up language - $languageDirectory = $this->user->getConfigValue('language'); - - if ($languageDirectory === false) { - $languageDirectory = DEFAULT_THEME; - } - - $this->currentLanguage = $languageDirectory; + $this->pagination = new Paginator($this->user->getConfigValue('pager'), 'p'); + $this->language = new Language($this); + $this->tpl = new Template($this); + $this->store = new Database(); + $this->messages = new Messages(); + $this->routing = new Routing($this); } - public function configFileIsAvailable() { - if (! self::$configFileAvailable) { - $this->notInstalledMessage[] = 'You have to copy (don\'t just rename!) inc/poche/config.inc.default.php to inc/poche/config.inc.php.'; - - return false; - } - - return true; - } - - public function themeIsInstalled() { - $passTheme = TRUE; - # Twig is an absolute requirement for Poche to function. Abort immediately if the Composer installer hasn't been run yet - if (! self::$canRenderTemplates) { - $this->notInstalledMessage[] = 'Twig does not seem to be installed. Please initialize the Composer installation to automatically fetch dependencies. You can also download vendor.zip and extract it in your wallabag folder.'; - $passTheme = FALSE; - } - - if (! is_writable(CACHE)) { - $this->notInstalledMessage[] = 'You don\'t have write access on cache directory.'; - - self::$canRenderTemplates = false; - - $passTheme = FALSE; - } - - # Check if the selected theme and its requirements are present - $theme = $this->getTheme(); - - if ($theme != '' && ! is_dir(THEME . '/' . $theme)) { - $this->notInstalledMessage[] = 'The currently selected theme (' . $theme . ') does not seem to be properly installed (Missing directory: ' . THEME . '/' . $theme . ')'; - - self::$canRenderTemplates = false; - - $passTheme = FALSE; - } - - $themeInfo = $this->getThemeInfo($theme); - if (isset($themeInfo['requirements']) && is_array($themeInfo['requirements'])) { - foreach ($themeInfo['requirements'] as $requiredTheme) { - if (! is_dir(THEME . '/' . $requiredTheme)) { - $this->notInstalledMessage[] = 'The required "' . $requiredTheme . '" theme is missing for the current theme (' . $theme . ')'; - - self::$canRenderTemplates = false; - - $passTheme = FALSE; - } - } - } - - if (!$passTheme) { - return FALSE; - } - - - return true; + public function run() + { + $this->routing->run(); } /** - * all checks before installation. - * @todo move HTML to template - * @return boolean + * Creates a new user */ - public function systemIsInstalled() + public function createNewUser() { - $msg = TRUE; - - $configSalt = defined('SALT') ? constant('SALT') : ''; - - if (empty($configSalt)) { - $this->notInstalledMessage[] = 'You have not yet filled in the SALT value in the config.inc.php file.'; - $msg = FALSE; - } - if (STORAGE == 'sqlite' && ! file_exists(STORAGE_SQLITE)) { - Tools::logm('sqlite file doesn\'t exist'); - $this->notInstalledMessage[] = 'sqlite file doesn\'t exist, you can find it in install folder. Copy it in /db folder.'; - $msg = FALSE; - } - if (is_dir(ROOT . '/install') && ! DEBUG_POCHE) { - $this->notInstalledMessage[] = 'you have to delete the /install folder before using poche.'; - $msg = FALSE; - } - if (STORAGE == 'sqlite' && ! is_writable(STORAGE_SQLITE)) { - Tools::logm('you don\'t have write access on sqlite file'); - $this->notInstalledMessage[] = 'You don\'t have write access on sqlite file.'; - $msg = FALSE; - } - - if (! $msg) { - return false; - } - - return true; - } - - public function getNotInstalledMessage() { - return $this->notInstalledMessage; - } - - private function initTpl() - { - $loaderChain = new Twig_Loader_Chain(); - $theme = $this->getTheme(); - - # add the current theme as first to the loader chain so Twig will look there first for overridden template files - try { - $loaderChain->addLoader(new Twig_Loader_Filesystem(THEME . '/' . $theme)); - } catch (Twig_Error_Loader $e) { - # @todo isInstalled() should catch this, inject Twig later - die('The currently selected theme (' . $theme . ') does not seem to be properly installed (' . THEME . '/' . $theme .' is missing)'); - } - - # add all required themes to the loader chain - $themeInfo = $this->getThemeInfo($theme); - if (isset($themeInfo['requirements']) && is_array($themeInfo['requirements'])) { - foreach ($themeInfo['requirements'] as $requiredTheme) { - try { - $loaderChain->addLoader(new Twig_Loader_Filesystem(THEME . '/' . $requiredTheme)); - } catch (Twig_Error_Loader $e) { - # @todo isInstalled() should catch this, inject Twig later - die('The required "' . $requiredTheme . '" theme is missing for the current theme (' . $theme . ')'); - } - } - } - - if (DEBUG_POCHE) { - $twigParams = array(); - } else { - $twigParams = array('cache' => CACHE); - } - - $this->tpl = new Twig_Environment($loaderChain, $twigParams); - $this->tpl->addExtension(new Twig_Extensions_Extension_I18n()); - - # filter to display domain name of an url - $filter = new Twig_SimpleFilter('getDomain', 'Tools::getDomain'); - $this->tpl->addFilter($filter); - - # filter for reading time - $filter = new Twig_SimpleFilter('getReadingTime', 'Tools::getReadingTime'); - $this->tpl->addFilter($filter); - } - - public function createNewUser() { if (isset($_GET['newuser'])){ if ($_POST['newusername'] != "" && $_POST['password4newuser'] != ""){ $newusername = filter_var($_POST['newusername'], FILTER_SANITIZE_STRING); @@ -266,7 +99,11 @@ class Poche } } - public function deleteUser(){ + /** + * Delete an existing user + */ + public function deleteUser() + { if (isset($_GET['deluser'])){ if ($this->store->listUsers() > 1) { if (Tools::encodeString($_POST['password4deletinguser'].$this->user->getUsername()) == $this->store->getUserPassword($this->user->getId())) { @@ -294,115 +131,6 @@ class Poche } } - private function install() - { - Tools::logm('poche still not installed'); - echo $this->tpl->render('install.twig', array( - 'token' => Session::getToken(), - 'theme' => $this->getTheme(), - 'poche_url' => Tools::getPocheUrl() - )); - if (isset($_GET['install'])) { - if (($_POST['password'] == $_POST['password_repeat']) - && $_POST['password'] != "" && $_POST['login'] != "") { - # let's rock, install poche baby ! - if ($this->store->install($_POST['login'], Tools::encodeString($_POST['password'] . $_POST['login']))) - { - Session::logout(); - Tools::logm('poche is now installed'); - Tools::redirect(); - } - } - else { - Tools::logm('error during installation'); - Tools::redirect(); - } - } - exit(); - } - - public function getTheme() { - return $this->currentTheme; - } - - /** - * Provides theme information by parsing theme.ini file if present in the theme's root directory. - * In all cases, the following data will be returned: - * - name: theme's name, or key if the theme is unnamed, - * - current: boolean informing if the theme is the current user theme. - * - * @param string $theme Theme key (directory name) - * @return array|boolean Theme information, or false if the theme doesn't exist. - */ - public function getThemeInfo($theme) { - if (!is_dir(THEME . '/' . $theme)) { - return false; - } - - $themeIniFile = THEME . '/' . $theme . '/theme.ini'; - $themeInfo = array(); - - if (is_file($themeIniFile) && is_readable($themeIniFile)) { - $themeInfo = parse_ini_file($themeIniFile); - } - - if ($themeInfo === false) { - $themeInfo = array(); - } - if (!isset($themeInfo['name'])) { - $themeInfo['name'] = $theme; - } - $themeInfo['current'] = ($theme === $this->getTheme()); - - return $themeInfo; - } - - public function getInstalledThemes() { - $handle = opendir(THEME); - $themes = array(); - - while (($theme = readdir($handle)) !== false) { - # Themes are stored in a directory, so all directory names are themes - # @todo move theme installation data to database - if (!is_dir(THEME . '/' . $theme) || in_array($theme, array('.', '..'))) { - continue; - } - - $themes[$theme] = $this->getThemeInfo($theme); - } - - ksort($themes); - - return $themes; - } - - public function getLanguage() { - return $this->currentLanguage; - } - - public function getInstalledLanguages() { - $handle = opendir(LOCALE); - $languages = array(); - - while (($language = readdir($handle)) !== false) { - # Languages are stored in a directory, so all directory names are languages - # @todo move language installation data to database - if (! is_dir(LOCALE . '/' . $language) || in_array($language, array('..', '.', 'tools'))) { - continue; - } - - $current = false; - - if ($language === $this->getLanguage()) { - $current = true; - } - - $languages[] = array('name' => (isset($this->language_names[$language]) ? $this->language_names[$language] : $language), 'value' => $language, 'current' => $current); - } - - return $languages; - } - public function getDefaultConfig() { return array( @@ -437,7 +165,7 @@ class Poche if ( $last_id ) { Tools::logm('add link ' . $url->getUrl()); if (DOWNLOAD_PICTURES) { - $content = filtre_picture($body, $url->getUrl(), $last_id); + $content = Picture::filterPicture($body, $url->getUrl(), $last_id); Tools::logm('updating content article'); $this->store->updateContent($last_id, $content, $this->user->getId()); } @@ -472,7 +200,7 @@ class Poche $msg = 'delete link #' . $id; if ($this->store->deleteById($id, $this->user->getId())) { if (DOWNLOAD_PICTURES) { - remove_directory(ABS_PATH . $id); + Picture::removeDirectory(ABS_PATH . $id); } $this->messages->add('s', _('the link has been deleted successfully')); } @@ -598,8 +326,8 @@ class Poche $check_time_prod = date('d-M-Y H:i', $prod_infos[1]); $compare_dev = version_compare(POCHE, $dev); $compare_prod = version_compare(POCHE, $prod); - $themes = $this->getInstalledThemes(); - $languages = $this->getInstalledLanguages(); + $themes = $this->tpl->getInstalledThemes(); + $languages = $this->language->getInstalledLanguages(); $token = $this->user->getConfigValue('token'); $http_auth = (isset($_SERVER['PHP_AUTH_USER']) || isset($_SERVER['REMOTE_USER'])) ? true : false; $only_user = ($this->store->listUsers() > 1) ? false : true; @@ -703,7 +431,7 @@ class Poche 'listmode' => (isset($_COOKIE['listmode']) ? true : false), ); - //if id is given - we retrive entries by tag: id is tag id + //if id is given - we retrieve entries by tag: id is tag id if ($id) { $tpl_vars['tag'] = $this->store->retrieveTag($id, $this->user->getId()); $tpl_vars['id'] = intval($id); @@ -757,85 +485,6 @@ class Poche } } - public function updateTheme() - { - # no data - if (empty($_POST['theme'])) { - } - - # we are not going to change it to the current theme... - if ($_POST['theme'] == $this->getTheme()) { - $this->messages->add('w', _('still using the "' . $this->getTheme() . '" theme!')); - Tools::redirect('?view=config'); - } - - $themes = $this->getInstalledThemes(); - $actualTheme = false; - - foreach (array_keys($themes) as $theme) { - if ($theme == $_POST['theme']) { - $actualTheme = true; - break; - } - } - - if (! $actualTheme) { - $this->messages->add('e', _('that theme does not seem to be installed')); - Tools::redirect('?view=config'); - } - - $this->store->updateUserConfig($this->user->getId(), 'theme', $_POST['theme']); - $this->messages->add('s', _('you have changed your theme preferences')); - - $currentConfig = $_SESSION['poche_user']->config; - $currentConfig['theme'] = $_POST['theme']; - - $_SESSION['poche_user']->setConfig($currentConfig); - - $this->emptyCache(); - - Tools::redirect('?view=config'); - } - - public function updateLanguage() - { - # no data - if (empty($_POST['language'])) { - } - - # we are not going to change it to the current language... - if ($_POST['language'] == $this->getLanguage()) { - $this->messages->add('w', _('still using the "' . $this->getLanguage() . '" language!')); - Tools::redirect('?view=config'); - } - - $languages = $this->getInstalledLanguages(); - $actualLanguage = false; - - foreach ($languages as $language) { - if ($language['value'] == $_POST['language']) { - $actualLanguage = true; - break; - } - } - - if (! $actualLanguage) { - $this->messages->add('e', _('that language does not seem to be installed')); - Tools::redirect('?view=config'); - } - - $this->store->updateUserConfig($this->user->getId(), 'language', $_POST['language']); - $this->messages->add('s', _('you have changed your language preferences')); - - $currentConfig = $_SESSION['poche_user']->config; - $currentConfig['language'] = $_POST['language']; - - $_SESSION['poche_user']->setConfig($currentConfig); - - $this->emptyCache(); - - Tools::redirect('?view=config'); - } /** * get credentials from differents sources * it redirects the user to the $referer link diff --git a/inc/poche/Routing.class.php b/inc/poche/Routing.class.php new file mode 100644 index 000000000..7e259c240 --- /dev/null +++ b/inc/poche/Routing.class.php @@ -0,0 +1,149 @@ + + * @copyright 2013 + * @license http://opensource.org/licenses/MIT see COPYING file + */ + +class Routing +{ + protected $wallabag; + protected $referer; + protected $view; + protected $action; + protected $id; + protected $url; + protected $file; + protected $defaultVars = array(); + protected $vars = array(); + + public function __construct(Poche $wallabag) + { + $this->wallabag = $wallabag; + $this->_init(); + } + + private function _init() + { + # Parse GET & REFERER vars + $this->referer = empty($_SERVER['HTTP_REFERER']) ? '' : $_SERVER['HTTP_REFERER']; + $this->view = Tools::checkVar('view', 'home'); + $this->action = Tools::checkVar('action'); + $this->id = Tools::checkVar('id'); + $_SESSION['sort'] = Tools::checkVar('sort', 'id'); + $this->url = new Url((isset ($_GET['url'])) ? $_GET['url'] : ''); + } + + public function run() + { + # vars to _always_ send to templates + $this->defaultVars = array( + 'referer' => $this->referer, + 'view' => $this->view, + 'poche_url' => Tools::getPocheUrl(), + 'title' => _('wallabag, a read it later open source system'), + 'token' => \Session::getToken(), + 'theme' => $this->wallabag->tpl->getTheme() + ); + + $this->_launchAction(); + $this->_defineTplInformation(); + + # because messages can be added in $poche->action(), we have to add this entry now (we can add it before) + $this->vars = array_merge($this->vars, array('messages' => $this->wallabag->messages->display('all', FALSE))); + + $this->_render($this->file, $this->vars); + } + + private function _defineTplInformation() + { + $tplFile = array(); + $tplVars = array(); + + if (\Session::isLogged()) { + $this->wallabag->action($this->action, $this->url, $this->id); + $tplFile = Tools::getTplFile($this->view); + $tplVars = array_merge($this->vars, $this->wallabag->displayView($this->view, $this->id)); + } elseif(isset($_SERVER['PHP_AUTH_USER'])) { + if($this->wallabag->store->userExists($_SERVER['PHP_AUTH_USER'])) { + $this->wallabag->login($this->referer); + } else { + $this->wallabag->messages->add('e', _('login failed: user doesn\'t exist')); + Tools::logm('user doesn\'t exist'); + $tplFile = Tools::getTplFile('login'); + $tplVars['http_auth'] = 1; + } + } elseif(isset($_SERVER['REMOTE_USER'])) { + if($this->wallabag->store->userExists($_SERVER['REMOTE_USER'])) { + $this->wallabag->login($this->referer); + } else { + $this->wallabag->messages->add('e', _('login failed: user doesn\'t exist')); + Tools::logm('user doesn\'t exist'); + $tplFile = Tools::getTplFile('login'); + $tplVars['http_auth'] = 1; + } + } else { + $tplFile = Tools::getTplFile('login'); + $tplVars['http_auth'] = 0; + \Session::logout(); + } + + $this->file = $tplFile; + $this->vars = array_merge($this->defaultVars, $tplVars); + } + + private function _launchAction() + { + if (isset($_GET['login'])) { + // hello you + $this->wallabag->login($this->referer); + } elseif (isset($_GET['logout'])) { + // see you soon ! + $this->wallabag->logout(); + } elseif (isset($_GET['config'])) { + // update password + $this->wallabag->updatePassword(); + } elseif (isset($_GET['newuser'])) { + $this->wallabag->createNewUser(); + } elseif (isset($_GET['deluser'])) { + $this->wallabag->deleteUser(); + } elseif (isset($_GET['epub'])) { + $this->wallabag->createEpub(); + } elseif (isset($_GET['import'])) { + $import = $this->wallabag->import(); + $tplVars = array_merge($this->vars, $import); + } elseif (isset($_GET['download'])) { + Tools::downloadDb(); + } elseif (isset($_GET['empty-cache'])) { + $this->wallabag->emptyCache(); + } elseif (isset($_GET['export'])) { + $this->wallabag->export(); + } elseif (isset($_GET['updatetheme'])) { + $this->wallabag->tpl->updateTheme($_POST['theme']); + } elseif (isset($_GET['updatelanguage'])) { + $this->wallabag->language->updateLanguage($_POST['language']); + } elseif (isset($_GET['uploadfile'])) { + $this->wallabag->uploadFile(); + } elseif (isset($_GET['feed'])) { + if (isset($_GET['action']) && $_GET['action'] == 'generate') { + $this->wallabag->generateToken(); + } + else { + $tag_id = (isset($_GET['tag_id']) ? intval($_GET['tag_id']) : 0); + $this->wallabag->generateFeeds($_GET['token'], filter_var($_GET['user_id'],FILTER_SANITIZE_NUMBER_INT), $tag_id, $_GET['type']); + } + } + elseif (isset($_GET['plainurl']) && !empty($_GET['plainurl'])) { + $plainUrl = new Url(base64_encode($_GET['plainurl'])); + $this->wallabag->action('add', $plainUrl); + } + } + + private function _render($file, $vars) + { + echo $this->wallabag->tpl->render($file, $vars); + } +} \ No newline at end of file diff --git a/inc/poche/Template.class.php b/inc/poche/Template.class.php new file mode 100644 index 000000000..0e09ad64a --- /dev/null +++ b/inc/poche/Template.class.php @@ -0,0 +1,236 @@ + + * @copyright 2013 + * @license http://opensource.org/licenses/MIT see COPYING file + */ + +class Template extends Twig_Environment +{ + protected $wallabag; + + private $canRenderTemplates = TRUE; + private $currentTheme = ''; + + public function __construct(Poche $wallabag) + { + $this->wallabag = $wallabag; + + // Set up theme + $pocheUser = Session::getParam('poche_user'); + + $themeDirectory = (is_null($pocheUser) ? DEFAULT_THEME : $pocheUser->getConfigValue('theme')); + + if ($themeDirectory === false) { + $themeDirectory = DEFAULT_THEME; + } + + $this->currentTheme = $themeDirectory; + + if ($this->_themeIsInstalled() === array()) { + $this->_init(); + } + } + + /** + * Returns true if selected theme is installed + * + * @return bool + */ + private function _themeIsInstalled() + { + $errors = array(); + + // Twig is an absolute requirement for wallabag to function. + // Abort immediately if the Composer installer hasn't been run yet + if (!$this->canRenderTemplates) { + $errors[] = 'Twig does not seem to be installed. Please initialize the Composer installation to automatically fetch dependencies. You can also download vendor.zip and extract it in your wallabag folder.'; + } + + // Check if the selected theme and its requirements are present + $theme = $this->getTheme(); + if ($theme != '' && !is_dir(THEME . '/' . $theme)) { + $errors[] = 'The currently selected theme (' . $theme . ') does not seem to be properly installed (Missing directory: ' . THEME . '/' . $theme . ')'; + $this->canRenderTemplates = FALSE; + } + + $themeInfo = $this->getThemeInfo($theme); + if (isset($themeInfo['requirements']) && is_array($themeInfo['requirements'])) { + foreach ($themeInfo['requirements'] as $requiredTheme) { + if (! is_dir(THEME . '/' . $requiredTheme)) { + $errors[] = 'The required "' . $requiredTheme . '" theme is missing for the current theme (' . $theme . ')'; + $this->canRenderTemplates = FALSE; + } + } + } + + $currentErrors = (is_null(Session::getParam('errors'))? array() : Session::getParam('errors')); + Session::setParam('errors', array_merge($errors, $currentErrors)); + + return $errors; + } + + /** + * Initialization for templates + */ + private function _init() + { + $loaderChain = new Twig_Loader_Chain(); + $theme = $this->getTheme(); + + // add the current theme as first to the loader chain + // so Twig will look there first for overridden template files + try { + $loaderChain->addLoader(new Twig_Loader_Filesystem(THEME . '/' . $theme)); + } catch (Twig_Error_Loader $e) { + # @todo isInstalled() should catch this, inject Twig later + die('The currently selected theme (' . $theme . ') does not seem to be properly installed (' . THEME . '/' . $theme .' is missing)'); + } + + // add all required themes to the loader chain + $themeInfo = $this->getThemeInfo($theme); + if (isset($themeInfo['requirements']) && is_array($themeInfo['requirements'])) { + foreach ($themeInfo['requirements'] as $requiredTheme) { + try { + $loaderChain->addLoader(new Twig_Loader_Filesystem(THEME . '/' . $requiredTheme)); + } catch (Twig_Error_Loader $e) { + # @todo isInstalled() should catch this, inject Twig later + die('The required "' . $requiredTheme . '" theme is missing for the current theme (' . $theme . ')'); + } + } + } + + if (DEBUG_POCHE) { + $twigParams = array(); + } else { + $twigParams = array('cache' => CACHE); + } + + parent::__construct($loaderChain, $twigParams); + + //$tpl = new Twig_Environment($loaderChain, $twigParams); + $this->addExtension(new Twig_Extensions_Extension_I18n()); + + # filter to display domain name of an url + $filter = new Twig_SimpleFilter('getDomain', 'Tools::getDomain'); + $this->addFilter($filter); + + # filter for reading time + $filter = new Twig_SimpleFilter('getReadingTime', 'Tools::getReadingTime'); + $this->addFilter($filter); + } + + /** + * Returns current theme + * + * @return string + */ + public function getTheme() + { + return $this->currentTheme; + } + + /** + * Provides theme information by parsing theme.ini file if present in the theme's root directory. + * In all cases, the following data will be returned: + * - name: theme's name, or key if the theme is unnamed, + * - current: boolean informing if the theme is the current user theme. + * + * @param string $theme Theme key (directory name) + * @return array|boolean Theme information, or false if the theme doesn't exist. + */ + public function getThemeInfo($theme) + { + if (!is_dir(THEME . '/' . $theme)) { + return false; + } + + $themeIniFile = THEME . '/' . $theme . '/theme.ini'; + $themeInfo = array(); + + if (is_file($themeIniFile) && is_readable($themeIniFile)) { + $themeInfo = parse_ini_file($themeIniFile); + } + + if ($themeInfo === false) { + $themeInfo = array(); + } + + if (!isset($themeInfo['name'])) { + $themeInfo['name'] = $theme; + } + + $themeInfo['current'] = ($theme === $this->getTheme()); + + return $themeInfo; + } + + /** + * Returns an array with installed themes + * + * @return array + */ + public function getInstalledThemes() + { + $handle = opendir(THEME); + $themes = array(); + + while (($theme = readdir($handle)) !== false) { + # Themes are stored in a directory, so all directory names are themes + # @todo move theme installation data to database + if (!is_dir(THEME . '/' . $theme) || in_array($theme, array('.', '..'))) { + continue; + } + + $themes[$theme] = $this->getThemeInfo($theme); + } + + ksort($themes); + + return $themes; + } + + /** + * Update theme for the current user + * + * @param $newTheme + */ + public function updateTheme($newTheme) + { + # we are not going to change it to the current theme... + if ($newTheme == $this->getTheme()) { + $this->wallabag->messages->add('w', _('still using the "' . $this->getTheme() . '" theme!')); + Tools::redirect('?view=config'); + } + + $themes = $this->getInstalledThemes(); + $actualTheme = false; + + foreach (array_keys($themes) as $theme) { + if ($theme == $newTheme) { + $actualTheme = true; + break; + } + } + + if (!$actualTheme) { + $this->wallabag->messages->add('e', _('that theme does not seem to be installed')); + Tools::redirect('?view=config'); + } + + $this->wallabag->store->updateUserConfig($this->wallabag->user->getId(), 'theme', $newTheme); + $this->wallabag->messages->add('s', _('you have changed your theme preferences')); + + $currentConfig = $_SESSION['poche_user']->config; + $currentConfig['theme'] = $newTheme; + + $_SESSION['poche_user']->setConfig($currentConfig); + + $this->wallabag->emptyCache(); + + Tools::redirect('?view=config'); + } +} \ No newline at end of file diff --git a/inc/poche/Tools.class.php b/inc/poche/Tools.class.php index cc01f4030..762e44460 100755 --- a/inc/poche/Tools.class.php +++ b/inc/poche/Tools.class.php @@ -5,19 +5,23 @@ * @category wallabag * @author Nicolas Lœuillet * @copyright 2013 - * @license http://www.wtfpl.net/ see COPYING file + * @license http://opensource.org/licenses/MIT see COPYING file */ -class Tools +final class Tools { + private function __construct() + { + + } + + /** + * Initialize PHP environment + */ public static function initPhp() { define('START_TIME', microtime(true)); - if (phpversion() < 5) { - die(_('Oops, it seems you don\'t have PHP 5.')); - } - function stripslashesDeep($value) { return is_array($value) ? array_map('stripslashesDeep', $value) @@ -34,6 +38,11 @@ class Tools register_shutdown_function('ob_end_flush'); } + /** + * Get wallabag instance URL + * + * @return string + */ public static function getPocheUrl() { $https = (!empty($_SERVER['HTTPS']) @@ -67,6 +76,11 @@ class Tools . $host . $serverport . $scriptname; } + /** + * Redirects to a URL + * + * @param string $url + */ public static function redirect($url = '') { if ($url === '') { @@ -87,11 +101,18 @@ class Tools $url = $ref; } } + self::logm('redirect to ' . $url); header('Location: '.$url); exit(); } + /** + * Returns name of the template file to display + * + * @param $view + * @return string + */ public static function getTplFile($view) { $views = array( @@ -99,13 +120,15 @@ class Tools 'edit-tags', 'view', 'login', 'error' ); - if (in_array($view, $views)) { - return $view . '.twig'; - } - - return 'home.twig'; + return (in_array($view, $views) ? $view . '.twig' : 'home.twig'); } + /** + * Download a file (typically, for downloading pictures on web server) + * + * @param $url + * @return bool|mixed|string + */ public static function getFile($url) { $timeout = 15; @@ -186,6 +209,11 @@ class Tools } } + /** + * Headers for JSON export + * + * @param $data + */ public static function renderJson($data) { header('Cache-Control: no-cache, must-revalidate'); @@ -195,6 +223,11 @@ class Tools exit(); } + /** + * Create new line in log file + * + * @param $message + */ public static function logm($message) { if (DEBUG_POCHE && php_sapi_name() != 'cli') { @@ -204,36 +237,57 @@ class Tools } } + /** + * Encode a URL by using a salt + * + * @param $string + * @return string + */ public static function encodeString($string) { return sha1($string . SALT); } + /** + * Cleans a variable + * + * @param $var + * @param string $default + * @return string + */ public static function checkVar($var, $default = '') { - return ((isset ($_REQUEST["$var"])) ? htmlentities($_REQUEST["$var"]) : $default); + return ((isset($_REQUEST["$var"])) ? htmlentities($_REQUEST["$var"]) : $default); } + /** + * Returns the domain name for a URL + * + * @param $url + * @return string + */ public static function getDomain($url) { return parse_url($url, PHP_URL_HOST); } - public static function getReadingTime($text) { - $word = str_word_count(strip_tags($text)); - $minutes = floor($word / 200); - $seconds = floor($word % 200 / (200 / 60)); - $time = array('minutes' => $minutes, 'seconds' => $seconds); - - return $minutes; + /** + * For a given text, we calculate reading time for an article + * + * @param $text + * @return float + */ + public static function getReadingTime($text) + { + return floor(str_word_count(strip_tags($text)) / 200); } - public static function getDocLanguage($userlanguage) { - $lang = explode('.', $userlanguage); - return str_replace('_', '-', $lang[0]); - } - - public static function status($status_code) + /** + * Returns the correct header for a status code + * + * @param $status_code + */ + private static function _status($status_code) { if (strpos(php_sapi_name(), 'apache') !== false) { @@ -245,9 +299,13 @@ class Tools } } - public static function download_db() { + /** + * Download the sqlite database + */ + public static function downloadDb() + { header('Content-Disposition: attachment; filename="poche.sqlite.gz"'); - self::status(200); + self::_status(200); header('Content-Transfer-Encoding: binary'); header('Content-Type: application/octet-stream'); @@ -256,18 +314,24 @@ class Tools exit; } + /** + * Get the content for a given URL (by a call to FullTextFeed) + * + * @param Url $url + * @return mixed + */ public static function getPageContent(Url $url) { // Saving and clearing context $REAL = array(); foreach( $GLOBALS as $key => $value ) { if( $key != 'GLOBALS' && $key != '_SESSION' && $key != 'HTTP_SESSION_VARS' ) { - $GLOBALS[$key] = array(); - $REAL[$key] = $value; + $GLOBALS[$key] = array(); + $REAL[$key] = $value; } } // Saving and clearing session - if ( isset($_SESSION) ) { + if (isset($_SESSION)) { $REAL_SESSION = array(); foreach( $_SESSION as $key => $value ) { $REAL_SESSION[$key] = $value; @@ -279,12 +343,12 @@ class Tools $scope = function() { extract( func_get_arg(1) ); $_GET = $_REQUEST = array( - "url" => $url->getUrl(), - "max" => 5, - "links" => "preserve", - "exc" => "", - "format" => "json", - "submit" => "Create Feed" + "url" => $url->getUrl(), + "max" => 5, + "links" => "preserve", + "exc" => "", + "format" => "json", + "submit" => "Create Feed" ); ob_start(); require func_get_arg(0); @@ -292,23 +356,26 @@ class Tools ob_end_clean(); return $json; }; - $json = $scope( "inc/3rdparty/makefulltextfeed.php", array("url" => $url) ); + + $json = $scope("inc/3rdparty/makefulltextfeed.php", array("url" => $url)); // Clearing and restoring context - foreach( $GLOBALS as $key => $value ) { - if( $key != "GLOBALS" && $key != "_SESSION" ) { + foreach ($GLOBALS as $key => $value) { + if($key != "GLOBALS" && $key != "_SESSION" ) { unset($GLOBALS[$key]); } } - foreach( $REAL as $key => $value ) { + foreach ($REAL as $key => $value) { $GLOBALS[$key] = $value; } + // Clearing and restoring session - if ( isset($REAL_SESSION) ) { - foreach( $_SESSION as $key => $value ) { + if (isset($REAL_SESSION)) { + foreach($_SESSION as $key => $value) { unset($_SESSION[$key]); } - foreach( $REAL_SESSION as $key => $value ) { + + foreach($REAL_SESSION as $key => $value) { $_SESSION[$key] = $value; } } @@ -318,11 +385,12 @@ class Tools /** * Returns whether we handle an AJAX (XMLHttpRequest) request. + * * @return boolean whether we handle an AJAX (XMLHttpRequest) request. */ public static function isAjaxRequest() { - return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH']==='XMLHttpRequest'; + return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH']==='XMLHttpRequest'; } } diff --git a/inc/poche/Url.class.php b/inc/poche/Url.class.php index aba236fa5..d9172b7d0 100644 --- a/inc/poche/Url.class.php +++ b/inc/poche/Url.class.php @@ -5,7 +5,7 @@ * @category wallabag * @author Nicolas Lœuillet * @copyright 2013 - * @license http://www.wtfpl.net/ see COPYING file + * @license http://opensource.org/licenses/MIT see COPYING file */ class Url diff --git a/inc/poche/User.class.php b/inc/poche/User.class.php index cc8bec650..eaadd3e5b 100644 --- a/inc/poche/User.class.php +++ b/inc/poche/User.class.php @@ -5,7 +5,7 @@ * @category wallabag * @author Nicolas Lœuillet * @copyright 2013 - * @license http://www.wtfpl.net/ see COPYING file + * @license http://opensource.org/licenses/MIT see COPYING file */ class User @@ -44,7 +44,14 @@ class User $this->config = $config; } - public function getConfigValue($name) { + /** + * Returns configuration entry for a user + * + * @param $name + * @return bool + */ + public function getConfigValue($name) + { return (isset($this->config[$name])) ? $this->config[$name] : FALSE; } } \ No newline at end of file diff --git a/inc/poche/config.inc.default.php b/inc/poche/config.inc.default.php index 95f727c68..6f03af188 100755 --- a/inc/poche/config.inc.default.php +++ b/inc/poche/config.inc.default.php @@ -5,7 +5,7 @@ * @category wallabag * @author Nicolas Lœuillet * @copyright 2013 - * @license http://www.wtfpl.net/ see COPYING file + * @license http://opensource.org/licenses/MIT see COPYING file */ @define ('SALT', ''); # put a strong string here diff --git a/inc/poche/global.inc.php b/inc/poche/global.inc.php index 8cf86d03d..2c22c0145 100755 --- a/inc/poche/global.inc.php +++ b/inc/poche/global.inc.php @@ -5,7 +5,7 @@ * @category wallabag * @author Nicolas Lœuillet * @copyright 2013 - * @license http://www.wtfpl.net/ see COPYING file + * @license http://opensource.org/licenses/MIT see COPYING file */ # the poche system root directory (/inc) @@ -18,6 +18,10 @@ require_once INCLUDES . '/poche/Tools.class.php'; require_once INCLUDES . '/poche/User.class.php'; require_once INCLUDES . '/poche/Url.class.php'; require_once INCLUDES . '/3rdparty/class.messages.php'; +require_once ROOT . '/vendor/autoload.php'; +require_once INCLUDES . '/poche/Template.class.php'; +require_once INCLUDES . '/poche/Language.class.php'; +require_once INCLUDES . '/poche/Routing.class.php'; require_once INCLUDES . '/poche/Poche.class.php'; require_once INCLUDES . '/poche/Database.class.php'; @@ -36,22 +40,11 @@ require_once INCLUDES . '/3rdparty/libraries/PHPePub/Logger.php'; require_once INCLUDES . '/3rdparty/libraries/PHPePub/EPub.php'; require_once INCLUDES . '/3rdparty/libraries/PHPePub/EPubChapterSplitter.php'; -# Composer its autoloader for automatically loading Twig -if (! file_exists(ROOT . '/vendor/autoload.php')) { - Poche::$canRenderTemplates = false; -} else { - require_once ROOT . '/vendor/autoload.php'; -} - # system configuration; database credentials et caetera -if (! file_exists(INCLUDES . '/poche/config.inc.php')) { - Poche::$configFileAvailable = false; -} else { - require_once INCLUDES . '/poche/config.inc.php'; - require_once INCLUDES . '/poche/config.inc.default.php'; -} +require_once INCLUDES . '/poche/config.inc.php'; +require_once INCLUDES . '/poche/config.inc.default.php'; -if (Poche::$configFileAvailable && DOWNLOAD_PICTURES) { +if (DOWNLOAD_PICTURES) { require_once INCLUDES . '/poche/pochePictures.php'; } diff --git a/inc/poche/pochePictures.php b/inc/poche/pochePictures.php index 7c319a857..26bf07063 100644 --- a/inc/poche/pochePictures.php +++ b/inc/poche/pochePictures.php @@ -5,154 +5,169 @@ * @category wallabag * @author Nicolas Lœuillet * @copyright 2013 - * @license http://www.wtfpl.net/ see COPYING file + * @license http://opensource.org/licenses/MIT see COPYING file */ -/** - * On modifie les URLS des images dans le corps de l'article - */ -function filtre_picture($content, $url, $id) + +final class Picture { - $matches = array(); - $processing_pictures = array(); // list of processing image to avoid processing the same pictures twice - preg_match_all('#<\s*(img)[^>]+src="([^"]*)"[^>]*>#Si', $content, $matches, PREG_SET_ORDER); - foreach($matches as $i => $link) { - $link[1] = trim($link[1]); - if (!preg_match('#^(([a-z]+://)|(\#))#', $link[1])) { - $absolute_path = get_absolute_link($link[2],$url); - $filename = basename(parse_url($absolute_path, PHP_URL_PATH)); - $directory = create_assets_directory($id); - $fullpath = $directory . '/' . $filename; - - if (in_array($absolute_path, $processing_pictures) === true) { - // replace picture's URL only if processing is OK : already processing -> go to next picture - continue; + private function __construct() + { + + } + + /** + * Changing pictures URL in article content + */ + public static function filterPicture($content, $url, $id) + { + $matches = array(); + $processing_pictures = array(); // list of processing image to avoid processing the same pictures twice + preg_match_all('#<\s*(img)[^>]+src="([^"]*)"[^>]*>#Si', $content, $matches, PREG_SET_ORDER); + foreach($matches as $i => $link) { + $link[1] = trim($link[1]); + if (!preg_match('#^(([a-z]+://)|(\#))#', $link[1])) { + $absolute_path = self::_getAbsoluteLink($link[2], $url); + $filename = basename(parse_url($absolute_path, PHP_URL_PATH)); + $directory = self::_createAssetsDirectory($id); + $fullpath = $directory . '/' . $filename; + + if (in_array($absolute_path, $processing_pictures) === true) { + // replace picture's URL only if processing is OK : already processing -> go to next picture + continue; + } + + if (self::_downloadPictures($absolute_path, $fullpath) === true) { + $content = str_replace($matches[$i][2], $fullpath, $content); + } + + $processing_pictures[] = $absolute_path; } - - if (download_pictures($absolute_path, $fullpath) === true) { - $content = str_replace($matches[$i][2], $fullpath, $content); - } - - $processing_pictures[] = $absolute_path; } + return $content; } - return $content; -} + /** + * Get absolute URL + */ + private static function _getAbsoluteLink($relativeLink, $url) + { + /* return if already absolute URL */ + if (parse_url($relativeLink, PHP_URL_SCHEME) != '') return $relativeLink; -/** - * Retourne le lien absolu - */ -function get_absolute_link($relative_link, $url) { - /* return if already absolute URL */ - if (parse_url($relative_link, PHP_URL_SCHEME) != '') return $relative_link; + /* queries and anchors */ + if ($relativeLink[0]=='#' || $relativeLink[0]=='?') return $url . $relativeLink; - /* queries and anchors */ - if ($relative_link[0]=='#' || $relative_link[0]=='?') return $url . $relative_link; + /* parse base URL and convert to local variables: + $scheme, $host, $path */ + extract(parse_url($url)); - /* parse base URL and convert to local variables: - $scheme, $host, $path */ - extract(parse_url($url)); + /* remove non-directory element from path */ + $path = preg_replace('#/[^/]*$#', '', $path); - /* remove non-directory element from path */ - $path = preg_replace('#/[^/]*$#', '', $path); + /* destroy path if relative url points to root */ + if ($relativeLink[0] == '/') $path = ''; - /* destroy path if relative url points to root */ - if ($relative_link[0] == '/') $path = ''; + /* dirty absolute URL */ + $abs = $host . $path . '/' . $relativeLink; - /* dirty absolute URL */ - $abs = $host . $path . '/' . $relative_link; + /* replace '//' or '/./' or '/foo/../' with '/' */ + $re = array('#(/\.?/)#', '#/(?!\.\.)[^/]+/\.\./#'); + for($n=1; $n>0; $abs=preg_replace($re, '/', $abs, -1, $n)) {} - /* replace '//' or '/./' or '/foo/../' with '/' */ - $re = array('#(/\.?/)#', '#/(?!\.\.)[^/]+/\.\./#'); - for($n=1; $n>0; $abs=preg_replace($re, '/', $abs, -1, $n)) {} - - /* absolute URL is ready! */ - return $scheme.'://'.$abs; -} - -/** - * Téléchargement des images - * - * @return bool true if the download and processing is OK, false else - */ -function download_pictures($absolute_path, $fullpath) -{ - $rawdata = Tools::getFile($absolute_path); - $fullpath = urldecode($fullpath); - - if(file_exists($fullpath)) { - unlink($fullpath); - } - - // check extension - $file_ext = strrchr($fullpath, '.'); - $whitelist = array(".jpg",".jpeg",".gif",".png"); - if (!(in_array($file_ext, $whitelist))) { - Tools::logm('processed image with not allowed extension. Skipping ' . $fullpath); - return false; - } - - // check headers - $imageinfo = getimagesize($absolute_path); - if ($imageinfo['mime'] != 'image/gif' && $imageinfo['mime'] != 'image/jpeg'&& $imageinfo['mime'] != 'image/jpg'&& $imageinfo['mime'] != 'image/png') { - Tools::logm('processed image with bad header. Skipping ' . $fullpath); - return false; - } - - // regenerate image - $im = imagecreatefromstring($rawdata); - if ($im === false) { - Tools::logm('error while regenerating image ' . $fullpath); - return false; - } - - switch ($imageinfo['mime']) { - case 'image/gif': - $result = imagegif($im, $fullpath); - break; - case 'image/jpeg': - case 'image/jpg': - $result = imagejpeg($im, $fullpath, REGENERATE_PICTURES_QUALITY); - break; - case 'image/png': - $result = imagepng($im, $fullpath, ceil(REGENERATE_PICTURES_QUALITY / 100 * 9)); - break; - } - imagedestroy($im); - - return $result; -} - -/** - * Crée un répertoire de médias pour l'article - */ -function create_assets_directory($id) -{ - $assets_path = ABS_PATH; - if(!is_dir($assets_path)) { - mkdir($assets_path, 0715); + /* absolute URL is ready! */ + return $scheme.'://'.$abs; } - $article_directory = $assets_path . $id; - if(!is_dir($article_directory)) { - mkdir($article_directory, 0715); - } + /** + * Downloading pictures + * + * @return bool true if the download and processing is OK, false else + */ + private static function _downloadPictures($absolute_path, $fullpath) + { + $rawdata = Tools::getFile($absolute_path); + $fullpath = urldecode($fullpath); - return $article_directory; -} - -/** - * Suppression du répertoire d'images - */ -function remove_directory($directory) -{ - if(is_dir($directory)) { - $files = array_diff(scandir($directory), array('.','..')); - foreach ($files as $file) { - (is_dir("$directory/$file")) ? remove_directory("$directory/$file") : unlink("$directory/$file"); + if(file_exists($fullpath)) { + unlink($fullpath); } - return rmdir($directory); + + // check extension + $file_ext = strrchr($fullpath, '.'); + $whitelist = array(".jpg",".jpeg",".gif",".png"); + if (!(in_array($file_ext, $whitelist))) { + Tools::logm('processed image with not allowed extension. Skipping ' . $fullpath); + return false; + } + + // check headers + $imageinfo = getimagesize($absolute_path); + if ($imageinfo['mime'] != 'image/gif' && $imageinfo['mime'] != 'image/jpeg'&& $imageinfo['mime'] != 'image/jpg'&& $imageinfo['mime'] != 'image/png') { + Tools::logm('processed image with bad header. Skipping ' . $fullpath); + return false; + } + + // regenerate image + $im = imagecreatefromstring($rawdata); + if ($im === false) { + Tools::logm('error while regenerating image ' . $fullpath); + return false; + } + + switch ($imageinfo['mime']) { + case 'image/gif': + $result = imagegif($im, $fullpath); + break; + case 'image/jpeg': + case 'image/jpg': + $result = imagejpeg($im, $fullpath, REGENERATE_PICTURES_QUALITY); + break; + case 'image/png': + $result = imagepng($im, $fullpath, ceil(REGENERATE_PICTURES_QUALITY / 100 * 9)); + break; + } + imagedestroy($im); + + return $result; } -} + + /** + * Create a directory for an article + * + * @param $id ID of the article + * @return string + */ + private static function _createAssetsDirectory($id) + { + $assets_path = ABS_PATH; + if (!is_dir($assets_path)) { + mkdir($assets_path, 0715); + } + + $article_directory = $assets_path . $id; + if (!is_dir($article_directory)) { + mkdir($article_directory, 0715); + } + + return $article_directory; + } + + /** + * Remove the directory + * + * @param $directory + * @return bool + */ + public static function removeDirectory($directory) + { + if (is_dir($directory)) { + $files = array_diff(scandir($directory), array('.','..')); + foreach ($files as $file) { + (is_dir("$directory/$file")) ? self::removeDirectory("$directory/$file") : unlink("$directory/$file"); + } + return rmdir($directory); + } + } +} \ No newline at end of file diff --git a/index.php b/index.php index 481841ece..825e9d5a6 100755 --- a/index.php +++ b/index.php @@ -5,139 +5,21 @@ * @category wallabag * @author Nicolas Lœuillet * @copyright 2013 - * @license http://www.wtfpl.net/ see COPYING file + * @license http://opensource.org/licenses/MIT see COPYING file */ -define ('POCHE', '1.7.1'); +define ('POCHE', '1.8.0'); require 'check_setup.php'; require_once 'inc/poche/global.inc.php'; -# Set error reporting level if (defined('ERROR_REPORTING')) { error_reporting(ERROR_REPORTING); } -# Start session -Session::$sessionName = 'poche'; +// Start session +Session::$sessionName = 'wallabag'; Session::init(); -# Start Poche -$poche = new Poche(); -$notInstalledMessage = $poche -> getNotInstalledMessage(); - -# Parse GET & REFERER vars -$referer = empty($_SERVER['HTTP_REFERER']) ? '' : $_SERVER['HTTP_REFERER']; -$view = Tools::checkVar('view', 'home'); -$action = Tools::checkVar('action'); -$id = Tools::checkVar('id'); -$_SESSION['sort'] = Tools::checkVar('sort', 'id'); -$url = new Url((isset ($_GET['url'])) ? $_GET['url'] : ''); - -# vars to _always_ send to templates -$tpl_vars = array( - 'referer' => $referer, - 'view' => $view, - 'poche_url' => Tools::getPocheUrl(), - 'title' => _('wallabag, a read it later open source system'), - 'token' => Session::getToken(), - 'theme' => $poche->getTheme() -); - -if (! empty($notInstalledMessage)) { - if (! Poche::$canRenderTemplates || ! Poche::$configFileAvailable) { - # We cannot use Twig to display the error message - echo '

Errors

    '; - foreach ($notInstalledMessage as $message) { - echo '
  1. ' . $message . '
  2. '; - } - echo '
'; - die(); - } else { - # Twig is installed, put the error message in the template - $tpl_file = Tools::getTplFile('error'); - $tpl_vars = array_merge($tpl_vars, array('msg' => $poche->getNotInstalledMessage())); - echo $poche->tpl->render($tpl_file, $tpl_vars); - exit; - } -} - -# poche actions -if (isset($_GET['login'])) { - # hello you - $poche->login($referer); -} elseif (isset($_GET['logout'])) { - # see you soon ! - $poche->logout(); -} elseif (isset($_GET['config'])) { - # Update password - $poche->updatePassword(); -} elseif (isset($_GET['newuser'])) { - $poche->createNewUser(); -} elseif (isset($_GET['deluser'])) { - $poche->deleteUser(); -} elseif (isset($_GET['epub'])) { - $poche->createEpub(); -} elseif (isset($_GET['import'])) { - $import = $poche->import(); - $tpl_vars = array_merge($tpl_vars, $import); -} elseif (isset($_GET['download'])) { - Tools::download_db(); -} elseif (isset($_GET['empty-cache'])) { - $poche->emptyCache(); -} elseif (isset($_GET['export'])) { - $poche->export(); -} elseif (isset($_GET['updatetheme'])) { - $poche->updateTheme(); -} elseif (isset($_GET['updatelanguage'])) { - $poche->updateLanguage(); -} elseif (isset($_GET['uploadfile'])) { - $poche->uploadFile(); -} elseif (isset($_GET['feed'])) { - if (isset($_GET['action']) && $_GET['action'] == 'generate') { - $poche->generateToken(); - } - else { - $tag_id = (isset($_GET['tag_id']) ? intval($_GET['tag_id']) : 0); - $poche->generateFeeds($_GET['token'], filter_var($_GET['user_id'],FILTER_SANITIZE_NUMBER_INT), $tag_id, $_GET['type']); - } -} - -elseif (isset($_GET['plainurl']) && !empty($_GET['plainurl'])) { - $plain_url = new Url(base64_encode($_GET['plainurl'])); - $poche->action('add', $plain_url); -} - -if (Session::isLogged()) { - $poche->action($action, $url, $id); - $tpl_file = Tools::getTplFile($view); - $tpl_vars = array_merge($tpl_vars, $poche->displayView($view, $id)); -} elseif(isset($_SERVER['PHP_AUTH_USER'])) { - if($poche->store->userExists($_SERVER['PHP_AUTH_USER'])) { - $poche->login($referer); - } else { - $poche->messages->add('e', _('login failed: user doesn\'t exist')); - Tools::logm('user doesn\'t exist'); - $tpl_file = Tools::getTplFile('login'); - $tpl_vars['http_auth'] = 1; - } -} elseif(isset($_SERVER['REMOTE_USER'])) { - if($poche->store->userExists($_SERVER['REMOTE_USER'])) { - $poche->login($referer); - } else { - $poche->messages->add('e', _('login failed: user doesn\'t exist')); - Tools::logm('user doesn\'t exist'); - $tpl_file = Tools::getTplFile('login'); - $tpl_vars['http_auth'] = 1; - } -} else { - $tpl_file = Tools::getTplFile('login'); - $tpl_vars['http_auth'] = 0; - Session::logout(); -} - -# because messages can be added in $poche->action(), we have to add this entry now (we can add it before) -$messages = $poche->messages->display('all', FALSE); -$tpl_vars = array_merge($tpl_vars, array('messages' => $messages)); - -# display poche -echo $poche->tpl->render($tpl_file, $tpl_vars); +// Let's rock ! +$wallabag = new Poche(); +$wallabag->run(); diff --git a/install/index.php b/install/index.php index e702891bb..1ae782a2b 100755 --- a/install/index.php +++ b/install/index.php @@ -1,4 +1,13 @@ + * @copyright 2013 + * @license http://opensource.org/licenses/MIT see COPYING file + */ + $errors = array(); $successes = array(); diff --git a/wallabag_compatibility_test.php b/wallabag_compatibility_test.php index d6f221564..da0786234 100644 --- a/wallabag_compatibility_test.php +++ b/wallabag_compatibility_test.php @@ -1,4 +1,13 @@ + * @copyright 2013 + * @license http://opensource.org/licenses/MIT see COPYING file + */ + $app_name = 'wallabag'; $php_ok = (function_exists('version_compare') && version_compare(phpversion(), '5.3.3', '>=')); From b3cda72e93fff3a4c3476e9e7e78ef2b2a3f02b9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicolas=20L=C5=93uillet?= Date: Fri, 11 Jul 2014 17:06:51 +0200 Subject: [PATCH 02/13] PicoFarad framework for routing --- inc/3rdparty/PicoFarad/Request.php | 78 ++++++++++++++ inc/3rdparty/PicoFarad/Response.php | 156 +++++++++++++++++++++++++++ inc/3rdparty/PicoFarad/Router.php | 157 ++++++++++++++++++++++++++++ inc/3rdparty/PicoFarad/Session.php | 57 ++++++++++ inc/3rdparty/PicoFarad/Template.php | 36 +++++++ inc/poche/Database.class.php | 138 +++++++++++++++--------- inc/poche/Routing.class.php | 8 +- inc/poche/global.inc.php | 19 +++- index.php | 60 +++++++++-- 9 files changed, 646 insertions(+), 63 deletions(-) create mode 100644 inc/3rdparty/PicoFarad/Request.php create mode 100644 inc/3rdparty/PicoFarad/Response.php create mode 100644 inc/3rdparty/PicoFarad/Router.php create mode 100644 inc/3rdparty/PicoFarad/Session.php create mode 100644 inc/3rdparty/PicoFarad/Template.php diff --git a/inc/3rdparty/PicoFarad/Request.php b/inc/3rdparty/PicoFarad/Request.php new file mode 100644 index 000000000..46c82bca9 --- /dev/null +++ b/inc/3rdparty/PicoFarad/Request.php @@ -0,0 +1,78 @@ + $_FILES[$field]['name'], + 'mimetype' => $_FILES[$field]['type'], + 'size' => $_FILES[$field]['size'], + ); + } + + return false; +} + + +function file_move($field, $destination) +{ + if (isset($_FILES[$field]) && ! file_exists($destination)) { + @mkdir(dirname($destination), 0777, true); + move_uploaded_file($_FILES[$field]['tmp_name'], $destination); + } +} \ No newline at end of file diff --git a/inc/3rdparty/PicoFarad/Response.php b/inc/3rdparty/PicoFarad/Response.php new file mode 100644 index 000000000..9114fde04 --- /dev/null +++ b/inc/3rdparty/PicoFarad/Response.php @@ -0,0 +1,156 @@ + $hosts) { + + if (is_array($hosts)) { + + $acl = ''; + + foreach ($hosts as &$host) { + + if ($host === '*' || $host === 'self' || strpos($host, 'http') === 0) { + $acl .= $host.' '; + } + } + } + else { + + $acl = $hosts; + } + + $values .= $policy.' '.trim($acl).'; '; + } + + header('Content-Security-Policy: '.$values); +} + + +function nosniff() +{ + header('X-Content-Type-Options: nosniff'); +} + + +function xss() +{ + header('X-XSS-Protection: 1; mode=block'); +} + + +function hsts() +{ + header('Strict-Transport-Security: max-age=31536000'); +} + + +function xframe($mode = 'DENY', array $urls = array()) +{ + header('X-Frame-Options: '.$mode.' '.implode(' ', $urls)); +} \ No newline at end of file diff --git a/inc/3rdparty/PicoFarad/Router.php b/inc/3rdparty/PicoFarad/Router.php new file mode 100644 index 000000000..b62b8e2da --- /dev/null +++ b/inc/3rdparty/PicoFarad/Router.php @@ -0,0 +1,157 @@ + 'value']); +function load() +{ + if (func_num_args() < 1 || func_num_args() > 2) { + die('Invalid template arguments'); + } + + if (! file_exists(PATH.func_get_arg(0).'.php')) { + die('Unable to load the template: "'.func_get_arg(0).'"'); + } + + if (func_num_args() === 2) { + + if (! is_array(func_get_arg(1))) { + die('Template variables must be an array'); + } + + extract(func_get_arg(1)); + } + + ob_start(); + include PATH.func_get_arg(0).'.php'; + return ob_get_clean(); +} + + +function layout($template_name, array $template_args = array(), $layout_name = 'layout') +{ + return load($layout_name, $template_args + array('content_for_layout' => load($template_name, $template_args))); +} diff --git a/inc/poche/Database.class.php b/inc/poche/Database.class.php index 9c1c0286b..8d74f2ff0 100755 --- a/inc/poche/Database.class.php +++ b/inc/poche/Database.class.php @@ -9,6 +9,7 @@ */ class Database { + var $handle; private $order = array( 'ia' => 'ORDER BY entries.id', @@ -42,11 +43,13 @@ class Database { Tools::logm('storage type ' . STORAGE); } - private function getHandle() { + private function getHandle() + { return $this->handle; } - private function _checkTags() { + private function _checkTags() + { if (STORAGE == 'sqlite') { $sql = ' @@ -110,7 +113,8 @@ class Database { $query = $this->executeQuery($sql, array()); } - public function install($login, $password) { + public function install($login, $password) + { $sql = 'INSERT INTO users ( username, password, name, email) VALUES (?, ?, ?, ?)'; $params = array($login, $password, $login, ' '); $query = $this->executeQuery($sql, $params); @@ -137,7 +141,8 @@ class Database { return TRUE; } - public function getConfigUser($id) { + public function getConfigUser($id) + { $sql = "SELECT * FROM users_config WHERE user_id = ?"; $query = $this->executeQuery($sql, array($id)); $result = $query->fetchAll(); @@ -150,7 +155,8 @@ class Database { return $user_config; } - public function userExists($username) { + public function userExists($username) + { $sql = "SELECT * FROM users WHERE username=?"; $query = $this->executeQuery($sql, array($username)); $login = $query->fetchAll(); @@ -161,7 +167,8 @@ class Database { } } - public function login($username, $password, $isauthenticated=false) { + public function login($username, $password, $isauthenticated = FALSE) + { if ($isauthenticated) { $sql = "SELECT * FROM users WHERE username=?"; $query = $this->executeQuery($sql, array($username)); @@ -191,7 +198,8 @@ class Database { $query = $this->executeQuery($sql_update, $params_update); } - public function updateUserConfig($userId, $key, $value) { + public function updateUserConfig($userId, $key, $value) + { $config = $this->getConfigUser($userId); if (! isset($config[$key])) { @@ -205,7 +213,8 @@ class Database { $query = $this->executeQuery($sql, $params); } - private function executeQuery($sql, $params) { + private function executeQuery($sql, $params) + { try { $query = $this->getHandle()->prepare($sql); @@ -219,28 +228,32 @@ class Database { } } - public function listUsers($username=null) { + public function listUsers($username = NULL) + { $sql = 'SELECT count(*) FROM users'.( $username ? ' WHERE username=?' : ''); $query = $this->executeQuery($sql, ( $username ? array($username) : array())); list($count) = $query->fetch(); return $count; } - public function getUserPassword($userID) { + public function getUserPassword($userID) + { $sql = "SELECT * FROM users WHERE id=?"; $query = $this->executeQuery($sql, array($userID)); $password = $query->fetchAll(); return isset($password[0]['password']) ? $password[0]['password'] : null; } - public function deleteUserConfig($userID) { + public function deleteUserConfig($userID) + { $sql_action = 'DELETE from users_config WHERE user_id=?'; $params_action = array($userID); $query = $this->executeQuery($sql_action, $params_action); return $query; } - public function deleteTagsEntriesAndEntries($userID) { + public function deleteTagsEntriesAndEntries($userID) + { $entries = $this->retrieveAll($userID); foreach($entries as $entryid) { $tags = $this->retrieveTagsByEntry($entryid); @@ -251,20 +264,23 @@ class Database { } } - public function deleteUser($userID) { + public function deleteUser($userID) + { $sql_action = 'DELETE from users WHERE id=?'; $params_action = array($userID); $query = $this->executeQuery($sql_action, $params_action); } - public function updateContentAndTitle($id, $title, $body, $user_id) { + public function updateContentAndTitle($id, $title, $body, $user_id) + { $sql_action = 'UPDATE entries SET content = ?, title = ? WHERE id=? AND user_id=?'; $params_action = array($body, $title, $id, $user_id); $query = $this->executeQuery($sql_action, $params_action); return $query; } - public function retrieveUnfetchedEntries($user_id, $limit) { + public function retrieveUnfetchedEntries($user_id, $limit) + { $sql_limit = "LIMIT 0,".$limit; if (STORAGE == 'postgres') { @@ -278,7 +294,8 @@ class Database { return $entries; } - public function retrieveUnfetchedEntriesCount($user_id) { + public function retrieveUnfetchedEntriesCount($user_id) + { $sql = "SELECT count(*) FROM entries WHERE (content = '' OR content IS NULL) AND title LIKE 'Untitled - Import%' AND user_id=?"; $query = $this->executeQuery($sql, array($user_id)); list($count) = $query->fetch(); @@ -286,7 +303,8 @@ class Database { return $count; } - public function retrieveAll($user_id) { + public function retrieveAll($user_id) + { $sql = "SELECT * FROM entries WHERE user_id=? ORDER BY id"; $query = $this->executeQuery($sql, array($user_id)); $entries = $query->fetchAll(); @@ -294,7 +312,8 @@ class Database { return $entries; } - public function retrieveOneById($id, $user_id) { + public function retrieveOneById($id, $user_id) + { $entry = NULL; $sql = "SELECT * FROM entries WHERE id=? AND user_id=?"; $params = array(intval($id), $user_id); @@ -304,7 +323,8 @@ class Database { return isset($entry[0]) ? $entry[0] : null; } - public function retrieveOneByURL($url, $user_id) { + public function retrieveOneByURL($url, $user_id) + { $entry = NULL; $sql = "SELECT * FROM entries WHERE url=? AND user_id=?"; $params = array($url, $user_id); @@ -314,13 +334,15 @@ class Database { return isset($entry[0]) ? $entry[0] : null; } - public function reassignTags($old_entry_id, $new_entry_id) { + public function reassignTags($old_entry_id, $new_entry_id) + { $sql = "UPDATE tags_entries SET entry_id=? WHERE entry_id=?"; $params = array($new_entry_id, $old_entry_id); $query = $this->executeQuery($sql, $params); } - public function getEntriesByView($view, $user_id, $limit = '', $tag_id = 0) { + public function getEntriesByView($view, $user_id, $limit = '', $tag_id = 0) + { switch ($view) { case 'archive': $sql = "SELECT * FROM entries WHERE user_id=? AND is_read=? "; @@ -348,9 +370,10 @@ class Database { $entries = $query->fetchAll(); return $entries; - } + } - public function getEntriesByViewCount($view, $user_id, $tag_id = 0) { + public function getEntriesByViewCount($view, $user_id, $tag_id = 0) + { switch ($view) { case 'archive': $sql = "SELECT count(*) FROM entries WHERE user_id=? AND is_read=? "; @@ -378,7 +401,8 @@ class Database { return $count; } - public function updateContent($id, $content, $user_id) { + public function updateContent($id, $content, $user_id) + { $sql_action = 'UPDATE entries SET content = ? WHERE id=? AND user_id=?'; $params_action = array($content, $id, $user_id); $query = $this->executeQuery($sql_action, $params_action); @@ -393,7 +417,8 @@ class Database { * @param integer $user_id * @return integer $id of inserted record */ - public function add($url, $title, $content, $user_id, $isFavorite=0, $isRead=0) { + public function add($url, $title, $content, $user_id, $isFavorite=0, $isRead=0) + { $sql_action = 'INSERT INTO entries ( url, title, content, user_id, is_fav, is_read ) VALUES (?, ?, ?, ?, ?, ?)'; $params_action = array($url, $title, $content, $user_id, $isFavorite, $isRead); @@ -406,36 +431,42 @@ class Database { return $id; } - public function deleteById($id, $user_id) { + public function deleteById($id, $user_id) + { $sql_action = "DELETE FROM entries WHERE id=? AND user_id=?"; $params_action = array($id, $user_id); $query = $this->executeQuery($sql_action, $params_action); return $query; } - public function favoriteById($id, $user_id) { + public function favoriteById($id, $user_id) + { $sql_action = "UPDATE entries SET is_fav=NOT is_fav WHERE id=? AND user_id=?"; $params_action = array($id, $user_id); $query = $this->executeQuery($sql_action, $params_action); } - public function archiveById($id, $user_id) { + public function archiveById($id, $user_id) + { $sql_action = "UPDATE entries SET is_read=NOT is_read WHERE id=? AND user_id=?"; $params_action = array($id, $user_id); $query = $this->executeQuery($sql_action, $params_action); } - public function archiveAll($user_id) { + public function archiveAll($user_id) + { $sql_action = "UPDATE entries SET is_read=? WHERE user_id=? AND is_read=?"; $params_action = array($user_id, 1, 0); $query = $this->executeQuery($sql_action, $params_action); } - public function getLastId($column = '') { + public function getLastId($column = '') + { return $this->getHandle()->lastInsertId($column); } - public function search($term, $user_id, $limit = '') { + public function search($term, $user_id, $limit = '') + { $search = '%'.$term.'%'; $sql_action = "SELECT * FROM entries WHERE user_id=? AND (content LIKE ? OR title LIKE ? OR url LIKE ?) "; //searches in content, title and URL $sql_action .= $this->getEntriesOrder().' ' . $limit; @@ -444,7 +475,8 @@ class Database { return $query->fetchAll(); } - public function retrieveAllTags($user_id, $term = null) { + public function retrieveAllTags($user_id, $term = NULL) + { $sql = "SELECT DISTINCT tags.*, count(entries.id) AS entriescount FROM tags LEFT JOIN tags_entries ON tags_entries.tag_id=tags.id LEFT JOIN entries ON tags_entries.entry_id=entries.id @@ -458,7 +490,8 @@ class Database { return $tags; } - public function retrieveTag($id, $user_id) { + public function retrieveTag($id, $user_id) + { $tag = NULL; $sql = "SELECT DISTINCT tags.* FROM tags LEFT JOIN tags_entries ON tags_entries.tag_id=tags.id @@ -468,10 +501,11 @@ class Database { $query = $this->executeQuery($sql, $params); $tag = $query->fetchAll(); - return isset($tag[0]) ? $tag[0] : null; + return isset($tag[0]) ? $tag[0] : NULL; } - public function retrieveEntriesByTag($tag_id, $user_id) { + public function retrieveEntriesByTag($tag_id, $user_id) + { $sql = "SELECT entries.* FROM entries LEFT JOIN tags_entries ON tags_entries.entry_id=entries.id @@ -482,7 +516,8 @@ class Database { return $entries; } - public function retrieveTagsByEntry($entry_id) { + public function retrieveTagsByEntry($entry_id) + { $sql = "SELECT tags.* FROM tags LEFT JOIN tags_entries ON tags_entries.tag_id=tags.id @@ -493,14 +528,16 @@ class Database { return $tags; } - public function removeTagForEntry($entry_id, $tag_id) { + public function removeTagForEntry($entry_id, $tag_id) + { $sql_action = "DELETE FROM tags_entries WHERE tag_id=? AND entry_id=?"; $params_action = array($tag_id, $entry_id); $query = $this->executeQuery($sql_action, $params_action); return $query; } - public function cleanUnusedTag($tag_id) { + public function cleanUnusedTag($tag_id) + { $sql_action = "SELECT tags.* FROM tags JOIN tags_entries ON tags_entries.tag_id=tags.id WHERE tags.id=?"; $query = $this->executeQuery($sql_action,array($tag_id)); $tagstokeep = $query->fetchAll(); @@ -519,7 +556,8 @@ class Database { } - public function retrieveTagByValue($value) { + public function retrieveTagByValue($value) + { $tag = NULL; $sql = "SELECT * FROM tags WHERE value=?"; $params = array($value); @@ -529,27 +567,29 @@ class Database { return isset($tag[0]) ? $tag[0] : null; } - public function createTag($value) { + public function createTag($value) + { $sql_action = 'INSERT INTO tags ( value ) VALUES (?)'; $params_action = array($value); $query = $this->executeQuery($sql_action, $params_action); return $query; } - public function setTagToEntry($tag_id, $entry_id) { + public function setTagToEntry($tag_id, $entry_id) + { $sql_action = 'INSERT INTO tags_entries ( tag_id, entry_id ) VALUES (?, ?)'; $params_action = array($tag_id, $entry_id); $query = $this->executeQuery($sql_action, $params_action); return $query; } - private function getEntriesOrder() { - if (isset($_SESSION['sort']) and array_key_exists($_SESSION['sort'], $this->order)) { - return $this->order[$_SESSION['sort']]; - } - else { - return $this->order['default']; - } + private function getEntriesOrder() + { + if (isset($_SESSION['sort']) and array_key_exists($_SESSION['sort'], $this->order)) { + return $this->order[$_SESSION['sort']]; } - + else { + return $this->order['default']; + } + } } diff --git a/inc/poche/Routing.class.php b/inc/poche/Routing.class.php index 7e259c240..6e2c046bf 100644 --- a/inc/poche/Routing.class.php +++ b/inc/poche/Routing.class.php @@ -11,8 +11,8 @@ class Routing { protected $wallabag; - protected $referer; - protected $view; + public $referer; + public $view; protected $action; protected $id; protected $url; @@ -55,7 +55,7 @@ class Routing # because messages can be added in $poche->action(), we have to add this entry now (we can add it before) $this->vars = array_merge($this->vars, array('messages' => $this->wallabag->messages->display('all', FALSE))); - $this->_render($this->file, $this->vars); + $this->render($this->file, $this->vars); } private function _defineTplInformation() @@ -142,7 +142,7 @@ class Routing } } - private function _render($file, $vars) + public function render($file, $vars) { echo $this->wallabag->tpl->render($file, $vars); } diff --git a/inc/poche/global.inc.php b/inc/poche/global.inc.php index 2c22c0145..9d710b6ce 100755 --- a/inc/poche/global.inc.php +++ b/inc/poche/global.inc.php @@ -40,6 +40,12 @@ require_once INCLUDES . '/3rdparty/libraries/PHPePub/Logger.php'; require_once INCLUDES . '/3rdparty/libraries/PHPePub/EPub.php'; require_once INCLUDES . '/3rdparty/libraries/PHPePub/EPubChapterSplitter.php'; +require_once INCLUDES . '/3rdparty/PicoFarad/Request.php'; +require_once INCLUDES . '/3rdparty/PicoFarad/Response.php'; +require_once INCLUDES . '/3rdparty/PicoFarad/Router.php'; +require_once INCLUDES . '/3rdparty/PicoFarad/Session.php'; +require_once INCLUDES . '/3rdparty/PicoFarad/Template.php'; + # system configuration; database credentials et caetera require_once INCLUDES . '/poche/config.inc.php'; require_once INCLUDES . '/poche/config.inc.default.php'; @@ -50,4 +56,15 @@ if (DOWNLOAD_PICTURES) { if (!ini_get('date.timezone') || !@date_default_timezone_set(ini_get('date.timezone'))) { date_default_timezone_set('UTC'); -} \ No newline at end of file +} + +if (defined('ERROR_REPORTING')) { + error_reporting(ERROR_REPORTING); +} + +// Start session +Session::$sessionName = 'wallabag'; +Session::init(); + +// Let's rock ! +$wallabag = new Poche(); diff --git a/index.php b/index.php index 825e9d5a6..6f190518b 100755 --- a/index.php +++ b/index.php @@ -12,14 +12,56 @@ define ('POCHE', '1.8.0'); require 'check_setup.php'; require_once 'inc/poche/global.inc.php'; -if (defined('ERROR_REPORTING')) { - error_reporting(ERROR_REPORTING); -} -// Start session -Session::$sessionName = 'wallabag'; -Session::init(); +use PicoFarad\Router; +use PicoFarad\Response; +use PicoFarad\Request; +use PicoFarad\Session; -// Let's rock ! -$wallabag = new Poche(); -$wallabag->run(); +// Called before each action +Router\before(function($action) { + + // Open a session only for the specified directory + Session\open(dirname($_SERVER['PHP_SELF'])); + + // HTTP secure headers + Response\csp(); + Response\xframe(); + Response\xss(); + Response\nosniff(); +}); + +// Show help +Router\get_action('unread', function() use ($wallabag) { + $view = 'home'; + $id = 0; + + $tpl_vars = array( + 'referer' => $wallabag->routing->referer, + 'view' => $wallabag->routing->view, + 'poche_url' => Tools::getPocheUrl(), + 'title' => _('wallabag, a read it later open source system'), + 'token' => \Session::getToken(), + 'theme' => $wallabag->tpl->getTheme(), + 'entries' => '', + 'page_links' => '', + 'nb_results' => '', + 'listmode' => (isset($_COOKIE['listmode']) ? true : false), + ); + + $count = $wallabag->store->getEntriesByViewCount($view, $wallabag->user->getId(), $id); + + if ($count > 0) { + $wallabag->pagination->set_total($count); + $page_links = str_replace(array('previous', 'next'), array(_('previous'), _('next')), + $wallabag->pagination->page_links('?view=' . $view . '&sort=' . $_SESSION['sort'] . (($id)?'&id='.$id:'') . '&' )); + $tpl_vars['entries'] = $wallabag->store->getEntriesByView($view, $wallabag->user->getId(), $wallabag->pagination->get_limit(), $id); + $tpl_vars['page_links'] = $page_links; + $tpl_vars['nb_results'] = $count; + } + + $wallabag->routing->render('home.twig', $tpl_vars); + + Tools::logm('display ' . $view . ' view'); + +}); From 26b77483ee7545c0e4f8eeb205a5743bf3589adb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicolas=20L=C5=93uillet?= Date: Sat, 12 Jul 2014 16:39:31 +0200 Subject: [PATCH 03/13] remove PicoFarad MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit I’ll implement it an other day. --- inc/3rdparty/PicoFarad/Request.php | 78 -------------- inc/3rdparty/PicoFarad/Response.php | 156 --------------------------- inc/3rdparty/PicoFarad/Router.php | 157 ---------------------------- inc/3rdparty/PicoFarad/Session.php | 57 ---------- inc/3rdparty/PicoFarad/Template.php | 36 ------- inc/poche/Routing.class.php | 8 +- inc/poche/global.inc.php | 13 --- index.php | 57 +--------- 8 files changed, 9 insertions(+), 553 deletions(-) delete mode 100644 inc/3rdparty/PicoFarad/Request.php delete mode 100644 inc/3rdparty/PicoFarad/Response.php delete mode 100644 inc/3rdparty/PicoFarad/Router.php delete mode 100644 inc/3rdparty/PicoFarad/Session.php delete mode 100644 inc/3rdparty/PicoFarad/Template.php diff --git a/inc/3rdparty/PicoFarad/Request.php b/inc/3rdparty/PicoFarad/Request.php deleted file mode 100644 index 46c82bca9..000000000 --- a/inc/3rdparty/PicoFarad/Request.php +++ /dev/null @@ -1,78 +0,0 @@ - $_FILES[$field]['name'], - 'mimetype' => $_FILES[$field]['type'], - 'size' => $_FILES[$field]['size'], - ); - } - - return false; -} - - -function file_move($field, $destination) -{ - if (isset($_FILES[$field]) && ! file_exists($destination)) { - @mkdir(dirname($destination), 0777, true); - move_uploaded_file($_FILES[$field]['tmp_name'], $destination); - } -} \ No newline at end of file diff --git a/inc/3rdparty/PicoFarad/Response.php b/inc/3rdparty/PicoFarad/Response.php deleted file mode 100644 index 9114fde04..000000000 --- a/inc/3rdparty/PicoFarad/Response.php +++ /dev/null @@ -1,156 +0,0 @@ - $hosts) { - - if (is_array($hosts)) { - - $acl = ''; - - foreach ($hosts as &$host) { - - if ($host === '*' || $host === 'self' || strpos($host, 'http') === 0) { - $acl .= $host.' '; - } - } - } - else { - - $acl = $hosts; - } - - $values .= $policy.' '.trim($acl).'; '; - } - - header('Content-Security-Policy: '.$values); -} - - -function nosniff() -{ - header('X-Content-Type-Options: nosniff'); -} - - -function xss() -{ - header('X-XSS-Protection: 1; mode=block'); -} - - -function hsts() -{ - header('Strict-Transport-Security: max-age=31536000'); -} - - -function xframe($mode = 'DENY', array $urls = array()) -{ - header('X-Frame-Options: '.$mode.' '.implode(' ', $urls)); -} \ No newline at end of file diff --git a/inc/3rdparty/PicoFarad/Router.php b/inc/3rdparty/PicoFarad/Router.php deleted file mode 100644 index b62b8e2da..000000000 --- a/inc/3rdparty/PicoFarad/Router.php +++ /dev/null @@ -1,157 +0,0 @@ - 'value']); -function load() -{ - if (func_num_args() < 1 || func_num_args() > 2) { - die('Invalid template arguments'); - } - - if (! file_exists(PATH.func_get_arg(0).'.php')) { - die('Unable to load the template: "'.func_get_arg(0).'"'); - } - - if (func_num_args() === 2) { - - if (! is_array(func_get_arg(1))) { - die('Template variables must be an array'); - } - - extract(func_get_arg(1)); - } - - ob_start(); - include PATH.func_get_arg(0).'.php'; - return ob_get_clean(); -} - - -function layout($template_name, array $template_args = array(), $layout_name = 'layout') -{ - return load($layout_name, $template_args + array('content_for_layout' => load($template_name, $template_args))); -} diff --git a/inc/poche/Routing.class.php b/inc/poche/Routing.class.php index 6e2c046bf..8c2f38e37 100644 --- a/inc/poche/Routing.class.php +++ b/inc/poche/Routing.class.php @@ -11,8 +11,8 @@ class Routing { protected $wallabag; - public $referer; - public $view; + protected $referer; + protected $view; protected $action; protected $id; protected $url; @@ -55,7 +55,7 @@ class Routing # because messages can be added in $poche->action(), we have to add this entry now (we can add it before) $this->vars = array_merge($this->vars, array('messages' => $this->wallabag->messages->display('all', FALSE))); - $this->render($this->file, $this->vars); + $this->_render($this->file, $this->vars); } private function _defineTplInformation() @@ -142,7 +142,7 @@ class Routing } } - public function render($file, $vars) + public function _render($file, $vars) { echo $this->wallabag->tpl->render($file, $vars); } diff --git a/inc/poche/global.inc.php b/inc/poche/global.inc.php index 9d710b6ce..3eb64df0e 100755 --- a/inc/poche/global.inc.php +++ b/inc/poche/global.inc.php @@ -40,12 +40,6 @@ require_once INCLUDES . '/3rdparty/libraries/PHPePub/Logger.php'; require_once INCLUDES . '/3rdparty/libraries/PHPePub/EPub.php'; require_once INCLUDES . '/3rdparty/libraries/PHPePub/EPubChapterSplitter.php'; -require_once INCLUDES . '/3rdparty/PicoFarad/Request.php'; -require_once INCLUDES . '/3rdparty/PicoFarad/Response.php'; -require_once INCLUDES . '/3rdparty/PicoFarad/Router.php'; -require_once INCLUDES . '/3rdparty/PicoFarad/Session.php'; -require_once INCLUDES . '/3rdparty/PicoFarad/Template.php'; - # system configuration; database credentials et caetera require_once INCLUDES . '/poche/config.inc.php'; require_once INCLUDES . '/poche/config.inc.default.php'; @@ -61,10 +55,3 @@ if (!ini_get('date.timezone') || !@date_default_timezone_set(ini_get('date.timez if (defined('ERROR_REPORTING')) { error_reporting(ERROR_REPORTING); } - -// Start session -Session::$sessionName = 'wallabag'; -Session::init(); - -// Let's rock ! -$wallabag = new Poche(); diff --git a/index.php b/index.php index 6f190518b..e199956c4 100755 --- a/index.php +++ b/index.php @@ -12,56 +12,9 @@ define ('POCHE', '1.8.0'); require 'check_setup.php'; require_once 'inc/poche/global.inc.php'; +// Start session +Session::$sessionName = 'wallabag'; +Session::init(); -use PicoFarad\Router; -use PicoFarad\Response; -use PicoFarad\Request; -use PicoFarad\Session; - -// Called before each action -Router\before(function($action) { - - // Open a session only for the specified directory - Session\open(dirname($_SERVER['PHP_SELF'])); - - // HTTP secure headers - Response\csp(); - Response\xframe(); - Response\xss(); - Response\nosniff(); -}); - -// Show help -Router\get_action('unread', function() use ($wallabag) { - $view = 'home'; - $id = 0; - - $tpl_vars = array( - 'referer' => $wallabag->routing->referer, - 'view' => $wallabag->routing->view, - 'poche_url' => Tools::getPocheUrl(), - 'title' => _('wallabag, a read it later open source system'), - 'token' => \Session::getToken(), - 'theme' => $wallabag->tpl->getTheme(), - 'entries' => '', - 'page_links' => '', - 'nb_results' => '', - 'listmode' => (isset($_COOKIE['listmode']) ? true : false), - ); - - $count = $wallabag->store->getEntriesByViewCount($view, $wallabag->user->getId(), $id); - - if ($count > 0) { - $wallabag->pagination->set_total($count); - $page_links = str_replace(array('previous', 'next'), array(_('previous'), _('next')), - $wallabag->pagination->page_links('?view=' . $view . '&sort=' . $_SESSION['sort'] . (($id)?'&id='.$id:'') . '&' )); - $tpl_vars['entries'] = $wallabag->store->getEntriesByView($view, $wallabag->user->getId(), $wallabag->pagination->get_limit(), $id); - $tpl_vars['page_links'] = $page_links; - $tpl_vars['nb_results'] = $count; - } - - $wallabag->routing->render('home.twig', $tpl_vars); - - Tools::logm('display ' . $view . ' view'); - -}); +// Let's rock ! +$wallabag = new Poche(); From d610968932539ea9c59d4a3b3c261a9adeb92234 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicolas=20L=C5=93uillet?= Date: Sat, 12 Jul 2014 16:40:00 +0200 Subject: [PATCH 04/13] ignore my PHPStorm config --- .gitignore | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index aec2e3ef5..c3377147c 100644 --- a/.gitignore +++ b/.gitignore @@ -4,4 +4,5 @@ vendor composer.phar db/poche.sqlite inc/poche/config.inc.php -inc/3rdparty/htmlpurifier/HTMLPurifier/DefinitionCache/Serializer/ \ No newline at end of file +inc/3rdparty/htmlpurifier/HTMLPurifier/DefinitionCache/Serializer/ +.idea/* \ No newline at end of file From b6a3c8866a4cb88b009e7ba45c5e223e0fdae188 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicolas=20L=C5=93uillet?= Date: Sat, 12 Jul 2014 16:41:55 +0200 Subject: [PATCH 05/13] forgot run() call --- index.php | 1 + 1 file changed, 1 insertion(+) diff --git a/index.php b/index.php index e199956c4..a26f458ae 100755 --- a/index.php +++ b/index.php @@ -18,3 +18,4 @@ Session::init(); // Let's rock ! $wallabag = new Poche(); +$wallabag->run(); \ No newline at end of file From 2f26729c841a68669a1baf799091cb2c6c9f585a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicolas=20L=C5=93uillet?= Date: Sat, 12 Jul 2014 19:01:11 +0200 Subject: [PATCH 06/13] Refactor --- inc/poche/Language.class.php | 3 +- inc/poche/Poche.class.php | 503 ++++++++++++------------------- inc/poche/Routing.class.php | 13 +- inc/poche/Template.class.php | 3 +- inc/poche/Tools.class.php | 41 ++- inc/poche/WallabagEpub.class.php | 137 +++++++++ inc/poche/global.inc.php | 1 + inc/poche/pochePictures.php | 5 - themes/baggy/home.twig | 6 +- themes/baggy/view.twig | 2 +- themes/courgette/_view.twig | 2 +- themes/courgette/home.twig | 6 +- themes/default/home.twig | 6 +- themes/default/view.twig | 2 +- 14 files changed, 391 insertions(+), 339 deletions(-) create mode 100644 inc/poche/WallabagEpub.class.php diff --git a/inc/poche/Language.class.php b/inc/poche/Language.class.php index 790cc197a..8d3912f5f 100644 --- a/inc/poche/Language.class.php +++ b/inc/poche/Language.class.php @@ -107,8 +107,7 @@ class Language $_SESSION['poche_user']->setConfig($currentConfig); - $this->wallabag->emptyCache(); - + Tools::emptyCache(); Tools::redirect('?view=config'); } } \ No newline at end of file diff --git a/inc/poche/Poche.class.php b/inc/poche/Poche.class.php index bc4320b83..a49413f23 100755 --- a/inc/poche/Poche.class.php +++ b/inc/poche/Poche.class.php @@ -74,27 +74,25 @@ class Poche /** * Creates a new user */ - public function createNewUser() + public function createNewUser($username, $password) { - if (isset($_GET['newuser'])){ - if ($_POST['newusername'] != "" && $_POST['password4newuser'] != ""){ - $newusername = filter_var($_POST['newusername'], FILTER_SANITIZE_STRING); - if (!$this->store->userExists($newusername)){ - if ($this->store->install($newusername, Tools::encodeString($_POST['password4newuser'] . $newusername))) { - Tools::logm('The new user '.$newusername.' has been installed'); - $this->messages->add('s', sprintf(_('The new user %s has been installed. Do you want to logout ?'),$newusername)); - Tools::redirect(); - } - else { - Tools::logm('error during adding new user'); - Tools::redirect(); - } - } - else { - $this->messages->add('e', sprintf(_('Error : An user with the name %s already exists !'),$newusername)); - Tools::logm('An user with the name '.$newusername.' already exists !'); + if (!empty($username) && !empty($password)){ + $newUsername = filter_var($username, FILTER_SANITIZE_STRING); + if (!$this->store->userExists($newUsername)){ + if ($this->store->install($newUsername, Tools::encodeString($password . $newUsername))) { + Tools::logm('The new user ' . $newUsername . ' has been installed'); + $this->messages->add('s', sprintf(_('The new user %s has been installed. Do you want to logout ?'), $newUsername)); Tools::redirect(); } + else { + Tools::logm('error during adding new user'); + Tools::redirect(); + } + } + else { + $this->messages->add('e', sprintf(_('Error : An user with the name %s already exists !'), $newUsername)); + Tools::logm('An user with the name ' . $newUsername . ' already exists !'); + Tools::redirect(); } } } @@ -102,33 +100,31 @@ class Poche /** * Delete an existing user */ - public function deleteUser() + public function deleteUser($password) { - if (isset($_GET['deluser'])){ - if ($this->store->listUsers() > 1) { - if (Tools::encodeString($_POST['password4deletinguser'].$this->user->getUsername()) == $this->store->getUserPassword($this->user->getId())) { - $username = $this->user->getUsername(); - $this->store->deleteUserConfig($this->user->getId()); - Tools::logm('The configuration for user '. $username .' has been deleted !'); - $this->store->deleteTagsEntriesAndEntries($this->user->getId()); - Tools::logm('The entries for user '. $username .' has been deleted !'); - $this->store->deleteUser($this->user->getId()); - Tools::logm('User '. $username .' has been completely deleted !'); - Session::logout(); - Tools::logm('logout'); - Tools::redirect(); - $this->messages->add('s', sprintf(_('User %s has been successfully deleted !'),$newusername)); - } - else { - Tools::logm('Bad password !'); - $this->messages->add('e', _('Error : The password is wrong !')); - } + if ($this->store->listUsers() > 1) { + if (Tools::encodeString($password . $this->user->getUsername()) == $this->store->getUserPassword($this->user->getId())) { + $username = $this->user->getUsername(); + $this->store->deleteUserConfig($this->user->getId()); + Tools::logm('The configuration for user '. $username .' has been deleted !'); + $this->store->deleteTagsEntriesAndEntries($this->user->getId()); + Tools::logm('The entries for user '. $username .' has been deleted !'); + $this->store->deleteUser($this->user->getId()); + Tools::logm('User '. $username .' has been completely deleted !'); + Session::logout(); + Tools::logm('logout'); + Tools::redirect(); + $this->messages->add('s', sprintf(_('User %s has been successfully deleted !'), $username)); } else { - Tools::logm('Only user !'); - $this->messages->add('e', _('Error : You are the only user, you cannot delete your account !')); + Tools::logm('Bad password !'); + $this->messages->add('e', _('Error : The password is wrong !')); } } + else { + Tools::logm('Only user !'); + $this->messages->add('e', _('Error : You are the only user, you cannot delete your account !')); + } } public function getDefaultConfig() @@ -153,7 +149,7 @@ class Poche $body = $content['rss']['channel']['item']['description']; // clean content from prevent xss attack - $purifier = $this->getPurifier(); + $purifier = $this->_getPurifier(); $title = $purifier->purify($title); $body = $purifier->purify($body); @@ -318,10 +314,10 @@ class Poche switch ($view) { case 'config': - $dev_infos = $this->getPocheVersion('dev'); + $dev_infos = $this->_getPocheVersion('dev'); $dev = trim($dev_infos[0]); $check_time_dev = date('d-M-Y H:i', $dev_infos[1]); - $prod_infos = $this->getPocheVersion('prod'); + $prod_infos = $this->_getPocheVersion('prod'); $prod = trim($prod_infos[0]); $check_time_prod = date('d-M-Y H:i', $prod_infos[1]); $compare_dev = version_compare(POCHE, $dev); @@ -461,7 +457,7 @@ class Poche * @todo set the new password in function header like this updatePassword($newPassword) * @return boolean */ - public function updatePassword() + public function updatePassword($password, $confirmPassword) { if (MODE_DEMO) { $this->messages->add('i', _('in demo mode, you can\'t update your password')); @@ -469,10 +465,10 @@ class Poche Tools::redirect('?view=config'); } else { - if (isset($_POST['password']) && isset($_POST['password_repeat'])) { - if ($_POST['password'] == $_POST['password_repeat'] && $_POST['password'] != "") { + if (isset($password) && isset($confirmPassword)) { + if ($password == $confirmPassword && !empty($password)) { $this->messages->add('s', _('your password has been updated')); - $this->store->updatePassword($this->user->getId(), Tools::encodeString($_POST['password'] . $this->user->getUsername())); + $this->store->updatePassword($this->user->getId(), Tools::encodeString($password . $this->user->getUsername())); Session::logout(); Tools::logm('password updated'); Tools::redirect(); @@ -486,22 +482,24 @@ class Poche } /** - * get credentials from differents sources - * it redirects the user to the $referer link + * Get credentials from differents sources + * It redirects the user to the $referer link + * * @return array */ - private function credentials() { - if(isset($_SERVER['PHP_AUTH_USER'])) { - return array($_SERVER['PHP_AUTH_USER'],'php_auth',true); + private function credentials() + { + if (isset($_SERVER['PHP_AUTH_USER'])) { + return array($_SERVER['PHP_AUTH_USER'], 'php_auth', true); } - if(!empty($_POST['login']) && !empty($_POST['password'])) { - return array($_POST['login'],$_POST['password'],false); + if (!empty($_POST['login']) && !empty($_POST['password'])) { + return array($_POST['login'], $_POST['password'], false); } - if(isset($_SERVER['REMOTE_USER'])) { - return array($_SERVER['REMOTE_USER'],'http_auth',true); + if (isset($_SERVER['REMOTE_USER'])) { + return array($_SERVER['REMOTE_USER'], 'http_auth', true); } - return array(false,false,false); + return array(false, false, false); } /** @@ -550,129 +548,148 @@ class Poche } /** - * import datas into your poche + * import datas into your wallabag * @return boolean */ - public function import() { + public function import() + { + if (isset($_FILES['file'])) { + Tools::logm('Import stated: parsing file'); - if ( isset($_FILES['file']) ) { - Tools::logm('Import stated: parsing file'); + // assume, that file is in json format - // assume, that file is in json format - $str_data = file_get_contents($_FILES['file']['tmp_name']); - $data = json_decode($str_data, true); + $str_data = file_get_contents($_FILES['file']['tmp_name']); + $data = json_decode($str_data, true); + if ($data === null) { - if ( $data === null ) { - //not json - assume html - $html = new simple_html_dom(); - $html->load_file($_FILES['file']['tmp_name']); - $data = array(); - $read = 0; - foreach (array('ol','ul') as $list) { - foreach ($html->find($list) as $ul) { - foreach ($ul->find('li') as $li) { - $tmpEntry = array(); - $a = $li->find('a'); - $tmpEntry['url'] = $a[0]->href; - $tmpEntry['tags'] = $a[0]->tags; - $tmpEntry['is_read'] = $read; - if ($tmpEntry['url']) { - $data[] = $tmpEntry; - } - } - # the second
    is for read links - $read = ((sizeof($data) && $read)?0:1); + // not json - assume html + + $html = new simple_html_dom(); + $html->load_file($_FILES['file']['tmp_name']); + $data = array(); + $read = 0; + foreach(array('ol','ul') as $list) { + foreach($html->find($list) as $ul) { + foreach($ul->find('li') as $li) { + $tmpEntry = array(); + $a = $li->find('a'); + $tmpEntry['url'] = $a[0]->href; + $tmpEntry['tags'] = $a[0]->tags; + $tmpEntry['is_read'] = $read; + if ($tmpEntry['url']) { + $data[] = $tmpEntry; + } + } + + // the second
      is for read links + + $read = ((sizeof($data) && $read) ? 0 : 1); + } + } } - } - } - //for readability structure - foreach ($data as $record) { - if (is_array($record)) { - $data[] = $record; - foreach ($record as $record2) { - if (is_array($record2)) { - $data[] = $record2; - } + // for readability structure + + foreach($data as $record) { + if (is_array($record)) { + $data[] = $record; + foreach($record as $record2) { + if (is_array($record2)) { + $data[] = $record2; + } + } + } } - } - } - $urlsInserted = array(); //urls of articles inserted - foreach ($data as $record) { - $url = trim( isset($record['article__url']) ? $record['article__url'] : (isset($record['url']) ? $record['url'] : '') ); - if ( $url and !in_array($url, $urlsInserted) ) { - $title = (isset($record['title']) ? $record['title'] : _('Untitled - Import - ').' '._('click to finish import').''); - $body = (isset($record['content']) ? $record['content'] : ''); - $isRead = (isset($record['is_read']) ? intval($record['is_read']) : (isset($record['archive'])?intval($record['archive']):0)); - $isFavorite = (isset($record['is_fav']) ? intval($record['is_fav']) : (isset($record['favorite'])?intval($record['favorite']):0) ); - //insert new record - $id = $this->store->add($url, $title, $body, $this->user->getId(), $isFavorite, $isRead); - if ( $id ) { - $urlsInserted[] = $url; //add + $urlsInserted = array(); //urls of articles inserted + foreach($data as $record) { + $url = trim(isset($record['article__url']) ? $record['article__url'] : (isset($record['url']) ? $record['url'] : '')); + if ($url and !in_array($url, $urlsInserted)) { + $title = (isset($record['title']) ? $record['title'] : _('Untitled - Import - ') . ' ' . _('click to finish import') . ''); + $body = (isset($record['content']) ? $record['content'] : ''); + $isRead = (isset($record['is_read']) ? intval($record['is_read']) : (isset($record['archive']) ? intval($record['archive']) : 0)); + $isFavorite = (isset($record['is_fav']) ? intval($record['is_fav']) : (isset($record['favorite']) ? intval($record['favorite']) : 0)); - if ( isset($record['tags']) && trim($record['tags']) ) { - //@TODO: set tags + // insert new record - } + $id = $this->store->add($url, $title, $body, $this->user->getId() , $isFavorite, $isRead); + if ($id) { + $urlsInserted[] = $url; //add + if (isset($record['tags']) && trim($record['tags'])) { + + // @TODO: set tags + + } + } + } } - } + + $i = sizeof($urlsInserted); + if ($i > 0) { + $this->messages->add('s', _('Articles inserted: ') . $i . _('. Please note, that some may be marked as "read".')); + } + + Tools::logm('Import of articles finished: ' . $i . ' articles added (w/o content if not provided).'); } - $i = sizeof($urlsInserted); - if ( $i > 0 ) { - $this->messages->add('s', _('Articles inserted: ').$i._('. Please note, that some may be marked as "read".')); + // file parsing finished here + // now download article contents if any + // check if we need to download any content + + $recordsDownloadRequired = $this->store->retrieveUnfetchedEntriesCount($this->user->getId()); + + if ($recordsDownloadRequired == 0) { + + // nothing to download + + $this->messages->add('s', _('Import finished.')); + Tools::logm('Import finished completely'); + Tools::redirect(); } - Tools::logm('Import of articles finished: '.$i.' articles added (w/o content if not provided).'); - } - //file parsing finished here + else { - //now download article contents if any + // if just inserted - don't download anything, download will start in next reload - //check if we need to download any content - $recordsDownloadRequired = $this->store->retrieveUnfetchedEntriesCount($this->user->getId()); - if ( $recordsDownloadRequired == 0 ) { - //nothing to download - $this->messages->add('s', _('Import finished.')); - Tools::logm('Import finished completely'); - Tools::redirect(); - } - else { - //if just inserted - don't download anything, download will start in next reload - if ( !isset($_FILES['file']) ) { - //download next batch - Tools::logm('Fetching next batch of articles...'); - $items = $this->store->retrieveUnfetchedEntries($this->user->getId(), IMPORT_LIMIT); + if (!isset($_FILES['file'])) { - $purifier = $this->getPurifier(); + // download next batch - foreach ($items as $item) { - $url = new Url(base64_encode($item['url'])); - Tools::logm('Fetching article '.$item['id']); - $content = Tools::getPageContent($url); + Tools::logm('Fetching next batch of articles...'); + $items = $this->store->retrieveUnfetchedEntries($this->user->getId() , IMPORT_LIMIT); + $purifier = $this->_getPurifier(); + foreach($items as $item) { + $url = new Url(base64_encode($item['url'])); + Tools::logm('Fetching article ' . $item['id']); + $content = Tools::getPageContent($url); + $title = (($content['rss']['channel']['item']['title'] != '') ? $content['rss']['channel']['item']['title'] : _('Untitled')); + $body = (($content['rss']['channel']['item']['description'] != '') ? $content['rss']['channel']['item']['description'] : _('Undefined')); - $title = (($content['rss']['channel']['item']['title'] != '') ? $content['rss']['channel']['item']['title'] : _('Untitled')); - $body = (($content['rss']['channel']['item']['description'] != '') ? $content['rss']['channel']['item']['description'] : _('Undefined')); - - //clean content to prevent xss attack - $title = $purifier->purify($title); - $body = $purifier->purify($body); - - $this->store->updateContentAndTitle($item['id'], $title, $body, $this->user->getId()); - Tools::logm('Article '.$item['id'].' updated.'); - } + // clean content to prevent xss attack + $title = $purifier->purify($title); + $body = $purifier->purify($body); + $this->store->updateContentAndTitle($item['id'], $title, $body, $this->user->getId()); + Tools::logm('Article ' . $item['id'] . ' updated.'); + } + } } - } - return array('includeImport'=>true, 'import'=>array('recordsDownloadRequired'=>$recordsDownloadRequired, 'recordsUnderDownload'=> IMPORT_LIMIT, 'delay'=> IMPORT_DELAY * 1000) ); + return array( + 'includeImport' => true, + 'import' => array( + 'recordsDownloadRequired' => $recordsDownloadRequired, + 'recordsUnderDownload' => IMPORT_LIMIT, + 'delay' => IMPORT_DELAY * 1000 + ) + ); } /** * export poche entries in json * @return json all poche entries */ - public function export() { + public function export() + { $filename = "wallabag-export-".$this->user->getId()."-".date("Y-m-d").".json"; header('Content-Disposition: attachment; filename='.$filename); @@ -688,7 +705,7 @@ class Poche * @param string $which 'prod' or 'dev' * @return string latest $which version */ - private function getPocheVersion($which = 'prod') { + private function _getPocheVersion($which = 'prod') { $cache_file = CACHE . '/' . $which; $check_time = time(); @@ -703,29 +720,27 @@ class Poche return array($version, $check_time); } - public function generateToken() + /** + * Update token for current user + */ + public function updateToken() { - if (ini_get('open_basedir') === '') { - if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') { - echo 'This is a server using Windows!'; - // alternative to /dev/urandom for Windows - $token = substr(base64_encode(uniqid(mt_rand(), true)), 0, 20); - } else { - $token = substr(base64_encode(file_get_contents('/dev/urandom', false, null, 0, 20)), 0, 15); - } - } - else { - $token = substr(base64_encode(uniqid(mt_rand(), true)), 0, 20); - } - - $token = str_replace('+', '', $token); - $this->store->updateUserConfig($this->user->getId(), 'token', $token); - $currentConfig = $_SESSION['poche_user']->config; - $currentConfig['token'] = $token; - $_SESSION['poche_user']->setConfig($currentConfig); - Tools::redirect(); + $token = Tools::generateToken(); + $this->store->updateUserConfig($this->user->getId(), 'token', $token); + $currentConfig = $_SESSION['poche_user']->config; + $currentConfig['token'] = $token; + $_SESSION['poche_user']->setConfig($currentConfig); + Tools::redirect(); } + /** + * Generate RSS feeds for current user + * + * @param $token + * @param $user_id + * @param $tag_id + * @param string $type + */ public function generateFeeds($token, $user_id, $tag_id, $type = 'home') { $allowed_types = array('home', 'fav', 'archive', 'tag'); @@ -738,7 +753,6 @@ class Poche if (!in_array($type, $allowed_types) || $token != $config['token']) { die(_('Uh, there is a problem while generating feeds.')); } - // Check the token $feed = new FeedWriter(RSS2); $feed->setTitle('wallabag — ' . $type . ' feed'); @@ -770,147 +784,22 @@ class Poche exit; } - public function emptyCache() { - $files = new RecursiveIteratorIterator( - new RecursiveDirectoryIterator(CACHE, RecursiveDirectoryIterator::SKIP_DOTS), - RecursiveIteratorIterator::CHILD_FIRST - ); - foreach ($files as $fileinfo) { - $todo = ($fileinfo->isDir() ? 'rmdir' : 'unlink'); - $todo($fileinfo->getRealPath()); - } - - Tools::logm('empty cache'); - $this->messages->add('s', _('Cache deleted.')); - Tools::redirect(); - } /** - * return new purifier object with actual config + * Returns new purifier object with actual config */ - protected function getPurifier() { - $config = HTMLPurifier_Config::createDefault(); - $config->set('Cache.SerializerPath', CACHE); - $config->set('HTML.SafeIframe', true); + private function _getPurifier() + { + $config = HTMLPurifier_Config::createDefault(); + $config->set('Cache.SerializerPath', CACHE); + $config->set('HTML.SafeIframe', true); - //allow YouTube, Vimeo and dailymotion videos - $config->set('URI.SafeIframeRegexp', '%^(https?:)?//(www\.youtube(?:-nocookie)?\.com/embed/|player\.vimeo\.com/video/|www\.dailymotion\.com/embed/video/)%'); + //allow YouTube, Vimeo and dailymotion videos + $config->set('URI.SafeIframeRegexp', '%^(https?:)?//(www\.youtube(?:-nocookie)?\.com/embed/|player\.vimeo\.com/video/|www\.dailymotion\.com/embed/video/)%'); - return new HTMLPurifier($config); + return new HTMLPurifier($config); } - /** - * handle epub - */ - public function createEpub() { - switch ($_GET['method']) { - case 'id': - $entryID = filter_var($_GET['id'],FILTER_SANITIZE_NUMBER_INT); - $entry = $this->store->retrieveOneById($entryID, $this->user->getId()); - $entries = array($entry); - $bookTitle = $entry['title']; - $bookFileName = substr($bookTitle, 0, 200); - break; - case 'all': - $entries = $this->store->retrieveAll($this->user->getId()); - $bookTitle = sprintf(_('All my articles on '), date(_('d.m.y'))); #translatable because each country has it's own date format system - $bookFileName = _('Allarticles') . date(_('dmY')); - break; - case 'tag': - $tag = filter_var($_GET['tag'],FILTER_SANITIZE_STRING); - $tags_id = $this->store->retrieveAllTags($this->user->getId(),$tag); - $tag_id = $tags_id[0]["id"]; // we take the first result, which is supposed to match perfectly. There must be a workaround. - $entries = $this->store->retrieveEntriesByTag($tag_id,$this->user->getId()); - $bookTitle = sprintf(_('Articles tagged %s'),$tag); - $bookFileName = substr(sprintf(_('Tag %s'),$tag), 0, 200); - break; - case 'category': - $category = filter_var($_GET['category'],FILTER_SANITIZE_STRING); - $entries = $this->store->getEntriesByView($category,$this->user->getId()); - $bookTitle = sprintf(_('All articles in category %s'), $category); - $bookFileName = substr(sprintf(_('Category %s'),$category), 0, 200); - break; - case 'search': - $search = filter_var($_GET['search'],FILTER_SANITIZE_STRING); - $entries = $this->store->search($search,$this->user->getId()); - $bookTitle = sprintf(_('All articles for search %s'), $search); - $bookFileName = substr(sprintf(_('Search %s'), $search), 0, 200); - break; - case 'default': - die(_('Uh, there is a problem while generating epub.')); - - } - - $content_start = - "\n" - . "\n" - . "" - . "\n" - . "wallabag articles book\n" - . "\n" - . "\n"; - - $bookEnd = "\n\n"; - - $log = new Logger("wallabag", TRUE); - $fileDir = CACHE; - - $book = new EPub(EPub::BOOK_VERSION_EPUB3, DEBUG_POCHE); - $log->logLine("new EPub()"); - $log->logLine("EPub class version: " . EPub::VERSION); - $log->logLine("EPub Req. Zip version: " . EPub::REQ_ZIP_VERSION); - $log->logLine("Zip version: " . Zip::VERSION); - $log->logLine("getCurrentServerURL: " . $book->getCurrentServerURL()); - $log->logLine("getCurrentPageURL..: " . $book->getCurrentPageURL()); - - $book->setTitle(_('wallabag\'s articles')); - $book->setIdentifier("http://$_SERVER[HTTP_HOST]", EPub::IDENTIFIER_URI); // Could also be the ISBN number, prefered for published books, or a UUID. - //$book->setLanguage("en"); // Not needed, but included for the example, Language is mandatory, but EPub defaults to "en". Use RFC3066 Language codes, such as "en", "da", "fr" etc. - $book->setDescription(_("Some articles saved on my wallabag")); - $book->setAuthor("wallabag","wallabag"); - $book->setPublisher("wallabag","wallabag"); // I hope this is a non existant address :) - $book->setDate(time()); // Strictly not needed as the book date defaults to time(). - //$book->setRights("Copyright and licence information specific for the book."); // As this is generated, this _could_ contain the name or licence information of the user who purchased the book, if needed. If this is used that way, the identifier must also be made unique for the book. - $book->setSourceURL("http://$_SERVER[HTTP_HOST]"); - - $book->addDublinCoreMetadata(DublinCore::CONTRIBUTOR, "PHP"); - $book->addDublinCoreMetadata(DublinCore::CONTRIBUTOR, "wallabag"); - - $cssData = "body {\n margin-left: .5em;\n margin-right: .5em;\n text-align: justify;\n}\n\np {\n font-family: serif;\n font-size: 10pt;\n text-align: justify;\n text-indent: 1em;\n margin-top: 0px;\n margin-bottom: 1ex;\n}\n\nh1, h2 {\n font-family: sans-serif;\n font-style: italic;\n text-align: center;\n background-color: #6b879c;\n color: white;\n width: 100%;\n}\n\nh1 {\n margin-bottom: 2px;\n}\n\nh2 {\n margin-top: -2px;\n margin-bottom: 2px;\n}\n"; - - $log->logLine("Add Cover"); - - $fullTitle = "

      " . $bookTitle . "

      \n"; - - $book->setCoverImage("Cover.png", file_get_contents("themes/baggy/img/apple-touch-icon-152.png"), "image/png", $fullTitle); - - $cover = $content_start . '

      ' . _('Produced by wallabag with PHPePub') . '

      '. _('Please open an issue if you have trouble with the display of this E-Book on your device.') . '

      ' . $bookEnd; - - //$book->addChapter("Table of Contents", "TOC.xhtml", NULL, false, EPub::EXTERNAL_REF_IGNORE); - $book->addChapter("Notices", "Cover2.html", $cover); - - $book->buildTOC(); - - foreach ($entries as $entry) { //set tags as subjects - $tags = $this->store->retrieveTagsByEntry($entry['id']); - foreach ($tags as $tag) { - $book->setSubject($tag['value']); - } - - $log->logLine("Set up parameters"); - - $chapter = $content_start . $entry['content'] . $bookEnd; - $book->addChapter($entry['title'], htmlspecialchars($entry['title']) . ".html", $chapter, true, EPub::EXTERNAL_REF_ADD); - $log->logLine("Added chapter " . $entry['title']); - } - - if (DEBUG_POCHE) { - $epuplog = $book->getLog(); - $book->addChapter("Log", "Log.html", $content_start . $log->getLog() . "\n" . $bookEnd); // log generation - } - $book->finalize(); - $zipData = $book->sendBook($bookFileName); - } } diff --git a/inc/poche/Routing.class.php b/inc/poche/Routing.class.php index 8c2f38e37..eb4c4d900 100644 --- a/inc/poche/Routing.class.php +++ b/inc/poche/Routing.class.php @@ -105,20 +105,21 @@ class Routing $this->wallabag->logout(); } elseif (isset($_GET['config'])) { // update password - $this->wallabag->updatePassword(); + $this->wallabag->updatePassword($_POST['password'], $_POST['password_repeat']); } elseif (isset($_GET['newuser'])) { - $this->wallabag->createNewUser(); + $this->wallabag->createNewUser($_POST['newusername'], $_POST['password4newuser']); } elseif (isset($_GET['deluser'])) { - $this->wallabag->deleteUser(); + $this->wallabag->deleteUser($_POST['password4deletinguser']); } elseif (isset($_GET['epub'])) { - $this->wallabag->createEpub(); + $epub = new WallabagEpub($this->wallabag, $_GET['method'], $_GET['id'], $_GET['value']); + $epub->run(); } elseif (isset($_GET['import'])) { $import = $this->wallabag->import(); $tplVars = array_merge($this->vars, $import); } elseif (isset($_GET['download'])) { Tools::downloadDb(); } elseif (isset($_GET['empty-cache'])) { - $this->wallabag->emptyCache(); + Tools::emptyCache(); } elseif (isset($_GET['export'])) { $this->wallabag->export(); } elseif (isset($_GET['updatetheme'])) { @@ -129,7 +130,7 @@ class Routing $this->wallabag->uploadFile(); } elseif (isset($_GET['feed'])) { if (isset($_GET['action']) && $_GET['action'] == 'generate') { - $this->wallabag->generateToken(); + $this->wallabag->updateToken(); } else { $tag_id = (isset($_GET['tag_id']) ? intval($_GET['tag_id']) : 0); diff --git a/inc/poche/Template.class.php b/inc/poche/Template.class.php index 0e09ad64a..b686f2ec7 100644 --- a/inc/poche/Template.class.php +++ b/inc/poche/Template.class.php @@ -229,8 +229,7 @@ class Template extends Twig_Environment $_SESSION['poche_user']->setConfig($currentConfig); - $this->wallabag->emptyCache(); - + Tools::emptyCache(); Tools::redirect('?view=config'); } } \ No newline at end of file diff --git a/inc/poche/Tools.class.php b/inc/poche/Tools.class.php index 762e44460..63137d765 100755 --- a/inc/poche/Tools.class.php +++ b/inc/poche/Tools.class.php @@ -10,11 +10,6 @@ final class Tools { - private function __construct() - { - - } - /** * Initialize PHP environment */ @@ -393,4 +388,40 @@ final class Tools return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH']==='XMLHttpRequest'; } + /* + * Empty cache folder + */ + public static function emptyCache() + { + $files = new RecursiveIteratorIterator( + new RecursiveDirectoryIterator(CACHE, RecursiveDirectoryIterator::SKIP_DOTS), + RecursiveIteratorIterator::CHILD_FIRST + ); + + foreach ($files as $fileInfo) { + $todo = ($fileInfo->isDir() ? 'rmdir' : 'unlink'); + $todo($fileInfo->getRealPath()); + } + + Tools::logm('empty cache'); + Tools::redirect(); + } + + public static function generateToken() + { + if (ini_get('open_basedir') === '') { + if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') { + // alternative to /dev/urandom for Windows + $token = substr(base64_encode(uniqid(mt_rand(), true)), 0, 20); + } else { + $token = substr(base64_encode(file_get_contents('/dev/urandom', false, null, 0, 20)), 0, 15); + } + } + else { + $token = substr(base64_encode(uniqid(mt_rand(), true)), 0, 20); + } + + return str_replace('+', '', $token); + } + } diff --git a/inc/poche/WallabagEpub.class.php b/inc/poche/WallabagEpub.class.php new file mode 100644 index 000000000..b81d9bfd2 --- /dev/null +++ b/inc/poche/WallabagEpub.class.php @@ -0,0 +1,137 @@ + + * @copyright 2013 + * @license http://opensource.org/licenses/MIT see COPYING file + */ + +class WallabagEpub +{ + protected $wallabag; + protected $method; + protected $id; + protected $value; + + public function __construct(Poche $wallabag, $method, $id, $value) + { + $this->wallabag = $wallabag; + $this->method = $method; + $this->id = $id; + $this->value = $value; + } + + /** + * handle ePub + */ + public function run() + { + switch ($this->method) { + case 'id': + $entryID = filter_var($this->id, FILTER_SANITIZE_NUMBER_INT); + $entry = $this->wallabag->store->retrieveOneById($entryID, $this->wallabag->user->getId()); + $entries = array($entry); + $bookTitle = $entry['title']; + $bookFileName = substr($bookTitle, 0, 200); + break; + case 'all': + $entries = $this->wallabag->store->retrieveAll($this->wallabag->user->getId()); + $bookTitle = sprintf(_('All my articles on '), date(_('d.m.y'))); #translatable because each country has it's own date format system + $bookFileName = _('Allarticles') . date(_('dmY')); + break; + case 'tag': + $tag = filter_var($this->value, FILTER_SANITIZE_STRING); + $tags_id = $this->wallabag->store->retrieveAllTags($this->wallabag->user->getId(), $tag); + $tag_id = $tags_id[0]["id"]; // we take the first result, which is supposed to match perfectly. There must be a workaround. + $entries = $this->wallabag->store->retrieveEntriesByTag($tag_id, $this->wallabag->user->getId()); + $bookTitle = sprintf(_('Articles tagged %s'), $tag); + $bookFileName = substr(sprintf(_('Tag %s'), $tag), 0, 200); + break; + case 'category': + $category = filter_var($this->value, FILTER_SANITIZE_STRING); + $entries = $this->wallabag->store->getEntriesByView($category, $this->wallabag->user->getId()); + $bookTitle = sprintf(_('All articles in category %s'), $category); + $bookFileName = substr(sprintf(_('Category %s'), $category), 0, 200); + break; + case 'search': + $search = filter_var($this->value, FILTER_SANITIZE_STRING); + $entries = $this->store->search($search, $this->wallabag->user->getId()); + $bookTitle = sprintf(_('All articles for search %s'), $search); + $bookFileName = substr(sprintf(_('Search %s'), $search), 0, 200); + break; + case 'default': + die(_('Uh, there is a problem while generating epub.')); + } + + $content_start = + "\n" + . "\n" + . "" + . "\n" + . "wallabag articles book\n" + . "\n" + . "\n"; + + $bookEnd = "\n\n"; + + $log = new Logger("wallabag", TRUE); + $fileDir = CACHE; + + $book = new EPub(EPub::BOOK_VERSION_EPUB3, DEBUG_POCHE); + $log->logLine("new EPub()"); + $log->logLine("EPub class version: " . EPub::VERSION); + $log->logLine("EPub Req. Zip version: " . EPub::REQ_ZIP_VERSION); + $log->logLine("Zip version: " . Zip::VERSION); + $log->logLine("getCurrentServerURL: " . $book->getCurrentServerURL()); + $log->logLine("getCurrentPageURL..: " . $book->getCurrentPageURL()); + + $book->setTitle(_('wallabag\'s articles')); + $book->setIdentifier("http://$_SERVER[HTTP_HOST]", EPub::IDENTIFIER_URI); // Could also be the ISBN number, prefered for published books, or a UUID. + //$book->setLanguage("en"); // Not needed, but included for the example, Language is mandatory, but EPub defaults to "en". Use RFC3066 Language codes, such as "en", "da", "fr" etc. + $book->setDescription(_("Some articles saved on my wallabag")); + $book->setAuthor("wallabag", "wallabag"); + $book->setPublisher("wallabag", "wallabag"); // I hope this is a non existant address :) + $book->setDate(time()); // Strictly not needed as the book date defaults to time(). + //$book->setRights("Copyright and licence information specific for the book."); // As this is generated, this _could_ contain the name or licence information of the user who purchased the book, if needed. If this is used that way, the identifier must also be made unique for the book. + $book->setSourceURL("http://$_SERVER[HTTP_HOST]"); + + $book->addDublinCoreMetadata(DublinCore::CONTRIBUTOR, "PHP"); + $book->addDublinCoreMetadata(DublinCore::CONTRIBUTOR, "wallabag"); + + $cssData = "body {\n margin-left: .5em;\n margin-right: .5em;\n text-align: justify;\n}\n\np {\n font-family: serif;\n font-size: 10pt;\n text-align: justify;\n text-indent: 1em;\n margin-top: 0px;\n margin-bottom: 1ex;\n}\n\nh1, h2 {\n font-family: sans-serif;\n font-style: italic;\n text-align: center;\n background-color: #6b879c;\n color: white;\n width: 100%;\n}\n\nh1 {\n margin-bottom: 2px;\n}\n\nh2 {\n margin-top: -2px;\n margin-bottom: 2px;\n}\n"; + + $log->logLine("Add Cover"); + + $fullTitle = "

      " . $bookTitle . "

      \n"; + + $book->setCoverImage("Cover.png", file_get_contents("themes/baggy/img/apple-touch-icon-152.png"), "image/png", $fullTitle); + + $cover = $content_start . '

      ' . _('Produced by wallabag with PHPePub') . '

      '. _('Please open an issue if you have trouble with the display of this E-Book on your device.') . '

      ' . $bookEnd; + + //$book->addChapter("Table of Contents", "TOC.xhtml", NULL, false, EPub::EXTERNAL_REF_IGNORE); + $book->addChapter("Notices", "Cover2.html", $cover); + + $book->buildTOC(); + + foreach ($entries as $entry) { //set tags as subjects + $tags = $this->wallabag->store->retrieveTagsByEntry($entry['id']); + foreach ($tags as $tag) { + $book->setSubject($tag['value']); + } + + $log->logLine("Set up parameters"); + + $chapter = $content_start . $entry['content'] . $bookEnd; + $book->addChapter($entry['title'], htmlspecialchars($entry['title']) . ".html", $chapter, true, EPub::EXTERNAL_REF_ADD); + $log->logLine("Added chapter " . $entry['title']); + } + + if (DEBUG_POCHE) { + $book->addChapter("Log", "Log.html", $content_start . $log->getLog() . "\n" . $bookEnd); // log generation + } + $book->finalize(); + $zipData = $book->sendBook($bookFileName); + } +} \ No newline at end of file diff --git a/inc/poche/global.inc.php b/inc/poche/global.inc.php index 3eb64df0e..b8c487e39 100755 --- a/inc/poche/global.inc.php +++ b/inc/poche/global.inc.php @@ -22,6 +22,7 @@ require_once ROOT . '/vendor/autoload.php'; require_once INCLUDES . '/poche/Template.class.php'; require_once INCLUDES . '/poche/Language.class.php'; require_once INCLUDES . '/poche/Routing.class.php'; +require_once INCLUDES . '/poche/WallabagEpub.class.php'; require_once INCLUDES . '/poche/Poche.class.php'; require_once INCLUDES . '/poche/Database.class.php'; diff --git a/inc/poche/pochePictures.php b/inc/poche/pochePictures.php index 26bf07063..7a914f90f 100644 --- a/inc/poche/pochePictures.php +++ b/inc/poche/pochePictures.php @@ -11,11 +11,6 @@ final class Picture { - private function __construct() - { - - } - /** * Changing pictures URL in article content */ diff --git a/themes/baggy/home.twig b/themes/baggy/home.twig index 3942d3bf8..e788b588f 100755 --- a/themes/baggy/home.twig +++ b/themes/baggy/home.twig @@ -61,9 +61,9 @@ {% if search_term is defined %}{% trans %} Apply the tag {{ search_term }} to this search {% endtrans %}{% endif %} - {% if tag %}{% trans "Download the articles from this tag in an epub" %} - {% elseif search_term is defined %}{% trans "Download the articles from this search in an epub" %} - {% else %}{% trans "Download the articles from this category in an epub" %}{% endif %} + {% if tag %}{% trans "Download the articles from this tag in an epub" %} + {% elseif search_term is defined %}{% trans "Download the articles from this search in an epub" %} + {% else %}{% trans "Download the articles from this category in an epub" %}{% endif %} {% endif %} {% endblock %} diff --git a/themes/baggy/view.twig b/themes/baggy/view.twig index af97407d0..7b65340a9 100755 --- a/themes/baggy/view.twig +++ b/themes/baggy/view.twig @@ -16,7 +16,7 @@ {% if constant('SHARE_SHAARLI') == 1 %}
    1. {% trans "shaarli" %}
    2. {% endif %} {% if constant('FLATTR') == 1 %}{% if flattr.status == constant('FLATTRABLE') %}
    3. {% trans "flattr" %}
    4. {% elseif flattr.status == constant('FLATTRED') %}
    5. {% trans "flattr" %} ({{ flattr.numflattrs }})
    6. {% endif %}{% endif %} {% if constant('SHOW_PRINTLINK') == 1 %}
    7. {% trans "Print" %}
    8. {% endif %} -
    9. EPUB
    10. +
    11. EPUB
    12. {% trans "Does this article appear wrong?" %}
    13. diff --git a/themes/courgette/_view.twig b/themes/courgette/_view.twig index 25479a3d7..c5c916c04 100755 --- a/themes/courgette/_view.twig +++ b/themes/courgette/_view.twig @@ -12,7 +12,7 @@ {% if constant('SHARE_MAIL') == 1 %}
    14. {% endif %} {% if constant('SHARE_SHAARLI') == 1 %}
    15. {% trans "shaarli" %}
    16. {% endif %} {% if constant('FLATTR') == 1 %}{% if flattr.status == constant('FLATTRABLE') %}
    17. {% trans "flattr" %}
    18. {% elseif flattr.status == constant('FLATTRED') %}
    19. {% trans "flattr" %}{{ flattr.numflattrs }}
    20. {% endif %}{% endif %} -
    21. EPUB
    22. +
    23. EPUB
    24. {% trans "this article appears wrong?" %}
    25. diff --git a/themes/courgette/home.twig b/themes/courgette/home.twig index 401f3f20d..811298eb5 100755 --- a/themes/courgette/home.twig +++ b/themes/courgette/home.twig @@ -53,9 +53,9 @@ {{ block('pager') }} - {% if tag %}{% trans "Download the articles from this tag in an epub" %} - {% elseif search_term is defined %}{% trans "Download the articles from this search in an epub" %} - {% else %}{% trans "Download the articles from this category in an epub" %}{% endif %} + {% if tag %}{% trans "Download the articles from this tag in an epub" %} + {% elseif search_term is defined %}{% trans "Download the articles from this search in an epub" %} + {% else %}{% trans "Download the articles from this category in an epub" %}{% endif %} {% endif %} diff --git a/themes/default/home.twig b/themes/default/home.twig index e6c781f58..093c2dc5e 100755 --- a/themes/default/home.twig +++ b/themes/default/home.twig @@ -60,9 +60,9 @@ {% if view == 'home' %}{% if nb_results > 1 %}{% trans "mark all the entries as read" %}{% endif %}{% endif %} - {% if tag %}{% trans "Download the articles from this tag in an epub" %} - {% elseif search_term is defined %}{% trans "Download the articles from this search in an epub" %} - {% else %}{% trans "Download the articles from this category in an epub" %}{% endif %} + {% if tag %}{% trans "Download the articles from this tag in an epub" %} + {% elseif search_term is defined %}{% trans "Download the articles from this search in an epub" %} + {% else %}{% trans "Download the articles from this category in an epub" %}{% endif %} {% endif %} {% endblock %} diff --git a/themes/default/view.twig b/themes/default/view.twig index b7d48c002..90b118394 100755 --- a/themes/default/view.twig +++ b/themes/default/view.twig @@ -15,7 +15,7 @@ {% if constant('SHARE_SHAARLI') == 1 %}
    26. {% trans "shaarli" %}
    27. {% endif %} {% if constant('FLATTR') == 1 %}{% if flattr.status == constant('FLATTRABLE') %}
    28. {% trans "flattr" %}
    29. {% elseif flattr.status == constant('FLATTRED') %}
    30. {% trans "flattr" %}{{ flattr.numflattrs }}
    31. {% endif %}{% endif %} {% if constant('SHOW_PRINTLINK') == 1 %}
    32. {% trans "Print" %}
    33. {% endif %} -
    34. EPUB
    35. +
    36. EPUB
    37. {% trans "Does this article appear wrong?" %}
    38. {% if constant('SHOW_READPERCENT') == 1 %}
    39. 0%
    40. {% endif %} From d423113b009ca7d44db7bc9d09556d9857b316c8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicolas=20L=C5=93uillet?= Date: Sat, 12 Jul 2014 21:50:29 +0200 Subject: [PATCH 07/13] =?UTF-8?q?#683=20Rename=20=C2=AB=20home=20=C2=BB=20?= =?UTF-8?q?into=20=C2=AB=20unread=20=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- themes/baggy/_menu.twig | 2 +- themes/courgette/_menu.twig | 2 +- themes/default/_menu.twig | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/themes/baggy/_menu.twig b/themes/baggy/_menu.twig index f1b75cd50..59b6a46b4 100644 --- a/themes/baggy/_menu.twig +++ b/themes/baggy/_menu.twig @@ -1,6 +1,6 @@