]> git.immae.eu Git - github/wallabag/wallabag.git/blobdiff - inc/poche/Poche.class.php
Final Fix of #570
[github/wallabag/wallabag.git] / inc / poche / Poche.class.php
index 33dddf1ec51d6c63e72950e399de182f9a5a5677..7d9faed14e386d04391891d3ea3c8ee3890bfe56 100755 (executable)
@@ -23,6 +23,20 @@ class Poche
     private $currentLanguage = '';
     private $notInstalledMessage = array();
 
+    private $language_names = array(
+      'cs_CZ.utf8' => 'čeština',
+      'de_DE.utf8' => 'German',
+      'en_EN.utf8' => 'English',
+      'es_ES.utf8' => 'Español',
+      'fa_IR.utf8' => 'فارسی',
+      'fr_FR.utf8' => 'Français',
+      'it_IT.utf8' => 'Italiano',
+      'pl_PL.utf8' => 'Polski',
+      'pt_BR.utf8' => 'Português (Brasil)',
+      'ru_RU.utf8' => 'Pусский',
+      'sl_SI.utf8' => 'Slovenščina',
+      'uk_UA.utf8' => 'Українська',
+    );
     public function __construct()
     {
         if ($this->configFileIsAvailable()) {
@@ -47,8 +61,6 @@ class Poche
     private function init() 
     {
         Tools::initPhp();
-        Session::$sessionName = 'poche'; 
-        Session::init();
 
         if (isset($_SESSION['poche_user']) && $_SESSION['poche_user'] != array()) {
             $this->user = $_SESSION['poche_user'];
@@ -323,7 +335,7 @@ class Poche
         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('..', '.'))) {
+            if (! is_dir(LOCALE . '/' . $language) || in_array($language, array('..', '.', 'tools'))) {
                 continue;
             }
             
@@ -333,7 +345,7 @@ class Poche
                 $current = true;
             }
             
-            $languages[] = array('name' => $language, 'current' => $current);
+            $languages[] = array('name' => (isset($this->language_names[$language]) ? $this->language_names[$language] : $language), 'value' => $language, 'current' => $current);
         }
         
         return $languages;
@@ -348,60 +360,6 @@ class Poche
         );
     }
 
-    protected function getPageContent(Url $url)
-    {
-        // Saving and clearing context
-        $REAL = array();
-        foreach( $GLOBALS as $key => $value ) {
-            if( $key != "GLOBALS" && $key != "_SESSION" ) {
-                $GLOBALS[$key] = array();
-                $REAL[$key] = $value;
-            }
-        }
-        // Saving and clearing 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_flush();
-            return $json;
-        };
-        $json = $scope( "inc/3rdparty/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
-        foreach( $_SESSION as $key => $value ) {
-            unset($_SESSION[$key]);
-        }
-        foreach( $REAL_SESSION as $key => $value ) {
-            $_SESSION[$key] = $value;
-        }
-        return json_decode($json, true);
-    }
-
     /**
      * Call action (mark as fav, archive, delete, etc.)
      */
@@ -410,11 +368,25 @@ class Poche
         switch ($action)
         {
             case 'add':
-                $content = $this->getPageContent($url);
-                $title = ($content['rss']['channel']['item']['title'] != '') ? $content['rss']['channel']['item']['title'] : _('Untitled');
-                $body = $content['rss']['channel']['item']['description'];
+                if (!$import) {
+                    $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
+                    $config = HTMLPurifier_Config::createDefault();
+                    $config->set('Cache.SerializerPath', CACHE);
+                    $purifier = new HTMLPurifier($config);
+                    $title = $purifier->purify($title);
+                    $body = $purifier->purify($body);
+                }
+                else {
+                    $title = '';
+                    $body = '';
+                }
 
                 //search for possible duplicate if not in import mode
+                $duplicate = NULL;
                 if (!$import) {
                     $duplicate = $this->store->retrieveOneByURL($url->getUrl(), $this->user->getId());
                 }
@@ -515,25 +487,33 @@ class Poche
                     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);
