From 6ad93dff69d7c2beb2196e73f641e6484fccbeb7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicolas=20L=C5=93uillet?= Date: Tue, 20 Jan 2015 07:40:39 +0100 Subject: new folders --- inc/poche/Database.class.php | 601 -------------------------- inc/poche/FlattrItem.class.php | 57 --- inc/poche/Language.class.php | 114 ----- inc/poche/Poche.class.php | 859 ------------------------------------- inc/poche/Routing.class.php | 161 ------- inc/poche/Template.class.php | 235 ---------- inc/poche/Tools.class.php | 420 ------------------ inc/poche/Url.class.php | 31 -- inc/poche/User.class.php | 57 --- inc/poche/WallabagEBooks.class.php | 245 ----------- inc/poche/config.inc.default.php | 78 ---- inc/poche/global.inc.php | 43 -- inc/poche/pochePictures.php | 168 -------- 13 files changed, 3069 deletions(-) delete mode 100755 inc/poche/Database.class.php delete mode 100644 inc/poche/FlattrItem.class.php delete mode 100644 inc/poche/Language.class.php delete mode 100755 inc/poche/Poche.class.php delete mode 100755 inc/poche/Routing.class.php delete mode 100644 inc/poche/Template.class.php delete mode 100755 inc/poche/Tools.class.php delete mode 100644 inc/poche/Url.class.php delete mode 100644 inc/poche/User.class.php delete mode 100644 inc/poche/WallabagEBooks.class.php delete mode 100755 inc/poche/config.inc.default.php delete mode 100755 inc/poche/global.inc.php delete mode 100644 inc/poche/pochePictures.php (limited to 'inc/poche') diff --git a/inc/poche/Database.class.php b/inc/poche/Database.class.php deleted file mode 100755 index f6ba4708..00000000 --- a/inc/poche/Database.class.php +++ /dev/null @@ -1,601 +0,0 @@ - - * @copyright 2013 - * @license http://opensource.org/licenses/MIT see COPYING file - */ - -class Database { - - var $handle; - private $order = array ( - 'ia' => 'ORDER BY entries.id', - 'id' => 'ORDER BY entries.id DESC', - 'ta' => 'ORDER BY lower(entries.title)', - 'td' => 'ORDER BY lower(entries.title) DESC', - 'default' => 'ORDER BY entries.id' - ); - - function __construct() - { - switch (STORAGE) { - case 'sqlite': - // Check if /db is writeable - if ( !is_writable(STORAGE_SQLITE) || !is_writable(dirname(STORAGE_SQLITE))) { - die('An error occured: "db" directory must be writeable for your web server user!'); - } - $db_path = 'sqlite:' . STORAGE_SQLITE; - $this->handle = new PDO($db_path); - break; - case 'mysql': - $db_path = 'mysql:host=' . STORAGE_SERVER . ';dbname=' . STORAGE_DB . ';charset=utf8mb4'; - $this->handle = new PDO($db_path, STORAGE_USER, STORAGE_PASSWORD, array( - PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8mb4', - )); - break; - case 'postgres': - $db_path = 'pgsql:host=' . STORAGE_SERVER . ';dbname=' . STORAGE_DB; - $this->handle = new PDO($db_path, STORAGE_USER, STORAGE_PASSWORD); - break; - default: - die(STORAGE . ' is not a recognised database system !'); - } - - $this->handle->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); - $this->_checkTags(); - Tools::logm('storage type ' . STORAGE); - } - - private function getHandle() - { - return $this->handle; - } - - private function _checkTags() - { - - if (STORAGE == 'sqlite') { - $sql = ' - CREATE TABLE IF NOT EXISTS tags ( - id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE, - value TEXT - )'; - } - elseif(STORAGE == 'mysql') { - $sql = ' - CREATE TABLE IF NOT EXISTS `tags` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `value` varchar(255) NOT NULL, - PRIMARY KEY (`id`) - ) ENGINE=InnoDB DEFAULT CHARSET=utf8; - '; - } - else { - $sql = ' - CREATE TABLE IF NOT EXISTS tags ( - id bigserial primary key, - value varchar(255) NOT NULL - ); - '; - } - - $query = $this->executeQuery($sql, array()); - - if (STORAGE == 'sqlite') { - $sql = ' - CREATE TABLE IF NOT EXISTS tags_entries ( - id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE, - entry_id INTEGER, - tag_id INTEGER, - FOREIGN KEY(entry_id) REFERENCES entries(id) ON DELETE CASCADE, - FOREIGN KEY(tag_id) REFERENCES tags(id) ON DELETE CASCADE - )'; - } - elseif(STORAGE == 'mysql') { - $sql = ' - CREATE TABLE IF NOT EXISTS `tags_entries` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `entry_id` int(11) NOT NULL, - `tag_id` int(11) NOT NULL, - FOREIGN KEY(entry_id) REFERENCES entries(id) ON DELETE CASCADE, - FOREIGN KEY(tag_id) REFERENCES tags(id) ON DELETE CASCADE, - PRIMARY KEY (`id`) - ) ENGINE=InnoDB DEFAULT CHARSET=utf8; - '; - } - else { - $sql = ' - CREATE TABLE IF NOT EXISTS tags_entries ( - id bigserial primary key, - entry_id integer NOT NULL, - tag_id integer NOT NULL - ) - '; - } - - $query = $this->executeQuery($sql, array()); - } - - public function install($login, $password, $email = '') - { - $sql = 'INSERT INTO users ( username, password, name, email) VALUES (?, ?, ?, ?)'; - $params = array($login, $password, $login, $email); - $query = $this->executeQuery($sql, $params); - - $sequence = ''; - if (STORAGE == 'postgres') { - $sequence = 'users_id_seq'; - } - - $id_user = intval($this->getLastId($sequence)); - - $sql = 'INSERT INTO users_config ( user_id, name, value ) VALUES (?, ?, ?)'; - $params = array($id_user, 'pager', PAGINATION); - $query = $this->executeQuery($sql, $params); - - $sql = 'INSERT INTO users_config ( user_id, name, value ) VALUES (?, ?, ?)'; - $params = array($id_user, 'language', LANG); - $query = $this->executeQuery($sql, $params); - - $sql = 'INSERT INTO users_config ( user_id, name, value ) VALUES (?, ?, ?)'; - $params = array($id_user, 'theme', DEFAULT_THEME); - $query = $this->executeQuery($sql, $params); - - return TRUE; - } - - public function getConfigUser($id) - { - $sql = "SELECT * FROM users_config WHERE user_id = ?"; - $query = $this->executeQuery($sql, array($id)); - $result = $query->fetchAll(); - $user_config = array(); - - foreach ($result as $key => $value) { - $user_config[$value['name']] = $value['value']; - } - - return $user_config; - } - - public function userExists($username) - { - $sql = "SELECT * FROM users WHERE username=?"; - $query = $this->executeQuery($sql, array($username)); - $login = $query->fetchAll(); - if (isset($login[0])) { - return true; - } else { - return false; - } - } - - public function login($username, $password, $isauthenticated = FALSE) - { - if ($isauthenticated) { - $sql = "SELECT * FROM users WHERE username=?"; - $query = $this->executeQuery($sql, array($username)); - } else { - $sql = "SELECT * FROM users WHERE username=? AND password=?"; - $query = $this->executeQuery($sql, array($username, $password)); - } - $login = $query->fetchAll(); - - $user = array(); - if (isset($login[0])) { - $user['id'] = $login[0]['id']; - $user['username'] = $login[0]['username']; - $user['password'] = $login[0]['password']; - $user['name'] = $login[0]['name']; - $user['email'] = $login[0]['email']; - $user['config'] = $this->getConfigUser($login[0]['id']); - } - - return $user; - } - - public function updatePassword($userId, $password) - { - $sql_update = "UPDATE users SET password=? WHERE id=?"; - $params_update = array($password, $userId); - $query = $this->executeQuery($sql_update, $params_update); - } - - public function updateUserConfig($userId, $key, $value) - { - $config = $this->getConfigUser($userId); - - if (! isset($config[$key])) { - $sql = "INSERT INTO users_config (value, user_id, name) VALUES (?, ?, ?)"; - } - else { - $sql = "UPDATE users_config SET value=? WHERE user_id=? AND name=?"; - } - - $params = array($value, $userId, $key); - $query = $this->executeQuery($sql, $params); - } - - private function executeQuery($sql, $params) - { - try - { - $query = $this->getHandle()->prepare($sql); - $query->execute($params); - return $query; - } - catch (Exception $e) - { - Tools::logm('execute query error : '.$e->getMessage()); - return FALSE; - } - } - - 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) - { - $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) - { - $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) - { - $entries = $this->retrieveAll($userID); - foreach($entries as $entryid) { - $tags = $this->retrieveTagsByEntry($entryid); - foreach($tags as $tag) { - $this->removeTagForEntry($entryid,$tags); - } - $this->deleteById($entryid,$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) - { - $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) - { - - $sql_limit = "LIMIT 0,".$limit; - if (STORAGE == 'postgres') { - $sql_limit = "LIMIT ".$limit." OFFSET 0"; - } - - $sql = "SELECT * FROM entries WHERE (content = '' OR content IS NULL) AND title LIKE 'Untitled - Import%' AND user_id=? ORDER BY id " . $sql_limit; - $query = $this->executeQuery($sql, array($user_id)); - $entries = $query->fetchAll(); - - return $entries; - } - - 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(); - - return $count; - } - - 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(); - - return $entries; - } - - public function retrieveOneById($id, $user_id) - { - $entry = NULL; - $sql = "SELECT * FROM entries WHERE id=? AND user_id=?"; - $params = array(intval($id), $user_id); - $query = $this->executeQuery($sql, $params); - $entry = $query->fetchAll(); - - return isset($entry[0]) ? $entry[0] : null; - } - - public function retrieveOneByURL($url, $user_id) - { - $entry = NULL; - $sql = "SELECT * FROM entries WHERE url=? AND user_id=?"; - $params = array($url, $user_id); - $query = $this->executeQuery($sql, $params); - $entry = $query->fetchAll(); - - return isset($entry[0]) ? $entry[0] : null; - } - - 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) - { - switch ($view) { - case 'archive': - $sql = "SELECT * FROM entries WHERE user_id=? AND is_read=? "; - $params = array($user_id, 1); - break; - case 'fav' : - $sql = "SELECT * FROM entries WHERE user_id=? AND is_fav=? "; - $params = array($user_id, 1); - break; - case 'tag' : - $sql = "SELECT entries.* FROM entries - LEFT JOIN tags_entries ON tags_entries.entry_id=entries.id - WHERE entries.user_id=? AND tags_entries.tag_id = ? "; - $params = array($user_id, $tag_id); - break; - default: - $sql = "SELECT * FROM entries WHERE user_id=? AND is_read=? "; - $params = array($user_id, 0); - break; - } - - $sql .= $this->getEntriesOrder().' ' . $limit; - - $query = $this->executeQuery($sql, $params); - $entries = $query->fetchAll(); - - return $entries; - } - - public function getEntriesByViewCount($view, $user_id, $tag_id = 0) - { - switch ($view) { - case 'archive': - $sql = "SELECT count(*) FROM entries WHERE user_id=? AND is_read=? "; - $params = array($user_id, 1); - break; - case 'fav' : - $sql = "SELECT count(*) FROM entries WHERE user_id=? AND is_fav=? "; - $params = array($user_id, 1); - break; - case 'tag' : - $sql = "SELECT count(*) FROM entries - LEFT JOIN tags_entries ON tags_entries.entry_id=entries.id - WHERE entries.user_id=? AND tags_entries.tag_id = ? "; - $params = array($user_id, $tag_id); - break; - default: - $sql = "SELECT count(*) FROM entries WHERE user_id=? AND is_read=? "; - $params = array($user_id, 0); - break; - } - - $query = $this->executeQuery($sql, $params); - list($count) = $query->fetch(); - - return $count; - } - - 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); - return $query; - } - - /** - * - * @param string $url - * @param string $title - * @param string $content - * @param integer $user_id - * @return integer $id of inserted record - */ - 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); - - if ( !$this->executeQuery($sql_action, $params_action) ) { - $id = null; - } - else { - $id = intval($this->getLastId( (STORAGE == 'postgres') ? 'entries_id_seq' : '') ); - } - return $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) - { - $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) - { - $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) - { - $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 = '') - { - return $this->getHandle()->lastInsertId($column); - } - - 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; - $params_action = array($user_id, $search, $search, $search); - $query = $this->executeQuery($sql_action, $params_action); - return $query->fetchAll(); - } - - 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 - WHERE entries.user_id=? - ". (($term) ? "AND lower(tags.value) LIKE ?" : '') ." - GROUP BY tags.id, tags.value - ORDER BY tags.value"; - $query = $this->executeQuery($sql, (($term)? array($user_id, strtolower('%'.$term.'%')) : array($user_id) )); - $tags = $query->fetchAll(); - - return $tags; - } - - 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 - LEFT JOIN entries ON tags_entries.entry_id=entries.id - WHERE tags.id=? AND entries.user_id=?"; - $params = array(intval($id), $user_id); - $query = $this->executeQuery($sql, $params); - $tag = $query->fetchAll(); - - return isset($tag[0]) ? $tag[0] : NULL; - } - - public function retrieveEntriesByTag($tag_id, $user_id) - { - $sql = - "SELECT entries.* FROM entries - LEFT JOIN tags_entries ON tags_entries.entry_id=entries.id - WHERE tags_entries.tag_id = ? AND entries.user_id=? ORDER by entries.id DESC"; - $query = $this->executeQuery($sql, array($tag_id, $user_id)); - $entries = $query->fetchAll(); - - return $entries; - } - - public function retrieveTagsByEntry($entry_id) - { - $sql = - "SELECT tags.* FROM tags - LEFT JOIN tags_entries ON tags_entries.tag_id=tags.id - WHERE tags_entries.entry_id = ?"; - $query = $this->executeQuery($sql, array($entry_id)); - $tags = $query->fetchAll(); - - return $tags; - } - - 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) - { - $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(); - $sql_action = "SELECT tags.* FROM tags LEFT JOIN tags_entries ON tags_entries.tag_id=tags.id WHERE tags.id=?"; - $query = $this->executeQuery($sql_action,array($tag_id)); - $alltags = $query->fetchAll(); - - foreach ($alltags as $tag) { - if ($tag && !in_array($tag,$tagstokeep)) { - $sql_action = "DELETE FROM tags WHERE id=?"; - $params_action = array($tag[0]); - $this->executeQuery($sql_action, $params_action); - return true; - } - } - - } - - public function retrieveTagByValue($value) - { - $tag = NULL; - $sql = "SELECT * FROM tags WHERE value=?"; - $params = array($value); - $query = $this->executeQuery($sql, $params); - $tag = $query->fetchAll(); - - return isset($tag[0]) ? $tag[0] : null; - } - - 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) - { - $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']; - } - } -} diff --git a/inc/poche/FlattrItem.class.php b/inc/poche/FlattrItem.class.php deleted file mode 100644 index ef8c62f7..00000000 --- a/inc/poche/FlattrItem.class.php +++ /dev/null @@ -1,57 +0,0 @@ - - * @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); - $flattrResponse = file_get_contents(CACHE . "/flattr/".$id.".cache"); - if($flattrResponse != FALSE) { - $result = json_decode($flattrResponse); - if (isset($result->message)) { - if ($result->message == "flattrable") { - $this->status = FLATTRABLE; - } - } - elseif (is_object($result) && $result->link) { - $this->status = FLATTRED; - $this->flattrItemURL = $result->link; - $this->numFlattrs = $result->flattrs; - } - else { - $this->status = NOT_FLATTRABLE; - } - } - else { - $this->status = "FLATTR_ERR_CONNECTION"; - } - } - - private function _cacheFlattrFile($urlToFlattr, $id) - { - if (!is_dir(CACHE . '/flattr')) { - mkdir(CACHE . '/flattr', 0777); - } - - // if a cache flattr file for this url already exists and it's been less than one day than it have been updated, see in /cache - if ((!file_exists(CACHE . "/flattr/".$id.".cache")) || (time() - filemtime(CACHE . "/flattr/".$id.".cache") > 86400)) { - $askForFlattr = Tools::getFile(FLATTR_API . $urlToFlattr); - $flattrCacheFile = fopen(CACHE . "/flattr/".$id.".cache", 'w+'); - fwrite($flattrCacheFile, $askForFlattr); - fclose($flattrCacheFile); - } - } -} diff --git a/inc/poche/Language.class.php b/inc/poche/Language.class.php deleted file mode 100644 index 420f2fb9..00000000 --- a/inc/poche/Language.class.php +++ /dev/null @@ -1,114 +0,0 @@ - - * @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', - 'en_US.utf8' => 'English (US)', - '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); - - Tools::emptyCache(); - Tools::redirect('?view=config'); - } -} diff --git a/inc/poche/Poche.class.php b/inc/poche/Poche.class.php deleted file mode 100755 index 8b0d3a19..00000000 --- a/inc/poche/Poche.class.php +++ /dev/null @@ -1,859 +0,0 @@ - - * @copyright 2013 - * @license http://opensource.org/licenses/MIT see COPYING file - */ - -class Poche -{ - /** - * @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; - - public function __construct() - { - $this->init(); - } - - private function init() - { - Tools::initPhp(); - - $pocheUser = Session::getParam('poche_user'); - - if ($pocheUser && $pocheUser != array()) { - $this->user = $pocheUser; - } else { - // fake user, just for install & login screens - $this->user = new User(); - $this->user->setConfig($this->getDefaultConfig()); - } - - $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 run() - { - $this->routing->run(); - } - - /** - * Creates a new user - */ - public function createNewUser($username, $password, $email = "") - { - if (!empty($username) && !empty($password)){ - $newUsername = filter_var($username, FILTER_SANITIZE_STRING); - $email = filter_var($email, FILTER_SANITIZE_STRING); - if (!$this->store->userExists($newUsername)){ - if ($this->store->install($newUsername, Tools::encodeString($password . $newUsername), $email)) { - 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(); - } - } - } - - /** - * Delete an existing user - */ - public function deleteUser($password) - { - 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('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() - { - return array( - 'pager' => PAGINATION, - 'language' => LANG, - 'theme' => DEFAULT_THEME - ); - } - - /** - * Call action (mark as fav, archive, delete, etc.) - */ - public function action($action, Url $url, $id = 0, $import = FALSE, $autoclose = FALSE, $tags = null) - { - switch ($action) - { - case 'add': - $content = Tools::getPageContent($url); - $title = ($content['rss']['channel']['item']['title'] != '') ? $content['rss']['channel']['item']['title'] : _('Untitled'); - $body = $content['rss']['channel']['item']['description']; - - // clean content from prevent xss attack - $purifier = $this->_getPurifier(); - $title = $purifier->purify($title); - $body = $purifier->purify($body); - - //search for possible duplicate - $duplicate = NULL; - $duplicate = $this->store->retrieveOneByURL($url->getUrl(), $this->user->getId()); - - $last_id = $this->store->add($url->getUrl(), $title, $body, $this->user->getId()); - if ( $last_id ) { - Tools::logm('add link ' . $url->getUrl()); - if (DOWNLOAD_PICTURES) { - $content = Picture::filterPicture($body, $url->getUrl(), $last_id); - Tools::logm('updating content article'); - $this->store->updateContent($last_id, $content, $this->user->getId()); - } - - if ($duplicate != NULL) { - // duplicate exists, so, older entry needs to be deleted (as new entry should go to the top of list), BUT favorite mark and tags should be preserved - Tools::logm('link ' . $url->getUrl() . ' is a duplicate'); - // 1) - preserve tags and favorite, then drop old entry - $this->store->reassignTags($duplicate['id'], $last_id); - if ($duplicate['is_fav']) { - $this->store->favoriteById($last_id, $this->user->getId()); - } - if ($this->store->deleteById($duplicate['id'], $this->user->getId())) { - Tools::logm('previous link ' . $url->getUrl() .' entry deleted'); - } - } - - // if there are tags, add them to the new article - if (isset($_GET['tags'])) { - $_POST['value'] = $_GET['tags']; - $_POST['entry_id'] = $last_id; - $this->action('add_tag', $url); - } - - $this->messages->add('s', _('the link has been added successfully')); - } - else { - $this->messages->add('e', _('error during insertion : the link wasn\'t added')); - Tools::logm('error during insertion : the link wasn\'t added ' . $url->getUrl()); - } - - if ($autoclose == TRUE) { - Tools::redirect('?view=home'); - } else { - Tools::redirect('?view=home&closewin=true'); - } - break; - case 'delete': - if (isset($_GET['search'])) { - //when we want to apply a delete to a search - $tags = array($_GET['search']); - $allentry_ids = $this->store->search($tags[0], $this->user->getId()); - $entry_ids = array(); - foreach ($allentry_ids as $eachentry) { - $entry_ids[] = $eachentry[0]; - } - } else { // delete a single article - $entry_ids = array($id); - } - foreach($entry_ids as $id) { - $msg = 'delete link #' . $id; - if ($this->store->deleteById($id, $this->user->getId())) { - if (DOWNLOAD_PICTURES) { - Picture::removeDirectory(ABS_PATH . $id); - } - $this->messages->add('s', _('the link has been deleted successfully')); - } - else { - $this->messages->add('e', _('the link wasn\'t deleted')); - $msg = 'error : can\'t delete link #' . $id; - } - Tools::logm($msg); - } - Tools::redirect('?'); - break; - case 'toggle_fav' : - $this->store->favoriteById($id, $this->user->getId()); - Tools::logm('mark as favorite link #' . $id); - if ( Tools::isAjaxRequest() ) { - echo 1; - exit; - } - else { - Tools::redirect(); - } - break; - case 'toggle_archive' : - if (isset($_GET['tag_id'])) { - //when we want to archive a whole tag - $tag_id = $_GET['tag_id']; - $allentry_ids = $this->store->retrieveEntriesByTag($tag_id, $this->user->getId()); - $entry_ids = array(); - foreach ($allentry_ids as $eachentry) { - $entry_ids[] = $eachentry[0]; - } - } else { //archive a single article - $entry_ids = array($id); - } - foreach($entry_ids as $id) { - $this->store->archiveById($id, $this->user->getId()); - Tools::logm('archive link #' . $id); - } - if ( Tools::isAjaxRequest() ) { - echo 1; - exit; - } - else { - Tools::redirect(); - } - break; - case 'archive_all' : - $this->store->archiveAll($this->user->getId()); - Tools::logm('archive all links'); - Tools::redirect(); - break; - case 'add_tag' : - if (isset($_GET['search'])) { - //when we want to apply a tag to a search - $tags = array($_GET['search']); - $allentry_ids = $this->store->search($tags[0], $this->user->getId()); - $entry_ids = array(); - foreach ($allentry_ids as $eachentry) { - $entry_ids[] = $eachentry[0]; - } - } else { //add a tag to a single article - $tags = explode(',', $_POST['value']); - $entry_ids = array($_POST['entry_id']); - } - foreach($entry_ids as $entry_id) { - $entry = $this->store->retrieveOneById($entry_id, $this->user->getId()); - if (!$entry) { - $this->messages->add('e', _('Article not found!')); - Tools::logm('error : article not found'); - Tools::redirect(); - } - //get all already set tags to preven duplicates - $already_set_tags = array(); - $entry_tags = $this->store->retrieveTagsByEntry($entry_id); - foreach ($entry_tags as $tag) { - $already_set_tags[] = $tag['value']; - } - foreach($tags as $key => $tag_value) { - $value = trim($tag_value); - if ($value && !in_array($value, $already_set_tags)) { - $tag = $this->store->retrieveTagByValue($value); - if (is_null($tag)) { - # we create the tag - $tag = $this->store->createTag($value); - $sequence = ''; - if (STORAGE == 'postgres') { - $sequence = 'tags_id_seq'; - } - $tag_id = $this->store->getLastId($sequence); - } - else { - $tag_id = $tag['id']; - } - - # we assign the tag to the article - $this->store->setTagToEntry($tag_id, $entry_id); - } - } - } - $this->messages->add('s', _('The tag has been applied successfully')); - Tools::logm('The tag has been applied successfully'); - Tools::redirect(); - break; - case 'remove_tag' : - $tag_id = $_GET['tag_id']; - $entry = $this->store->retrieveOneById($id, $this->user->getId()); - if (!$entry) { - $this->messages->add('e', _('Article not found!')); - Tools::logm('error : article not found'); - Tools::redirect(); - } - $this->store->removeTagForEntry($id, $tag_id); - Tools::logm('tag entry deleted'); - if ($this->store->cleanUnusedTag($tag_id)) { - Tools::logm('tag deleted'); - } - $this->messages->add('s', _('The tag has been successfully deleted')); - Tools::redirect(); - break; - default: - break; - } - } - - function displayView($view, $id = 0) - { - $tpl_vars = array(); - - switch ($view) - { - case 'about': - break; - case 'config': - $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 = trim($prod_infos[0]); - $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->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; - $tpl_vars = array( - 'themes' => $themes, - 'languages' => $languages, - 'dev' => $dev, - 'prod' => $prod, - 'check_time_dev' => $check_time_dev, - 'check_time_prod' => $check_time_prod, - 'compare_dev' => $compare_dev, - 'compare_prod' => $compare_prod, - 'token' => $token, - 'user_id' => $this->user->getId(), - 'http_auth' => $http_auth, - 'only_user' => $only_user - ); - Tools::logm('config view'); - break; - case 'edit-tags': - # tags - $entry = $this->store->retrieveOneById($id, $this->user->getId()); - if (!$entry) { - $this->messages->add('e', _('Article not found!')); - Tools::logm('error : article not found'); - Tools::redirect(); - } - $tags = $this->store->retrieveTagsByEntry($id); - $tpl_vars = array( - 'entry_id' => $id, - 'tags' => $tags, - 'entry' => $entry, - ); - break; - case 'tags': - $token = $this->user->getConfigValue('token'); - //if term is set - search tags for this term - $term = Tools::checkVar('term'); - $tags = $this->store->retrieveAllTags($this->user->getId(), $term); - if (Tools::isAjaxRequest()) { - $result = array(); - foreach ($tags as $tag) { - $result[] = $tag['value']; - } - echo json_encode($result); - exit; - } - $tpl_vars = array( - 'token' => $token, - 'user_id' => $this->user->getId(), - 'tags' => $tags, - ); - break; - case 'search': - if (isset($_GET['search'])) { - $search = filter_var($_GET['search'], FILTER_SANITIZE_STRING); - $tpl_vars['entries'] = $this->store->search($search, $this->user->getId()); - $count = count($tpl_vars['entries']); - $this->pagination->set_total($count); - $page_links = str_replace(array('previous', 'next'), array(_('previous'), _('next')), - $this->pagination->page_links('?view=' . $view . '?search=' . $search . '&sort=' . $_SESSION['sort'] . '&' )); - $tpl_vars['page_links'] = $page_links; - $tpl_vars['nb_results'] = $count; - $tpl_vars['searchterm'] = $search; - } - break; - case 'view': - $entry = $this->store->retrieveOneById($id, $this->user->getId()); - if ($entry != NULL) { - Tools::logm('view link #' . $id); - $content = $entry['content']; - if (function_exists('tidy_parse_string')) { - $tidy = tidy_parse_string($content, array('indent'=>true, 'show-body-only' => true), 'UTF8'); - $tidy->cleanRepair(); - $content = $tidy->value; - } - - # flattr checking - $flattr = NULL; - if (FLATTR) { - $flattr = new FlattrItem(); - $flattr->checkItem($entry['url'], $entry['id']); - } - - # tags - $tags = $this->store->retrieveTagsByEntry($entry['id']); - - $tpl_vars = array( - 'entry' => $entry, - 'content' => $content, - 'flattr' => $flattr, - 'tags' => $tags - ); - } - else { - Tools::logm('error in view call : entry is null'); - } - break; - default: # home, favorites, archive and tag views - $tpl_vars = array( - 'entries' => '', - 'page_links' => '', - 'nb_results' => '', - 'listmode' => (isset($_COOKIE['listmode']) ? true : false), - ); - - //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); - } - - $count = $this->store->getEntriesByViewCount($view, $this->user->getId(), $id); - - if ($count > 0) { - $this->pagination->set_total($count); - $page_links = str_replace(array('previous', 'next'), array(_('previous'), _('next')), - $this->pagination->page_links('?view=' . $view . '&sort=' . $_SESSION['sort'] . (($id)?'&id='.$id:'') . '&' )); - $tpl_vars['entries'] = $this->store->getEntriesByView($view, $this->user->getId(), $this->pagination->get_limit(), $id); - $tpl_vars['page_links'] = $page_links; - $tpl_vars['nb_results'] = $count; - } - Tools::logm('display ' . $view . ' view'); - break; - } - - return $tpl_vars; - } - - /** - * update the password of the current user. - * if MODE_DEMO is TRUE, the password can't be updated. - * @todo add the return value - * @todo set the new password in function header like this updatePassword($newPassword) - * @return boolean - */ - public function updatePassword($password, $confirmPassword) - { - if (MODE_DEMO) { - $this->messages->add('i', _('in demo mode, you can\'t update your password')); - Tools::logm('in demo mode, you can\'t do this'); - Tools::redirect('?view=config'); - } - else { - 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($password . $this->user->getUsername())); - Session::logout(); - Tools::logm('password updated'); - Tools::redirect(); - } - else { - $this->messages->add('e', _('the two fields have to be filled & the password must be the same in the two fields')); - Tools::redirect('?view=config'); - } - } - } - } - - /** - * 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); - } - 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); - } - - return array(false, false, false); - } - - /** - * checks if login & password are correct and save the user in session. - * it redirects the user to the $referer link - * @param string $referer the url to redirect after login - * @todo add the return value - * @return boolean - */ - public function login($referer) - { - list($login,$password,$isauthenticated)=$this->credentials(); - if($login === false || $password === false) { - $this->messages->add('e', _('login failed: you have to fill all fields')); - Tools::logm('login failed'); - Tools::redirect(); - } - if (!empty($login) && !empty($password)) { - $user = $this->store->login($login, Tools::encodeString($password . $login), $isauthenticated); - if ($user != array()) { - # Save login into Session - $longlastingsession = isset($_POST['longlastingsession']); - $passwordTest = ($isauthenticated) ? $user['password'] : Tools::encodeString($password . $login); - Session::login($user['username'], $user['password'], $login, $passwordTest, $longlastingsession, array('poche_user' => new User($user))); - - # reload l10n - $language = $user['config']['language']; - @putenv('LC_ALL=' . $language); - setlocale(LC_ALL, $language); - bindtextdomain($language, LOCALE); - textdomain($language); - - $this->messages->add('s', _('welcome to your wallabag')); - Tools::logm('login successful'); - Tools::redirect($referer); - } - $this->messages->add('e', _('login failed: bad login or password')); - // log login failure in web server log to allow fail2ban usage - error_log('user '.$login.' authentication failure'); - Tools::logm('login failed'); - Tools::redirect(); - } - } - - /** - * log out the poche user. It cleans the session. - * @todo add the return value - * @return boolean - */ - public function logout() - { - $this->user = array(); - Session::logout(); - Tools::logm('logout'); - Tools::redirect(); - } - - /** - * import datas into your wallabag - * @return boolean - */ - - public function import() { - - if ( isset($_FILES['file']) && $_FILES['file']['tmp_name'] ) { - Tools::logm('Import stated: parsing file'); - - // assume, that file is in json format - $str_data = file_get_contents($_FILES['file']['tmp_name']); - $data = json_decode($str_data, true); - - 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); - } - } - } - - // 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 - 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).'); - } - else { - $this->messages->add('s', _('Did you forget to select a file?')); - } - // 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(); - } - 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); - $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')); - - // 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 - ) - ); - } - - /** - * export poche entries in json - * @return json all poche entries - */ - public function export() - { - $filename = "wallabag-export-".$this->user->getId()."-".date("Y-m-d").".json"; - header('Content-Disposition: attachment; filename='.$filename); - - $entries = $this->store->retrieveAll($this->user->getId()); - echo $this->tpl->render('export.twig', array( - 'export' => Tools::renderJson($entries), - )); - Tools::logm('export view'); - } - - /** - * Checks online the latest version of poche and cache it - * @param string $which 'prod' or 'dev' - * @return string latest $which version - */ - private function _getPocheVersion($which = 'prod') { - $cache_file = CACHE . '/' . $which; - $check_time = time(); - - # checks if the cached version file exists - if (file_exists($cache_file) && (filemtime($cache_file) > (time() - 86400 ))) { - $version = file_get_contents($cache_file); - $check_time = filemtime($cache_file); - } else { - $version = file_get_contents('http://static.wallabag.org/versions/' . $which); - file_put_contents($cache_file, $version, LOCK_EX); - } - return array($version, $check_time); - } - - /** - * Update token for current user - */ - public function updateToken() - { - $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 if $type is 'tag', the id of the tag to generate feed for - * @param string $type the type of feed to generate - * @param int $limit the maximum number of items (0 means all) - */ - public function generateFeeds($token, $user_id, $tag_id, $type = 'home', $limit = 0) - { - $allowed_types = array('home', 'fav', 'archive', 'tag'); - $config = $this->store->getConfigUser($user_id); - - if ($config == null) { - die(sprintf(_('User with this id (%d) does not exist.'), $user_id)); - } - - if (!in_array($type, $allowed_types) || !isset($config['token']) || $token != $config['token']) { - die(_('Uh, there is a problem while generating feed. Wrong token used?')); - } - - $feed = new FeedWriter(RSS2); - $feed->setTitle('wallabag — ' . $type . ' feed'); - $feed->setLink(Tools::getPocheUrl()); - $feed->setChannelElement('pubDate', date(DATE_RSS , time())); - $feed->setChannelElement('generator', 'wallabag'); - $feed->setDescription('wallabag ' . $type . ' elements'); - - if ($type == 'tag') { - $entries = $this->store->retrieveEntriesByTag($tag_id, $user_id); - } - else { - $entries = $this->store->getEntriesByView($type, $user_id); - } - - // if $limit is set to zero, use all entries - if (0 == $limit) { - $limit = count($entries); - } - if (count($entries) > 0) { - for ($i = 0; $i < min(count($entries), $limit); $i++) { - $entry = $entries[$i]; - $newItem = $feed->createNewItem(); - $newItem->setTitle($entry['title']); - $newItem->setSource(Tools::getPocheUrl() . '?view=view&id=' . $entry['id']); - $newItem->setLink($entry['url']); - $newItem->setDate(time()); - $newItem->setDescription($entry['content']); - $feed->addItem($newItem); - } - } - - $feed->genarateFeed(); - exit; - } - - - - /** - * Returns new purifier object with actual config - */ - 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/)%'); - - return new HTMLPurifier($config); - } - - -} diff --git a/inc/poche/Routing.class.php b/inc/poche/Routing.class.php deleted file mode 100755 index be06a433..00000000 --- a/inc/poche/Routing.class.php +++ /dev/null @@ -1,161 +0,0 @@ - - * @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 to you - $this->wallabag->login($this->referer); - } elseif (isset($_GET['feed']) && isset($_GET['user_id'])) { - $tag_id = (isset($_GET['tag_id']) ? intval($_GET['tag_id']) : 0); - $limit = (isset($_GET['limit']) ? intval($_GET['limit']) : 0); - $this->wallabag->generateFeeds($_GET['token'], filter_var($_GET['user_id'],FILTER_SANITIZE_NUMBER_INT), $tag_id, $_GET['type'], $limit); - } - - //allowed ONLY to logged in user - if (\Session::isLogged() === true) - { - if (isset($_GET['logout'])) { - // see you soon ! - $this->wallabag->logout(); - } elseif (isset($_GET['config'])) { - // update password - $this->wallabag->updatePassword($_POST['password'], $_POST['password_repeat']); - } elseif (isset($_GET['newuser'])) { - $this->wallabag->createNewUser($_POST['newusername'], $_POST['password4newuser']); - } elseif (isset($_GET['deluser'])) { - $this->wallabag->deleteUser($_POST['password4deletinguser']); - } elseif (isset($_GET['epub'])) { - $epub = new WallabagEpub($this->wallabag, $_GET['method'], $_GET['value']); - $epub->prepareData(); - $epub->produceEpub(); - } elseif (isset($_GET['mobi'])) { - $mobi = new WallabagMobi($this->wallabag, $_GET['method'], $_GET['value']); - $mobi->prepareData(); - $mobi->produceMobi(); - } elseif (isset($_GET['pdf'])) { - $pdf = new WallabagPDF($this->wallabag, $_GET['method'], $_GET['value']); - $pdf->prepareData(); - $pdf->producePDF(); - } elseif (isset($_GET['import'])) { - $import = $this->wallabag->import(); - $tplVars = array_merge($this->vars, $import); - } elseif (isset($_GET['empty-cache'])) { - Tools::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']) && isset($_GET['action']) && $_GET['action'] == 'generate') { - $this->wallabag->updateToken(); - } - elseif (isset($_GET['plainurl']) && !empty($_GET['plainurl'])) { - $plainUrl = new Url(base64_encode($_GET['plainurl'])); - $this->wallabag->action('add', $plainUrl); - } - } - } - - public function _render($file, $vars) - { - echo $this->wallabag->tpl->render($file, $vars); - } -} diff --git a/inc/poche/Template.class.php b/inc/poche/Template.class.php deleted file mode 100644 index 4d0bfdbb..00000000 --- a/inc/poche/Template.class.php +++ /dev/null @@ -1,235 +0,0 @@ - - * @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 || !is_dir(THEME . '/' . $themeDirectory)) { - $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('.', '..', '_global'))) { - 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); - - Tools::emptyCache(); - Tools::redirect('?view=config'); - } -} diff --git a/inc/poche/Tools.class.php b/inc/poche/Tools.class.php deleted file mode 100755 index d625fc40..00000000 --- a/inc/poche/Tools.class.php +++ /dev/null @@ -1,420 +0,0 @@ - - * @copyright 2013 - * @license http://opensource.org/licenses/MIT see COPYING file - */ - -final class Tools -{ - /** - * Initialize PHP environment - */ - public static function initPhp() - { - define('START_TIME', microtime(true)); - - function stripslashesDeep($value) { - return is_array($value) - ? array_map('stripslashesDeep', $value) - : stripslashes($value); - } - - if (get_magic_quotes_gpc()) { - $_POST = array_map('stripslashesDeep', $_POST); - $_GET = array_map('stripslashesDeep', $_GET); - $_COOKIE = array_map('stripslashesDeep', $_COOKIE); - } - - ob_start(); - register_shutdown_function('ob_end_flush'); - } - - /** - * Get wallabag instance URL - * - * @return string - */ - public static function getPocheUrl() - { - $https = (!empty($_SERVER['HTTPS']) - && (strtolower($_SERVER['HTTPS']) == 'on')) - || (isset($_SERVER["SERVER_PORT"]) - && $_SERVER["SERVER_PORT"] == '443') // HTTPS detection. - || (isset($_SERVER["SERVER_PORT"]) //Custom HTTPS port detection - && $_SERVER["SERVER_PORT"] == SSL_PORT) - || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) - && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https'); - - $serverport = (!isset($_SERVER["SERVER_PORT"]) - || $_SERVER["SERVER_PORT"] == '80' - || $_SERVER["SERVER_PORT"] == HTTP_PORT - || ($https && $_SERVER["SERVER_PORT"] == '443') - || ($https && $_SERVER["SERVER_PORT"]==SSL_PORT) //Custom HTTPS port detection - ? '' : ':' . $_SERVER["SERVER_PORT"]); - - if (isset($_SERVER["HTTP_X_FORWARDED_PORT"])) { - $serverport = ':' . $_SERVER["HTTP_X_FORWARDED_PORT"]; - } - - $scriptname = str_replace('/index.php', '/', $_SERVER["SCRIPT_NAME"]); - - if (!isset($_SERVER["HTTP_HOST"])) { - return $scriptname; - } - - $host = (isset($_SERVER['HTTP_X_FORWARDED_HOST']) ? $_SERVER['HTTP_X_FORWARDED_HOST'] : (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : $_SERVER['SERVER_NAME'])); - - if (strpos($host, ':') !== false) { - $serverport = ''; - } - - return 'http' . ($https ? 's' : '') . '://' - . $host . $serverport . $scriptname; - } - - /** - * Redirects to a URL - * - * @param string $url - */ - public static function redirect($url = '') - { - if ($url === '') { - $url = (empty($_SERVER['HTTP_REFERER'])?'?':$_SERVER['HTTP_REFERER']); - if (isset($_POST['returnurl'])) { - $url = $_POST['returnurl']; - } - } - - # prevent loop - if (empty($url) || parse_url($url, PHP_URL_QUERY) === $_SERVER['QUERY_STRING']) { - $url = Tools::getPocheUrl(); - } - - if (substr($url, 0, 1) !== '?') { - $ref = Tools::getPocheUrl(); - if (substr($url, 0, strlen($ref)) !== $ref) { - $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( - 'install', 'import', 'export', 'config', 'tags', - 'edit-tags', 'view', 'login', 'error', 'about' - ); - - 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; - $useragent = "Mozilla/5.0 (Windows NT 5.1; rv:18.0) Gecko/20100101 Firefox/18.0"; - - if (in_array ('curl', get_loaded_extensions())) { - # Fetch feed from URL - $curl = curl_init(); - curl_setopt($curl, CURLOPT_URL, $url); - curl_setopt($curl, CURLOPT_TIMEOUT, $timeout); - if (!ini_get('open_basedir') && !ini_get('safe_mode')) { - curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true); - } - curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); - curl_setopt($curl, CURLOPT_HEADER, false); - - # for ssl, do not verified certificate - curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE); - curl_setopt($curl, CURLOPT_AUTOREFERER, TRUE ); - - # FeedBurner requires a proper USER-AGENT... - curl_setopt($curl, CURL_HTTP_VERSION_1_1, true); - curl_setopt($curl, CURLOPT_ENCODING, "gzip, deflate"); - curl_setopt($curl, CURLOPT_USERAGENT, $useragent); - - $data = curl_exec($curl); - $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE); - $httpcodeOK = isset($httpcode) and ($httpcode == 200 or $httpcode == 301); - curl_close($curl); - } else { - # create http context and add timeout and user-agent - $context = stream_context_create( - array( - 'http' => array( - 'timeout' => $timeout, - 'header' => "User-Agent: " . $useragent, - 'follow_location' => true - ), - 'ssl' => array( - 'verify_peer' => false, - 'allow_self_signed' => true - ) - ) - ); - - # only download page lesser than 4MB - $data = @file_get_contents($url, false, $context, -1, 4000000); - - if (isset($http_response_header) and isset($http_response_header[0])) { - $httpcodeOK = isset($http_response_header) and isset($http_response_header[0]) and ((strpos($http_response_header[0], '200 OK') !== FALSE) or (strpos($http_response_header[0], '301 Moved Permanently') !== FALSE)); - } - } - - # if response is not empty and response is OK - if (isset($data) and isset($httpcodeOK) and $httpcodeOK) { - - # take charset of page and get it - preg_match('##Usi', $data, $meta); - - # if meta tag is found - if (!empty($meta[0])) { - preg_match('#charset="?(.*)"#si', $meta[0], $encoding); - # if charset is found set it otherwise, set it to utf-8 - $html_charset = (!empty($encoding[1])) ? strtolower($encoding[1]) : 'utf-8'; - if (empty($encoding[1])) $encoding[1] = 'utf-8'; - } else { - $html_charset = 'utf-8'; - $encoding[1] = ''; - } - - # replace charset of url to charset of page - $data = str_replace('charset=' . $encoding[1], 'charset=' . $html_charset, $data); - - return $data; - } - else { - return FALSE; - } - } - - /** - * Headers for JSON export - * - * @param $data - */ - public static function renderJson($data) - { - header('Cache-Control: no-cache, must-revalidate'); - header('Expires: Sat, 26 Jul 1997 05:00:00 GMT'); - header('Content-type: application/json; charset=UTF-8'); - echo json_encode($data); - exit(); - } - - /** - * Create new line in log file - * - * @param $message - */ - public static function logm($message) - { - if (DEBUG_POCHE && php_sapi_name() != 'cli') { - $t = strval(date('Y/m/d_H:i:s')) . ' - ' . $_SERVER["REMOTE_ADDR"] . ' - ' . strval($message) . "\n"; - file_put_contents(CACHE . '/log.txt', $t, FILE_APPEND); - error_log('DEBUG POCHE : ' . $message); - } - } - - /** - * 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); - } - - /** - * Returns the domain name for a URL - * - * @param $url - * @return string - */ - public static function getDomain($url) - { - return parse_url($url, PHP_URL_HOST); - } - - /** - * 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); - } - - /** - * Returns the correct header for a status code - * - * @param $status_code - */ - private static function _status($status_code) - { - if (strpos(php_sapi_name(), 'apache') !== false) { - - header('HTTP/1.0 '.$status_code); - } - else { - - header('Status: '.$status_code); - } - } - - /** - * 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; - } - } - // Saving and clearing session - if (isset($_SESSION)) { - $REAL_SESSION = array(); - foreach( $_SESSION as $key => $value ) { - $REAL_SESSION[$key] = $value; - unset($_SESSION[$key]); - } - } - - // Running code in different context - $scope = function() { - extract( func_get_arg(1) ); - $_GET = $_REQUEST = array( - "url" => $url->getUrl(), - "max" => 5, - "links" => "preserve", - "exc" => "", - "format" => "json", - "submit" => "Create Feed" - ); - ob_start(); - require func_get_arg(0); - $json = ob_get_contents(); - ob_end_clean(); - return $json; - }; - - // Silence $scope function to avoid - // issues with FTRSS when error_reporting is to high - // FTRSS generates PHP warnings which break output - $json = @$scope("vendor/wallabag/Fivefilters_Libraries/makefulltextfeed.php", array("url" => $url)); - - // Clearing and restoring context - foreach ($GLOBALS as $key => $value) { - if($key != "GLOBALS" && $key != "_SESSION" ) { - unset($GLOBALS[$key]); - } - } - foreach ($REAL as $key => $value) { - $GLOBALS[$key] = $value; - } - - // Clearing and restoring session - if (isset($REAL_SESSION)) { - foreach($_SESSION as $key => $value) { - unset($_SESSION[$key]); - } - - foreach($REAL_SESSION as $key => $value) { - $_SESSION[$key] = $value; - } - } - - return json_decode($json, true); - } - - /** - * 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'; - } - - /* - * 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/Url.class.php b/inc/poche/Url.class.php deleted file mode 100644 index d9172b7d..00000000 --- a/inc/poche/Url.class.php +++ /dev/null @@ -1,31 +0,0 @@ - - * @copyright 2013 - * @license http://opensource.org/licenses/MIT see COPYING file - */ - -class Url -{ - public $url; - - function __construct($url) - { - $this->url = base64_decode($url); - } - - public function getUrl() { - return $this->url; - } - - public function setUrl($url) { - $this->url = $url; - } - - public function isCorrect() { - return filter_var($this->url, FILTER_VALIDATE_URL) !== FALSE; - } -} \ No newline at end of file diff --git a/inc/poche/User.class.php b/inc/poche/User.class.php deleted file mode 100644 index eaadd3e5..00000000 --- a/inc/poche/User.class.php +++ /dev/null @@ -1,57 +0,0 @@ - - * @copyright 2013 - * @license http://opensource.org/licenses/MIT see COPYING file - */ - -class User -{ - public $id; - public $username; - public $name; - public $password; - public $email; - public $config; - - function __construct($user = array()) - { - if ($user != array()) { - $this->id = $user['id']; - $this->username = $user['username']; - $this->name = $user['name']; - $this->password = $user['password']; - $this->email = $user['email']; - $this->config = $user['config']; - } - } - - public function getId() - { - return $this->id; - } - - public function getUsername() - { - return $this->username; - } - - public function setConfig($config) - { - $this->config = $config; - } - - /** - * 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/WallabagEBooks.class.php b/inc/poche/WallabagEBooks.class.php deleted file mode 100644 index a9c62af9..00000000 --- a/inc/poche/WallabagEBooks.class.php +++ /dev/null @@ -1,245 +0,0 @@ - - * @copyright 2013 - * @license http://opensource.org/licenses/MIT see COPYING file - */ - -class WallabagEBooks -{ - protected $wallabag; - protected $method; - protected $value; - protected $entries; - protected $bookTitle; - protected $bookFileName; - protected $author = 'wallabag'; - - public function __construct(Poche $wallabag, $method, $value) - { - $this->wallabag = $wallabag; - $this->method = $method; - $this->value = $value; - } - - public function prepareData() - { - switch ($this->method) { - case 'id': - $entryID = filter_var($this->value, FILTER_SANITIZE_NUMBER_INT); - $entry = $this->wallabag->store->retrieveOneById($entryID, $this->wallabag->user->getId()); - $this->entries = array($entry); - $this->bookTitle = $entry['title']; - $this->bookFileName = substr($this->bookTitle, 0, 200); - $this->author = preg_replace('#^w{3}.#', '', Tools::getdomain($entry["url"])); # if only one article, set author to domain name (we strip the eventual www part) - Tools::logm('Producing ebook from article ' . $this->bookTitle); - break; - case 'all': - $this->entries = $this->wallabag->store->retrieveAll($this->wallabag->user->getId()); - $this->bookTitle = sprintf(_('All my articles on %s'), date(_('d.m.y'))); #translatable because each country has it's own date format system - $this->bookFileName = _('Allarticles') . date(_('dmY')); - Tools::logm('Producing ebook from all articles'); - 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. - $this->entries = $this->wallabag->store->retrieveEntriesByTag($tag_id, $this->wallabag->user->getId()); - $this->bookTitle = sprintf(_('Articles tagged %s'), $tag); - $this->bookFileName = substr(sprintf(_('Tag %s'), $tag), 0, 200); - Tools::logm('Producing ebook from tag ' . $tag); - break; - case 'category': - $category = filter_var($this->value, FILTER_SANITIZE_STRING); - $this->entries = $this->wallabag->store->getEntriesByView($category, $this->wallabag->user->getId()); - $this->bookTitle = sprintf(_('Articles in category %s'), $category); - $this->bookFileName = substr(sprintf(_('Category %s'), $category), 0, 200); - Tools::logm('Producing ebook from category ' . $category); - break; - case 'search': - $search = filter_var($this->value, FILTER_SANITIZE_STRING); - Tools::logm($search); - $this->entries = $this->wallabag->store->search($search, $this->wallabag->user->getId()); - $this->bookTitle = sprintf(_('Articles for search %s'), $search); - $this->bookFileName = substr(sprintf(_('Search %s'), $search), 0, 200); - Tools::logm('Producing ebook from search ' . $search); - break; - case 'default': - die(_('Uh, there is a problem while generating eBook.')); - } - } -} - -class WallabagEpub extends WallabagEBooks -{ - /** - * handle ePub - */ - public function produceEpub() - { - Tools::logm('Starting to produce ePub 3 file'); - $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()); - - Tools::logm('Filling metadata for ePub...'); - - $book->setTitle($this->bookTitle); - $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($this->author,$this->author); - $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 = "

    " . $this->bookTitle . "

    \n"; - - $book->setCoverImage("Cover.png", file_get_contents("themes/_global/img/appicon/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(); - - Tools::logm('Adding actual content...'); - - foreach ($this->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 - Tools::logm('Production log available in produced file'); - } - $book->finalize(); - $zipData = $book->sendBook($this->bookFileName); - Tools::logm('Ebook produced'); - } -} - -class WallabagMobi extends WallabagEBooks -{ - /** - * MOBI Class - * @author Sander Kromwijk - */ - - public function produceMobi() - { - - Tools::logm('Starting to produce Mobi file'); - $mobi = new MOBI(); - $content = new MOBIFile(); - - $messages = new Messages(); // for later - - Tools::logm('Filling metadata for Mobi...'); - - $content->set("title", $this->bookTitle); - $content->set("author", $this->author); - $content->set("subject", $this->bookTitle); - - # introduction - $content->appendParagraph('

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

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

    '); - $content->appendImage(imagecreatefrompng("themes/_global/img/appicon/apple-touch-icon-152.png")); - $content->appendPageBreak(); - - Tools::logm('Adding actual content...'); - - foreach ($this->entries as $item) { - $content->appendChapterTitle($item['title']); - $content->appendParagraph($item['content']); - $content->appendPageBreak(); - } - $mobi->setContentProvider($content); - - // we offer file to download - $mobi->download($this->bookFileName.'.mobi'); - Tools::logm('Mobi file produced'); - } -} - -class WallabagPDF extends WallabagEbooks -{ - public function producePDF() - { - - Tools::logm('Starting to produce PDF file'); - - $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false); - - Tools::logm('Filling metadata for PDF...'); - $pdf->SetCreator(PDF_CREATOR); - $pdf->SetAuthor(''); - $pdf->SetTitle($this->bookTitle); - $pdf->SetSubject($this->bookTitle); - - Tools::logm('Adding introduction...'); - $pdf->AddPage(); - $intro = '

    ' . $this->bookTitle . '

    -

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

    -

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

    -
    '; - - - $pdf->writeHTMLCell(0, 0, '', '', $intro, 0, 1, 0, true, '', true); - - $i = 1; - Tools::logm('Adding actual content...'); - foreach ($this->entries as $item) { - $pdf->AddPage(); - $html = '

    ' . $item['title'] . '

    '; - $html .= $item['content']; - $pdf->writeHTMLCell(0, 0, '', '', $html, 0, 1, 0, true, '', true); - $i = $i+1; - } - - // set image scale factor - $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO); - - - $pdf->Output(CACHE . '/' . $this->bookFileName . '.pdf', 'FD'); - - } -} diff --git a/inc/poche/config.inc.default.php b/inc/poche/config.inc.default.php deleted file mode 100755 index a159e713..00000000 --- a/inc/poche/config.inc.default.php +++ /dev/null @@ -1,78 +0,0 @@ - - * @copyright 2013 - * @license http://opensource.org/licenses/MIT see COPYING file - */ - -@define ('SALT', ''); # put a strong string here -@define ('LANG', 'en_EN.utf8'); - -@define ('STORAGE', 'sqlite'); # postgres, mysql or sqlite - -@define ('STORAGE_SQLITE', ROOT . '/db/poche.sqlite'); # if you are using sqlite, where the database file is located - -# only for postgres & mysql -@define ('STORAGE_SERVER', 'localhost'); -@define ('STORAGE_DB', 'poche'); -@define ('STORAGE_USER', 'poche'); -@define ('STORAGE_PASSWORD', 'poche'); - -################################################################################# -# Do not trespass unless you know what you are doing -################################################################################# -// Change this if http is running on nonstandard port - i.e is behind cache proxy -@define ('HTTP_PORT', 80); - -// Change this if not using the standart port for SSL - i.e you server is behind sslh -@define ('SSL_PORT', 443); - -@define ('MODE_DEMO', FALSE); -@define ('DEBUG_POCHE', FALSE); - -//default level of error reporting in application. Developers should override it in their config.inc.php: set to E_ALL. -@define ('ERROR_REPORTING', E_ALL & ~E_NOTICE); - -@define ('DOWNLOAD_PICTURES', FALSE); # This can slow down the process of adding articles -@define ('REGENERATE_PICTURES_QUALITY', 75); -@define ('CONVERT_LINKS_FOOTNOTES', FALSE); -@define ('REVERT_FORCED_PARAGRAPH_ELEMENTS', FALSE); -@define ('SHARE_TWITTER', TRUE); -@define ('SHARE_MAIL', TRUE); -@define ('SHARE_SHAARLI', FALSE); -@define ('SHAARLI_URL', 'http://myshaarliurl.com'); -@define ('SHARE_DIASPORA', FALSE); -@define ('DIASPORA_URL', 'http://diasporapod.com'); # Don't add a / at the end -@define ('FLATTR', TRUE); -@define ('FLATTR_API', 'https://api.flattr.com/rest/v2/things/lookup/?url='); -@define ('NOT_FLATTRABLE', '0'); -@define ('FLATTRABLE', '1'); -@define ('FLATTRED', '2'); -@define ('CARROT', FALSE); - -// ebook -@define ('EPUB', TRUE); -@define ('MOBI', FALSE); -@define ('PDF', FALSE); - -// display or not print link in article view -@define ('SHOW_PRINTLINK', '1'); -// display or not percent of read in article view. Affects only default theme. -@define ('SHOW_READPERCENT', '1'); -@define ('ABS_PATH', 'assets/'); - -@define ('DEFAULT_THEME', 'baggy'); - -@define ('THEME', ROOT . '/themes'); -@define ('LOCALE', ROOT . '/locale'); -@define ('CACHE', ROOT . '/cache'); - -@define ('PAGINATION', '12'); - -//limit for download of articles during import -@define ('IMPORT_LIMIT', 5); -//delay between downloads (in sec) -@define ('IMPORT_DELAY', 5); diff --git a/inc/poche/global.inc.php b/inc/poche/global.inc.php deleted file mode 100755 index ff7ebf64..00000000 --- a/inc/poche/global.inc.php +++ /dev/null @@ -1,43 +0,0 @@ - - * @copyright 2013 - * @license http://opensource.org/licenses/MIT see COPYING file - */ - -# the poche system root directory (/inc) -define('INCLUDES', dirname(__FILE__) . '/..'); - -# the poche root directory -define('ROOT', INCLUDES . '/..'); - -require_once ROOT . '/vendor/autoload.php'; -require_once INCLUDES . '/poche/Tools.class.php'; -require_once INCLUDES . '/poche/User.class.php'; -require_once INCLUDES . '/poche/Url.class.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/WallabagEBooks.class.php'; -require_once INCLUDES . '/poche/Poche.class.php'; -require_once INCLUDES . '/poche/Database.class.php'; -require_once INCLUDES . '/poche/FlattrItem.class.php'; - -# system configuration; database credentials et caetera -require_once INCLUDES . '/poche/config.inc.php'; -require_once INCLUDES . '/poche/config.inc.default.php'; - -if (DOWNLOAD_PICTURES) { - require_once INCLUDES . '/poche/pochePictures.php'; -} - -if (!ini_get('date.timezone') || !@date_default_timezone_set(ini_get('date.timezone'))) { - date_default_timezone_set('UTC'); -} - -if (defined('ERROR_REPORTING')) { - error_reporting(ERROR_REPORTING); -} \ No newline at end of file diff --git a/inc/poche/pochePictures.php b/inc/poche/pochePictures.php deleted file mode 100644 index 52394c70..00000000 --- a/inc/poche/pochePictures.php +++ /dev/null @@ -1,168 +0,0 @@ - - * @copyright 2013 - * @license http://opensource.org/licenses/MIT see COPYING file - */ - - -final class Picture -{ - /** - * 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], Tools::getPocheUrl() . $fullpath, $content); - } - - $processing_pictures[] = $absolute_path; - } - } - - 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; - - /* queries and anchors */ - if ($relativeLink[0]=='#' || $relativeLink[0]=='?') return $url . $relativeLink; - - /* 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); - - /* destroy path if relative url points to root */ - if ($relativeLink[0] == '/') $path = ''; - - /* dirty absolute URL */ - $abs = $host . $path . '/' . $relativeLink; - - /* 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; - } - - /** - * 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); - - 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; - } - - /** - * 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 -- cgit v1.2.3