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);
315 public function getLanguage() {
316 return $this->currentLanguage
;
319 public function getInstalledLanguages() {
320 $handle = opendir(LOCALE
);
321 $languages = array();
323 while (($language = readdir($handle)) !== false) {
324 # Languages are stored in a directory, so all directory names are languages
325 # @todo move language installation data to database
326 if (! is_dir(LOCALE
. '/' . $language) || in_array($language, array('..', '.'))) {
332 if ($language === $this->getLanguage()) {
336 $languages[] = array('name' => $language, 'current' => $current);
342 public function getDefaultConfig()
345 'pager' => PAGINATION
,
347 'theme' => DEFAULT_THEME
351 protected function getPageContent(Url
$url)
353 // Saving and clearing context
355 foreach( $GLOBALS as $key => $value ) {
356 if( $key != "GLOBALS" && $key != "_SESSION" ) {
357 $GLOBALS[$key] = array();
358 $REAL[$key] = $value;
361 // Saving and clearing session
362 $REAL_SESSION = array();
363 foreach( $_SESSION as $key => $value ) {
364 $REAL_SESSION[$key] = $value;
365 unset($_SESSION[$key]);
368 // Running code in different context
369 $scope = function() {
370 extract( func_get_arg(1) );
371 $_GET = $_REQUEST = array(
372 "url" => $url->getUrl(),
374 "links" => "preserve",
377 "submit" => "Create Feed"
380 require func_get_arg(0);
381 $json = ob_get_flush();
384 $json = $scope( "inc/3rdparty/makefulltextfeed.php", array("url" => $url) );
386 // Clearing and restoring context
387 foreach( $GLOBALS as $key => $value ) {
388 if( $key != "GLOBALS" && $key != "_SESSION" ) {
389 unset($GLOBALS[$key]);
392 foreach( $REAL as $key => $value ) {
393 $GLOBALS[$key] = $value;
395 // Clearing and restoring session
396 foreach( $_SESSION as $key => $value ) {
397 unset($_SESSION[$key]);
399 foreach( $REAL_SESSION as $key => $value ) {
400 $_SESSION[$key] = $value;
402 return json_decode($json, true);
406 * Call action (mark as fav, archive, delete, etc.)
408 public function action($action, Url
$url, $id = 0, $import = FALSE, $autoclose = FALSE, $tags = null)
413 $content = $this->getPageContent($url);
414 $title = ($content['rss']['channel']['item']['title'] != '') ? $content['rss']['channel']['item']['title'] : _('Untitled');
415 $body = $content['rss']['channel']['item']['description'];
417 //search for possible duplicate if not in import mode
419 $duplicate = $this->store
->retrieveOneByURL($url->getUrl(), $this->user
->getId());
422 if ($this->store
->add($url->getUrl(), $title, $body, $this->user
->getId())) {
423 Tools
::logm('add link ' . $url->getUrl());
425 if (STORAGE
== 'postgres') {
426 $sequence = 'entries_id_seq';
428 $last_id = $this->store
->getLastId($sequence);
429 if (DOWNLOAD_PICTURES
) {
430 $content = filtre_picture($body, $url->getUrl(), $last_id);
431 Tools
::logm('updating content article');
432 $this->store
->updateContent($last_id, $content, $this->user
->getId());
435 if ($duplicate != NULL) {
436 // 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
437 Tools
::logm('link ' . $url->getUrl() . ' is a duplicate');
438 // 1) - preserve tags and favorite, then drop old entry
439 $this->store
->reassignTags($duplicate['id'], $last_id);
440 if ($duplicate['is_fav']) {
441 $this->store
->favoriteById($last_id, $this->user
->getId());
443 if ($this->store
->deleteById($duplicate['id'], $this->user
->getId())) {
444 Tools
::logm('previous link ' . $url->getUrl() .' entry deleted');
449 $this->messages
->add('s', _('the link has been added successfully'));
454 $this->messages
->add('e', _('error during insertion : the link wasn\'t added'));
455 Tools
::logm('error during insertion : the link wasn\'t added ' . $url->getUrl());
460 if ($autoclose == TRUE) {
461 Tools
::redirect('?view=home');
463 Tools
::redirect('?view=home&closewin=true');
468 $msg = 'delete link #' . $id;
469 if ($this->store
->deleteById($id, $this->user
->getId())) {
470 if (DOWNLOAD_PICTURES
) {
471 remove_directory(ABS_PATH
. $id);
473 $this->messages
->add('s', _('the link has been deleted successfully'));
476 $this->messages
->add('e', _('the link wasn\'t deleted'));
477 $msg = 'error : can\'t delete link #' . $id;
480 Tools
::redirect('?');
483 $this->store
->favoriteById($id, $this->user
->getId());
484 Tools
::logm('mark as favorite link #' . $id);
489 case 'toggle_archive' :
490 $this->store
->archiveById($id, $this->user
->getId());
491 Tools
::logm('archive link #' . $id);
497 $this->store
->archiveAll($this->user
->getId());
498 Tools
::logm('archive all links');
506 $tags = explode(',', $tags);
509 $tags = explode(',', $_POST['value']);
510 $entry_id = $_POST['entry_id'];
512 $entry = $this->store
->retrieveOneById($entry_id, $this->user
->getId());
514 $this->messages
->add('e', _('Article not found!'));
515 Tools
::logm('error : article not found');
518 foreach($tags as $key => $tag_value) {
519 $value = trim($tag_value);
520 $tag = $this->store
->retrieveTagByValue($value);
524 $tag = $this->store
->createTag($value);
526 if (STORAGE
== 'postgres') {
527 $sequence = 'tags_id_seq';
529 $tag_id = $this->store
->getLastId($sequence);
532 $tag_id = $tag['id'];
535 # we assign the tag to the article
536 $this->store
->setTagToEntry($tag_id, $entry_id);
543 $tag_id = $_GET['tag_id'];
544 $entry = $this->store
->retrieveOneById($id, $this->user
->getId());
546 $this->messages
->add('e', _('Article not found!'));
547 Tools
::logm('error : article not found');
550 $this->store
->removeTagForEntry($id, $tag_id);
558 function displayView($view, $id = 0)
565 $dev = trim($this->getPocheVersion('dev'));
566 $prod = trim($this->getPocheVersion('prod'));
567 $compare_dev = version_compare(POCHE
, $dev);
568 $compare_prod = version_compare(POCHE
, $prod);
569 $themes = $this->getInstalledThemes();
570 $languages = $this->getInstalledLanguages();
571 $token = $this->user
->getConfigValue('token');
572 $http_auth = (isset($_SERVER['PHP_AUTH_USER']) || isset($_SERVER['REMOTE_USER'])) ? true : false;
575 'languages' => $languages,
578 'compare_dev' => $compare_dev,
579 'compare_prod' => $compare_prod,
581 'user_id' => $this->user
->getId(),
582 'http_auth' => $http_auth,
584 Tools
::logm('config view');
588 $entry = $this->store
->retrieveOneById($id, $this->user
->getId());
590 $this->messages
->add('e', _('Article not found!'));
591 Tools
::logm('error : article not found');
594 $tags = $this->store
->retrieveTagsByEntry($id);
602 $token = $this->user
->getConfigValue('token');
603 $tags = $this->store
->retrieveAllTags($this->user
->getId());
606 'user_id' => $this->user
->getId(),
611 $entry = $this->store
->retrieveOneById($id, $this->user
->getId());
612 if ($entry != NULL) {
613 Tools
::logm('view link #' . $id);
614 $content = $entry['content'];
615 if (function_exists('tidy_parse_string')) {
616 $tidy = tidy_parse_string($content, array('indent'=>true, 'show-body-only' => true), 'UTF8');
617 $tidy->cleanRepair();
618 $content = $tidy->value
;
622 $flattr = new FlattrItem();
623 $flattr->checkItem($entry['url'], $entry['id']);
626 $tags = $this->store
->retrieveTagsByEntry($entry['id']);
630 'content' => $content,
636 Tools
::logm('error in view call : entry is null');
639 default: # home, favorites, archive and tag views
646 //if id is given - we retrive entries by tag: id is tag id
648 $tpl_vars['tag'] = $this->store
->retrieveTag($id, $this->user
->getId());
649 $tpl_vars['id'] = intval($id);
652 $count = $this->store
->getEntriesByViewCount($view, $this->user
->getId(), $id);
655 $this->pagination
->set_total($count);
656 $page_links = str_replace(array('previous', 'next'), array(_('previous'), _('next')),
657 $this->pagination
->page_links('?view=' . $view . '&sort=' . $_SESSION['sort'] . (($id)?'&id='.$id:'') . '&' ));
658 $tpl_vars['entries'] = $this->store
->getEntriesByView($view, $this->user
->getId(), $this->pagination
->get_limit(), $id);
659 $tpl_vars['page_links'] = $page_links;
660 $tpl_vars['nb_results'] = $count;
662 Tools
::logm('display ' . $view . ' view');
670 * update the password of the current user.
671 * if MODE_DEMO is TRUE, the password can't be updated.
672 * @todo add the return value
673 * @todo set the new password in function header like this updatePassword($newPassword)
676 public function updatePassword()
679 $this->messages
->add('i', _('in demo mode, you can\'t update your password'));
680 Tools
::logm('in demo mode, you can\'t do this');
681 Tools
::redirect('?view=config');
684 if (isset($_POST['password']) && isset($_POST['password_repeat'])) {
685 if ($_POST['password'] == $_POST['password_repeat'] && $_POST['password'] != "") {
686 $this->messages
->add('s', _('your password has been updated'));
687 $this->store
->updatePassword($this->user
->getId(), Tools
::encodeString($_POST['password'] . $this->user
->getUsername()));
689 Tools
::logm('password updated');
693 $this->messages
->add('e', _('the two fields have to be filled & the password must be the same in the two fields'));
694 Tools
::redirect('?view=config');
700 public function updateTheme()
703 if (empty($_POST['theme'])) {
706 # we are not going to change it to the current theme...
707 if ($_POST['theme'] == $this->getTheme()) {
708 $this->messages
->add('w', _('still using the "' . $this->getTheme() . '" theme!'));
709 Tools
::redirect('?view=config');
712 $themes = $this->getInstalledThemes();
713 $actualTheme = false;
715 foreach (array_keys($themes) as $theme) {
716 if ($theme == $_POST['theme']) {
722 if (! $actualTheme) {
723 $this->messages
->add('e', _('that theme does not seem to be installed'));
724 Tools
::redirect('?view=config');
727 $this->store
->updateUserConfig($this->user
->getId(), 'theme', $_POST['theme']);
728 $this->messages
->add('s', _('you have changed your theme preferences'));
730 $currentConfig = $_SESSION['poche_user']->config
;
731 $currentConfig['theme'] = $_POST['theme'];
733 $_SESSION['poche_user']->setConfig($currentConfig);
735 Tools
::redirect('?view=config');
738 public function updateLanguage()
741 if (empty($_POST['language'])) {
744 # we are not going to change it to the current language...
745 if ($_POST['language'] == $this->getLanguage()) {
746 $this->messages
->add('w', _('still using the "' . $this->getLanguage() . '" language!'));
747 Tools
::redirect('?view=config');
750 $languages = $this->getInstalledLanguages();
751 $actualLanguage = false;
753 foreach ($languages as $language) {
754 if ($language['name'] == $_POST['language']) {
755 $actualLanguage = true;
760 if (! $actualLanguage) {
761 $this->messages
->add('e', _('that language does not seem to be installed'));
762 Tools
::redirect('?view=config');
765 $this->store
->updateUserConfig($this->user
->getId(), 'language', $_POST['language']);
766 $this->messages
->add('s', _('you have changed your language preferences'));
768 $currentConfig = $_SESSION['poche_user']->config
;
769 $currentConfig['language'] = $_POST['language'];
771 $_SESSION['poche_user']->setConfig($currentConfig);
773 Tools
::redirect('?view=config');
777 * get credentials from differents sources
778 * it redirects the user to the $referer link
781 private function credentials() {
782 if(isset($_SERVER['PHP_AUTH_USER'])) {
783 return array($_SERVER['PHP_AUTH_USER'],'php_auth',true);
785 if(!empty($_POST['login']) && !empty($_POST['password'])) {
786 return array($_POST['login'],$_POST['password'],false);
788 if(isset($_SERVER['REMOTE_USER'])) {
789 return array($_SERVER['REMOTE_USER'],'http_auth',true);
792 return array(false,false,false);
796 * checks if login & password are correct and save the user in session.
797 * it redirects the user to the $referer link
798 * @param string $referer the url to redirect after login
799 * @todo add the return value
802 public function login($referer)
804 list($login,$password,$isauthenticated)=$this->credentials();
805 if($login === false || $password === false) {
806 $this->messages
->add('e', _('login failed: you have to fill all fields'));
807 Tools
::logm('login failed');
810 if (!empty($login) && !empty($password)) {
811 $user = $this->store
->login($login, Tools
::encodeString($password . $login), $isauthenticated);
812 if ($user != array()) {
813 # Save login into Session
814 $longlastingsession = isset($_POST['longlastingsession']);
815 $passwordTest = ($isauthenticated) ? $user['password'] : Tools
::encodeString($password . $login);
816 Session
::login($user['username'], $user['password'], $login, $passwordTest, $longlastingsession, array('poche_user' => new User($user)));
817 $this->messages
->add('s', _('welcome to your wallabag'));
818 Tools
::logm('login successful');
819 Tools
::redirect($referer);
821 $this->messages
->add('e', _('login failed: bad login or password'));
822 Tools
::logm('login failed');
828 * log out the poche user. It cleans the session.
829 * @todo add the return value
832 public function logout()
834 $this->user
= array();
836 Tools
::logm('logout');
841 * import from Instapaper. poche needs a ./instapaper-export.html file
842 * @todo add the return value
843 * @param string $targetFile the file used for importing
846 private function importFromInstapaper($targetFile)
848 # TODO gestion des articles favs
849 $html = new simple_html_dom();
850 $html->load_file($targetFile);
851 Tools
::logm('starting import from instapaper');
855 foreach($html->find('ol') as $ul)
857 foreach($ul->find('li') as $li)
860 $url = new Url(base64_encode($a[0]->href
));
861 $this->action('add', $url, 0, TRUE);
864 if (STORAGE
== 'postgres') {
865 $sequence = 'entries_id_seq';
867 $last_id = $this->store
->getLastId($sequence);
868 $this->action('toggle_archive', $url, $last_id, TRUE);
872 # the second <ol> is for read links
875 $this->messages
->add('s', _('import from instapaper completed'));
876 Tools
::logm('import from instapaper completed');
881 * import from Pocket. poche needs a ./ril_export.html file
882 * @todo add the return value
883 * @param string $targetFile the file used for importing
886 private function importFromPocket($targetFile)
888 # TODO gestion des articles favs
889 $html = new simple_html_dom();
890 $html->load_file($targetFile);
891 Tools
::logm('starting import from pocket');
895 foreach($html->find('ul') as $ul)
897 foreach($ul->find('li') as $li)
900 $url = new Url(base64_encode($a[0]->href
));
901 $this->action('add', $url, 0, TRUE);
903 if (STORAGE
== 'postgres') {
904 $sequence = 'entries_id_seq';
906 $last_id = $this->store
->getLastId($sequence);
908 $this->action('toggle_archive', $url, $last_id, TRUE);
912 $this->action('add_tag',$url,$last_id,true,false,$tags);
916 # the second <ul> is for read links
919 $this->messages
->add('s', _('import from pocket completed'));
920 Tools
::logm('import from pocket completed');
925 * import from Readability. poche needs a ./readability file
926 * @todo add the return value
927 * @param string $targetFile the file used for importing
930 private function importFromReadability($targetFile)
932 # TODO gestion des articles lus / favs
933 $str_data = file_get_contents($targetFile);
934 $data = json_decode($str_data,true);
935 Tools
::logm('starting import from Readability');
937 foreach ($data as $key => $value) {
941 foreach ($value as $item) {
942 foreach ($item as $attr => $value) {
943 if ($attr == 'article__url') {
944 $url = new Url(base64_encode($value));
947 if (STORAGE
== 'postgres') {
948 $sequence = 'entries_id_seq';
950 if ($value == 'true') {
951 if ($attr == 'favorite') {
954 if ($attr == 'archive') {
961 if (!is_null($url) && $url->isCorrect()) {
962 $this->action('add', $url, 0, TRUE);
965 $last_id = $this->store
->getLastId($sequence);
966 $this->action('toggle_fav', $url, $last_id, TRUE);
969 $last_id = $this->store
->getLastId($sequence);
970 $this->action('toggle_archive', $url, $last_id, TRUE);
975 $this->messages
->add('s', _('import from Readability completed. ' . $count . ' new links.'));
976 Tools
::logm('import from Readability completed');
981 * import from Poche exported file
982 * @param string $targetFile the file used for importing
985 private function importFromPoche($targetFile)
987 $str_data = file_get_contents($targetFile);
988 $data = json_decode($str_data,true);
989 Tools
::logm('starting import from Poche');
993 if (STORAGE
== 'postgres') {
994 $sequence = 'entries_id_seq';
998 foreach ($data as $value) {
1000 $url = new Url(base64_encode($value['url']));
1001 $favorite = ($value['is_fav'] == -1);
1002 $archive = ($value['is_read'] == -1);
1004 # we can add the url
1005 if (!is_null($url) && $url->isCorrect()) {
1007 $this->action('add', $url, 0, TRUE);
1011 $last_id = $this->store
->getLastId($sequence);
1012 $this->action('toggle_fav', $url, $last_id, TRUE);
1015 $last_id = $this->store
->getLastId($sequence);
1016 $this->action('toggle_archive', $url, $last_id, TRUE);
1021 $this->messages
->add('s', _('import from Poche completed. ' . $count . ' new links.'));
1022 Tools
::logm('import from Poche completed');
1027 * import datas into your poche
1028 * @param string $from name of the service to import : pocket, instapaper or readability
1029 * @todo add the return value
1032 public function import($from)
1035 'pocket' => 'importFromPocket',
1036 'readability' => 'importFromReadability',
1037 'instapaper' => 'importFromInstapaper',
1038 'poche' => 'importFromPoche',
1041 if (! isset($providers[$from])) {
1042 $this->messages
->add('e', _('Unknown import provider.'));
1046 $targetDefinition = 'IMPORT_' . strtoupper($from) . '_FILE';
1047 $targetFile = constant($targetDefinition);
1049 if (! defined($targetDefinition)) {
1050 $this->messages
->add('e', _('Incomplete inc/poche/define.inc.php file, please define "' . $targetDefinition . '".'));
1054 if (! file_exists($targetFile)) {
1055 $this->messages
->add('e', _('Could not find required "' . $targetFile . '" import file.'));
1059 $this->$providers[$from]($targetFile);
1063 * export poche entries in json
1064 * @return json all poche entries
1066 public function export()
1068 $entries = $this->store
->retrieveAll($this->user
->getId());
1069 echo $this->tpl
->render('export.twig', array(
1070 'export' => Tools
::renderJson($entries),
1072 Tools
::logm('export view');
1076 * Checks online the latest version of poche and cache it
1077 * @param string $which 'prod' or 'dev'
1078 * @return string latest $which version
1080 private function getPocheVersion($which = 'prod')
1082 $cache_file = CACHE
. '/' . $which;
1084 # checks if the cached version file exists
1085 if (file_exists($cache_file) && (filemtime($cache_file) > (time() - 86400 ))) {
1086 $version = file_get_contents($cache_file);
1088 $version = file_get_contents('http://static.wallabag.org/versions/' . $which);
1089 file_put_contents($cache_file, $version, LOCK_EX
);
1094 public function generateToken()
1096 if (ini_get('open_basedir') === '') {
1097 $token = substr(base64_encode(file_get_contents('/dev/urandom', false, null, 0, 20)), 0, 15);
1100 $token = substr(base64_encode(uniqid(mt_rand(), true)), 0, 20);
1103 $token = str_replace('+', '', $token);
1104 $this->store
->updateUserConfig($this->user
->getId(), 'token', $token);
1105 $currentConfig = $_SESSION['poche_user']->config
;
1106 $currentConfig['token'] = $token;
1107 $_SESSION['poche_user']->setConfig($currentConfig);
1110 public function generateFeeds($token, $user_id, $tag_id, $type = 'home')
1112 $allowed_types = array('home', 'fav', 'archive', 'tag');
1113 $config = $this->store
->getConfigUser($user_id);
1115 if (!in_array($type, $allowed_types) ||
1116 $token != $config['token']) {
1117 die(_('Uh, there is a problem while generating feeds.'));
1121 $feed = new FeedWriter(RSS2
);
1122 $feed->setTitle('wallabag — ' . $type . ' feed');
1123 $feed->setLink(Tools
::getPocheUrl());
1124 $feed->setChannelElement('updated', date(DATE_RSS
, time()));
1125 $feed->setChannelElement('author', 'wallabag');
1127 if ($type == 'tag') {
1128 $entries = $this->store
->retrieveEntriesByTag($tag_id, $user_id);
1131 $entries = $this->store
->getEntriesByView($type, $user_id);
1134 if (count($entries) > 0) {
1135 foreach ($entries as $entry) {
1136 $newItem = $feed->createNewItem();
1137 $newItem->setTitle($entry['title']);
1138 $newItem->setLink(Tools
::getPocheUrl() . '?view=view&id=' . $entry['id']);
1139 $newItem->setDate(time());
1140 $newItem->setDescription($entry['content']);
1141 $feed->addItem($newItem);
1145 $feed->genarateFeed();
1149 public function emptyCache() {
1150 $files = new RecursiveIteratorIterator(
1151 new RecursiveDirectoryIterator(CACHE
, RecursiveDirectoryIterator
::SKIP_DOTS
),
1152 RecursiveIteratorIterator
::CHILD_FIRST
1155 foreach ($files as $fileinfo) {
1156 $todo = ($fileinfo->isDir() ? 'rmdir' : 'unlink');
1157 $todo($fileinfo->getRealPath());
1160 Tools
::logm('empty cache');
1161 $this->messages
->add('s', _('Cache deleted.'));