-                    $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'];
+                    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);
                     }
-
-                    # we assign the tag to the article
-                    $this->store->setTagToEntry($tag_id, $entry_id);
                 }
                 if(!$import) {
                     Tools::redirect();
@@ -562,8 +542,12 @@ class Poche
         switch ($view)
         {
             case 'config':
-                $dev = trim($this->getPocheVersion('dev'));
-                $prod = trim($this->getPocheVersion('prod'));
+                $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->getInstalledThemes();
@@ -575,6 +559,8 @@ class Poche
                     '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,
@@ -600,13 +586,31 @@ class Poche
                 break;
             case 'tags':
                 $token = $this->user->getConfigValue('token');
-                $tags = $this->store->retrieveAllTags($this->user->getId());
+                //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 = $_GET['search'];
+                                       $tpl_vars['entries'] = $this->store->search($search);
+                                       $tpl_vars['nb_results'] = count($tpl_vars['entries']);
+                               }
+                               break;
             case 'view':
                 $entry = $this->store->retrieveOneById($id, $this->user->getId());
                 if ($entry != NULL) {
@@ -641,6 +645,7 @@ class Poche
                     'entries' => '',
                     'page_links' => '',
                     'nb_results' => '',
+                    'listmode' => (isset($_COOKIE['listmode']) ? true : false),
                 );
                 
                 //if id is given - we retrive entries by tag: id is tag id
@@ -731,6 +736,8 @@ class Poche
         $currentConfig['theme'] = $_POST['theme'];
         
         $_SESSION['poche_user']->setConfig($currentConfig);
+
+        $this->emptyCache();
         
         Tools::redirect('?view=config');
     }
