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' => 'Український',
39 public function __construct()
41 if ($this->configFileIsAvailable()) {
45 if ($this->themeIsInstalled()) {
49 if ($this->systemIsInstalled()) {
50 $this->store
= new Database();
51 $this->messages
= new Messages();
53 if (! $this->store
->isInstalled()) {
56 $this->store
->checkTags();
60 private function init()
63 Session
::$sessionName = 'poche';
66 if (isset($_SESSION['poche_user']) && $_SESSION['poche_user'] != array()) {
67 $this->user
= $_SESSION['poche_user'];
69 # fake user, just for install & login screens
70 $this->user
= new User();
71 $this->user
->setConfig($this->getDefaultConfig());
75 $language = $this->user
->getConfigValue('language');
76 putenv('LC_ALL=' . $language);
77 setlocale(LC_ALL
, $language);
78 bindtextdomain($language, LOCALE
);
79 textdomain($language);
82 $this->pagination
= new Paginator($this->user
->getConfigValue('pager'), 'p');
85 $themeDirectory = $this->user
->getConfigValue('theme');
87 if ($themeDirectory === false) {
88 $themeDirectory = DEFAULT_THEME
;
91 $this->currentTheme
= $themeDirectory;
94 $languageDirectory = $this->user
->getConfigValue('language');
96 if ($languageDirectory === false) {
97 $languageDirectory = DEFAULT_THEME
;
100 $this->currentLanguage
= $languageDirectory;
103 public function configFileIsAvailable() {
104 if (! self
::$configFileAvailable) {
105 $this->notInstalledMessage
[] = 'You have to rename inc/poche/config.inc.php.new to inc/poche/config.inc.php.';
113 public function themeIsInstalled() {
115 # Twig is an absolute requirement for Poche to function. Abort immediately if the Composer installer hasn't been run yet
116 if (! self
::$canRenderTemplates) {
117 $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.';
121 if (! is_writable(CACHE
)) {
122 $this->notInstalledMessage
[] = 'You don\'t have write access on cache directory.';
124 self
::$canRenderTemplates = false;
129 # Check if the selected theme and its requirements are present
130 $theme = $this->getTheme();
132 if ($theme != '' && ! is_dir(THEME
. '/' . $theme)) {
133 $this->notInstalledMessage
[] = 'The currently selected theme (' . $theme . ') does not seem to be properly installed (Missing directory: ' . THEME
. '/' . $theme . ')';
135 self
::$canRenderTemplates = false;
140 $themeInfo = $this->getThemeInfo($theme);
141 if (isset($themeInfo['requirements']) && is_array($themeInfo['requirements'])) {
142 foreach ($themeInfo['requirements'] as $requiredTheme) {
143 if (! is_dir(THEME
. '/' . $requiredTheme)) {
144 $this->notInstalledMessage
[] = 'The required "' . $requiredTheme . '" theme is missing for the current theme (' . $theme . ')';
146 self
::$canRenderTemplates = false;
162 * all checks before installation.
163 * @todo move HTML to template
166 public function systemIsInstalled()
170 $configSalt = defined('SALT') ? constant('SALT') : '';
172 if (empty($configSalt)) {
173 $this->notInstalledMessage
[] = 'You have not yet filled in the SALT value in the config.inc.php file.';
176 if (STORAGE
== 'sqlite' && ! file_exists(STORAGE_SQLITE
)) {
177 Tools
::logm('sqlite file doesn\'t exist');
178 $this->notInstalledMessage
[] = 'sqlite file doesn\'t exist, you can find it in install folder. Copy it in /db folder.';
181 if (is_dir(ROOT
. '/install') && ! DEBUG_POCHE
) {
182 $this->notInstalledMessage
[] = 'you have to delete the /install folder before using poche.';
185 if (STORAGE
== 'sqlite' && ! is_writable(STORAGE_SQLITE
)) {
186 Tools
::logm('you don\'t have write access on sqlite file');
187 $this->notInstalledMessage
[] = 'You don\'t have write access on sqlite file.';
198 public function getNotInstalledMessage() {
199 return $this->notInstalledMessage
;
202 private function initTpl()
204 $loaderChain = new Twig_Loader_Chain();
205 $theme = $this->getTheme();
207 # add the current theme as first to the loader chain so Twig will look there first for overridden template files
209 $loaderChain->addLoader(new Twig_Loader_Filesystem(THEME
. '/' . $theme));
210 } catch (Twig_Error_Loader
$e) {
211 # @todo isInstalled() should catch this, inject Twig later
212 die('The currently selected theme (' . $theme . ') does not seem to be properly installed (' . THEME
. '/' . $theme .' is missing)');
215 # add all required themes to the loader chain
216 $themeInfo = $this->getThemeInfo($theme);
217 if (isset($themeInfo['requirements']) && is_array($themeInfo['requirements'])) {
218 foreach ($themeInfo['requirements'] as $requiredTheme) {
220 $loaderChain->addLoader(new Twig_Loader_Filesystem(THEME
. '/' . $requiredTheme));
221 } catch (Twig_Error_Loader
$e) {
222 # @todo isInstalled() should catch this, inject Twig later
223 die('The required "' . $requiredTheme . '" theme is missing for the current theme (' . $theme . ')');
229 $twigParams = array();
231 $twigParams = array('cache' => CACHE
);
234 $this->tpl
= new Twig_Environment($loaderChain, $twigParams);
235 $this->tpl
->addExtension(new Twig_Extensions_Extension_I18n());
237 # filter to display domain name of an url
238 $filter = new Twig_SimpleFilter('getDomain', 'Tools::getDomain');
239 $this->tpl
->addFilter($filter);
241 # filter for reading time
242 $filter = new Twig_SimpleFilter('getReadingTime', 'Tools::getReadingTime');
243 $this->tpl
->addFilter($filter);
246 private function install()
248 Tools
::logm('poche still not installed');
249 echo $this->tpl
->render('install.twig', array(
250 'token' => Session
::getToken(),
251 'theme' => $this->getTheme(),
252 'poche_url' => Tools
::getPocheUrl()
254 if (isset($_GET['install'])) {
255 if (($_POST['password'] == $_POST['password_repeat'])
256 && $_POST['password'] != "" && $_POST['login'] != "") {
257 # let's rock, install poche baby !
258 if ($this->store
->install($_POST['login'], Tools
::encodeString($_POST['password'] . $_POST['login'])))
261 Tools
::logm('poche is now installed');
266 Tools
::logm('error during installation');
273 public function getTheme() {
274 return $this->currentTheme
;
278 * Provides theme information by parsing theme.ini file if present in the theme's root directory.
279 * In all cases, the following data will be returned:
280 * - name: theme's name, or key if the theme is unnamed,
281 * - current: boolean informing if the theme is the current user theme.
283 * @param string $theme Theme key (directory name)
284 * @return array|boolean Theme information, or false if the theme doesn't exist.
286 public function getThemeInfo($theme) {
287 if (!is_dir(THEME
. '/' . $theme)) {
291 $themeIniFile = THEME
. '/' . $theme . '/theme.ini';
292 $themeInfo = array();
294 if (is_file($themeIniFile) && is_readable($themeIniFile)) {
295 $themeInfo = parse_ini_file($themeIniFile);
298 if ($themeInfo === false) {
299 $themeInfo = array();
301 if (!isset($themeInfo['name'])) {
302 $themeInfo['name'] = $theme;
304 $themeInfo['current'] = ($theme === $this->getTheme());
309 public function getInstalledThemes() {
310 $handle = opendir(THEME
);
313 while (($theme = readdir($handle)) !== false) {
314 # Themes are stored in a directory, so all directory names are themes
315 # @todo move theme installation data to database
316 if (!is_dir(THEME
. '/' . $theme) || in_array($theme, array('.', '..'))) {
320 $themes[$theme] = $this->getThemeInfo($theme);
328 public function getLanguage() {
329 return $this->currentLanguage
;
332 public function getInstalledLanguages() {
333 $handle = opendir(LOCALE
);
334 $languages = array();
336 while (($language = readdir($handle)) !== false) {
337 # Languages are stored in a directory, so all directory names are languages
338 # @todo move language installation data to database
339 if (! is_dir(LOCALE
. '/' . $language) || in_array($language, array('..', '.'))) {
345 if ($language === $this->getLanguage()) {
349 $languages[] = array('name' => $this->language_names
[$language], 'value' => $language, 'current' => $current);
355 public function getDefaultConfig()
358 'pager' => PAGINATION
,
360 'theme' => DEFAULT_THEME
364 protected function getPageContent(Url
$url)
366 // Saving and clearing context
368 foreach( $GLOBALS as $key => $value ) {
369 if( $key != "GLOBALS" && $key != "_SESSION" ) {
370 $GLOBALS[$key] = array();
371 $REAL[$key] = $value;
374 // Saving and clearing session
375 $REAL_SESSION = array();
376 foreach( $_SESSION as $key => $value ) {
377 $REAL_SESSION[$key] = $value;
378 unset($_SESSION[$key]);
381 // Running code in different context
382 $scope = function() {
383 extract( func_get_arg(1) );
384 $_GET = $_REQUEST = array(
385 "url" => $url->getUrl(),
387 "links" => "preserve",
390 "submit" => "Create Feed"
393 require func_get_arg(0);
394 $json = ob_get_flush();
397 $json = $scope( "inc/3rdparty/makefulltextfeed.php", array("url" => $url) );
399 // Clearing and restoring context
400 foreach( $GLOBALS as $key => $value ) {
401 if( $key != "GLOBALS" && $key != "_SESSION" ) {
402 unset($GLOBALS[$key]);
405 foreach( $REAL as $key => $value ) {
406 $GLOBALS[$key] = $value;
408 // Clearing and restoring session
409 foreach( $_SESSION as $key => $value ) {
410 unset($_SESSION[$key]);
412 foreach( $REAL_SESSION as $key => $value ) {
413 $_SESSION[$key] = $value;
415 return json_decode($json, true);
419 * Call action (mark as fav, archive, delete, etc.)
421 public function action($action, Url
$url, $id = 0, $import = FALSE, $autoclose = FALSE, $tags = null)
426 $content = $this->getPageContent($url);
427 $title = ($content['rss']['channel']['item']['title'] != '') ? $content['rss']['channel']['item']['title'] : _('Untitled');
428 $body = $content['rss']['channel']['item']['description'];
430 // clean content from prevent xss attack
431 $config = HTMLPurifier_Config
::createDefault();
432 $purifier = new HTMLPurifier($config);
433 $title = $purifier->purify($title);
434 $body = $purifier->purify($body);
436 //search for possible duplicate if not in import mode
438 $duplicate = $this->store
->retrieveOneByURL($url->getUrl(), $this->user
->getId());
441 if ($this->store
->add($url->getUrl(), $title, $body, $this->user
->getId())) {
442 Tools
::logm('add link ' . $url->getUrl());
444 if (STORAGE
== 'postgres') {
445 $sequence = 'entries_id_seq';
447 $last_id = $this->store
->getLastId($sequence);
448 if (DOWNLOAD_PICTURES
) {
449 $content = filtre_picture($body, $url->getUrl(), $last_id);
450 Tools
::logm('updating content article');
451 $this->store
->updateContent($last_id, $content, $this->user
->getId());
454 if ($duplicate != NULL) {
455 // 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
456 Tools
::logm('link ' . $url->getUrl() . ' is a duplicate');
457 // 1) - preserve tags and favorite, then drop old entry
458 $this->store
->reassignTags($duplicate['id'], $last_id);
459 if ($duplicate['is_fav']) {
460 $this->store
->favoriteById($last_id, $this->user
->getId());
462 if ($this->store
->deleteById($duplicate['id'], $this->user
->getId())) {
463 Tools
::logm('previous link ' . $url->getUrl() .' entry deleted');
468 $this->messages
->add('s', _('the link has been added successfully'));
473 $this->messages
->add('e', _('error during insertion : the link wasn\'t added'));
474 Tools
::logm('error during insertion : the link wasn\'t added ' . $url->getUrl());
479 if ($autoclose == TRUE) {
480 Tools
::redirect('?view=home');
482 Tools
::redirect('?view=home&closewin=true');
487 $msg = 'delete link #' . $id;
488 if ($this->store
->deleteById($id, $this->user
->getId())) {
489 if (DOWNLOAD_PICTURES
) {
490 remove_directory(ABS_PATH
. $id);
492 $this->messages
->add('s', _('the link has been deleted successfully'));
495 $this->messages
->add('e', _('the link wasn\'t deleted'));
496 $msg = 'error : can\'t delete link #' . $id;
499 Tools
::redirect('?');
502 $this->store
->favoriteById($id, $this->user
->getId());
503 Tools
::logm('mark as favorite link #' . $id);
508 case 'toggle_archive' :
509 $this->store
->archiveById($id, $this->user
->getId());
510 Tools
::logm('archive link #' . $id);
516 $this->store
->archiveAll($this->user
->getId());
517 Tools
::logm('archive all links');
525 $tags = explode(',', $tags);
528 $tags = explode(',', $_POST['value']);
529 $entry_id = $_POST['entry_id'];
531 $entry = $this->store
->retrieveOneById($entry_id, $this->user
->getId());
533 $this->messages
->add('e', _('Article not found!'));
534 Tools
::logm('error : article not found');
537 foreach($tags as $key => $tag_value) {
538 $value = trim($tag_value);
539 $tag = $this->store
->retrieveTagByValue($value);
543 $tag = $this->store
->createTag($value);
545 if (STORAGE
== 'postgres') {
546 $sequence = 'tags_id_seq';
548 $tag_id = $this->store
->getLastId($sequence);
551 $tag_id = $tag['id'];
554 # we assign the tag to the article
555 $this->store
->setTagToEntry($tag_id, $entry_id);
562 $tag_id = $_GET['tag_id'];
563 $entry = $this->store
->retrieveOneById($id, $this->user
->getId());
565 $this->messages
->add('e', _('Article not found!'));
566 Tools
::logm('error : article not found');
569 $this->store
->removeTagForEntry($id, $tag_id);
577 function displayView($view, $id = 0)
584 $dev = trim($this->getPocheVersion('dev'));
585 $prod = trim($this->getPocheVersion('prod'));
586 $compare_dev = version_compare(POCHE
, $dev);
587 $compare_prod = version_compare(POCHE
, $prod);
588 $themes = $this->getInstalledThemes();
589 $languages = $this->getInstalledLanguages();
590 $token = $this->user
->getConfigValue('token');
591 $http_auth = (isset($_SERVER['PHP_AUTH_USER']) || isset($_SERVER['REMOTE_USER'])) ? true : false;
594 'languages' => $languages,
597 'compare_dev' => $compare_dev,
598 'compare_prod' => $compare_prod,
600 'user_id' => $this->user
->getId(),
601 'http_auth' => $http_auth,
603 Tools
::logm('config view');
607 $entry = $this->store
->retrieveOneById($id, $this->user
->getId());
609 $this->messages
->add('e', _('Article not found!'));
610 Tools
::logm('error : article not found');
613 $tags = $this->store
->retrieveTagsByEntry($id);
621 $token = $this->user
->getConfigValue('token');
622 $tags = $this->store
->retrieveAllTags($this->user
->getId());
625 'user_id' => $this->user
->getId(),
630 $entry = $this->store
->retrieveOneById($id, $this->user
->getId());
631 if ($entry != NULL) {
632 Tools
::logm('view link #' . $id);
633 $content = $entry['content'];
634 if (function_exists('tidy_parse_string')) {
635 $tidy = tidy_parse_string($content, array('indent'=>true, 'show-body-only' => true), 'UTF8');
636 $tidy->cleanRepair();
637 $content = $tidy->value
;
641 $flattr = new FlattrItem();
642 $flattr->checkItem($entry['url'], $entry['id']);
645 $tags = $this->store
->retrieveTagsByEntry($entry['id']);
649 'content' => $content,
655 Tools
::logm('error in view call : entry is null');
658 default: # home, favorites, archive and tag views
665 //if id is given - we retrive entries by tag: id is tag id
667 $tpl_vars['tag'] = $this->store
->retrieveTag($id, $this->user
->getId());
668 $tpl_vars['id'] = intval($id);
671 $count = $this->store
->getEntriesByViewCount($view, $this->user
->getId(), $id);
674 $this->pagination
->set_total($count);
675 $page_links = str_replace(array('previous', 'next'), array(_('previous'), _('next')),
676 $this->pagination
->page_links('?view=' . $view . '&sort=' . $_SESSION['sort'] . (($id)?'&id='.$id:'') . '&' ));
677 $tpl_vars['entries'] = $this->store
->getEntriesByView($view, $this->user
->getId(), $this->pagination
->get_limit(), $id);
678 $tpl_vars['page_links'] = $page_links;
679 $tpl_vars['nb_results'] = $count;
681 Tools
::logm('display ' . $view . ' view');
689 * update the password of the current user.
690 * if MODE_DEMO is TRUE, the password can't be updated.
691 * @todo add the return value
692 * @todo set the new password in function header like this updatePassword($newPassword)
695 public function updatePassword()
698 $this->messages
->add('i', _('in demo mode, you can\'t update your password'));
699 Tools
::logm('in demo mode, you can\'t do this');
700 Tools
::redirect('?view=config');
703 if (isset($_POST['password']) && isset($_POST['password_repeat'])) {
704 if ($_POST['password'] == $_POST['password_repeat'] && $_POST['password'] != "") {
705 $this->messages
->add('s', _('your password has been updated'));
706 $this->store
->updatePassword($this->user
->getId(), Tools
::encodeString($_POST['password'] . $this->user
->getUsername()));
708 Tools
::logm('password updated');
712 $this->messages
->add('e', _('the two fields have to be filled & the password must be the same in the two fields'));
713 Tools
::redirect('?view=config');
719 public function updateTheme()
722 if (empty($_POST['theme'])) {
725 # we are not going to change it to the current theme...
726 if ($_POST['theme'] == $this->getTheme()) {
727 $this->messages
->add('w', _('still using the "' . $this->getTheme() . '" theme!'));
728 Tools
::redirect('?view=config');
731 $themes = $this->getInstalledThemes();
732 $actualTheme = false;
734 foreach (array_keys($themes) as $theme) {
735 if ($theme == $_POST['theme']) {
741 if (! $actualTheme) {
742 $this->messages
->add('e', _('that theme does not seem to be installed'));
743 Tools
::redirect('?view=config');
746 $this->store
->updateUserConfig($this->user
->getId(), 'theme', $_POST['theme']);
747 $this->messages
->add('s', _('you have changed your theme preferences'));
749 $currentConfig = $_SESSION['poche_user']->config
;
750 $currentConfig['theme'] = $_POST['theme'];
752 $_SESSION['poche_user']->setConfig($currentConfig);
754 Tools
::redirect('?view=config');
757 public function updateLanguage()
760 if (empty($_POST['language'])) {
763 # we are not going to change it to the current language...
764 if ($_POST['language'] == $this->getLanguage()) {
765 $this->messages
->add('w', _('still using the "' . $this->getLanguage() . '" language!'));
766 Tools
::redirect('?view=config');
769 $languages = $this->getInstalledLanguages();
770 $actualLanguage = false;
772 foreach ($languages as $language) {
773 if ($language['value'] == $_POST['language']) {
774 $actualLanguage = true;
779 if (! $actualLanguage) {
780 $this->messages
->add('e', _('that language does not seem to be installed'));
781 Tools
::redirect('?view=config');
784 $this->store
->updateUserConfig($this->user
->getId(), 'language', $_POST['language']);
785 $this->messages
->add('s', _('you have changed your language preferences'));
787 $currentConfig = $_SESSION['poche_user']->config
;
788 $currentConfig['language'] = $_POST['language'];
790 $_SESSION['poche_user']->setConfig($currentConfig);
792 Tools
::redirect('?view=config');
796 * get credentials from differents sources
797 * it redirects the user to the $referer link
800 private function credentials() {
801 if(isset($_SERVER['PHP_AUTH_USER'])) {
802 return array($_SERVER['PHP_AUTH_USER'],'php_auth',true);
804 if(!empty($_POST['login']) && !empty($_POST['password'])) {
805 return array($_POST['login'],$_POST['password'],false);
807 if(isset($_SERVER['REMOTE_USER'])) {
808 return array($_SERVER['REMOTE_USER'],'http_auth',true);
811 return array(false,false,false);
815 * checks if login & password are correct and save the user in session.
816 * it redirects the user to the $referer link
817 * @param string $referer the url to redirect after login
818 * @todo add the return value
821 public function login($referer)
823 list($login,$password,$isauthenticated)=$this->credentials();
824 if($login === false || $password === false) {
825 $this->messages
->add('e', _('login failed: you have to fill all fields'));
826 Tools
::logm('login failed');
829 if (!empty($login) && !empty($password)) {
830 $user = $this->store
->login($login, Tools
::encodeString($password . $login), $isauthenticated);
831 if ($user != array()) {
832 # Save login into Session
833 $longlastingsession = isset($_POST['longlastingsession']);
834 $passwordTest = ($isauthenticated) ? $user['password'] : Tools
::encodeString($password . $login);
835 Session
::login($user['username'], $user['password'], $login, $passwordTest, $longlastingsession, array('poche_user' => new User($user)));
836 $this->messages
->add('s', _('welcome to your wallabag'));
837 Tools
::logm('login successful');
838 Tools
::redirect($referer);
840 $this->messages
->add('e', _('login failed: bad login or password'));
841 Tools
::logm('login failed');
847 * log out the poche user. It cleans the session.
848 * @todo add the return value
851 public function logout()
853 $this->user
= array();
855 Tools
::logm('logout');
860 * import from Instapaper. poche needs a ./instapaper-export.html file
861 * @todo add the return value
862 * @param string $targetFile the file used for importing
865 private function importFromInstapaper($targetFile)
867 # TODO gestion des articles favs
868 $html = new simple_html_dom();
869 $html->load_file($targetFile);
870 Tools
::logm('starting import from instapaper');
874 foreach($html->find('ol') as $ul)
876 foreach($ul->find('li') as $li)
879 $url = new Url(base64_encode($a[0]->href
));
880 $this->action('add', $url, 0, TRUE);
883 if (STORAGE
== 'postgres') {
884 $sequence = 'entries_id_seq';
886 $last_id = $this->store
->getLastId($sequence);
887 $this->action('toggle_archive', $url, $last_id, TRUE);
891 # the second <ol> is for read links
894 $this->messages
->add('s', _('import from instapaper completed'));
895 Tools
::logm('import from instapaper completed');
900 * import from Pocket. poche needs a ./ril_export.html file
901 * @todo add the return value
902 * @param string $targetFile the file used for importing
905 private function importFromPocket($targetFile)
907 # TODO gestion des articles favs
908 $html = new simple_html_dom();
909 $html->load_file($targetFile);
910 Tools
::logm('starting import from pocket');
914 foreach($html->find('ul') as $ul)
916 foreach($ul->find('li') as $li)
919 $url = new Url(base64_encode($a[0]->href
));
920 $this->action('add', $url, 0, TRUE);
922 if (STORAGE
== 'postgres') {
923 $sequence = 'entries_id_seq';
925 $last_id = $this->store
->getLastId($sequence);
927 $this->action('toggle_archive', $url, $last_id, TRUE);
931 $this->action('add_tag',$url,$last_id,true,false,$tags);
935 # the second <ul> is for read links
938 $this->messages
->add('s', _('import from pocket completed'));
939 Tools
::logm('import from pocket completed');
944 * import from Readability. poche needs a ./readability file
945 * @todo add the return value
946 * @param string $targetFile the file used for importing
949 private function importFromReadability($targetFile)
951 # TODO gestion des articles lus / favs
952 $str_data = file_get_contents($targetFile);
953 $data = json_decode($str_data,true);
954 Tools
::logm('starting import from Readability');
956 foreach ($data as $key => $value) {
960 foreach ($value as $item) {
961 foreach ($item as $attr => $value) {
962 if ($attr == 'article__url') {
963 $url = new Url(base64_encode($value));
966 if (STORAGE
== 'postgres') {
967 $sequence = 'entries_id_seq';
969 if ($value == 'true') {
970 if ($attr == 'favorite') {
973 if ($attr == 'archive') {
980 if (!is_null($url) && $url->isCorrect()) {
981 $this->action('add', $url, 0, TRUE);
984 $last_id = $this->store
->getLastId($sequence);
985 $this->action('toggle_fav', $url, $last_id, TRUE);
988 $last_id = $this->store
->getLastId($sequence);
989 $this->action('toggle_archive', $url, $last_id, TRUE);
994 $this->messages
->add('s', _('import from Readability completed. ' . $count . ' new links.'));
995 Tools
::logm('import from Readability completed');
1000 * import from Poche exported file
1001 * @param string $targetFile the file used for importing
1004 private function importFromPoche($targetFile)
1006 $str_data = file_get_contents($targetFile);
1007 $data = json_decode($str_data,true);
1008 Tools
::logm('starting import from Poche');
1012 if (STORAGE
== 'postgres') {
1013 $sequence = 'entries_id_seq';
1017 foreach ($data as $value) {
1019 $url = new Url(base64_encode($value['url']));
1020 $favorite = ($value['is_fav'] == -1);
1021 $archive = ($value['is_read'] == -1);
1023 # we can add the url
1024 if (!is_null($url) && $url->isCorrect()) {
1026 $this->action('add', $url, 0, TRUE);
1030 $last_id = $this->store
->getLastId($sequence);
1031 $this->action('toggle_fav', $url, $last_id, TRUE);
1034 $last_id = $this->store
->getLastId($sequence);
1035 $this->action('toggle_archive', $url, $last_id, TRUE);
1040 $this->messages
->add('s', _('import from Poche completed. ' . $count . ' new links.'));
1041 Tools
::logm('import from Poche completed');
1046 * import datas into your poche
1047 * @param string $from name of the service to import : pocket, instapaper or readability
1048 * @todo add the return value
1051 public function import($from)
1054 'pocket' => 'importFromPocket',
1055 'readability' => 'importFromReadability',
1056 'instapaper' => 'importFromInstapaper',
1057 'poche' => 'importFromPoche',
1060 if (! isset($providers[$from])) {
1061 $this->messages
->add('e', _('Unknown import provider.'));
1065 $targetDefinition = 'IMPORT_' . strtoupper($from) . '_FILE';
1066 $targetFile = constant($targetDefinition);
1068 if (! defined($targetDefinition)) {
1069 $this->messages
->add('e', _('Incomplete inc/poche/define.inc.php file, please define "' . $targetDefinition . '".'));
1073 if (! file_exists($targetFile)) {
1074 $this->messages
->add('e', _('Could not find required "' . $targetFile . '" import file.'));
1078 $this->$providers[$from]($targetFile);
1082 * export poche entries in json
1083 * @return json all poche entries
1085 public function export()
1087 $entries = $this->store
->retrieveAll($this->user
->getId());
1088 echo $this->tpl
->render('export.twig', array(
1089 'export' => Tools
::renderJson($entries),
1091 Tools
::logm('export view');
1095 * Checks online the latest version of poche and cache it
1096 * @param string $which 'prod' or 'dev'
1097 * @return string latest $which version
1099 private function getPocheVersion($which = 'prod')
1101 $cache_file = CACHE
. '/' . $which;
1103 # checks if the cached version file exists
1104 if (file_exists($cache_file) && (filemtime($cache_file) > (time() - 86400 ))) {
1105 $version = file_get_contents($cache_file);
1107 $version = file_get_contents('http://static.wallabag.org/versions/' . $which);
1108 file_put_contents($cache_file, $version, LOCK_EX
);
1113 public function generateToken()
1115 if (ini_get('open_basedir') === '') {
1116 $token = substr(base64_encode(file_get_contents('/dev/urandom', false, null, 0, 20)), 0, 15);
1119 $token = substr(base64_encode(uniqid(mt_rand(), true)), 0, 20);
1122 $token = str_replace('+', '', $token);
1123 $this->store
->updateUserConfig($this->user
->getId(), 'token', $token);
1124 $currentConfig = $_SESSION['poche_user']->config
;
1125 $currentConfig['token'] = $token;
1126 $_SESSION['poche_user']->setConfig($currentConfig);
1130 public function generateFeeds($token, $user_id, $tag_id, $type = 'home')
1132 $allowed_types = array('home', 'fav', 'archive', 'tag');
1133 $config = $this->store
->getConfigUser($user_id);
1135 if (!in_array($type, $allowed_types) ||
1136 $token != $config['token']) {
1137 die(_('Uh, there is a problem while generating feeds.'));
1141 $feed = new FeedWriter(RSS2
);
1142 $feed->setTitle('wallabag — ' . $type . ' feed');
1143 $feed->setLink(Tools
::getPocheUrl());
1144 $feed->setChannelElement('updated', date(DATE_RSS
, time()));
1145 $feed->setChannelElement('author', 'wallabag');
1147 if ($type == 'tag') {
1148 $entries = $this->store
->retrieveEntriesByTag($tag_id, $user_id);
1151 $entries = $this->store
->getEntriesByView($type, $user_id);
1154 if (count($entries) > 0) {
1155 foreach ($entries as $entry) {
1156 $newItem = $feed->createNewItem();
1157 $newItem->setTitle($entry['title']);
1158 $newItem->setLink(Tools
::getPocheUrl() . '?view=view&id=' . $entry['id']);
1159 $newItem->setDate(time());
1160 $newItem->setDescription($entry['content']);
1161 $feed->addItem($newItem);
1165 $feed->genarateFeed();
1169 public function emptyCache() {
1170 $files = new RecursiveIteratorIterator(
1171 new RecursiveDirectoryIterator(CACHE
, RecursiveDirectoryIterator
::SKIP_DOTS
),
1172 RecursiveIteratorIterator
::CHILD_FIRST
1175 foreach ($files as $fileinfo) {
1176 $todo = ($fileinfo->isDir() ? 'rmdir' : 'unlink');
1177 $todo($fileinfo->getRealPath());
1180 Tools
::logm('empty cache');
1181 $this->messages
->add('s', _('Cache deleted.'));