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 public function __construct()
28 if ($this->configFileIsAvailable()) {
32 if ($this->themeIsInstalled()) {
36 if ($this->systemIsInstalled()) {
37 $this->store
= new Database();
38 $this->messages
= new Messages();
40 if (! $this->store
->isInstalled()) {
43 $this->store
->checkTags();
47 private function init()
50 Session
::$sessionName = 'poche';
53 if (isset($_SESSION['poche_user']) && $_SESSION['poche_user'] != array()) {
54 $this->user
= $_SESSION['poche_user'];
56 # fake user, just for install & login screens
57 $this->user
= new User();
58 $this->user
->setConfig($this->getDefaultConfig());
62 $language = $this->user
->getConfigValue('language');
63 putenv('LC_ALL=' . $language);
64 setlocale(LC_ALL
, $language);
65 bindtextdomain($language, LOCALE
);
66 textdomain($language);
69 $this->pagination
= new Paginator($this->user
->getConfigValue('pager'), 'p');
72 $themeDirectory = $this->user
->getConfigValue('theme');
74 if ($themeDirectory === false) {
75 $themeDirectory = DEFAULT_THEME
;
78 $this->currentTheme
= $themeDirectory;
81 $languageDirectory = $this->user
->getConfigValue('language');
83 if ($languageDirectory === false) {
84 $languageDirectory = DEFAULT_THEME
;
87 $this->currentLanguage
= $languageDirectory;
90 public function configFileIsAvailable() {
91 if (! self
::$configFileAvailable) {
92 $this->notInstalledMessage
[] = 'You have to rename inc/poche/config.inc.php.new to inc/poche/config.inc.php.';
100 public function themeIsInstalled() {
102 # Twig is an absolute requirement for Poche to function. Abort immediately if the Composer installer hasn't been run yet
103 if (! self
::$canRenderTemplates) {
104 $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.';
108 if (! is_writable(CACHE
)) {
109 $this->notInstalledMessage
[] = 'You don\'t have write access on cache directory.';
111 self
::$canRenderTemplates = false;
116 # Check if the selected theme and its requirements are present
117 $theme = $this->getTheme();
119 if ($theme != '' && ! is_dir(THEME
. '/' . $theme)) {
120 $this->notInstalledMessage
[] = 'The currently selected theme (' . $theme . ') does not seem to be properly installed (Missing directory: ' . THEME
. '/' . $theme . ')';
122 self
::$canRenderTemplates = false;
127 $themeInfo = $this->getThemeInfo($theme);
128 if (isset($themeInfo['requirements']) && is_array($themeInfo['requirements'])) {
129 foreach ($themeInfo['requirements'] as $requiredTheme) {
130 if (! is_dir(THEME
. '/' . $requiredTheme)) {
131 $this->notInstalledMessage
[] = 'The required "' . $requiredTheme . '" theme is missing for the current theme (' . $theme . ')';
133 self
::$canRenderTemplates = false;
149 * all checks before installation.
150 * @todo move HTML to template
153 public function systemIsInstalled()
157 $configSalt = defined('SALT') ? constant('SALT') : '';
159 if (empty($configSalt)) {
160 $this->notInstalledMessage
[] = 'You have not yet filled in the SALT value in the config.inc.php file.';
163 if (STORAGE
== 'sqlite' && ! file_exists(STORAGE_SQLITE
)) {
164 Tools
::logm('sqlite file doesn\'t exist');
165 $this->notInstalledMessage
[] = 'sqlite file doesn\'t exist, you can find it in install folder. Copy it in /db folder.';
168 if (is_dir(ROOT
. '/install') && ! DEBUG_POCHE
) {
169 $this->notInstalledMessage
[] = 'you have to delete the /install folder before using poche.';
172 if (STORAGE
== 'sqlite' && ! is_writable(STORAGE_SQLITE
)) {
173 Tools
::logm('you don\'t have write access on sqlite file');
174 $this->notInstalledMessage
[] = 'You don\'t have write access on sqlite file.';
185 public function getNotInstalledMessage() {
186 return $this->notInstalledMessage
;
189 private function initTpl()
191 $loaderChain = new Twig_Loader_Chain();
192 $theme = $this->getTheme();
194 # add the current theme as first to the loader chain so Twig will look there first for overridden template files
196 $loaderChain->addLoader(new Twig_Loader_Filesystem(THEME
. '/' . $theme));
197 } catch (Twig_Error_Loader
$e) {
198 # @todo isInstalled() should catch this, inject Twig later
199 die('The currently selected theme (' . $theme . ') does not seem to be properly installed (' . THEME
. '/' . $theme .' is missing)');
202 # add all required themes to the loader chain
203 $themeInfo = $this->getThemeInfo($theme);
204 if (isset($themeInfo['requirements']) && is_array($themeInfo['requirements'])) {
205 foreach ($themeInfo['requirements'] as $requiredTheme) {
207 $loaderChain->addLoader(new Twig_Loader_Filesystem(THEME
. '/' . $requiredTheme));
208 } catch (Twig_Error_Loader
$e) {
209 # @todo isInstalled() should catch this, inject Twig later
210 die('The required "' . $requiredTheme . '" theme is missing for the current theme (' . $theme . ')');
216 $twigParams = array();
218 $twigParams = array('cache' => CACHE
);
221 $this->tpl
= new Twig_Environment($loaderChain, $twigParams);
222 $this->tpl
->addExtension(new Twig_Extensions_Extension_I18n());
224 # filter to display domain name of an url
225 $filter = new Twig_SimpleFilter('getDomain', 'Tools::getDomain');
226 $this->tpl
->addFilter($filter);
228 # filter for reading time
229 $filter = new Twig_SimpleFilter('getReadingTime', 'Tools::getReadingTime');
230 $this->tpl
->addFilter($filter);
233 private function install()
235 Tools
::logm('poche still not installed');
236 echo $this->tpl
->render('install.twig', array(
237 'token' => Session
::getToken(),
238 'theme' => $this->getTheme(),
239 'poche_url' => Tools
::getPocheUrl()
241 if (isset($_GET['install'])) {
242 if (($_POST['password'] == $_POST['password_repeat'])
243 && $_POST['password'] != "" && $_POST['login'] != "") {
244 # let's rock, install poche baby !
245 if ($this->store
->install($_POST['login'], Tools
::encodeString($_POST['password'] . $_POST['login'])))
248 Tools
::logm('poche is now installed');
253 Tools
::logm('error during installation');
260 public function getTheme() {
261 return $this->currentTheme
;
265 * Provides theme information by parsing theme.ini file if present in the theme's root directory.
266 * In all cases, the following data will be returned:
267 * - name: theme's name, or key if the theme is unnamed,
268 * - current: boolean informing if the theme is the current user theme.
270 * @param string $theme Theme key (directory name)
271 * @return array|boolean Theme information, or false if the theme doesn't exist.
273 public function getThemeInfo($theme) {
274 if (!is_dir(THEME
. '/' . $theme)) {
278 $themeIniFile = THEME
. '/' . $theme . '/theme.ini';
279 $themeInfo = array();
281 if (is_file($themeIniFile) && is_readable($themeIniFile)) {
282 $themeInfo = parse_ini_file($themeIniFile);
285 if ($themeInfo === false) {
286 $themeInfo = array();
288 if (!isset($themeInfo['name'])) {
289 $themeInfo['name'] = $theme;
291 $themeInfo['current'] = ($theme === $this->getTheme());
296 public function getInstalledThemes() {
297 $handle = opendir(THEME
);
300 while (($theme = readdir($handle)) !== false) {
301 # Themes are stored in a directory, so all directory names are themes
302 # @todo move theme installation data to database
303 if (!is_dir(THEME
. '/' . $theme) || in_array($theme, array('.', '..'))) {
307 $themes[$theme] = $this->getThemeInfo($theme);
313 public function getLanguage() {
314 return $this->currentLanguage
;
317 public function getInstalledLanguages() {
318 $handle = opendir(LOCALE
);
319 $languages = array();
321 while (($language = readdir($handle)) !== false) {
322 # Languages are stored in a directory, so all directory names are languages
323 # @todo move language installation data to database
324 if (! is_dir(LOCALE
. '/' . $language) || in_array($language, array('..', '.'))) {
330 if ($language === $this->getLanguage()) {
334 $languages[] = array('name' => $language, 'current' => $current);
340 public function getDefaultConfig()
343 'pager' => PAGINATION
,
345 'theme' => DEFAULT_THEME
349 protected function getPageContent(Url
$url)
351 $options = array('http' => array('user_agent' => 'poche'));
352 if (isset($_SERVER['AUTH_TYPE']) && "basic" === strtolower($_SERVER['AUTH_TYPE'])) {
353 $options['http']['header'] = sprintf(
354 "Authorization: Basic %s",
356 sprintf('%s:%s', $_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW'])
360 $context = stream_context_create($options);
361 $json = file_get_contents(Tools
::getPocheUrl() . '/inc/3rdparty/makefulltextfeed.php?url='.urlencode($url->getUrl()).'&max=5&links=preserve&exc=&format=json&submit=Create+Feed', false, $context);
362 return json_decode($json, true);
366 * Call action (mark as fav, archive, delete, etc.)
368 public function action($action, Url
$url, $id = 0, $import = FALSE, $autoclose = FALSE, $tags = null)
373 $content = $this->getPageContent($url);
374 $title = ($content['rss']['channel']['item']['title'] != '') ? $content['rss']['channel']['item']['title'] : _('Untitled');
375 $body = $content['rss']['channel']['item']['description'];
377 //search for possible duplicate if not in import mode
379 $duplicate = $this->store
->retrieveOneByURL($url->getUrl(), $this->user
->getId());
382 if ($this->store
->add($url->getUrl(), $title, $body, $this->user
->getId())) {
383 Tools
::logm('add link ' . $url->getUrl());
385 if (STORAGE
== 'postgres') {
386 $sequence = 'entries_id_seq';
388 $last_id = $this->store
->getLastId($sequence);
389 if (DOWNLOAD_PICTURES
) {
390 $content = filtre_picture($body, $url->getUrl(), $last_id);
391 Tools
::logm('updating content article');
392 $this->store
->updateContent($last_id, $content, $this->user
->getId());
395 if ($duplicate != NULL) {
396 // 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
397 Tools
::logm('link ' . $url->getUrl() . ' is a duplicate');
398 // 1) - preserve tags and favorite, then drop old entry
399 $this->store
->reassignTags($duplicate['id'], $last_id);
400 if ($duplicate['is_fav']) {
401 $this->store
->favoriteById($last_id, $this->user
->getId());
403 if ($this->store
->deleteById($duplicate['id'], $this->user
->getId())) {
404 Tools
::logm('previous link ' . $url->getUrl() .' entry deleted');
409 $this->messages
->add('s', _('the link has been added successfully'));
414 $this->messages
->add('e', _('error during insertion : the link wasn\'t added'));
415 Tools
::logm('error during insertion : the link wasn\'t added ' . $url->getUrl());
420 if ($autoclose == TRUE) {
421 Tools
::redirect('?view=home');
423 Tools
::redirect('?view=home&closewin=true');
428 $msg = 'delete link #' . $id;
429 if ($this->store
->deleteById($id, $this->user
->getId())) {
430 if (DOWNLOAD_PICTURES
) {
431 remove_directory(ABS_PATH
. $id);
433 $this->messages
->add('s', _('the link has been deleted successfully'));
436 $this->messages
->add('e', _('the link wasn\'t deleted'));
437 $msg = 'error : can\'t delete link #' . $id;
440 Tools
::redirect('?');
443 $this->store
->favoriteById($id, $this->user
->getId());
444 Tools
::logm('mark as favorite link #' . $id);
449 case 'toggle_archive' :
450 $this->store
->archiveById($id, $this->user
->getId());
451 Tools
::logm('archive link #' . $id);
457 $this->store
->archiveAll($this->user
->getId());
458 Tools
::logm('archive all links');
466 $tags = explode(',', $tags);
469 $tags = explode(',', $_POST['value']);
470 $entry_id = $_POST['entry_id'];
472 $entry = $this->store
->retrieveOneById($entry_id, $this->user
->getId());
474 $this->messages
->add('e', _('Article not found!'));
475 Tools
::logm('error : article not found');
478 foreach($tags as $key => $tag_value) {
479 $value = trim($tag_value);
480 $tag = $this->store
->retrieveTagByValue($value);
484 $tag = $this->store
->createTag($value);
486 if (STORAGE
== 'postgres') {
487 $sequence = 'tags_id_seq';
489 $tag_id = $this->store
->getLastId($sequence);
492 $tag_id = $tag['id'];
495 # we assign the tag to the article
496 $this->store
->setTagToEntry($tag_id, $entry_id);
503 $tag_id = $_GET['tag_id'];
504 $entry = $this->store
->retrieveOneById($id, $this->user
->getId());
506 $this->messages
->add('e', _('Article not found!'));
507 Tools
::logm('error : article not found');
510 $this->store
->removeTagForEntry($id, $tag_id);
518 function displayView($view, $id = 0)
525 $dev = trim($this->getPocheVersion('dev'));
526 $prod = trim($this->getPocheVersion('prod'));
527 $compare_dev = version_compare(POCHE
, $dev);
528 $compare_prod = version_compare(POCHE
, $prod);
529 $themes = $this->getInstalledThemes();
530 $languages = $this->getInstalledLanguages();
531 $token = $this->user
->getConfigValue('token');
532 $http_auth = (isset($_SERVER['PHP_AUTH_USER']) || isset($_SERVER['REMOTE_USER'])) ? true : false;
535 'languages' => $languages,
538 'compare_dev' => $compare_dev,
539 'compare_prod' => $compare_prod,
541 'user_id' => $this->user
->getId(),
542 'http_auth' => $http_auth,
544 Tools
::logm('config view');
548 $entry = $this->store
->retrieveOneById($id, $this->user
->getId());
550 $this->messages
->add('e', _('Article not found!'));
551 Tools
::logm('error : article not found');
554 $tags = $this->store
->retrieveTagsByEntry($id);
561 $entries = $this->store
->retrieveEntriesByTag($id, $this->user
->getId());
562 $tag = $this->store
->retrieveTag($id, $this->user
->getId());
565 'entries' => $entries,
569 $token = $this->user
->getConfigValue('token');
570 $tags = $this->store
->retrieveAllTags($this->user
->getId());
573 'user_id' => $this->user
->getId(),
578 $entry = $this->store
->retrieveOneById($id, $this->user
->getId());
579 if ($entry != NULL) {
580 Tools
::logm('view link #' . $id);
581 $content = $entry['content'];
582 if (function_exists('tidy_parse_string')) {
583 $tidy = tidy_parse_string($content, array('indent'=>true, 'show-body-only' => true), 'UTF8');
584 $tidy->cleanRepair();
585 $content = $tidy->value
;
589 $flattr = new FlattrItem();
590 $flattr->checkItem($entry['url'], $entry['id']);
593 $tags = $this->store
->retrieveTagsByEntry($entry['id']);
597 'content' => $content,
603 Tools
::logm('error in view call : entry is null');
606 default: # home, favorites and archive views
607 $entries = $this->store
->getEntriesByView($view, $this->user
->getId());
614 if (count($entries) > 0) {
615 $this->pagination
->set_total(count($entries));
616 $page_links = str_replace(array('previous', 'next'), array(_('previous'), _('next')),
617 $this->pagination
->page_links('?view=' . $view . '&sort=' . $_SESSION['sort'] . '&'));
618 $datas = $this->store
->getEntriesByView($view, $this->user
->getId(), $this->pagination
->get_limit());
619 $tpl_vars['entries'] = $datas;
620 $tpl_vars['page_links'] = $page_links;
621 $tpl_vars['nb_results'] = count($entries);
623 Tools
::logm('display ' . $view . ' view');
631 * update the password of the current user.
632 * if MODE_DEMO is TRUE, the password can't be updated.
633 * @todo add the return value
634 * @todo set the new password in function header like this updatePassword($newPassword)
637 public function updatePassword()
640 $this->messages
->add('i', _('in demo mode, you can\'t update your password'));
641 Tools
::logm('in demo mode, you can\'t do this');
642 Tools
::redirect('?view=config');
645 if (isset($_POST['password']) && isset($_POST['password_repeat'])) {
646 if ($_POST['password'] == $_POST['password_repeat'] && $_POST['password'] != "") {
647 $this->messages
->add('s', _('your password has been updated'));
648 $this->store
->updatePassword($this->user
->getId(), Tools
::encodeString($_POST['password'] . $this->user
->getUsername()));
650 Tools
::logm('password updated');
654 $this->messages
->add('e', _('the two fields have to be filled & the password must be the same in the two fields'));
655 Tools
::redirect('?view=config');
661 public function updateTheme()
664 if (empty($_POST['theme'])) {
667 # we are not going to change it to the current theme...
668 if ($_POST['theme'] == $this->getTheme()) {
669 $this->messages
->add('w', _('still using the "' . $this->getTheme() . '" theme!'));
670 Tools
::redirect('?view=config');
673 $themes = $this->getInstalledThemes();
674 $actualTheme = false;
676 foreach (array_keys($themes) as $theme) {
677 if ($theme == $_POST['theme']) {
683 if (! $actualTheme) {
684 $this->messages
->add('e', _('that theme does not seem to be installed'));
685 Tools
::redirect('?view=config');
688 $this->store
->updateUserConfig($this->user
->getId(), 'theme', $_POST['theme']);
689 $this->messages
->add('s', _('you have changed your theme preferences'));
691 $currentConfig = $_SESSION['poche_user']->config
;
692 $currentConfig['theme'] = $_POST['theme'];
694 $_SESSION['poche_user']->setConfig($currentConfig);
696 Tools
::redirect('?view=config');
699 public function updateLanguage()
702 if (empty($_POST['language'])) {
705 # we are not going to change it to the current language...
706 if ($_POST['language'] == $this->getLanguage()) {
707 $this->messages
->add('w', _('still using the "' . $this->getLanguage() . '" language!'));
708 Tools
::redirect('?view=config');
711 $languages = $this->getInstalledLanguages();
712 $actualLanguage = false;
714 foreach ($languages as $language) {
715 if ($language['name'] == $_POST['language']) {
716 $actualLanguage = true;
721 if (! $actualLanguage) {
722 $this->messages
->add('e', _('that language does not seem to be installed'));
723 Tools
::redirect('?view=config');
726 $this->store
->updateUserConfig($this->user
->getId(), 'language', $_POST['language']);
727 $this->messages
->add('s', _('you have changed your language preferences'));
729 $currentConfig = $_SESSION['poche_user']->config
;
730 $currentConfig['language'] = $_POST['language'];
732 $_SESSION['poche_user']->setConfig($currentConfig);
734 Tools
::redirect('?view=config');
738 * get credentials from differents sources
739 * it redirects the user to the $referer link
742 private function credentials() {
743 if(isset($_SERVER['PHP_AUTH_USER'])) {
744 return array($_SERVER['PHP_AUTH_USER'],'php_auth',true);
746 if(!empty($_POST['login']) && !empty($_POST['password'])) {
747 return array($_POST['login'],$_POST['password'],false);
749 if(isset($_SERVER['REMOTE_USER'])) {
750 return array($_SERVER['REMOTE_USER'],'http_auth',true);
753 return array(false,false,false);
757 * checks if login & password are correct and save the user in session.
758 * it redirects the user to the $referer link
759 * @param string $referer the url to redirect after login
760 * @todo add the return value
763 public function login($referer)
765 list($login,$password,$isauthenticated)=$this->credentials();
766 if($login === false || $password === false) {
767 $this->messages
->add('e', _('login failed: you have to fill all fields'));
768 Tools
::logm('login failed');
771 if (!empty($login) && !empty($password)) {
772 $user = $this->store
->login($login, Tools
::encodeString($password . $login), $isauthenticated);
773 if ($user != array()) {
774 # Save login into Session
775 $longlastingsession = isset($_POST['longlastingsession']);
776 $passwordTest = ($isauthenticated) ? $user['password'] : Tools
::encodeString($password . $login);
777 Session
::login($user['username'], $user['password'], $login, $passwordTest, $longlastingsession, array('poche_user' => new User($user)));
778 $this->messages
->add('s', _('welcome to your wallabag'));
779 Tools
::logm('login successful');
780 Tools
::redirect($referer);
782 $this->messages
->add('e', _('login failed: bad login or password'));
783 Tools
::logm('login failed');
789 * log out the poche user. It cleans the session.
790 * @todo add the return value
793 public function logout()
795 $this->user
= array();
797 Tools
::logm('logout');
802 * import from Instapaper. poche needs a ./instapaper-export.html file
803 * @todo add the return value
804 * @param string $targetFile the file used for importing
807 private function importFromInstapaper($targetFile)
809 # TODO gestion des articles favs
810 $html = new simple_html_dom();
811 $html->load_file($targetFile);
812 Tools
::logm('starting import from instapaper');
816 foreach($html->find('ol') as $ul)
818 foreach($ul->find('li') as $li)
821 $url = new Url(base64_encode($a[0]->href
));
822 $this->action('add', $url, 0, TRUE);
825 if (STORAGE
== 'postgres') {
826 $sequence = 'entries_id_seq';
828 $last_id = $this->store
->getLastId($sequence);
829 $this->action('toggle_archive', $url, $last_id, TRUE);
833 # the second <ol> is for read links
836 $this->messages
->add('s', _('import from instapaper completed'));
837 Tools
::logm('import from instapaper completed');
842 * import from Pocket. poche needs a ./ril_export.html file
843 * @todo add the return value
844 * @param string $targetFile the file used for importing
847 private function importFromPocket($targetFile)
849 # TODO gestion des articles favs
850 $html = new simple_html_dom();
851 $html->load_file($targetFile);
852 Tools
::logm('starting import from pocket');
856 foreach($html->find('ul') as $ul)
858 foreach($ul->find('li') as $li)
861 $url = new Url(base64_encode($a[0]->href
));
862 $this->action('add', $url, 0, TRUE);
864 if (STORAGE
== 'postgres') {
865 $sequence = 'entries_id_seq';
867 $last_id = $this->store
->getLastId($sequence);
869 $this->action('toggle_archive', $url, $last_id, TRUE);
873 $this->action('add_tag',$url,$last_id,true,false,$tags);
877 # the second <ul> is for read links
880 $this->messages
->add('s', _('import from pocket completed'));
881 Tools
::logm('import from pocket completed');
886 * import from Readability. poche needs a ./readability file
887 * @todo add the return value
888 * @param string $targetFile the file used for importing
891 private function importFromReadability($targetFile)
893 # TODO gestion des articles lus / favs
894 $str_data = file_get_contents($targetFile);
895 $data = json_decode($str_data,true);
896 Tools
::logm('starting import from Readability');
898 foreach ($data as $key => $value) {
902 foreach ($value as $item) {
903 foreach ($item as $attr => $value) {
904 if ($attr == 'article__url') {
905 $url = new Url(base64_encode($value));
908 if (STORAGE
== 'postgres') {
909 $sequence = 'entries_id_seq';
911 if ($value == 'true') {
912 if ($attr == 'favorite') {
915 if ($attr == 'archive') {
922 if (!is_null($url) && $url->isCorrect()) {
923 $this->action('add', $url, 0, TRUE);
926 $last_id = $this->store
->getLastId($sequence);
927 $this->action('toggle_fav', $url, $last_id, TRUE);
930 $last_id = $this->store
->getLastId($sequence);
931 $this->action('toggle_archive', $url, $last_id, TRUE);
936 $this->messages
->add('s', _('import from Readability completed. ' . $count . ' new links.'));
937 Tools
::logm('import from Readability completed');
942 * import from Poche exported file
943 * @param string $targetFile the file used for importing
946 private function importFromPoche($targetFile)
948 $str_data = file_get_contents($targetFile);
949 $data = json_decode($str_data,true);
950 Tools
::logm('starting import from Poche');
954 if (STORAGE
== 'postgres') {
955 $sequence = 'entries_id_seq';
959 foreach ($data as $value) {
961 $url = new Url(base64_encode($value['url']));
962 $favorite = ($value['is_fav'] == -1);
963 $archive = ($value['is_read'] == -1);
966 if (!is_null($url) && $url->isCorrect()) {
968 $this->action('add', $url, 0, TRUE);
972 $last_id = $this->store
->getLastId($sequence);
973 $this->action('toggle_fav', $url, $last_id, TRUE);
976 $last_id = $this->store
->getLastId($sequence);
977 $this->action('toggle_archive', $url, $last_id, TRUE);
982 $this->messages
->add('s', _('import from Poche completed. ' . $count . ' new links.'));
983 Tools
::logm('import from Poche completed');
988 * import datas into your poche
989 * @param string $from name of the service to import : pocket, instapaper or readability
990 * @todo add the return value
993 public function import($from)
996 'pocket' => 'importFromPocket',
997 'readability' => 'importFromReadability',
998 'instapaper' => 'importFromInstapaper',
999 'poche' => 'importFromPoche',
1002 if (! isset($providers[$from])) {
1003 $this->messages
->add('e', _('Unknown import provider.'));
1007 $targetDefinition = 'IMPORT_' . strtoupper($from) . '_FILE';
1008 $targetFile = constant($targetDefinition);
1010 if (! defined($targetDefinition)) {
1011 $this->messages
->add('e', _('Incomplete inc/poche/define.inc.php file, please define "' . $targetDefinition . '".'));
1015 if (! file_exists($targetFile)) {
1016 $this->messages
->add('e', _('Could not find required "' . $targetFile . '" import file.'));
1020 $this->$providers[$from]($targetFile);
1024 * export poche entries in json
1025 * @return json all poche entries
1027 public function export()
1029 $entries = $this->store
->retrieveAll($this->user
->getId());
1030 echo $this->tpl
->render('export.twig', array(
1031 'export' => Tools
::renderJson($entries),
1033 Tools
::logm('export view');
1037 * Checks online the latest version of poche and cache it
1038 * @param string $which 'prod' or 'dev'
1039 * @return string latest $which version
1041 private function getPocheVersion($which = 'prod')
1043 $cache_file = CACHE
. '/' . $which;
1045 # checks if the cached version file exists
1046 if (file_exists($cache_file) && (filemtime($cache_file) > (time() - 86400 ))) {
1047 $version = file_get_contents($cache_file);
1049 $version = file_get_contents('http://static.wallabag.org/versions/' . $which);
1050 file_put_contents($cache_file, $version, LOCK_EX
);
1055 public function generateToken()
1057 if (ini_get('open_basedir') === '') {
1058 $token = substr(base64_encode(file_get_contents('/dev/urandom', false, null, 0, 20)), 0, 15);
1061 $token = substr(base64_encode(uniqid(mt_rand(), true)), 0, 20);
1064 $token = str_replace('+', '', $token);
1065 $this->store
->updateUserConfig($this->user
->getId(), 'token', $token);
1066 $currentConfig = $_SESSION['poche_user']->config
;
1067 $currentConfig['token'] = $token;
1068 $_SESSION['poche_user']->setConfig($currentConfig);
1071 public function generateFeeds($token, $user_id, $tag_id, $type = 'home')
1073 $allowed_types = array('home', 'fav', 'archive', 'tag');
1074 $config = $this->store
->getConfigUser($user_id);
1076 if (!in_array($type, $allowed_types) ||
1077 $token != $config['token']) {
1078 die(_('Uh, there is a problem while generating feeds.'));
1082 $feed = new FeedWriter(RSS2
);
1083 $feed->setTitle('wallabag — ' . $type . ' feed');
1084 $feed->setLink(Tools
::getPocheUrl());
1085 $feed->setChannelElement('updated', date(DATE_RSS
, time()));
1086 $feed->setChannelElement('author', 'wallabag');
1088 if ($type == 'tag') {
1089 $entries = $this->store
->retrieveEntriesByTag($tag_id, $user_id);
1092 $entries = $this->store
->getEntriesByView($type, $user_id);
1095 if (count($entries) > 0) {
1096 foreach ($entries as $entry) {
1097 $newItem = $feed->createNewItem();
1098 $newItem->setTitle($entry['title']);
1099 $newItem->setLink(Tools
::getPocheUrl() . '?view=view&id=' . $entry['id']);
1100 $newItem->setDate(time());
1101 $newItem->setDescription($entry['content']);
1102 $feed->addItem($newItem);
1106 $feed->genarateFeed();
1110 public function emptyCache() {
1111 $files = new RecursiveIteratorIterator(
1112 new RecursiveDirectoryIterator(CACHE
, RecursiveDirectoryIterator
::SKIP_DOTS
),
1113 RecursiveIteratorIterator
::CHILD_FIRST
1116 foreach ($files as $fileinfo) {
1117 $todo = ($fileinfo->isDir() ? 'rmdir' : 'unlink');
1118 $todo($fileinfo->getRealPath());
1121 Tools
::logm('empty cache');
1122 $this->messages
->add('s', _('Cache deleted.'));