@@ -751,7 +758,7 @@ class Poche
         $actualLanguage = false;
         
         foreach ($languages as $language) {
-            if ($language['name'] == $_POST['language']) {
+            if ($language['value'] == $_POST['language']) {
                 $actualLanguage = true;
                 break;
             }
@@ -769,10 +776,11 @@ class Poche
         $currentConfig['language'] = $_POST['language'];
         
         $_SESSION['poche_user']->setConfig($currentConfig);
+
+        $this->emptyCache();
         
         Tools::redirect('?view=config');
-    }
-
+    }  
     /**
      * get credentials from differents sources
      * it redirects the user to the $referer link
@@ -872,7 +880,9 @@ class Poche
             # the second <ol> is for read links
             $read = 1;
         }
-        $this->messages->add('s', _('import from instapaper completed'));
+
+        $unlink = unlink($targetFile);
+        $this->messages->add('s', _('import from instapaper completed. You have to execute the cron to fetch content.'));
         Tools::logm('import from instapaper completed');
         Tools::redirect();
     }
@@ -916,7 +926,9 @@ class Poche
             # the second <ul> is for read links
             $read = 1;
         }
-        $this->messages->add('s', _('import from pocket completed'));
+
+        $unlink = unlink($targetFile);
+        $this->messages->add('s', _('import from pocket completed. You have to execute the cron to fetch content.'));
         Tools::logm('import from pocket completed');
         Tools::redirect();
     }
@@ -972,7 +984,9 @@ class Poche
                 }
             }
         }
-        $this->messages->add('s', _('import from Readability completed. ' . $count . ' new links.'));
+
+        unlink($targetFile);
+        $this->messages->add('s', _('import from Readability completed. You have to execute the cron to fetch content.'));
         Tools::logm('import from Readability completed');
         Tools::redirect();
     }
@@ -1018,7 +1032,9 @@ class Poche
             }
             
         }
-        $this->messages->add('s', _('import from Poche completed. ' . $count . ' new links.'));
+
+        unlink($targetFile);
+        $this->messages->add('s', _('import from Poche completed. You have to execute the cron to fetch content.'));
         Tools::logm('import from Poche completed');
         Tools::redirect();
     }
@@ -1043,13 +1059,7 @@ class Poche
             Tools::redirect();
         }
         
-        $targetDefinition = 'IMPORT_' . strtoupper($from) . '_FILE';
-        $targetFile = constant($targetDefinition);
-        
-        if (! defined($targetDefinition)) {
-            $this->messages->add('e', _('Incomplete inc/poche/define.inc.php file, please define "' . $targetDefinition . '".'));
-            Tools::redirect();
-        }
+        $targetFile = CACHE . '/' . constant(strtoupper($from) . '_FILE');
         
         if (! file_exists($targetFile)) {
             $this->messages->add('e', _('Could not find required "' . $targetFile . '" import file.'));
@@ -1059,12 +1069,31 @@ class Poche
         $this->$providers[$from]($targetFile);
     }
 
+    public function uploadFile() {
+        if(isset($_FILES['file']))
+        { 
+            $dir = CACHE . '/';
+            $file = basename($_FILES['file']['name']);
+            if(move_uploaded_file($_FILES['file']['tmp_name'], $dir . $file)) {
+                $this->messages->add('s', _('File uploaded. You can now execute import.'));
+            }
+            else {
+                $this->messages->add('e', _('Error while importing file. Do you have access to upload it?'));
+            }
+        }
+        
+        Tools::redirect('?view=config');
+    }
+
     /**
      * 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),
@@ -1080,21 +1109,29 @@ class Poche
     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 $version;
+        return array($version, $check_time);
     }
 
     public function generateToken()
     {
         if (ini_get('open_basedir') === '') {
-            $token = substr(base64_encode(file_get_contents('/dev/urandom', false, null, 0, 20)), 0, 15);
+                       if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
+                       echo 'This is a server using Windows!';
+                       // alternative to /dev/urandom for Windows
+                       $token = substr(base64_encode(uniqid(mt_rand(), true)), 0, 20);
+                       } else {
+                       $token = substr(base64_encode(file_get_contents('/dev/urandom', false, null, 0, 20)), 0, 15);
+                       }
         }
         else {
             $token = substr(base64_encode(uniqid(mt_rand(), true)), 0, 20);
@@ -1105,6 +1142,7 @@ class Poche
         $currentConfig = $_SESSION['poche_user']->config;
         $currentConfig['token'] = $token;
         $_SESSION['poche_user']->setConfig($currentConfig);
+        Tools::redirect();
     }
 
     public function generateFeeds($token, $user_id, $tag_id, $type = 'home')
@@ -1112,6 +1150,10 @@ class Poche
         $allowed_types = array('home', 'fav', 'archive', 'tag');
         $config = $this->store->getConfigUser($user_id);
 
+        if ($config == null) {
+            die(_('User with this id (' . $user_id . ') does not exist.'));
+        }
+
         if (!in_array($type, $allowed_types) ||
             $token != $config['token']) {
             die(_('Uh, there is a problem while generating feeds.'));
@@ -1121,8 +1163,9 @@ class Poche
         $feed = new FeedWriter(RSS2);
         $feed->setTitle('wallabag — ' . $type . ' feed');
         $feed->setLink(Tools::getPocheUrl());
-        $feed->setChannelElement('updated', date(DATE_RSS , time()));
-        $feed->setChannelElement('author', 'wallabag');
+        $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);
@@ -1135,7 +1178,7 @@ class Poche
             foreach ($entries as $entry) {
                 $newItem = $feed->createNewItem();
                 $newItem->setTitle($entry['title']);
-                $newItem->setLink(Tools::getPocheUrl() . '?view=view&amp;id=' . $entry['id']);
+                $newItem->setLink($entry['url']);
                 $newItem->setDate(time());
                 $newItem->setDescription($entry['content']);
                 $feed->addItem($newItem);