3 * wallabag, self hostable application allowing you to not miss any content anymore
6 * @author Nicolas Lœuillet <nicolas@loeuillet.org>
8 * @license http://www.wtfpl.net/ see COPYING file
13 public static $canRenderTemplates = true;
14 public static $configFileAvailable = true;
22 private $currentTheme = '';
23 private $currentLanguage = '';
24 private $notInstalledMessage = array();
26 private $language_names = array(
27 'cs_CZ.utf8' => 'čeština',
28 'de_DE.utf8' => 'German',
29 'en_EN.utf8' => 'English',
30 'es_ES.utf8' => 'Español',
31 'fa_IR.utf8' => 'فارسی',
32 'fr_FR.utf8' => 'Français',
33 'it_IT.utf8' => 'Italiano',
34 'pl_PL.utf8' => 'Polski',
35 'ru_RU.utf8' => 'Pусский',
36 'sl_SI.utf8' => 'Slovenščina',
37 'uk_UA.utf8' => 'Українська',
38 'pt_BR.utf8' => 'Brasileiro',
40 public function __construct()
42 if ($this->configFileIsAvailable()) {
46 if ($this->themeIsInstalled()) {
50 if ($this->systemIsInstalled()) {
51 $this->store
= new Database();
52 $this->messages
= new Messages();
54 if (! $this->store
->isInstalled()) {
57 $this->store
->checkTags();
61 private function init()
64 Session
::$sessionName = 'poche';
67 if (isset($_SESSION['poche_user']) && $_SESSION['poche_user'] != array()) {
68 $this->user
= $_SESSION['poche_user'];
70 # fake user, just for install & login screens
71 $this->user
= new User();
72 $this->user
->setConfig($this->getDefaultConfig());
76 $language = $this->user
->getConfigValue('language');
77 putenv('LC_ALL=' . $language);
78 setlocale(LC_ALL
, $language);
79 bindtextdomain($language, LOCALE
);
80 textdomain($language);
83 $this->pagination
= new Paginator($this->user
->getConfigValue('pager'), 'p');
86 $themeDirectory = $this->user
->getConfigValue('theme');
88 if ($themeDirectory === false) {
89 $themeDirectory = DEFAULT_THEME
;
92 $this->currentTheme
= $themeDirectory;
95 $languageDirectory = $this->user
->getConfigValue('language');
97 if ($languageDirectory === false) {
98 $languageDirectory = DEFAULT_THEME
;
101 $this->currentLanguage
= $languageDirectory;
104 public function configFileIsAvailable() {
105 if (! self
::$configFileAvailable) {
106 $this->notInstalledMessage
[] = 'You have to rename inc/poche/config.inc.php.new to inc/poche/config.inc.php.';
114 public function themeIsInstalled() {
116 # Twig is an absolute requirement for Poche to function. Abort immediately if the Composer installer hasn't been run yet
117 if (! self
::$canRenderTemplates) {
118 $this->notInstalledMessage
[] = 'Twig does not seem to be installed. Please initialize the Composer installation to automatically fetch dependencies. You can also download <a href="http://wllbg.org/vendor">vendor.zip</a> and extract it in your wallabag folder.';
122 if (! is_writable(CACHE
)) {
123 $this->notInstalledMessage
[] = 'You don\'t have write access on cache directory.';
125 self
::$canRenderTemplates = false;
130 # Check if the selected theme and its requirements are present
131 $theme = $this->getTheme();
133 if ($theme != '' && ! is_dir(THEME
. '/' . $theme)) {
134 $this->notInstalledMessage
[] = 'The currently selected theme (' . $theme . ') does not seem to be properly installed (Missing directory: ' . THEME
. '/' . $theme . ')';
136 self
::$canRenderTemplates = false;
141 $themeInfo = $this->getThemeInfo($theme);
142 if (isset($themeInfo['requirements']) && is_array($themeInfo['requirements'])) {
143 foreach ($themeInfo['requirements'] as $requiredTheme) {
144 if (! is_dir(THEME
. '/' . $requiredTheme)) {
145 $this->notInstalledMessage
[] = 'The required "' . $requiredTheme . '" theme is missing for the current theme (' . $theme . ')';
147 self
::$canRenderTemplates = false;
163 * all checks before installation.
164 * @todo move HTML to template
167 public function systemIsInstalled()
171 $configSalt = defined('SALT') ? constant('SALT') : '';
173 if (empty($configSalt)) {
174 $this->notInstalledMessage
[] = 'You have not yet filled in the SALT value in the config.inc.php file.';
177 if (STORAGE
== 'sqlite' && ! file_exists(STORAGE_SQLITE
)) {
178 Tools
::logm('sqlite file doesn\'t exist');
179 $this->notInstalledMessage
[] = 'sqlite file doesn\'t exist, you can find it in install folder. Copy it in /db folder.';
182 if (is_dir(ROOT
. '/install') && ! DEBUG_POCHE
) {
183 $this->notInstalledMessage
[] = 'you have to delete the /install folder before using poche.';
186 if (STORAGE
== 'sqlite' && ! is_writable(STORAGE_SQLITE
)) {
187 Tools
::logm('you don\'t have write access on sqlite file');
188 $this->notInstalledMessage
[] = 'You don\'t have write access on sqlite file.';
199 public function getNotInstalledMessage() {
200 return $this->notInstalledMessage
;
203 private function initTpl()
205 $loaderChain = new Twig_Loader_Chain();
206 $theme = $this->getTheme();
208 # add the current theme as first to the loader chain so Twig will look there first for overridden template files
210 $loaderChain->addLoader(new Twig_Loader_Filesystem(THEME
. '/' . $theme));
211 } catch (Twig_Error_Loader
$e) {
212 # @todo isInstalled() should catch this, inject Twig later
213 die('The currently selected theme (' . $theme . ') does not seem to be properly installed (' . THEME
. '/' . $theme .' is missing)');
216 # add all required themes to the loader chain
217 $themeInfo = $this->getThemeInfo($theme);
218 if (isset($themeInfo['requirements']) && is_array($themeInfo['requirements'])) {
219 foreach ($themeInfo['requirements'] as $requiredTheme) {
221 $loaderChain->addLoader(new Twig_Loader_Filesystem(THEME
. '/' . $requiredTheme));
222 } catch (Twig_Error_Loader
$e) {
223 # @todo isInstalled() should catch this, inject Twig later
224 die('The required "' . $requiredTheme . '" theme is missing for the current theme (' . $theme . ')');
230 $twigParams = array();
232 $twigParams = array('cache' => CACHE
);
235 $this->tpl
= new Twig_Environment($loaderChain, $twigParams);
236 $this->tpl
->addExtension(new Twig_Extensions_Extension_I18n());
238 # filter to display domain name of an url
239 $filter = new Twig_SimpleFilter('getDomain', 'Tools::getDomain');
240 $this->tpl
->addFilter($filter);
242 # filter for reading time
243 $filter = new Twig_SimpleFilter('getReadingTime', 'Tools::getReadingTime');
244 $this->tpl
->addFilter($filter);
247 private function install()
249 Tools
::logm('poche still not installed');
250 echo $this->tpl
->render('install.twig', array(
251 'token' => Session
::getToken(),
252 'theme' => $this->getTheme(),
253 'poche_url' => Tools
::getPocheUrl()
255 if (isset($_GET['install'])) {
256 if (($_POST['password'] == $_POST['password_repeat'])
257 && $_POST['password'] != "" && $_POST['login'] != "") {
258 # let's rock, install poche baby !
259 if ($this->store
->install($_POST['login'], Tools
::encodeString($_POST['password'] . $_POST['login'])))
262 Tools
::logm('poche is now installed');
267 Tools
::logm('error during installation');
274 public function getTheme() {
275 return $this->currentTheme
;
279 * Provides theme information by parsing theme.ini file if present in the theme's root directory.
280 * In all cases, the following data will be returned:
281 * - name: theme's name, or key if the theme is unnamed,
282 * - current: boolean informing if the theme is the current user theme.
284 * @param string $theme Theme key (directory name)
285 * @return array|boolean Theme information, or false if the theme doesn't exist.
287 public function getThemeInfo($theme) {
288 if (!is_dir(THEME
. '/' . $theme)) {
292 $themeIniFile = THEME
. '/' . $theme . '/theme.ini';
293 $themeInfo = array();
295 if (is_file($themeIniFile) && is_readable($themeIniFile)) {
296 $themeInfo = parse_ini_file($themeIniFile);
299 if ($themeInfo === false) {
300 $themeInfo = array();
302 if (!isset($themeInfo['name'])) {
303 $themeInfo['name'] = $theme;
305 $themeInfo['current'] = ($theme === $this->getTheme());
310 public function getInstalledThemes() {
311 $handle = opendir(THEME
);
314 while (($theme = readdir($handle)) !== false) {
315 # Themes are stored in a directory, so all directory names are themes
316 # @todo move theme installation data to database
317 if (!is_dir(THEME
. '/' . $theme) || in_array($theme, array('.', '..'))) {
321 $themes[$theme] = $this->getThemeInfo($theme);
329 public function getLanguage() {
330 return $this->currentLanguage
;
333 public function getInstalledLanguages() {
334 $handle = opendir(LOCALE
);
335 $languages = array();
337 while (($language = readdir($handle)) !== false) {
338 # Languages are stored in a directory, so all directory names are languages
339 # @todo move language installation data to database
340 if (! is_dir(LOCALE
. '/' . $language) || in_array($language, array('..', '.', 'tools'))) {
346 if ($language === $this->getLanguage()) {
350 $languages[] = array('name' => (isset($this->language_names
[$language]) ? $this->language_names
[$language] : $language), 'value' => $language, 'current' => $current);
356 public function getDefaultConfig()
359 'pager' => PAGINATION
,
361 'theme' => DEFAULT_THEME
365 protected function getPageContent(Url
$url)
367 // Saving and clearing context
369 foreach( $GLOBALS as $key => $value ) {
370 if( $key != 'GLOBALS' && $key != '_SESSION' && $key != 'HTTP_SESSION_VARS' ) {
371 $GLOBALS[$key] = array();
372 $REAL[$key] = $value;
375 // Saving and clearing session
376 $REAL_SESSION = array();
377 foreach( $_SESSION as $key => $value ) {
378 $REAL_SESSION[$key] = $value;
379 unset($_SESSION[$key]);
382 // Running code in different context
383 $scope = function() {
384 extract( func_get_arg(1) );
385 $_GET = $_REQUEST = array(
386 "url" => $url->getUrl(),
388 "links" => "preserve",
391 "submit" => "Create Feed"
394 require func_get_arg(0);
395 $json = ob_get_flush();
398 $json = $scope( "inc/3rdparty/makefulltextfeed.php", array("url" => $url) );
400 // Clearing and restoring context
401 foreach( $GLOBALS as $key => $value ) {
402 if( $key != "GLOBALS" && $key != "_SESSION" ) {
403 unset($GLOBALS[$key]);
406 foreach( $REAL as $key => $value ) {
407 $GLOBALS[$key] = $value;
409 // Clearing and restoring session
410 foreach( $_SESSION as $key => $value ) {
411 unset($_SESSION[$key]);
413 foreach( $REAL_SESSION as $key => $value ) {
414 $_SESSION[$key] = $value;
416 return json_decode($json, true);
420 * Call action (mark as fav, archive, delete, etc.)
422 public function action($action, Url
$url, $id = 0, $import = FALSE, $autoclose = FALSE, $tags = null)
427 $content = $this->getPageContent($url);
428 $title = ($content['rss']['channel']['item']['title'] != '') ? $content['rss']['channel']['item']['title'] : _('Untitled');
429 $body = $content['rss']['channel']['item']['description'];
431 // clean content from prevent xss attack
432 $config = HTMLPurifier_Config
::createDefault();
433 $purifier = new HTMLPurifier($config);
434 $title = $purifier->purify($title);
435 $body = $purifier->purify($body);
437 //search for possible duplicate if not in import mode
439 $duplicate = $this->store
->retrieveOneByURL($url->getUrl(), $this->user
->getId());
442 if ($this->store
->add($url->getUrl(), $title, $body, $this->user
->getId())) {
443 Tools
::logm('add link ' . $url->getUrl());
445 if (STORAGE
== 'postgres') {
446 $sequence = 'entries_id_seq';
448 $last_id = $this->store
->getLastId($sequence);
449 if (DOWNLOAD_PICTURES
) {
450 $content = filtre_picture($body, $url->getUrl(), $last_id);
451 Tools
::logm('updating content article');
452 $this->store
->updateContent($last_id, $content, $this->user
->getId());
455 if ($duplicate != NULL) {
456 // duplicate exists, so, older entry needs to be deleted (as new entry should go to the top of list), BUT favorite mark and tags should be preserved
457 Tools
::logm('link ' . $url->getUrl() . ' is a duplicate');
458 // 1) - preserve tags and favorite, then drop old entry
459 $this->store
->reassignTags($duplicate['id'], $last_id);
460 if ($duplicate['is_fav']) {
461 $this->store
->favoriteById($last_id, $this->user
->getId());
463 if ($this->store
->deleteById($duplicate['id'], $this->user
->getId())) {
464 Tools
::logm('previous link ' . $url->getUrl() .' entry deleted');
469 $this->messages
->add('s', _('the link has been added successfully'));
474 $this->messages
->add('e', _('error during insertion : the link wasn\'t added'));
475 Tools
::logm('error during insertion : the link wasn\'t added ' . $url->getUrl());
480 if ($autoclose == TRUE) {
481 Tools
::redirect('?view=home');
483 Tools
::redirect('?view=home&closewin=true');
488 $msg = 'delete link #' . $id;
489 if ($this->store
->deleteById($id, $this->user
->getId())) {
490 if (DOWNLOAD_PICTURES
) {
491 remove_directory(ABS_PATH
. $id);
493 $this->messages
->add('s', _('the link has been deleted successfully'));
496 $this->messages
->add('e', _('the link wasn\'t deleted'));
497 $msg = 'error : can\'t delete link #' . $id;
500 Tools
::redirect('?');
503 $this->store
->favoriteById($id, $this->user
->getId());
504 Tools
::logm('mark as favorite link #' . $id);
509 case 'toggle_archive' :
510 $this->store
->archiveById($id, $this->user
->getId());
511 Tools
::logm('archive link #' . $id);
517 $this->store
->archiveAll($this->user
->getId());
518 Tools
::logm('archive all links');
526 $tags = explode(',', $tags);
529 $tags = explode(',', $_POST['value']);
530 $entry_id = $_POST['entry_id'];
532 $entry = $this->store
->retrieveOneById($entry_id, $this->user
->getId());
534 $this->messages
->add('e', _('Article not found!'));
535 Tools
::logm('error : article not found');
538 foreach($tags as $key => $tag_value) {
539 $value = trim($tag_value);
540 $tag = $this->store
->retrieveTagByValue($value);
544 $tag = $this->store
->createTag($value);
546 if (STORAGE
== 'postgres') {
547 $sequence = 'tags_id_seq';
549 $tag_id = $this->store
->getLastId($sequence);
552 $tag_id = $tag['id'];
555 # we assign the tag to the article
556 $this->store
->setTagToEntry($tag_id, $entry_id);
563 $tag_id = $_GET['tag_id'];
564 $entry = $this->store
->retrieveOneById($id, $this->user
->getId());
566 $this->messages
->add('e', _('Article not found!'));
567 Tools
::logm('error : article not found');
570 $this->store
->removeTagForEntry($id, $tag_id);
578 function displayView($view, $id = 0)
585 $dev_infos = $this->getPocheVersion('dev');
586 $dev = trim($dev_infos[0]);
587 $check_time_dev = date('d-M-Y H:i', $dev_infos[1]);
588 $prod_infos = $this->getPocheVersion('prod');
589 $prod = trim($prod_infos[0]);
590 $check_time_prod = date('d-M-Y H:i', $prod_infos[1]);
591 $compare_dev = version_compare(POCHE
, $dev);
592 $compare_prod = version_compare(POCHE
, $prod);
593 $themes = $this->getInstalledThemes();
594 $languages = $this->getInstalledLanguages();
595 $token = $this->user
->getConfigValue('token');
596 $http_auth = (isset($_SERVER['PHP_AUTH_USER']) || isset($_SERVER['REMOTE_USER'])) ? true : false;
599 'languages' => $languages,
602 'check_time_dev' => $check_time_dev,
603 'check_time_prod' => $check_time_prod,
604 'compare_dev' => $compare_dev,
605 'compare_prod' => $compare_prod,
607 'user_id' => $this->user
->getId(),
608 'http_auth' => $http_auth,
610 Tools
::logm('config view');
614 $entry = $this->store
->retrieveOneById($id, $this->user
->getId());
616 $this->messages
->add('e', _('Article not found!'));
617 Tools
::logm('error : article not found');
620 $tags = $this->store
->retrieveTagsByEntry($id);
628 $token = $this->user
->getConfigValue('token');
629 $tags = $this->store
->retrieveAllTags($this->user
->getId());
632 'user_id' => $this->user
->getId(),
637 $entry = $this->store
->retrieveOneById($id, $this->user
->getId());
638 if ($entry != NULL) {
639 Tools
::logm('view link #' . $id);
640 $content = $entry['content'];
641 if (function_exists('tidy_parse_string')) {
642 $tidy = tidy_parse_string($content, array('indent'=>true, 'show-body-only' => true), 'UTF8');
643 $tidy->cleanRepair();
644 $content = $tidy->value
;
648 $flattr = new FlattrItem();
649 $flattr->checkItem($entry['url'], $entry['id']);
652 $tags = $this->store
->retrieveTagsByEntry($entry['id']);
656 'content' => $content,
662 Tools
::logm('error in view call : entry is null');
665 default: # home, favorites, archive and tag views
670 'listmode' => (isset($_COOKIE['listmode']) ? true : false),
673 //if id is given - we retrive entries by tag: id is tag id
675 $tpl_vars['tag'] = $this->store
->retrieveTag($id, $this->user
->getId());
676 $tpl_vars['id'] = intval($id);
679 $count = $this->store
->getEntriesByViewCount($view, $this->user
->getId(), $id);
682 $this->pagination
->set_total($count);
683 $page_links = str_replace(array('previous', 'next'), array(_('previous'), _('next')),
684 $this->pagination
->page_links('?view=' . $view . '&sort=' . $_SESSION['sort'] . (($id)?'&id='.$id:'') . '&' ));
685 $tpl_vars['entries'] = $this->store
->getEntriesByView($view, $this->user
->getId(), $this->pagination
->get_limit(), $id);
686 $tpl_vars['page_links'] = $page_links;
687 $tpl_vars['nb_results'] = $count;
689 Tools
::logm('display ' . $view . ' view');
697 * update the password of the current user.
698 * if MODE_DEMO is TRUE, the password can't be updated.
699 * @todo add the return value
700 * @todo set the new password in function header like this updatePassword($newPassword)
703 public function updatePassword()
706 $this->messages
->add('i', _('in demo mode, you can\'t update your password'));
707 Tools
::logm('in demo mode, you can\'t do this');
708 Tools
::redirect('?view=config');
711 if (isset($_POST['password']) && isset($_POST['password_repeat'])) {
712 if ($_POST['password'] == $_POST['password_repeat'] && $_POST['password'] != "") {
713 $this->messages
->add('s', _('your password has been updated'));
714 $this->store
->updatePassword($this->user
->getId(), Tools
::encodeString($_POST['password'] . $this->user
->getUsername()));
716 Tools
::logm('password updated');
720 $this->messages
->add('e', _('the two fields have to be filled & the password must be the same in the two fields'));
721 Tools
::redirect('?view=config');
727 public function updateTheme()
730 if (empty($_POST['theme'])) {
733 # we are not going to change it to the current theme...
734 if ($_POST['theme'] == $this->getTheme()) {
735 $this->messages
->add('w', _('still using the "' . $this->getTheme() . '" theme!'));
736 Tools
::redirect('?view=config');
739 $themes = $this->getInstalledThemes();
740 $actualTheme = false;
742 foreach (array_keys($themes) as $theme) {
743 if ($theme == $_POST['theme']) {
749 if (! $actualTheme) {
750 $this->messages
->add('e', _('that theme does not seem to be installed'));
751 Tools
::redirect('?view=config');
754 $this->store
->updateUserConfig($this->user
->getId(), 'theme', $_POST['theme']);
755 $this->messages
->add('s', _('you have changed your theme preferences'));
757 $currentConfig = $_SESSION['poche_user']->config
;
758 $currentConfig['theme'] = $_POST['theme'];
760 $_SESSION['poche_user']->setConfig($currentConfig);
764 Tools
::redirect('?view=config');
767 public function updateLanguage()
770 if (empty($_POST['language'])) {
773 # we are not going to change it to the current language...
774 if ($_POST['language'] == $this->getLanguage()) {
775 $this->messages
->add('w', _('still using the "' . $this->getLanguage() . '" language!'));
776 Tools
::redirect('?view=config');
779 $languages = $this->getInstalledLanguages();
780 $actualLanguage = false;
782 foreach ($languages as $language) {
783 if ($language['value'] == $_POST['language']) {
784 $actualLanguage = true;
789 if (! $actualLanguage) {
790 $this->messages
->add('e', _('that language does not seem to be installed'));
791 Tools
::redirect('?view=config');
794 $this->store
->updateUserConfig($this->user
->getId(), 'language', $_POST['language']);
795 $this->messages
->add('s', _('you have changed your language preferences'));
797 $currentConfig = $_SESSION['poche_user']->config
;
798 $currentConfig['language'] = $_POST['language'];
800 $_SESSION['poche_user']->setConfig($currentConfig);
804 Tools
::redirect('?view=config');
808 * get credentials from differents sources
809 * it redirects the user to the $referer link
812 private function credentials() {
813 if(isset($_SERVER['PHP_AUTH_USER'])) {
814 return array($_SERVER['PHP_AUTH_USER'],'php_auth',true);
816 if(!empty($_POST['login']) && !empty($_POST['password'])) {
817 return array($_POST['login'],$_POST['password'],false);
819 if(isset($_SERVER['REMOTE_USER'])) {
820 return array($_SERVER['REMOTE_USER'],'http_auth',true);
823 return array(false,false,false);
827 * checks if login & password are correct and save the user in session.
828 * it redirects the user to the $referer link
829 * @param string $referer the url to redirect after login
830 * @todo add the return value
833 public function login($referer)
835 list($login,$password,$isauthenticated)=$this->credentials();
836 if($login === false || $password === false) {
837 $this->messages
->add('e', _('login failed: you have to fill all fields'));
838 Tools
::logm('login failed');
841 if (!empty($login) && !empty($password)) {
842 $user = $this->store
->login($login, Tools
::encodeString($password . $login), $isauthenticated);
843 if ($user != array()) {
844 # Save login into Session
845 $longlastingsession = isset($_POST['longlastingsession']);
846 $passwordTest = ($isauthenticated) ? $user['password'] : Tools
::encodeString($password . $login);
847 Session
::login($user['username'], $user['password'], $login, $passwordTest, $longlastingsession, array('poche_user' => new User($user)));
848 $this->messages
->add('s', _('welcome to your wallabag'));
849 Tools
::logm('login successful');
850 Tools
::redirect($referer);
852 $this->messages
->add('e', _('login failed: bad login or password'));
853 Tools
::logm('login failed');
859 * log out the poche user. It cleans the session.
860 * @todo add the return value
863 public function logout()
865 $this->user
= array();
867 Tools
::logm('logout');
872 * import from Instapaper. poche needs a ./instapaper-export.html file
873 * @todo add the return value
874 * @param string $targetFile the file used for importing
877 private function importFromInstapaper($targetFile)
879 # TODO gestion des articles favs
880 $html = new simple_html_dom();
881 $html->load_file($targetFile);
882 Tools
::logm('starting import from instapaper');
886 foreach($html->find('ol') as $ul)
888 foreach($ul->find('li') as $li)
891 $url = new Url(base64_encode($a[0]->href
));
892 $this->action('add', $url, 0, TRUE);
895 if (STORAGE
== 'postgres') {
896 $sequence = 'entries_id_seq';
898 $last_id = $this->store
->getLastId($sequence);
899 $this->action('toggle_archive', $url, $last_id, TRUE);
903 # the second <ol> is for read links
906 $this->messages
->add('s', _('import from instapaper completed'));
907 Tools
::logm('import from instapaper completed');
912 * import from Pocket. poche needs a ./ril_export.html file
913 * @todo add the return value
914 * @param string $targetFile the file used for importing
917 private function importFromPocket($targetFile)
919 # TODO gestion des articles favs
920 $html = new simple_html_dom();
921 $html->load_file($targetFile);
922 Tools
::logm('starting import from pocket');
926 foreach($html->find('ul') as $ul)
928 foreach($ul->find('li') as $li)
931 $url = new Url(base64_encode($a[0]->href
));
932 $this->action('add', $url, 0, TRUE);
934 if (STORAGE
== 'postgres') {
935 $sequence = 'entries_id_seq';
937 $last_id = $this->store
->getLastId($sequence);
939 $this->action('toggle_archive', $url, $last_id, TRUE);
943 $this->action('add_tag',$url,$last_id,true,false,$tags);
947 # the second <ul> is for read links
950 $this->messages
->add('s', _('import from pocket completed'));
951 Tools
::logm('import from pocket completed');
956 * import from Readability. poche needs a ./readability file
957 * @todo add the return value
958 * @param string $targetFile the file used for importing
961 private function importFromReadability($targetFile)
963 # TODO gestion des articles lus / favs
964 $str_data = file_get_contents($targetFile);
965 $data = json_decode($str_data,true);
966 Tools
::logm('starting import from Readability');
968 foreach ($data as $key => $value) {
972 foreach ($value as $item) {
973 foreach ($item as $attr => $value) {
974 if ($attr == 'article__url') {
975 $url = new Url(base64_encode($value));
978 if (STORAGE
== 'postgres') {
979 $sequence = 'entries_id_seq';
981 if ($value == 'true') {
982 if ($attr == 'favorite') {
985 if ($attr == 'archive') {
992 if (!is_null($url) && $url->isCorrect()) {
993 $this->action('add', $url, 0, TRUE);
996 $last_id = $this->store
->getLastId($sequence);
997 $this->action('toggle_fav', $url, $last_id, TRUE);
1000 $last_id = $this->store
->getLastId($sequence);
1001 $this->action('toggle_archive', $url, $last_id, TRUE);
1006 $this->messages
->add('s', _('import from Readability completed. ' . $count . ' new links.'));
1007 Tools
::logm('import from Readability completed');
1012 * import from Poche exported file
1013 * @param string $targetFile the file used for importing
1016 private function importFromPoche($targetFile)
1018 $str_data = file_get_contents($targetFile);
1019 $data = json_decode($str_data,true);
1020 Tools
::logm('starting import from Poche');
1024 if (STORAGE
== 'postgres') {
1025 $sequence = 'entries_id_seq';
1029 foreach ($data as $value) {
1031 $url = new Url(base64_encode($value['url']));
1032 $favorite = ($value['is_fav'] == -1);
1033 $archive = ($value['is_read'] == -1);
1035 # we can add the url
1036 if (!is_null($url) && $url->isCorrect()) {
1038 $this->action('add', $url, 0, TRUE);
1042 $last_id = $this->store
->getLastId($sequence);
1043 $this->action('toggle_fav', $url, $last_id, TRUE);
1046 $last_id = $this->store
->getLastId($sequence);
1047 $this->action('toggle_archive', $url, $last_id, TRUE);
1052 $this->messages
->add('s', _('import from Poche completed. ' . $count . ' new links.'));
1053 Tools
::logm('import from Poche completed');
1058 * import datas into your poche
1059 * @param string $from name of the service to import : pocket, instapaper or readability
1060 * @todo add the return value
1063 public function import($from)
1066 'pocket' => 'importFromPocket',
1067 'readability' => 'importFromReadability',
1068 'instapaper' => 'importFromInstapaper',
1069 'poche' => 'importFromPoche',
1072 if (! isset($providers[$from])) {
1073 $this->messages
->add('e', _('Unknown import provider.'));
1077 $targetDefinition = 'IMPORT_' . strtoupper($from) . '_FILE';
1078 $targetFile = constant($targetDefinition);
1080 if (! defined($targetDefinition)) {
1081 $this->messages
->add('e', _('Incomplete inc/poche/define.inc.php file, please define "' . $targetDefinition . '".'));
1085 if (! file_exists($targetFile)) {
1086 $this->messages
->add('e', _('Could not find required "' . $targetFile . '" import file.'));
1090 $this->$providers[$from]($targetFile);
1094 * export poche entries in json
1095 * @return json all poche entries
1097 public function export()
1099 $entries = $this->store
->retrieveAll($this->user
->getId());
1100 echo $this->tpl
->render('export.twig', array(
1101 'export' => Tools
::renderJson($entries),
1103 Tools
::logm('export view');
1107 * Checks online the latest version of poche and cache it
1108 * @param string $which 'prod' or 'dev'
1109 * @return string latest $which version
1111 private function getPocheVersion($which = 'prod')
1113 $cache_file = CACHE
. '/' . $which;
1114 $check_time = time();
1116 # checks if the cached version file exists
1117 if (file_exists($cache_file) && (filemtime($cache_file) > (time() - 86400 ))) {
1118 $version = file_get_contents($cache_file);
1119 $check_time = filemtime($cache_file);
1121 $version = file_get_contents('http://static.wallabag.org/versions/' . $which);
1122 file_put_contents($cache_file, $version, LOCK_EX
);
1124 return array($version, $check_time);
1127 public function generateToken()
1129 if (ini_get('open_basedir') === '') {
1130 $token = substr(base64_encode(file_get_contents('/dev/urandom', false, null, 0, 20)), 0, 15);
1133 $token = substr(base64_encode(uniqid(mt_rand(), true)), 0, 20);
1136 $token = str_replace('+', '', $token);
1137 $this->store
->updateUserConfig($this->user
->getId(), 'token', $token);
1138 $currentConfig = $_SESSION['poche_user']->config
;
1139 $currentConfig['token'] = $token;
1140 $_SESSION['poche_user']->setConfig($currentConfig);
1144 public function generateFeeds($token, $user_id, $tag_id, $type = 'home')
1146 $allowed_types = array('home', 'fav', 'archive', 'tag');
1147 $config = $this->store
->getConfigUser($user_id);
1149 if (!in_array($type, $allowed_types) ||
1150 $token != $config['token']) {
1151 die(_('Uh, there is a problem while generating feeds.'));
1155 $feed = new FeedWriter(RSS2
);
1156 $feed->setTitle('wallabag — ' . $type . ' feed');
1157 $feed->setLink(Tools
::getPocheUrl());
1158 $feed->setChannelElement('pubDate', date(DATE_RSS
, time()));
1159 $feed->setChannelElement('generator', 'wallabag');
1160 $feed->setDescription('wallabag ' . $type . ' elements');
1162 if ($type == 'tag') {
1163 $entries = $this->store
->retrieveEntriesByTag($tag_id, $user_id);
1166 $entries = $this->store
->getEntriesByView($type, $user_id);
1169 if (count($entries) > 0) {
1170 foreach ($entries as $entry) {
1171 $newItem = $feed->createNewItem();
1172 $newItem->setTitle($entry['title']);
1173 $newItem->setLink(Tools
::getPocheUrl() . '?view=view&id=' . $entry['id']);
1174 $newItem->setDate(time());
1175 $newItem->setDescription($entry['content']);
1176 $feed->addItem($newItem);
1180 $feed->genarateFeed();
1184 public function emptyCache() {
1185 $files = new RecursiveIteratorIterator(
1186 new RecursiveDirectoryIterator(CACHE
, RecursiveDirectoryIterator
::SKIP_DOTS
),
1187 RecursiveIteratorIterator
::CHILD_FIRST
1190 foreach ($files as $fileinfo) {
1191 $todo = ($fileinfo->isDir() ? 'rmdir' : 'unlink');
1192 $todo($fileinfo->getRealPath());
1195 Tools
::logm('empty cache');
1196 $this->messages
->add('s', _('Cache deleted.'));