]> git.immae.eu Git - github/wallabag/wallabag.git/blobdiff - inc/functions.php
Merge branch 'dev'
[github/wallabag/wallabag.git] / inc / functions.php
old mode 100755 (executable)
new mode 100644 (file)
index 37abafd..73e591c
@@ -1,4 +1,12 @@
 <?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
+ */
 
 /**
  * Permet de générer l'URL de poche pour le bookmarklet
@@ -7,7 +15,7 @@ function get_poche_url()
 {
     $protocol = "http";
     if(isset($_SERVER['HTTPS'])) {
-        if($_SERVER['HTTPS'] != "off") {
+        if($_SERVER['HTTPS'] != "off" && $_SERVER['HTTPS'] != "") {
             $protocol = "https";
         }
     }
@@ -15,6 +23,11 @@ function get_poche_url()
     return $protocol . "://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
 }
 
+function encode_string($string) 
+{
+    return sha1($string . SALT);
+}
+
 // function define to retrieve url content
 function get_external_file($url)
 {
@@ -31,6 +44,10 @@ function get_external_file($url)
         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");
@@ -46,7 +63,15 @@ function get_external_file($url)
     } else {
 
         // create http context and add timeout and user-agent
-        $context = stream_context_create(array('http'=>array('timeout' => $timeout,'header'=> "User-Agent: ".$useragent,/*spoot Mozilla Firefox*/'follow_location' => true)));
+        $context = stream_context_create(array(
+                                'http'=>array('timeout' => $timeout,
+                                    'header'=> "User-Agent: ".$useragent,      /*spoot Mozilla Firefox*/
+                                    'follow_location' => true),
+                                // FOR SSL do not verified certificate
+                                'ssl' => array('verify_peer' => false,
+                                        'allow_self_signed' => true)
+                                )
+                            );
 
         // only download page lesser than 4MB
         $data = @file_get_contents($url, false, $context, -1, 4000000); // We download at most 4 MB from source.
@@ -88,10 +113,10 @@ function get_external_file($url)
 /**
  * Préparation de l'URL avec récupération du contenu avant insertion en base
  */
-function prepare_url($url, $id)
+function prepare_url($url)
 {
     $parametres = array();
-    $url    = html_entity_decode(trim($url));
+    $url        = html_entity_decode(trim($url));
 
     // We remove the annoying parameters added by FeedBurner and GoogleFeedProxy (?utm_source=...)
     // from shaarli, by sebsauvage
@@ -99,25 +124,36 @@ function prepare_url($url, $id)
     $i=strpos($url,'?utm_source='); if ($i!==false) $url=substr($url,0,$i);
     $i=strpos($url,'#xtor=RSS-'); if ($i!==false) $url=substr($url,0,$i);
 
-    $title  = $url;
-    if (!preg_match('!^https?://!i', $url))
+    $title = $url;
+    $html = Encoding::toUTF8(get_external_file($url,15));
+    // 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,15));
+    }
+
+    if (function_exists('tidy_parse_string')) {
+        $tidy = tidy_parse_string($html, array(), 'UTF8');
+        $tidy->cleanRepair();
+        $html = $tidy->value;
+    }
 
-    $html = Encoding::toUTF8(get_external_file($url,15));
     if (isset($html) and strlen($html) > 0)
     {
         $r = new Readability($html, $url);
-        $r->convertLinksToFootnotes = TRUE;
+
+        $r->convertLinksToFootnotes = CONVERT_LINKS_FOOTNOTES;
+        $r->revertForcedParagraphElements = REVERT_FORCED_PARAGRAPH_ELEMENTS;
+
         if($r->init())
         {
             $content = $r->articleContent->innerHTML;
             $parametres['title'] = $r->articleTitle->innerHTML;
-            $parametres['content'] = filtre_picture($content, $url, $id);
+            $parametres['content'] = $content;
             return $parametres;
         }
     }
 
-    logm('error during url preparation');
     return FALSE;
 }
 
