]> git.immae.eu Git - github/wallabag/wallabag.git/commitdiff
PicoFarad framework for routing
authorNicolas Lœuillet <nicolas@loeuillet.org>
Fri, 11 Jul 2014 15:06:51 +0000 (17:06 +0200)
committerNicolas Lœuillet <nicolas@loeuillet.org>
Fri, 11 Jul 2014 15:06:51 +0000 (17:06 +0200)
inc/3rdparty/PicoFarad/Request.php [new file with mode: 0644]
inc/3rdparty/PicoFarad/Response.php [new file with mode: 0644]
inc/3rdparty/PicoFarad/Router.php [new file with mode: 0644]
inc/3rdparty/PicoFarad/Session.php [new file with mode: 0644]
inc/3rdparty/PicoFarad/Template.php [new file with mode: 0644]
inc/poche/Database.class.php
inc/poche/Routing.class.php
inc/poche/global.inc.php
index.php

diff --git a/inc/3rdparty/PicoFarad/Request.php b/inc/3rdparty/PicoFarad/Request.php
new file mode 100644 (file)
index 0000000..46c82bc
--- /dev/null
@@ -0,0 +1,78 @@
+<?php
+
+namespace PicoFarad\Request;
+
+
+function param($name, $default_value = null)
+{
+    return isset($_GET[$name]) ? $_GET[$name] : $default_value;
+}
+
+
+function int_param($name, $default_value = 0)
+{
+    return isset($_GET[$name]) && ctype_digit($_GET[$name]) ? (int) $_GET[$name] : $default_value;
+}
+
+
+function value($name)
+{
+    $values = values();
+    return isset($values[$name]) ? $values[$name] : null;
+}
+
+
+function values()
+{
+    if (! empty($_POST)) {
+
+        return $_POST;
+    }
+
+    $result = json_decode(body(), true);
+
+    if ($result) {
+        return $result;
+    }
+
+    return array();
+}
+
+
+function body()
+{
+    return file_get_contents('php://input');
+}
+
+
+function file_content($field)
+{
+    if (isset($_FILES[$field])) {
+        return file_get_contents($_FILES[$field]['tmp_name']);
+    }
+
+    return '';
+}
+
+
+function file_info($field)
+{
+    if (isset($_FILES[$field])) {
+        return array(
+            'name' => $_FILES[$field]['name'],
+            'mimetype' => $_FILES[$field]['type'],
+            'size' => $_FILES[$field]['size'],
+        );
+    }
+
+    return false;
+}
+
+
+function file_move($field, $destination)
+{
+    if (isset($_FILES[$field]) && ! file_exists($destination)) {
+        @mkdir(dirname($destination), 0777, true);
+        move_uploaded_file($_FILES[$field]['tmp_name'], $destination);
+    }
+}
\ No newline at end of file
diff --git a/inc/3rdparty/PicoFarad/Response.php b/inc/3rdparty/PicoFarad/Response.php
new file mode 100644 (file)
index 0000000..9114fde
--- /dev/null
@@ -0,0 +1,156 @@
+<?php
+
+namespace PicoFarad\Response;
+
+
+function force_download($filename)
+{
+    header('Content-Disposition: attachment; filename="'.$filename.'"');
+}
+
+
+function content_type($mimetype)
+{
+    header('Content-Type: '.$mimetype);
+}
+
+
+function status($status_code)
+{
+    $sapi_name = php_sapi_name();
+
+    if (strpos($sapi_name, 'apache') !== false || $sapi_name === 'cli-server') {
+        header('HTTP/1.0 '.$status_code);
+    }
+    else {
+        header('Status: '.$status_code);
+    }
+}
+
+
+function redirect($url)
+{
+    header('Location: '.$url);
+    exit;
+}
+
+
+function json(array $data, $status_code = 200)
+{
+    status($status_code);
+
+    header('Content-Type: application/json');
+    echo json_encode($data);
+
+    exit;
+}
+
+
+function text($data, $status_code = 200)
+{
+    status($status_code);
+
+    header('Content-Type: text/plain; charset=utf-8');
+    echo $data;
+
+    exit;
+}
+
+
+function html($data, $status_code = 200)
+{
+    status($status_code);
+
+    header('Content-Type: text/html; charset=utf-8');
+    echo $data;
+
+    exit;
+}
+
+
+function xml($data, $status_code = 200)
+{
+    status($status_code);
+
+    header('Content-Type: text/xml; charset=utf-8');
+    echo $data;
+
+    exit;
+}
+
+
+function js($data, $status_code = 200)
+{
+    status($status_code);
+
+    header('Content-Type: text/javascript; charset=utf-8');
+    echo $data;
+
+    exit;
+}
+
+
+function binary($data, $status_code = 200)
+{
+    status($status_code);
+
+    header('Content-Transfer-Encoding: binary');
+    header('Content-Type: application/octet-stream');
+    echo $data;
+
+    exit;
+}
+
+
+function csp(array $policies = array())
+{
+    $policies['default-src'] = "'self'";
+    $values = '';
+
+    foreach ($policies as $policy => $hosts) {
+
+        if (is_array($hosts)) {
+
+            $acl = '';
+
+            foreach ($hosts as &$host) {
+
+                if ($host === '*' || $host === 'self' || strpos($host, 'http') === 0) {
+                    $acl .= $host.' ';
+                }
+            }
+        }
+        else {
+
+            $acl = $hosts;
+        }
+
+        $values .= $policy.' '.trim($acl).'; ';
+    }
+
+    header('Content-Security-Policy: '.$values);
+}
+
+
+function nosniff()
+{
+    header('X-Content-Type-Options: nosniff');
+}
+
+
+function xss()
+{
+    header('X-XSS-Protection: 1; mode=block');
+}
+
+
+function hsts()
+{
+    header('Strict-Transport-Security: max-age=31536000');
+}
+
+
+function xframe($mode = 'DENY', array $urls = array())
+{
+    header('X-Frame-Options: '.$mode.' '.implode(' ', $urls));
+}
\ No newline at end of file
diff --git a/inc/3rdparty/PicoFarad/Router.php b/inc/3rdparty/PicoFarad/Router.php
new file mode 100644 (file)
index 0000000..b62b8e2
--- /dev/null
@@ -0,0 +1,157 @@
+<?php
+
+namespace PicoFarad\Router;
+
+// Load controllers: bootstrap('controllers', 'controller1', 'controller2')
+function bootstrap()
+{
+    $files = \func_get_args();
+    $base_path = array_shift($files);
+
+    foreach ($files as $file) {
+        require $base_path.'/'.$file.'.php';
+    }
+}
+
+// Execute a callback before each action
+function before($value = null)
+{
+    static $before_callback = null;
+
+    if (is_callable($value)) {
+        $before_callback = $value;
+    }
+    else if (is_callable($before_callback)) {
+        $before_callback($value);
+    }
+}
+
+// Execute a callback before a specific action
+function before_action($name, $value = null)
+{
+    static $callbacks = array();
+
+    if (is_callable($value)) {
+        $callbacks[$name] = $value;
+    }
+    else if (isset($callbacks[$name]) && is_callable($callbacks[$name])) {
+        $callbacks[$name]($value);
+    }
+}
+
+// Execute an action
+function action($name, \Closure $callback)
+{
+    $handler = isset($_GET['action']) ? $_GET['action'] : 'default';
+
+    if ($handler === $name) {
+        before($name);
+        before_action($name);
+        $callback();
+    }
+}
+
+// Execute an action only for POST requests
+function post_action($name, \Closure $callback)
+{
+    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
+        action($name, $callback);
+    }
+}
+
+// Execute an action only for GET requests
+function get_action($name, \Closure $callback)
+{
+    if ($_SERVER['REQUEST_METHOD'] === 'GET') {
+        action($name, $callback);
+    }
+}
+
+// Run when no action have been executed before
+function notfound(\Closure $callback)
+{
+    before('notfound');
+    before_action('notfound');
+    $callback();
+}
+
+// Match a request like this one: GET /myhandler
+function get($url, \Closure $callback)
+{
+    find_route('GET', $url, $callback);
+}
+
+// Match a request like this one: POST /myhandler
+function post($url, \Closure $callback)
+{
+    find_route('POST', $url, $callback);
+}
+
+// Match a request like this one: PUT /myhandler
+function put($url, \Closure $callback)
+{
+    find_route('PUT', $url, $callback);
+}
+
+// Match a request like this one: DELETE /myhandler
+function delete($url, \Closure $callback)
+{
+    find_route('DELETE', $url, $callback);
+}
+
+// Define which callback to execute according to the URL and the HTTP verb
+function find_route($method, $route, \Closure $callback)
+{
+    if ($_SERVER['REQUEST_METHOD'] === $method) {
+
+        if (! empty($_SERVER['QUERY_STRING'])) {
+            $url = substr($_SERVER['REQUEST_URI'], 0, -(strlen($_SERVER['QUERY_STRING']) + 1));
+        }
+        else {
+            $url = $_SERVER['REQUEST_URI'];
+        }
+
+        $params = array();
+
+        if (url_match($route, $url, $params)) {
+
+            before($route);
+            \call_user_func_array($callback, $params);
+            exit;
+        }
+    }
+}
+
+// Parse url and find matches
+function url_match($route_uri, $request_uri, array &$params)
+{
+    if ($request_uri === $route_uri) return true;
+    if ($route_uri === '/' || $request_uri === '/') return false;
+
+    $route_uri = trim($route_uri, '/');
+    $request_uri = trim($request_uri, '/');
+
+    $route_items = explode('/', $route_uri);
+    $request_items = explode('/', $request_uri);
+    $nb_route_items = count($route_items);
+
+    if ($nb_route_items === count($request_items)) {
+
+        for ($i = 0; $i < $nb_route_items; ++$i) {
+
+            if ($route_items[$i][0] === ':') {
+
+                $params[substr($route_items[$i], 1)] = $request_items[$i];
+            }
+            else if ($route_items[$i] !== $request_items[$i]) {
+
+                $params = array();
+                return false;
+            }
+        }
+
+        return true;
+    }
+
+    return false;
+}
diff --git a/inc/3rdparty/PicoFarad/Session.php b/inc/3rdparty/PicoFarad/Session.php
new file mode 100644 (file)
index 0000000..ee7b415
--- /dev/null
@@ -0,0 +1,57 @@
+<?php
+
+namespace PicoFarad\Session;
+
+const SESSION_LIFETIME = 2678400;
+
+
+function open($base_path = '/', $save_path = '')
+{
+    if ($save_path !== '') session_save_path($save_path);
+
+    // HttpOnly and secure flags for session cookie
+    session_set_cookie_params(
+        SESSION_LIFETIME,
+        $base_path ?: '/',
+        null,
+        isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on',
+        true
+    );
+
+    // Avoid session id in the URL
+    ini_set('session.use_only_cookies', true);
+
+    // Ensure session ID integrity
+    ini_set('session.entropy_file', '/dev/urandom');
+    ini_set('session.entropy_length', '32');
+    ini_set('session.hash_bits_per_character', 6);
+
+    // Custom session name
+    session_name('__$');
+
+    session_start();
+
+    // Regenerate the session id to avoid session fixation issue
+    if (empty($_SESSION['__validated'])) {
+        session_regenerate_id(true);
+        $_SESSION['__validated'] = 1;
+    }
+}
+
+
+function close()
+{
+    session_destroy();
+}
+
+
+function flash($message)
+{
+    $_SESSION['flash_message'] = $message;
+}
+
+
+function flash_error($message)
+{
+    $_SESSION['flash_error_message'] = $message;
+}
\ No newline at end of file
diff --git a/inc/3rdparty/PicoFarad/Template.php b/inc/3rdparty/PicoFarad/Template.php
new file mode 100644 (file)
index 0000000..c32be30
--- /dev/null
@@ -0,0 +1,36 @@
+<?php
+
+namespace PicoFarad\Template;
+
+const PATH = 'templates/';
+
+// Template\load('template_name', ['bla' => 'value']);
+function load()
+{
+    if (func_num_args() < 1 || func_num_args() > 2) {
+        die('Invalid template arguments');
+    }
+
+    if (! file_exists(PATH.func_get_arg(0).'.php')) {
+        die('Unable to load the template: "'.func_get_arg(0).'"');
+    }
+
+    if (func_num_args() === 2) {
+
+        if (! is_array(func_get_arg(1))) {
+            die('Template variables must be an array');
+        }
+
+        extract(func_get_arg(1));
+    }
+
+    ob_start();
+    include PATH.func_get_arg(0).'.php';
+    return ob_get_clean();
+}
+
+
+function layout($template_name, array $template_args = array(), $layout_name = 'layout')
+{
+    return load($layout_name, $template_args + array('content_for_layout' => load($template_name, $template_args)));
+}
index 9c1c0286b4fd2feafebea8e04b94c83c2bc2be3f..8d74f2ff0d4d25db92fd48b980790b4beb7a562d 100755 (executable)
@@ -9,6 +9,7 @@
  */
 
 class Database {
+
     var $handle;
     private $order = array(
       'ia' => 'ORDER BY entries.id',
@@ -42,11 +43,13 @@ class Database {
         Tools::logm('storage type ' . STORAGE);
     }
 
-    private function getHandle() {
+    private function getHandle()
+    {
         return $this->handle;
     }
 
-    private function _checkTags() {
+    private function _checkTags()
+    {
 
         if (STORAGE == 'sqlite') {
             $sql = '
@@ -110,7 +113,8 @@ class Database {
         $query = $this->executeQuery($sql, array());
     }
 
-    public function install($login, $password) {
+    public function install($login, $password)
+    {
         $sql = 'INSERT INTO users ( username, password, name, email) VALUES (?, ?, ?, ?)';
         $params = array($login, $password, $login, ' ');
         $query = $this->executeQuery($sql, $params);
@@ -137,7 +141,8 @@ class Database {
         return TRUE;
     }
 
-    public function getConfigUser($id) {
+    public function getConfigUser($id)
+    {
         $sql = "SELECT * FROM users_config WHERE user_id = ?";
         $query = $this->executeQuery($sql, array($id));
         $result = $query->fetchAll();
@@ -150,7 +155,8 @@ class Database {
         return $user_config;
     }
 
-    public function userExists($username) {
+    public function userExists($username)
+    {
         $sql = "SELECT * FROM users WHERE username=?";
         $query = $this->executeQuery($sql, array($username));
         $login = $query->fetchAll();
@@ -161,7 +167,8 @@ class Database {
         }
     }
 
-    public function login($username, $password, $isauthenticated=false) {
+    public function login($username, $password, $isauthenticated = FALSE)
+    {
         if ($isauthenticated) {
           $sql = "SELECT * FROM users WHERE username=?";
           $query = $this->executeQuery($sql, array($username));
@@ -191,7 +198,8 @@ class Database {
         $query = $this->executeQuery($sql_update, $params_update);
     }
 
-    public function updateUserConfig($userId, $key, $value) {
+    public function updateUserConfig($userId, $key, $value)
+    {
         $config = $this->getConfigUser($userId);
 
         if (! isset($config[$key])) {
@@ -205,7 +213,8 @@ class Database {
         $query = $this->executeQuery($sql, $params);
     }
 
-    private function executeQuery($sql, $params) {
+    private function executeQuery($sql, $params)
+    {
         try
         {
             $query = $this->getHandle()->prepare($sql);
@@ -219,28 +228,32 @@ class Database {
         }
     }
     
-    public function listUsers($username=null) {
+    public function listUsers($username = NULL)
+    {
         $sql = 'SELECT count(*) FROM users'.( $username ? ' WHERE username=?' : '');
         $query = $this->executeQuery($sql, ( $username ? array($username) : array()));
         list($count) = $query->fetch();
         return $count;
     }
     
-    public function getUserPassword($userID) {
+    public function getUserPassword($userID)
+    {
         $sql = "SELECT * FROM users WHERE id=?";
         $query = $this->executeQuery($sql, array($userID));
         $password = $query->fetchAll();
         return isset($password[0]['password']) ? $password[0]['password'] : null;
     }
     
-    public function deleteUserConfig($userID) {
+    public function deleteUserConfig($userID)
+    {
         $sql_action = 'DELETE from users_config WHERE user_id=?';
         $params_action = array($userID);
         $query = $this->executeQuery($sql_action, $params_action);
         return $query;
     }
     
-    public function deleteTagsEntriesAndEntries($userID) {
+    public function deleteTagsEntriesAndEntries($userID)
+    {
         $entries = $this->retrieveAll($userID);
         foreach($entries as $entryid) {
             $tags = $this->retrieveTagsByEntry($entryid);
@@ -251,20 +264,23 @@ class Database {
         }
     }
     
-    public function deleteUser($userID) {
+    public function deleteUser($userID)
+    {
         $sql_action = 'DELETE from users WHERE id=?';
         $params_action = array($userID);
         $query = $this->executeQuery($sql_action, $params_action);
     }
 
-    public function updateContentAndTitle($id, $title, $body, $user_id) {
+    public function updateContentAndTitle($id, $title, $body, $user_id)
+    {
         $sql_action = 'UPDATE entries SET content = ?, title = ? WHERE id=? AND user_id=?';
         $params_action = array($body, $title, $id, $user_id);
         $query = $this->executeQuery($sql_action, $params_action);
         return $query;
     }
 
-    public function retrieveUnfetchedEntries($user_id, $limit) {
+    public function retrieveUnfetchedEntries($user_id, $limit)
+    {
 
         $sql_limit = "LIMIT 0,".$limit;
         if (STORAGE == 'postgres') {
@@ -278,7 +294,8 @@ class Database {
         return $entries;
     }
 
-    public function retrieveUnfetchedEntriesCount($user_id) {
+    public function retrieveUnfetchedEntriesCount($user_id)
+    {
       $sql        = "SELECT count(*) FROM entries WHERE (content = '' OR content IS NULL) AND title LIKE 'Untitled - Import%' AND user_id=?";
       $query      = $this->executeQuery($sql, array($user_id));
       list($count) = $query->fetch();
@@ -286,7 +303,8 @@ class Database {
       return $count;
     }
 
-    public function retrieveAll($user_id) {
+    public function retrieveAll($user_id)
+    {
         $sql        = "SELECT * FROM entries WHERE user_id=? ORDER BY id";
         $query      = $this->executeQuery($sql, array($user_id));
         $entries    = $query->fetchAll();
@@ -294,7 +312,8 @@ class Database {
         return $entries;
     }
 
-    public function retrieveOneById($id, $user_id) {
+    public function retrieveOneById($id, $user_id)
+    {
         $entry  = NULL;
         $sql    = "SELECT * FROM entries WHERE id=? AND user_id=?";
         $params = array(intval($id), $user_id);
@@ -304,7 +323,8 @@ class Database {
         return isset($entry[0]) ? $entry[0] : null;
     }
 
-    public function retrieveOneByURL($url, $user_id) {
+    public function retrieveOneByURL($url, $user_id)
+    {
         $entry  = NULL;
         $sql    = "SELECT * FROM entries WHERE url=? AND user_id=?";
         $params = array($url, $user_id);
@@ -314,13 +334,15 @@ class Database {
         return isset($entry[0]) ? $entry[0] : null;
     }
 
-    public function reassignTags($old_entry_id, $new_entry_id) {
+    public function reassignTags($old_entry_id, $new_entry_id)
+    {
         $sql    = "UPDATE tags_entries SET entry_id=? WHERE entry_id=?";
         $params = array($new_entry_id, $old_entry_id);
         $query  = $this->executeQuery($sql, $params);
     }
 
-    public function getEntriesByView($view, $user_id, $limit = '', $tag_id = 0) {
+    public function getEntriesByView($view, $user_id, $limit = '', $tag_id = 0)
+    {
         switch ($view) {
             case 'archive':
                 $sql    = "SELECT * FROM entries WHERE user_id=? AND is_read=? ";
@@ -348,9 +370,10 @@ class Database {
                 $entries = $query->fetchAll();
 
                 return $entries;
-        }
+    }
 
-    public function getEntriesByViewCount($view, $user_id, $tag_id = 0) {
+    public function getEntriesByViewCount($view, $user_id, $tag_id = 0)
+    {
         switch ($view) {
             case 'archive':
                     $sql    = "SELECT count(*) FROM entries WHERE user_id=? AND is_read=? ";
@@ -378,7 +401,8 @@ class Database {
         return $count;
     }
 
-    public function updateContent($id, $content, $user_id) {
+    public function updateContent($id, $content, $user_id)
+    {
         $sql_action = 'UPDATE entries SET content = ? WHERE id=? AND user_id=?';
         $params_action = array($content, $id, $user_id);
         $query = $this->executeQuery($sql_action, $params_action);
@@ -393,7 +417,8 @@ class Database {
      * @param integer $user_id
      * @return integer $id of inserted record
      */
-    public function add($url, $title, $content, $user_id, $isFavorite=0, $isRead=0) {
+    public function add($url, $title, $content, $user_id, $isFavorite=0, $isRead=0)
+    {
         $sql_action = 'INSERT INTO entries ( url, title, content, user_id, is_fav, is_read ) VALUES (?, ?, ?, ?, ?, ?)';
         $params_action = array($url, $title, $content, $user_id, $isFavorite, $isRead);
 
@@ -406,36 +431,42 @@ class Database {
         return $id;
     }
 
-    public function deleteById($id, $user_id) {
+    public function deleteById($id, $user_id)
+    {
         $sql_action     = "DELETE FROM entries WHERE id=? AND user_id=?";
         $params_action  = array($id, $user_id);
         $query          = $this->executeQuery($sql_action, $params_action);
         return $query;
     }
 
-    public function favoriteById($id, $user_id) {
+    public function favoriteById($id, $user_id)
+    {
         $sql_action     = "UPDATE entries SET is_fav=NOT is_fav WHERE id=? AND user_id=?";
         $params_action  = array($id, $user_id);
         $query          = $this->executeQuery($sql_action, $params_action);
     }
 
-    public function archiveById($id, $user_id) {
+    public function archiveById($id, $user_id)
+    {
         $sql_action     = "UPDATE entries SET is_read=NOT is_read WHERE id=? AND user_id=?";
         $params_action  = array($id, $user_id);
         $query          = $this->executeQuery($sql_action, $params_action);
     }
 
-    public function archiveAll($user_id) {
+    public function archiveAll($user_id)
+    {
         $sql_action     = "UPDATE entries SET is_read=? WHERE user_id=? AND is_read=?";
         $params_action  = array($user_id, 1, 0);
         $query          = $this->executeQuery($sql_action, $params_action);
     }
 
-    public function getLastId($column = '') {
+    public function getLastId($column = '')
+    {
         return $this->getHandle()->lastInsertId($column);
     }
 
-    public function search($term, $user_id, $limit = '') {
+    public function search($term, $user_id, $limit = '')
+    {
         $search = '%'.$term.'%';
         $sql_action = "SELECT * FROM entries WHERE user_id=? AND (content LIKE ? OR title LIKE ? OR url LIKE ?) "; //searches in content, title and URL
         $sql_action .= $this->getEntriesOrder().' ' . $limit;
@@ -444,7 +475,8 @@ class Database {
         return $query->fetchAll();
        }
 
-    public function retrieveAllTags($user_id, $term = null) {
+    public function retrieveAllTags($user_id, $term = NULL)
+    {
         $sql = "SELECT DISTINCT tags.*, count(entries.id) AS entriescount FROM tags
           LEFT JOIN tags_entries ON tags_entries.tag_id=tags.id
           LEFT JOIN entries ON tags_entries.entry_id=entries.id
@@ -458,7 +490,8 @@ class Database {
         return $tags;
     }
 
-    public function retrieveTag($id, $user_id) {
+    public function retrieveTag($id, $user_id)
+    {
         $tag  = NULL;
         $sql    = "SELECT DISTINCT tags.* FROM tags
           LEFT JOIN tags_entries ON tags_entries.tag_id=tags.id
@@ -468,10 +501,11 @@ class Database {
         $query  = $this->executeQuery($sql, $params);
         $tag  = $query->fetchAll();
 
-        return isset($tag[0]) ? $tag[0] : null;
+        return isset($tag[0]) ? $tag[0] : NULL;
     }
 
-    public function retrieveEntriesByTag($tag_id, $user_id) {
+    public function retrieveEntriesByTag($tag_id, $user_id)
+    {
         $sql =
             "SELECT entries.* FROM entries
             LEFT JOIN tags_entries ON tags_entries.entry_id=entries.id
@@ -482,7 +516,8 @@ class Database {
         return $entries;
     }
 
-    public function retrieveTagsByEntry($entry_id) {
+    public function retrieveTagsByEntry($entry_id)
+    {
         $sql =
             "SELECT tags.* FROM tags
             LEFT JOIN tags_entries ON tags_entries.tag_id=tags.id
@@ -493,14 +528,16 @@ class Database {
         return $tags;
     }
 
-    public function removeTagForEntry($entry_id, $tag_id) {
+    public function removeTagForEntry($entry_id, $tag_id)
+    {
         $sql_action     = "DELETE FROM tags_entries WHERE tag_id=? AND entry_id=?";
         $params_action  = array($tag_id, $entry_id);
         $query          = $this->executeQuery($sql_action, $params_action);
         return $query;
     }
     
-    public function cleanUnusedTag($tag_id) {
+    public function cleanUnusedTag($tag_id)
+    {
         $sql_action = "SELECT tags.* FROM tags JOIN tags_entries ON tags_entries.tag_id=tags.id WHERE tags.id=?";
         $query = $this->executeQuery($sql_action,array($tag_id));
         $tagstokeep = $query->fetchAll();
@@ -519,7 +556,8 @@ class Database {
         
     }
 
-    public function retrieveTagByValue($value) {
+    public function retrieveTagByValue($value)
+    {
         $tag  = NULL;
         $sql    = "SELECT * FROM tags WHERE value=?";
         $params = array($value);
@@ -529,27 +567,29 @@ class Database {
         return isset($tag[0]) ? $tag[0] : null;
     }
 
-    public function createTag($value) {
+    public function createTag($value)
+    {
         $sql_action = 'INSERT INTO tags ( value ) VALUES (?)';
         $params_action = array($value);
         $query = $this->executeQuery($sql_action, $params_action);
         return $query;
     }
 
-    public function setTagToEntry($tag_id, $entry_id) {
+    public function setTagToEntry($tag_id, $entry_id)
+    {
         $sql_action = 'INSERT INTO tags_entries ( tag_id, entry_id ) VALUES (?, ?)';
         $params_action = array($tag_id, $entry_id);
         $query = $this->executeQuery($sql_action, $params_action);
         return $query;
     }
 
-        private function getEntriesOrder() {
-            if (isset($_SESSION['sort']) and array_key_exists($_SESSION['sort'], $this->order)) {
-                return $this->order[$_SESSION['sort']];
-            }
-            else {
-                return $this->order['default'];
-            }
+    private function getEntriesOrder()
+    {
+        if (isset($_SESSION['sort']) and array_key_exists($_SESSION['sort'], $this->order)) {
+            return $this->order[$_SESSION['sort']];
         }
-
+        else {
+            return $this->order['default'];
+        }
+    }
 }
index 7e259c2404d107838665c2fefc2d4522589060b7..6e2c046bf4997ec4f241c29f1230b21b5e8ea6d5 100644 (file)
@@ -11,8 +11,8 @@
 class Routing
 {
     protected $wallabag;
-    protected $referer;
-    protected $view;
+    public $referer;
+    public $view;
     protected $action;
     protected $id;
     protected $url;
@@ -55,7 +55,7 @@ class Routing
         # because messages can be added in $poche->action(), we have to add this entry now (we can add it before)
         $this->vars = array_merge($this->vars, array('messages' => $this->wallabag->messages->display('all', FALSE)));
 
-        $this->_render($this->file, $this->vars);
+        $this->render($this->file, $this->vars);
     }
 
     private function _defineTplInformation()
@@ -142,7 +142,7 @@ class Routing
         }
     }
 
-    private function _render($file, $vars)
+    public function render($file, $vars)
     {
         echo $this->wallabag->tpl->render($file, $vars);
     }
index 2c22c0145e48adf808ff18593eb630741f1bf202..9d710b6cee702cdc89cfa87b8b86a5a38352dda2 100755 (executable)
@@ -40,6 +40,12 @@ require_once INCLUDES . '/3rdparty/libraries/PHPePub/Logger.php';
 require_once INCLUDES . '/3rdparty/libraries/PHPePub/EPub.php';
 require_once INCLUDES . '/3rdparty/libraries/PHPePub/EPubChapterSplitter.php';
 
+require_once INCLUDES . '/3rdparty/PicoFarad/Request.php';
+require_once INCLUDES . '/3rdparty/PicoFarad/Response.php';
+require_once INCLUDES . '/3rdparty/PicoFarad/Router.php';
+require_once INCLUDES . '/3rdparty/PicoFarad/Session.php';
+require_once INCLUDES . '/3rdparty/PicoFarad/Template.php';
+
 # system configuration; database credentials et caetera
 require_once INCLUDES . '/poche/config.inc.php';
 require_once INCLUDES . '/poche/config.inc.default.php';
@@ -50,4 +56,15 @@ if (DOWNLOAD_PICTURES) {
 
 if (!ini_get('date.timezone') || !@date_default_timezone_set(ini_get('date.timezone'))) {
     date_default_timezone_set('UTC');
-}
\ No newline at end of file
+}
+
+if (defined('ERROR_REPORTING')) {
+    error_reporting(ERROR_REPORTING);
+}
+
+// Start session
+Session::$sessionName = 'wallabag';
+Session::init();
+
+// Let's rock !
+$wallabag = new Poche();
index 825e9d5a600c47f231230546fe660252fd23cb7c..6f190518b99ac599aa6eb56a3928cf8fa2ae6b00 100755 (executable)
--- a/index.php
+++ b/index.php
@@ -12,14 +12,56 @@ define ('POCHE', '1.8.0');
 require 'check_setup.php';
 require_once 'inc/poche/global.inc.php';
 
-if (defined('ERROR_REPORTING')) {
-       error_reporting(ERROR_REPORTING);
-}
 
-// Start session
-Session::$sessionName = 'wallabag';
-Session::init();
+use PicoFarad\Router;
+use PicoFarad\Response;
+use PicoFarad\Request;
+use PicoFarad\Session;
 
-// Let's rock !
-$wallabag = new Poche();
-$wallabag->run();
+// Called before each action
+Router\before(function($action) {
+
+    // Open a session only for the specified directory
+    Session\open(dirname($_SERVER['PHP_SELF']));
+
+    // HTTP secure headers
+    Response\csp();
+    Response\xframe();
+    Response\xss();
+    Response\nosniff();
+});
+
+// Show help
+Router\get_action('unread', function() use ($wallabag) {
+    $view = 'home';
+    $id = 0;
+
+    $tpl_vars = array(
+        'referer' => $wallabag->routing->referer,
+        'view' => $wallabag->routing->view,
+        'poche_url' => Tools::getPocheUrl(),
+        'title' => _('wallabag, a read it later open source system'),
+        'token' => \Session::getToken(),
+        'theme' => $wallabag->tpl->getTheme(),
+        'entries' => '',
+        'page_links' => '',
+        'nb_results' => '',
+        'listmode' => (isset($_COOKIE['listmode']) ? true : false),
+    );
+
+    $count = $wallabag->store->getEntriesByViewCount($view, $wallabag->user->getId(), $id);
+
+    if ($count > 0) {
+        $wallabag->pagination->set_total($count);
+        $page_links = str_replace(array('previous', 'next'), array(_('previous'), _('next')),
+            $wallabag->pagination->page_links('?view=' . $view . '&sort=' . $_SESSION['sort'] . (($id)?'&id='.$id:'') . '&' ));
+        $tpl_vars['entries'] = $wallabag->store->getEntriesByView($view, $wallabag->user->getId(), $wallabag->pagination->get_limit(), $id);
+        $tpl_vars['page_links'] = $page_links;
+        $tpl_vars['nb_results'] = $count;
+    }
+
+    $wallabag->routing->render('home.twig', $tpl_vars);
+
+    Tools::logm('display ' . $view . ' view');
+
+});