]> git.immae.eu Git - github/wallabag/wallabag.git/commitdiff
refactoring
authorNicolas Lœuillet <nicolas.loeuillet@gmail.com>
Sun, 4 Aug 2013 18:58:31 +0000 (20:58 +0200)
committerNicolas Lœuillet <nicolas.loeuillet@gmail.com>
Sun, 4 Aug 2013 18:58:31 +0000 (20:58 +0200)
inc/config.php [deleted file]
inc/poche/Poche.class.php [new file with mode: 0644]
inc/poche/Tools.class.php [new file with mode: 0644]
inc/poche/Url.class.php [new file with mode: 0644]
inc/poche/config.inc.php [new file with mode: 0644]
inc/poche/pocheCore.php [deleted file]
inc/poche/pochePictures.php
inc/poche/pocheTools.class.php [deleted file]
inc/store/sqlite.class.php
index.php
tpl/config.twig

diff --git a/inc/config.php b/inc/config.php
deleted file mode 100644 (file)
index 495dbb8..0000000
+++ /dev/null
@@ -1,79 +0,0 @@
-<?php
-/**
- * poche, a read it later open source system
- *
- * @category   poche
- * @author     Nicolas Lœuillet <nicolas@loeuillet.org>
- * @copyright  2013
- * @license    http://www.wtfpl.net/ see COPYING file
- */
-
-define ('POCHE_VERSION', '0.3');
-define ('MODE_DEMO', FALSE);
-define ('DEBUG_POCHE', FALSE);
-define ('CONVERT_LINKS_FOOTNOTES', FALSE);
-define ('REVERT_FORCED_PARAGRAPH_ELEMENTS', FALSE);
-define ('DOWNLOAD_PICTURES', FALSE);
-define ('SALT', '464v54gLLw928uz4zUBqkRJeiPY68zCX');
-define ('ABS_PATH', 'assets/');
-define ('TPL', './tpl');
-define ('LOCALE', './locale');
-define ('CACHE', './cache');
-define ('LANG', 'fr_FR.UTF8');
-
-$storage_type = 'sqlite'; # sqlite, file
-
-# /!\ Be careful if you change the lines below /!\
-require_once 'poche/pocheTools.class.php';
-require_once 'poche/pocheCore.php';
-require_once '3rdparty/Readability.php';
-require_once '3rdparty/Encoding.php';
-require_once '3rdparty/Session.class.php';
-require_once 'store/store.class.php';
-require_once 'store/' . $storage_type . '.class.php';
-require_once './vendor/autoload.php';
-
-if (DOWNLOAD_PICTURES) {
-    require_once 'poche/pochePicture.php';
-}
-
-# i18n
-putenv('LC_ALL=' . LANG);
-setlocale(LC_ALL, LANG);
-bindtextdomain(LANG, LOCALE); 
-textdomain(LANG); 
-
-# template engine
-// Twig_Autoloader::register();
-$loader = new Twig_Loader_Filesystem(TPL);
-$twig = new Twig_Environment($loader, array(
-    'cache' => CACHE,
-));
-$twig->addExtension(new Twig_Extensions_Extension_I18n());
-
-Session::init();
-$store = new $storage_type();
-
-# installation
-if(!$store->isInstalled())
-{
-    pocheTools::logm('poche still not installed');
-    echo $twig->render('install.twig', array(
-        'token' => Session::getToken(),
-    ));
-    if (isset($_GET['install'])) {
-        if (($_POST['password'] == $_POST['password_repeat']) 
-            && $_POST['password'] != "" && $_POST['login'] != "") {
-            # let's rock, install poche baby !
-            $store->install($_POST['login'], encode_string($_POST['password'] . $_POST['login']));
-            Session::logout();
-            pocheTools::redirect();
-        }
-    }
-    exit();
-}
-
-$_SESSION['login'] = (isset ($_SESSION['login'])) ? $_SESSION['login'] : $store->getLogin();
-$_SESSION['pass']  = (isset ($_SESSION['pass'])) ? $_SESSION['pass'] : $store->getPassword();
-
-pocheTools::initPhp();
\ No newline at end of file
diff --git a/inc/poche/Poche.class.php b/inc/poche/Poche.class.php
new file mode 100644 (file)
index 0000000..973ae3e
--- /dev/null
@@ -0,0 +1,176 @@
+<?php
+/**
+ * poche, a read it later open source system
+ *
+ * @category   poche
+ * @author     Nicolas Lœuillet <support@inthepoche.com>
+ * @copyright  2013
+ * @license    http://www.wtfpl.net/ see COPYING file
+ */
+
+class Poche
+{
+    public $store;
+    public $tpl;
+
+    function __construct($storage_type)
+    {
+        $this->store = new $storage_type();
+        $this->init();
+
+        # installation
+        if(!$this->store->isInstalled())
+        {
+            $this->install();
+        }
+
+        $this->saveUser();
+    }
+
+    private function init() 
+    {
+        # l10n
+        putenv('LC_ALL=' . LANG);
+        setlocale(LC_ALL, LANG);
+        bindtextdomain(LANG, LOCALE); 
+        textdomain(LANG); 
+
+        # template engine
+        $loader = new Twig_Loader_Filesystem(TPL);
+        $this->tpl = new Twig_Environment($loader, array(
+            'cache' => CACHE,
+        ));
+        $this->tpl->addExtension(new Twig_Extensions_Extension_I18n());
+
+        Tools::initPhp();
+        Session::init();
+    }
+
+    private function install() 
+    {
+        Tools::logm('poche still not installed');
+        echo $this->tpl->render('install.twig', array(
+            'token' => Session::getToken(),
+        ));
+        if (isset($_GET['install'])) {
+            if (($_POST['password'] == $_POST['password_repeat']) 
+                && $_POST['password'] != "" && $_POST['login'] != "") {
+                # let's rock, install poche baby !
+                $this->store->install($_POST['login'], Tools::encodeString($_POST['password'] . $_POST['login']));
+                Session::logout();
+                Tools::redirect();
+            }
+        }
+        exit();
+    }
+
+    private function saveUser()
+    {
+        $_SESSION['login'] = (isset ($_SESSION['login'])) ? $_SESSION['login'] : $this->store->getLogin();
+        $_SESSION['pass'] = (isset ($_SESSION['pass'])) ? $_SESSION['pass'] : $this->store->getPassword();
+    }
+
+    /**
+     * Call action (mark as fav, archive, delete, etc.)
+     */
+    public function action($action, Url $url, $id)
+    {
+        switch ($action)
+        {
+            case 'add':
+                if($parametres_url = $url->fetchContent()) {
+                    if ($this->store->add($url->getUrl(), $parametres_url['title'], $parametres_url['content'])) {
+                        Tools::logm('add link ' . $url->getUrl());
+                        $last_id = $this->store->getLastId();
+                        if (DOWNLOAD_PICTURES) {
+                            $content = filtre_picture($parametres_url['content'], $url->getUrl(), $last_id);
+                        }
+                        #$msg->add('s', _('the link has been added successfully'));
+                    }
+                    else {
+                        #$msg->add('e', _('error during insertion : the link wasn\'t added'));
+                        Tools::logm('error during insertion : the link wasn\'t added');
+                    }
+                }
+                else {
+                    #$msg->add('e', _('error during url preparation : the link wasn\'t added'));
+                    Tools::logm('error during content fetch');
+                }
+                break;
+            case 'delete':
+                if ($this->store->deleteById($id)) {
+                    if (DOWNLOAD_PICTURES) {
+                        remove_directory(ABS_PATH . $id);
+                    }
+                    #$msg->add('s', _('the link has been deleted successfully'));
+                    Tools::logm('delete link #' . $id);
+                }
+                else {
+                    #$msg->add('e', _('the link wasn\'t deleted'));
+                    Tools::logm('error : can\'t delete link #' . $id);
+                }
+                break;
+            case 'toggle_fav' :
+                $this->store->favoriteById($id);
+                Tools::logm('mark as favorite link #' . $id);
+                break;
+            case 'toggle_archive' :
+                $this->store->archiveById($id);
+                Tools::logm('archive link #' . $id);
+                break;
+            default:
+                break;
+        }
+    }
+
+    function displayView($view, $id = 0)
+    {
+        $tpl_vars = array();
+
+        switch ($view)
+        {
+            case 'install':
+                Tools::logm('install mode');
+                break;
+            case 'import';
+                Tools::logm('import mode');
+                break;
+            case 'export':
+                $entries = $this->store->retrieveAll();
+                // $tpl->assign('export', Tools::renderJson($entries));
+                // $tpl->draw('export');
+                Tools::logm('export view');
+                break;
+            case 'config':
+                Tools::logm('config view');
+                break;
+            case 'view':
+                $entry = $this->store->retrieveOneById($id);
+                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;
+                    }
+                    $tpl_vars = array(
+                        'entry' => $entry,
+                        'content' => $content,
+                    );
+                }
+                else {
+                    Tools::logm('error in view call : entry is NULL');
+                }
+                break;
+            default: # home view
+                $entries = $this->store->getEntriesByView($view);
+                $tpl_vars = array(
+                    'entries' => $entries,
+                );
+                break;
+        }
+
+        return $tpl_vars;
+    }
+}
\ No newline at end of file
diff --git a/inc/poche/Tools.class.php b/inc/poche/Tools.class.php
new file mode 100644 (file)
index 0000000..c277035
--- /dev/null
@@ -0,0 +1,208 @@
+<?php
+/**
+ * poche, a read it later open source system
+ *
+ * @category   poche
+ * @author     Nicolas Lœuillet <support@inthepoche.com>
+ * @copyright  2013
+ * @license    http://www.wtfpl.net/ see COPYING file
+ */
+class Tools
+{
+    public static function initPhp()
+    {
+        define('START_TIME', microtime(true));
+
+        if (phpversion() < 5) {
+            die(_('Oops, it seems you don\'t have PHP 5.'));
+        }
+
+        error_reporting(E_ALL);
+
+        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');
+    }
+
+    public static function getPocheUrl()
+    {
+        $https = (!empty($_SERVER['HTTPS'])
+                    && (strtolower($_SERVER['HTTPS']) == 'on'))
+            || (isset($_SERVER["SERVER_PORT"])
+                    && $_SERVER["SERVER_PORT"] == '443'); // HTTPS detection.
+        $serverport = (!isset($_SERVER["SERVER_PORT"])
+            || $_SERVER["SERVER_PORT"] == '80'
+            || ($https && $_SERVER["SERVER_PORT"] == '443')
+            ? '' : ':' . $_SERVER["SERVER_PORT"]);
+
+        $scriptname = str_replace('/index.php', '/', $_SERVER["SCRIPT_NAME"]);
+
+        if (!isset($_SERVER["SERVER_NAME"])) {
+            return $scriptname;
+        }
+
+        return 'http' . ($https ? 's' : '') . '://'
+            . $_SERVER["SERVER_NAME"] . $serverport . $scriptname;
+    }
+
+    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;
+            }
+        }
+        header('Location: '.$url);
+        exit();
+    }
+
+    public static function getTplFile($view)
+    {
+        $tpl_file = 'home.twig';
+        switch ($view)
+        {
+            case 'install':
+                $tpl_file = 'install.twig';
+                break;
+            case 'import';
+                $tpl_file = 'import.twig';
+                break;
+            case 'export':
+                $tpl_file = 'export.twig';
+                break;
+            case 'config':
+                $tpl_file = 'config.twig';
+                break;
+            case 'view':
+                $tpl_file = 'view.twig';
+                break;
+            default:
+            break;
+        }
+        return $tpl_file;
+    }
+
+    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);
+            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('#<meta .*charset=.*>#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';
+            } 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;
+        }
+    }
+
+    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();
+    }
+
+    public static function logm($message)
+    {
+        if (DEBUG_POCHE) {
+            $t = strval(date('Y/m/d_H:i:s')) . ' - ' . $_SERVER["REMOTE_ADDR"] . ' - ' . strval($message) . "\n";
+            file_put_contents('./log.txt', $t, FILE_APPEND);
+        }
+    }
+
+    public static function encodeString($string) 
+    {
+        return sha1($string . SALT);
+    }
+}
\ No newline at end of file
diff --git a/inc/poche/Url.class.php b/inc/poche/Url.class.php
new file mode 100644 (file)
index 0000000..f4a8f99
--- /dev/null
@@ -0,0 +1,94 @@
+<?php
+/**
+ * poche, a read it later open source system
+ *
+ * @category   poche
+ * @author     Nicolas Lœuillet <support@inthepoche.com>
+ * @copyright  2013
+ * @license    http://www.wtfpl.net/ 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()
+    {
+        $pattern = '|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i';
+
+        return preg_match($pattern, $this->url);
+    }
+
+    public function clean()
+    {
+        $url = html_entity_decode(trim($this->url));
+
+        $stuff = strpos($url,'&utm_source=');
+        if ($stuff !== FALSE)
+            $url = substr($url, 0, $stuff);
+        $stuff = strpos($url,'?utm_source=');
+        if ($stuff !== FALSE)
+            $url = substr($url, 0, $stuff);
+        $stuff = strpos($url,'#xtor=RSS-');
+        if ($stuff !== FALSE)
+            $url = substr($url, 0, $stuff);
+
+        $this->url = $url;
+    }
+
+    public function fetchContent()
+    {
+        if ($this->isCorrect()) {
+            $this->clean();
+            $html = Encoding::toUTF8(Tools::getFile($this->getUrl()));
+
+            # if Tools::getFile() if not able to retrieve HTTPS content, try the same URL with HTTP protocol
+            if (!preg_match('!^https?://!i', $this->getUrl()) && (!isset($html) || strlen($html) <= 0)) {
+                $this->setUrl('http://' . $this->getUrl());
+                $html = Encoding::toUTF8(Tools::getFile($this->getUrl()));
+            }
+
+            if (function_exists('tidy_parse_string')) {
+                $tidy = tidy_parse_string($html, array(), 'UTF8');
+                $tidy->cleanRepair();
+                $html = $tidy->value;
+            }
+
+            $parameters = array();
+            if (isset($html) and strlen($html) > 0)
+            {
+                $readability = new Readability($html, $this->getUrl());
+                $readability->convertLinksToFootnotes = CONVERT_LINKS_FOOTNOTES;
+                $readability->revertForcedParagraphElements = REVERT_FORCED_PARAGRAPH_ELEMENTS;
+
+                if($readability->init())
+                {
+                    $content = $readability->articleContent->innerHTML;
+                    $parameters['title'] = $readability->articleTitle->innerHTML;
+                    $parameters['content'] = $content;
+
+                    return $parameters;
+                }
+            }
+        }
+        else {
+            #$msg->add('e', _('error during url preparation : the link is not valid'));
+            Tools::logm($this->getUrl() . ' is not a valid url');
+        }
+
+        return FALSE;
+    }
+}
\ No newline at end of file
diff --git a/inc/poche/config.inc.php b/inc/poche/config.inc.php
new file mode 100644 (file)
index 0000000..81297e0
--- /dev/null
@@ -0,0 +1,40 @@
+<?php
+/**
+ * poche, a read it later open source system
+ *
+ * @category   poche
+ * @author     Nicolas Lœuillet <nicolas@loeuillet.org>
+ * @copyright  2013
+ * @license    http://www.wtfpl.net/ see COPYING file
+ */
+
+define ('POCHE_VERSION', '0.4');
+define ('MODE_DEMO', FALSE);
+define ('DEBUG_POCHE', FALSE);
+define ('CONVERT_LINKS_FOOTNOTES', FALSE);
+define ('REVERT_FORCED_PARAGRAPH_ELEMENTS', FALSE);
+define ('DOWNLOAD_PICTURES', FALSE);
+define ('SALT', '464v54gLLw928uz4zUBqkRJeiPY68zCX');
+define ('ABS_PATH', 'assets/');
+define ('TPL', './tpl');
+define ('LOCALE', './locale');
+define ('CACHE', './cache');
+define ('LANG', 'fr_FR.UTF8');
+$storage_type = 'sqlite'; # sqlite, file
+
+# /!\ Be careful if you change the lines below /!\
+require_once './inc/poche/Tools.class.php';
+require_once './inc/poche/Url.class.php';
+require_once './inc/poche/Poche.class.php';
+require_once './inc/3rdparty/Readability.php';
+require_once './inc/3rdparty/Encoding.php';
+require_once './inc/3rdparty/Session.class.php';
+require_once './inc/store/store.class.php';
+require_once './inc/store/' . $storage_type . '.class.php';
+require_once './vendor/autoload.php';
+
+if (DOWNLOAD_PICTURES) {
+    require_once './inc/poche/pochePicture.php';
+}
+
+$poche = new Poche($storage_type);
\ No newline at end of file
diff --git a/inc/poche/pocheCore.php b/inc/poche/pocheCore.php
deleted file mode 100644 (file)
index 74b063e..0000000
+++ /dev/null
@@ -1,269 +0,0 @@
-<?php
-/**
- * poche, a read it later open source system
- *
- * @category   poche
- * @author     Nicolas Lœuillet <support@inthepoche.com>
- * @copyright  2013
- * @license    http://www.wtfpl.net/ see COPYING file
- */
-
-function encode_string($string) 
-{
-    return sha1($string . SALT);
-}
-
-function get_external_file($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);
-        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('#<meta .*charset=.*>#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';
-        } 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;
-    }
-}
-
-function fetch_url_content($url)
-{
-    $url = base64_decode($url);
-    if (pocheTools::isUrl($url)) {
-        $url = pocheTools::cleanURL($url);
-        $html = Encoding::toUTF8(get_external_file($url));
-
-        # if get_external_file if not able to retrieve HTTPS content, try the same URL with HTTP protocol
-        if (!preg_match('!^https?://!i', $url) && (!isset($html) || strlen($html) <= 0)) {
-            $url = 'http://' . $url;
-            $html = Encoding::toUTF8(get_external_file($url));
-        }
-
-        if (function_exists('tidy_parse_string')) {
-            $tidy = tidy_parse_string($html, array(), 'UTF8');
-            $tidy->cleanRepair();
-            $html = $tidy->value;
-        }
-
-        $parameters = array();
-        if (isset($html) and strlen($html) > 0)
-        {
-            $readability = new Readability($html, $url);
-            $readability->convertLinksToFootnotes = CONVERT_LINKS_FOOTNOTES;
-            $readability->revertForcedParagraphElements = REVERT_FORCED_PARAGRAPH_ELEMENTS;
-
-            if($readability->init())
-            {
-                $content = $readability->articleContent->innerHTML;
-                $parameters['title'] = $readability->articleTitle->innerHTML;
-                $parameters['content'] = $content;
-
-                return $parameters;
-            }
-        }
-    }
-    else {
-        #$msg->add('e', _('error during url preparation : the link is not valid'));
-        pocheTools::logm($url . ' is not a valid url');
-    }
-
-    return FALSE;
-}
-
-function get_tpl_file($view)
-{
-    $tpl_file = 'home.twig';
-    switch ($view)
-    {
-        case 'install':
-            $tpl_file = 'install.twig';
-            break;
-        case 'import';
-            $tpl_file = 'import.twig';
-            break;
-        case 'export':
-            $tpl_file = 'export.twig';
-            break;
-        case 'config':
-            $tpl_file = 'config.twig';
-            break;
-        case 'view':
-            $tpl_file = 'view.twig';
-            break;
-        default:
-        break;
-    }
-    return $tpl_file;
-}
-
-function display_view($view, $id = 0)
-{
-    global $store;
-
-    $tpl_vars = array();
-
-    switch ($view)
-    {
-        case 'install':
-            pocheTools::logm('install mode');
-            break;
-        case 'import';
-            pocheTools::logm('import mode');
-            break;
-        case 'export':
-            $entries = $store->retrieveAll();
-            $tpl->assign('export', pocheTools::renderJson($entries));
-            $tpl->draw('export');
-            pocheTools::logm('export view');
-            break;
-        case 'config':
-            pocheTools::logm('config view');
-            break;
-        case 'view':
-            $entry = $store->retrieveOneById($id);
-            if ($entry != NULL) {
-                pocheTools::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;
-                }
-                $tpl_vars = array(
-                    'entry' => $entry,
-                    'content' => $content,
-                );
-            }
-            else {
-                pocheTools::logm('error in view call : entry is NULL');
-            }
-            break;
-        default: # home view
-            $entries = $store->getEntriesByView($view);
-            $tpl_vars = array(
-                'entries' => $entries,
-            );
-            break;
-    }
-
-    return $tpl_vars;
-}
-
-/**
- * Call action (mark as fav, archive, delete, etc.)
- */
-function action_to_do($action, $url, $id = 0)
-{
-    global $store;
-
-    switch ($action)
-    {
-        case 'add':
-            if($parametres_url = fetch_url_content($url)) {
-                if ($store->add($url, $parametres_url['title'], $parametres_url['content'])) {
-                    pocheTools::logm('add link ' . $url);
-                    $last_id = $store->getLastId();
-                    if (DOWNLOAD_PICTURES) {
-                        $content = filtre_picture($parametres_url['content'], $url, $last_id);
-                    }
-                    #$msg->add('s', _('the link has been added successfully'));
-                }
-                else {
-                    #$msg->add('e', _('error during insertion : the link wasn\'t added'));
-                    pocheTools::logm('error during insertion : the link wasn\'t added');
-                }
-            }
-            else {
-                #$msg->add('e', _('error during url preparation : the link wasn\'t added'));
-                pocheTools::logm('error during content fetch');
-            }
-            break;
-        case 'delete':
-            if ($store->deleteById($id)) {
-                if (DOWNLOAD_PICTURES) {
-                    remove_directory(ABS_PATH . $id);
-                }
-                #$msg->add('s', _('the link has been deleted successfully'));
-                pocheTools::logm('delete link #' . $id);
-            }
-            else {
-                #$msg->add('e', _('the link wasn\'t deleted'));
-                pocheTools::logm('error : can\'t delete link #' . $id);
-            }
-            break;
-        case 'toggle_fav' :
-            $store->favoriteById($id);
-            pocheTools::logm('mark as favorite link #' . $id);
-            break;
-        case 'toggle_archive' :
-            $store->archiveById($id);
-            pocheTools::logm('archive link #' . $id);
-            break;
-        default:
-            break;
-    }
-}
index 0d73a14985a4ccde25117db59310688af30b2eb2..4e4a0b08561eed78c8aecb81b459696842593501 100644 (file)
@@ -67,7 +67,7 @@ function get_absolute_link($relative_link, $url) {
  */
 function download_pictures($absolute_path, $fullpath)
 {
-    $rawdata = get_external_file($absolute_path);
+    $rawdata = Tools::getFile($absolute_path);
 
     if(file_exists($fullpath)) {
         unlink($fullpath);
diff --git a/inc/poche/pocheTools.class.php b/inc/poche/pocheTools.class.php
deleted file mode 100644 (file)
index 08c9dc8..0000000
+++ /dev/null
@@ -1,126 +0,0 @@
-<?php
-/**
- * poche, a read it later open source system
- *
- * @category   poche
- * @author     Nicolas Lœuillet <support@inthepoche.com>
- * @copyright  2013
- * @license    http://www.wtfpl.net/ see COPYING file
- */
-class pocheTools
-{
-    public static function initPhp()
-    {
-        define('START_TIME', microtime(true));
-
-        if (phpversion() < 5) {
-            die(_('Oops, it seems you don\'t have PHP 5.'));
-        }
-
-        error_reporting(E_ALL);
-
-        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');
-    }
-
-    public static function isUrl($url)
-    {
-        $pattern = '|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i';
-
-        return preg_match($pattern, $url);
-    }
-
-    public static function getUrl()
-    {
-        $https = (!empty($_SERVER['HTTPS'])
-                    && (strtolower($_SERVER['HTTPS']) == 'on'))
-            || (isset($_SERVER["SERVER_PORT"])
-                    && $_SERVER["SERVER_PORT"] == '443'); // HTTPS detection.
-        $serverport = (!isset($_SERVER["SERVER_PORT"])
-            || $_SERVER["SERVER_PORT"] == '80'
-            || ($https && $_SERVER["SERVER_PORT"] == '443')
-            ? '' : ':' . $_SERVER["SERVER_PORT"]);
-
-        $scriptname = str_replace('/index.php', '/', $_SERVER["SCRIPT_NAME"]);
-
-        if (!isset($_SERVER["SERVER_NAME"])) {
-            return $scriptname;
-        }
-
-        return 'http' . ($https ? 's' : '') . '://'
-            . $_SERVER["SERVER_NAME"] . $serverport . $scriptname;
-    }
-
-    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 = pocheTools::getUrl();
-        }
-
-        if (substr($url, 0, 1) !== '?') {
-            $ref = pocheTools::getUrl();
-            if (substr($url, 0, strlen($ref)) !== $ref) {
-                $url = $ref;
-            }
-        }
-        header('Location: '.$url);
-        exit();
-    }
-
-    public static function cleanURL($url)
-    {
-
-        $url = html_entity_decode(trim($url));
-
-        $stuff = strpos($url,'&utm_source=');
-        if ($stuff !== FALSE)
-            $url = substr($url, 0, $stuff);
-        $stuff = strpos($url,'?utm_source=');
-        if ($stuff !== FALSE)
-            $url = substr($url, 0, $stuff);
-        $stuff = strpos($url,'#xtor=RSS-');
-        if ($stuff !== FALSE)
-            $url = substr($url, 0, $stuff);
-
-        return $url;
-    }
-
-    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();
-    }
-
-    public static function logm($message)
-    {
-        if (DEBUG_POCHE) {
-            $t = strval(date('Y/m/d_H:i:s')) . ' - ' . $_SERVER["REMOTE_ADDR"] . ' - ' . strval($message) . "\n";
-            file_put_contents('./log.txt', $t, FILE_APPEND);
-        }
-    }
-}
\ No newline at end of file
index 210816084e1e0042e381b5bd6783fdcea8db2126..a15bc095b4a2e8c248e9baa4b563017190f45f9b 100644 (file)
@@ -90,7 +90,7 @@ class Sqlite extends Store {
         }
         catch (Exception $e)
         {
-            logm('execute query error : '.$e->getMessage());
+            Tools::logm('execute query error : '.$e->getMessage());
         }
     }
 