@@ -220,191 +256,138 @@ function remove_directory($directory)
     if(is_dir($directory)) {
         $files = array_diff(scandir($directory), array('.','..'));
         foreach ($files as $file) {
-            // FIXME c'est quoi delTree ??
-            (is_dir("$directory/$file")) ? delTree("$directory/$file") : unlink("$directory/$file");
+            (is_dir("$directory/$file")) ? remove_directory("$directory/$file") : unlink("$directory/$file");
         }
         return rmdir($directory);
     }
 }
 
-/**
- * Appel d'une action (mark as fav, archive, delete)
- */
-
-function action_to_do($action, $id, $url, $token)
+function display_view($view, $id = 0, $full_head = 'yes')
 {
-    global $db;
+    global $tpl, $store, $msg;
 
-    switch ($action)
+    switch ($view)
     {
-        case 'add':
-            if ($url == '')
-                continue;
-
-            $req = $db->getHandle()->query("SELECT id FROM entries ORDER BY id DESC");
-            $id = $req->fetchColumn()+1;
-
-            if($parametres_url = prepare_url($url, $id)) {
-                $sql_action     = 'INSERT INTO entries ( id, url, title, content ) VALUES (?,?, ?, ?)';
-                $params_action  = array($id,$url, $parametres_url['title'], $parametres_url['content']);
-            }
-
-            logm('add link ' . $url);
+        case 'export':
+            $entries = $store->retrieveAll();
+            $tpl->assign('export', myTool::renderJson($entries));
+            $tpl->draw('export');
+            logm('export view');
             break;
-        case 'delete':
-            if (verif_token($token)) {
-                remove_directory(ABS_PATH . $id);
-                $sql_action     = "DELETE FROM entries WHERE id=?";
-                $params_action  = array($id);
-                logm('delete link #' . $id);
-            }
-            else logm('csrf problem while deleting entry');
+        case 'config':
+            $tpl->assign('load_all_js', 0);
+            $tpl->draw('head');
+            $tpl->draw('home');
+            $tpl->draw('config');
+            $tpl->draw('js');
+            $tpl->draw('footer');
+            logm('config view');
             break;
-        case 'toggle_fav' :
-            if (verif_token($token)) {
-                $sql_action     = "UPDATE entries SET is_fav=~is_fav WHERE id=?";
-                $params_action  = array($id);
-                logm('mark as favorite link #' . $id);
+        case 'view':
+            $entry = $store->retrieveOneById($id);
+
+            if ($entry != NULL) {
+                $tpl->assign('id', $entry['id']);
+                $tpl->assign('url', $entry['url']);
+                $tpl->assign('title', $entry['title']);
+                $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->assign('content', $content);
+                $tpl->assign('is_fav', $entry['is_fav']);
+                $tpl->assign('is_read', $entry['is_read']);
+                $tpl->assign('load_all_js', 0);
+                $tpl->draw('view');
             }
-            else logm('csrf problem while fav entry');
-            break;
-        case 'toggle_archive' :
-            if (verif_token($token)) {
-                $sql_action     = "UPDATE entries SET is_read=~is_read WHERE id=?";
-                $params_action  = array($id);
-                logm('archive link #' . $id);
+            else {
+                logm('error in view call : entry is NULL');
             }
-            else logm('csrf problem while archive entry');
-            break;
-        default:
+
+            logm('view link #' . $id);
             break;
-    }
+        default: # home view
+            $entries = $store->getEntriesByView($view);
 
-    try
-    {
-        # action query
-        if (isset($sql_action))
-        {
-            $query = $db->getHandle()->prepare($sql_action);
-            $query->execute($params_action);
-        }
-    }
-    catch (Exception $e)
-    {
-        logm('action query error : '.$e->getMessage());
-    }
-}
+            $tpl->assign('entries', $entries);
 
-/**
- * Détermine quels liens afficher : home, fav ou archives
- */
-function display_view($view)
-{
-    global $db;
+            if ($full_head == 'yes') {
+                $tpl->assign('load_all_js', 1);
+                $tpl->draw('head');
+                $tpl->draw('home');
+            }
 
-    switch ($_SESSION['sort'])
-    {
-        case 'ia':
-            $order = 'ORDER BY id';
-            break;
-        case 'id':
-            $order = 'ORDER BY id DESC';
-            break;
-        case 'ta':
-            $order = 'ORDER BY lower(title)';
-            break;
-        case 'td':
-            $order = 'ORDER BY lower(title) DESC';
-            break;
-        default:
-            $order = 'ORDER BY id';
-            break;
-    }
+            $tpl->draw('entries');
 
-    switch ($view)
-    {
-        case 'archive':
-            $sql    = "SELECT * FROM entries WHERE is_read=? " . $order;
-            $params = array(-1);
-            break;
-        case 'fav' :
-            $sql    = "SELECT * FROM entries WHERE is_fav=? " . $order;
-            $params = array(-1);
-            break;
-        default:
-            $sql    = "SELECT * FROM entries WHERE is_read=? " . $order;
-            $params = array(0);
+            if ($full_head == 'yes') {
+                $tpl->draw('js');
+                $tpl->draw('footer');
+            }
             break;
     }
-
-    # view query
-    try
-    {
-        $query  = $db->getHandle()->prepare($sql);
-        $query->execute($params);
-        $entries = $query->fetchAll();
-    }
-    catch (Exception $e)
-    {
-        logm('view query error : '.$e->getMessage());
-    }
-
-    return $entries;
 }
 
 /**
- * Récupère un article en fonction d'un ID
+ * Appel d'une action (mark as fav, archive, delete)
  */
-function get_article($id)
+function action_to_do($action, $url, $id = 0)
 {
-    global $db;
+    global $store, $msg;
 
-    $entry  = NULL;
-    $sql    = "SELECT * FROM entries WHERE id=?";
-    $params = array(intval($id));
-
-    # view article query
-    try
-    {
-        $query  = $db->getHandle()->prepare($sql);
-        $query->execute($params);
-        $entry = $query->fetchAll();
-    }
-    catch (Exception $e)
+    switch ($action)
     {
-        logm('get article query error : '.$e->getMessage());
-    }
+        case 'add':
+            if ($url == '')
+                continue;
 
-    return $entry;
-}
+            if (MyTool::isUrl($url)) {
+                if($parametres_url = prepare_url($url)) {
+                    if ($store->add($url, $parametres_url['title'], $parametres_url['content'])) {
+                        $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');
+                    }
+                }
+                else {
+                    $msg->add('e', 'error during url preparation : the link wasn\'t added');
+                    logm('error during url preparation');
+                }
+            }
+            else {
+                $msg->add('e', 'error during url preparation : the link is not valid');
+                logm($url . ' is not a valid url');
+            }
 
-/**
- * Vérifie si le jeton passé en $_POST correspond à celui en session
- */
-function verif_token($token)
-{
-    if(isset($_SESSION['token_poche']) && isset($_SESSION['token_time_poche']) && isset($token))
-    {
-        if($_SESSION['token_poche'] == $token)
-        {
-            $old_timestamp = time() - (15*60);
-            if($_SESSION['token_time_poche'] >= $old_timestamp)
-            {
-                return TRUE;
+            logm('add link ' . $url);
+            break;
+        case 'delete':
+            if ($store->deleteById($id)) {
+                remove_directory(ABS_PATH . $id);
+                $msg->add('s', 'the link has been deleted successfully');
+                logm('delete link #' . $id);
             }
             else {
-                session_destroy();
-                logm('session expired');
+                $msg->add('e', 'the link wasn\'t deleted');
+                logm('error : can\'t delete link #' . $id);
             }
-        }
-        else {
-            logm('token error : the token is different');
-            return FALSE;
-        }
-    }
-    else {
-        logm('token error : the token is not here');
-        return FALSE;
+            break;
+        case 'toggle_fav' :
+            $store->favoriteById($id);
+            logm('mark as favorite link #' . $id);
+            break;
+        case 'toggle_archive' :
+            $store->archiveById($id);
+            logm('archive link #' . $id);
+            break;
+        default:
+            break;
     }
 }
 
@@ -412,4 +395,4 @@ function logm($message)
 {
     $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
+}