index dc064428d3a6a7f620bb210c24771c848a395be6..40779698c4c25a63d04c4afe45515a31d1b9f6cd 100644 (file)
--- a/index.php
+++ b/index.php
@@ -8,7 +8,7 @@
  * @license    http://www.wtfpl.net/ see COPYING file
  */
 
-include dirname(__FILE__).'/inc/config.php';
+include dirname(__FILE__).'/inc/poche/config.inc.php';
 
 $notices = array();
 
@@ -26,9 +26,9 @@ $referer = empty($_SERVER['HTTP_REFERER']) ? '' : $_SERVER['HTTP_REFERER'];
 if (isset($_GET['login'])) {
     # hello you
     if (!empty($_POST['login']) && !empty($_POST['password'])) {
-        if (Session::login($_SESSION['login'], $_SESSION['pass'], $_POST['login'], encode_string($_POST['password'] . $_POST['login']))) {
-            pocheTools::logm('login successful');
-            $pocheTools[]['value'] = _('login successful');
+        if (Session::login($_SESSION['login'], $_SESSION['pass'], $_POST['login'], Tools::encodeString($_POST['password'] . $_POST['login']))) {
+            Tools::logm('login successful');
+            $notices['value'] = _('login successful');
 
             if (!empty($_POST['longlastingsession'])) {
                 $_SESSION['longlastingsession'] = 31536000;
@@ -38,34 +38,34 @@ if (isset($_GET['login'])) {
                 session_set_cookie_params(0);
             }
             session_regenerate_id(true);
-            pocheTools::redirect($referer);
+            Tools::redirect($referer);
         }
-        pocheTools::logm('login failed');
-        $notices[]['value'] = _('Login failed !');
-        pocheTools::redirect();
+        Tools::logm('login failed');
+        $notices['value'] = _('Login failed !');
+        Tools::redirect();
     } else {
-        pocheTools::logm('login failed');
-        pocheTools::redirect();
+        Tools::logm('login failed');
+        Tools::redirect();
     }
 }
 elseif (isset($_GET['logout'])) {
     # see you soon !
-    pocheTools::logm('logout');
+    Tools::logm('logout');
     Session::logout();
-    pocheTools::redirect();
+    Tools::redirect();
 }
 elseif  (isset($_GET['config'])) {
     # Update password
     if (isset($_POST['password']) && isset($_POST['password_repeat'])) {
         if ($_POST['password'] == $_POST['password_repeat'] && $_POST['password'] != "") {
             if (!MODE_DEMO) {
-                pocheTools::logm('password updated');
-                $store->updatePassword(encode_string($_POST['password'] . $_SESSION['login']));
+                Tools::logm('password updated');
+                $poche->store->updatePassword(Tools::encodeString($_POST['password'] . $_SESSION['login']));
                 Session::logout();
-                pocheTools::redirect();
+                Tools::redirect();
             }
             else {
-                pocheTools::logm('in demo mode, you can\'t do this');
+                Tools::logm('in demo mode, you can\'t do this');
             }
         }
     }
@@ -77,12 +77,13 @@ $full_head = (isset ($_REQUEST['full_head'])) ? htmlentities($_REQUEST['full_hea
 $action = (isset ($_REQUEST['action'])) ? htmlentities($_REQUEST['action']) : '';
 $_SESSION['sort'] = (isset ($_REQUEST['sort'])) ? htmlentities($_REQUEST['sort']) : 'id';
 $id = (isset ($_REQUEST['id'])) ? htmlspecialchars($_REQUEST['id']) : '';
-$url = (isset ($_GET['url'])) ? $_GET['url'] : '';
+
+$url = new Url((isset ($_GET['url'])) ? $_GET['url'] : '');
 
 $tpl_vars = array(
     'referer' => $referer,
     'view' => $view,
-    'poche_url' => pocheTools::getUrl(),
+    'poche_url' => Tools::getPocheUrl(),
     'demo' => MODE_DEMO,
     'title' => _('poche, a read it later open source system'),
     'token' => Session::getToken(),
@@ -90,12 +91,12 @@ $tpl_vars = array(
 );
 
 if (Session::isLogged()) {
-    action_to_do($action, $url, $id);
-    $tpl_file = get_tpl_file($view);
-    $tpl_vars = array_merge($tpl_vars, display_view($view, $id));
+    $poche->action($action, $url, $id);
+    $tpl_file = Tools::getTplFile($view);
+    $tpl_vars = array_merge($tpl_vars, $poche->displayView($view, $id));
 }
 else {
     $tpl_file = 'login.twig';
 }
 
-echo $twig->render($tpl_file, $tpl_vars);
\ No newline at end of file
+echo $poche->tpl->render($tpl_file, $tpl_vars);
\ No newline at end of file
index be2c04547e24f7b02148b9282313771c36ae31e1..4e7bb9d4cf604b9f03a5eab0251acff61f0ea956 100644 (file)
@@ -15,7 +15,7 @@
                <h2>{% trans "Bookmarklet" %}</h2>
                <p>{% trans "Thanks to the bookmarklet, you will be able to easily add a link to your poche." %} {% trans "Have a look to this documentation:" %} <a href="http://inthepoche.com/?pages/Documentation" target="_blank">http://inthepoche.com/?pages/Documentation</a>.</p>
                <p>{% trans "Drag & drop this link to your bookmarks bar and have fun with poche." %}</p>
-                <p><a ondragend="this.click();" style="cursor: move; border: 1px dashed grey; background: white;" title="i am a bookmarklet, use me !" href="javascript:if(top['bookmarklet-url@inthepoche.com']){top['bookmarklet-url@inthepoche.com'];}else{(function(){var%20url%20=%20location.href%20||%20url;window.open('{$poche_url}?action=add&url='%20+%20btoa(url),'_self');})();void(0);}">{% trans "poche it!" %}</a></p>
+                <p><a ondragend="this.click();" style="cursor: move; border: 1px dashed grey; background: white;" title="i am a bookmarklet, use me !" href="javascript:if(top['bookmarklet-url@inthepoche.com']){top['bookmarklet-url@inthepoche.com'];}else{(function(){var%20url%20=%20location.href%20||%20url;window.open('{{ poche_url }}?action=add&url='%20+%20btoa(url),'_self');})();void(0);}">{% trans "poche it!" %}</a></p>
 
                 <h2>{% trans "Change your password" %}</h2>
                    <form method="post" action="?config" name="loginform">