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 'pt_BR.utf8' => 'Português (Brasil)',
36 'ru_RU.utf8' => 'Pусский',
37 'sl_SI.utf8' => 'Slovenščina',
38 'uk_UA.utf8' => 'Українська',
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()
65 if (isset($_SESSION['poche_user']) && $_SESSION['poche_user'] != array()) {
66 $this->user
= $_SESSION['poche_user'];
68 # fake user, just for install & login screens
69 $this->user
= new User();
70 $this->user
->setConfig($this->getDefaultConfig());
74 $language = $this->user
->getConfigValue('language');
75 putenv('LC_ALL=' . $language);
76 setlocale(LC_ALL
, $language);
77 bindtextdomain($language, LOCALE
);
78 textdomain($language);
81 $this->pagination
= new Paginator($this->user
->getConfigValue('pager'), 'p');
84 $themeDirectory = $this->user
->getConfigValue('theme');
86 if ($themeDirectory === false) {
87 $themeDirectory = DEFAULT_THEME
;
90 $this->currentTheme
= $themeDirectory;
93 $languageDirectory = $this->user
->getConfigValue('language');
95 if ($languageDirectory === false) {
96 $languageDirectory = DEFAULT_THEME
;
99 $this->currentLanguage
= $languageDirectory;
102 public function configFileIsAvailable() {
103 if (! self
::$configFileAvailable) {
104 $this->notInstalledMessage
[] = 'You have to rename inc/poche/config.inc.php.new to inc/poche/config.inc.php.';
112 public function themeIsInstalled() {
114 # Twig is an absolute requirement for Poche to function. Abort immediately if the Composer installer hasn't been run yet
115 if (! self
::$canRenderTemplates) {
116 $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.';
120 if (! is_writable(CACHE
)) {
121 $this->notInstalledMessage
[] = 'You don\'t have write access on cache directory.';
123 self
::$canRenderTemplates = false;
128 # Check if the selected theme and its requirements are present
129 $theme = $this->getTheme();
131 if ($theme != '' && ! is_dir(THEME
. '/' . $theme)) {
132 $this->notInstalledMessage
[] = 'The currently selected theme (' . $theme . ') does not seem to be properly installed (Missing directory: ' . THEME
. '/' . $theme . ')';
134 self
::$canRenderTemplates = false;
139 $themeInfo = $this->getThemeInfo($theme);
140 if (isset($themeInfo['requirements']) && is_array($themeInfo['requirements'])) {
141 foreach ($themeInfo['requirements'] as $requiredTheme) {
142 if (! is_dir(THEME
. '/' . $requiredTheme)) {
143 $this->notInstalledMessage
[] = 'The required "' . $requiredTheme . '" theme is missing for the current theme (' . $theme . ')';
145 self
::$canRenderTemplates = false;
161 * all checks before installation.
162 * @todo move HTML to template
165 public function systemIsInstalled()
169 $configSalt = defined('SALT') ? constant('SALT') : '';
171 if (empty($configSalt)) {
172 $this->notInstalledMessage
[] = 'You have not yet filled in the SALT value in the config.inc.php file.';
175 if (STORAGE
== 'sqlite' && ! file_exists(STORAGE_SQLITE
)) {
176 Tools
::logm('sqlite file doesn\'t exist');
177 $this->notInstalledMessage
[] = 'sqlite file doesn\'t exist, you can find it in install folder. Copy it in /db folder.';
180 if (is_dir(ROOT
. '/install') && ! DEBUG_POCHE
) {
181 $this->notInstalledMessage
[] = 'you have to delete the /install folder before using poche.';
184 if (STORAGE
== 'sqlite' && ! is_writable(STORAGE_SQLITE
)) {
185 Tools
::logm('you don\'t have write access on sqlite file');
186 $this->notInstalledMessage
[] = 'You don\'t have write access on sqlite file.';
197 public function getNotInstalledMessage() {
198 return $this->notInstalledMessage
;
201 private function initTpl()
203 $loaderChain = new Twig_Loader_Chain();
204 $theme = $this->getTheme();
206 # add the current theme as first to the loader chain so Twig will look there first for overridden template files
208 $loaderChain->addLoader(new Twig_Loader_Filesystem(THEME
. '/' . $theme));
209 } catch (Twig_Error_Loader
$e) {
210 # @todo isInstalled() should catch this, inject Twig later
211 die('The currently selected theme (' . $theme . ') does not seem to be properly installed (' . THEME
. '/' . $theme .' is missing)');
214 # add all required themes to the loader chain
215 $themeInfo = $this->getThemeInfo($theme);
216 if (isset($themeInfo['requirements']) && is_array($themeInfo['requirements'])) {
217 foreach ($themeInfo['requirements'] as $requiredTheme) {
219 $loaderChain->addLoader(new Twig_Loader_Filesystem(THEME
. '/' . $requiredTheme));
220 } catch (Twig_Error_Loader
$e) {
221 # @todo isInstalled() should catch this, inject Twig later
222 die('The required "' . $requiredTheme . '" theme is missing for the current theme (' . $theme . ')');
228 $twigParams = array();
230 $twigParams = array('cache' => CACHE
);
233 $this->tpl
= new Twig_Environment($loaderChain, $twigParams);
234 $this->tpl
->addExtension(new Twig_Extensions_Extension_I18n());
236 # filter to display domain name of an url
237 $filter = new Twig_SimpleFilter('getDomain', 'Tools::getDomain');
238 $this->tpl
->addFilter($filter);
240 # filter for reading time
241 $filter = new Twig_SimpleFilter('getReadingTime', 'Tools::getReadingTime');
242 $this->tpl
->addFilter($filter);
245 private function install()
247 Tools
::logm('poche still not installed');
248 echo $this->tpl
->render('install.twig', array(
249 'token' => Session
::getToken(),
250 'theme' => $this->getTheme(),
251 'poche_url' => Tools
::getPocheUrl()
253 if (isset($_GET['install'])) {
254 if (($_POST['password'] == $_POST['password_repeat'])
255 && $_POST['password'] != "" && $_POST['login'] != "") {
256 # let's rock, install poche baby !
257 if ($this->store
->install($_POST['login'], Tools
::encodeString($_POST['password'] . $_POST['login'])))
260 Tools
::logm('poche is now installed');
265 Tools
::logm('error during installation');
272 public function getTheme() {
273 return $this->currentTheme
;
277 * Provides theme information by parsing theme.ini file if present in the theme's root directory.
278 * In all cases, the following data will be returned:
279 * - name: theme's name, or key if the theme is unnamed,
280 * - current: boolean informing if the theme is the current user theme.
282 * @param string $theme Theme key (directory name)
283 * @return array|boolean Theme information, or false if the theme doesn't exist.
285 public function getThemeInfo($theme) {
286 if (!is_dir(THEME
. '/' . $theme)) {
290 $themeIniFile = THEME
. '/' . $theme . '/theme.ini';
291 $themeInfo = array();
293 if (is_file($themeIniFile) && is_readable($themeIniFile)) {
294 $themeInfo = parse_ini_file($themeIniFile);
297 if ($themeInfo === false) {
298 $themeInfo = array();
300 if (!isset($themeInfo['name'])) {
301 $themeInfo['name'] = $theme;
303 $themeInfo['current'] = ($theme === $this->getTheme());
308 public function getInstalledThemes() {
309 $handle = opendir(THEME
);
312 while (($theme = readdir($handle)) !== false) {
313 # Themes are stored in a directory, so all directory names are themes
314 # @todo move theme installation data to database
315 if (!is_dir(THEME
. '/' . $theme) || in_array($theme, array('.', '..'))) {
319 $themes[$theme] = $this->getThemeInfo($theme);
327 public function getLanguage() {
328 return $this->currentLanguage
;
331 public function getInstalledLanguages() {
332 $handle = opendir(LOCALE
);
333 $languages = array();
335 while (($language = readdir($handle)) !== false) {
336 # Languages are stored in a directory, so all directory names are languages
337 # @todo move language installation data to database
338 if (! is_dir(LOCALE
. '/' . $language) || in_array($language, array('..', '.', 'tools'))) {
344 if ($language === $this->getLanguage()) {
348 $languages[] = array('name' => (isset($this->language_names
[$language]) ? $this->language_names
[$language] : $language), 'value' => $language, 'current' => $current);
354 public function getDefaultConfig()
357 'pager' => PAGINATION
,
359 'theme' => DEFAULT_THEME
364 * Call action (mark as fav, archive, delete, etc.)
366 public function action($action, Url
$url, $id = 0, $import = FALSE, $autoclose = FALSE, $tags = null)
372 $content = Tools
::getPageContent($url);
373 $title = ($content['rss']['channel']['item']['title'] != '') ? $content['rss']['channel']['item']['title'] : _('Untitled');
374 $body = $content['rss']['channel']['item']['description'];
376 // clean content from prevent xss attack
377 $config = HTMLPurifier_Config
::createDefault();
378 $config->set('Cache.SerializerPath', CACHE
);
379 $purifier = new HTMLPurifier($config);
380 $title = $purifier->purify($title);
381 $body = $purifier->purify($body);
388 //search for possible duplicate if not in import mode
391 $duplicate = $this->store
->retrieveOneByURL($url->getUrl(), $this->user
->getId());
394 if ($this->store
->add($url->getUrl(), $title, $body, $this->user
->getId())) {
395 Tools
::logm('add link ' . $url->getUrl());
397 if (STORAGE
== 'postgres') {
398 $sequence = 'entries_id_seq';
400 $last_id = $this->store
->getLastId($sequence);
401 if (DOWNLOAD_PICTURES
) {
402 $content = filtre_picture($body, $url->getUrl(), $last_id);
403 Tools
::logm('updating content article');
404 $this->store
->updateContent($last_id, $content, $this->user
->getId());
407 if ($duplicate != NULL) {
408 // 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
409 Tools
::logm('link ' . $url->getUrl() . ' is a duplicate');
410 // 1) - preserve tags and favorite, then drop old entry
411 $this->store
->reassignTags($duplicate['id'], $last_id);
412 if ($duplicate['is_fav']) {
413 $this->store
->favoriteById($last_id, $this->user
->getId());
415 if ($this->store
->deleteById($duplicate['id'], $this->user
->getId())) {
416 Tools
::logm('previous link ' . $url->getUrl() .' entry deleted');
421 $this->messages
->add('s', _('the link has been added successfully'));
426 $this->messages
->add('e', _('error during insertion : the link wasn\'t added'));
427 Tools
::logm('error during insertion : the link wasn\'t added ' . $url->getUrl());
432 if ($autoclose == TRUE) {
433 Tools
::redirect('?view=home');
435 Tools
::redirect('?view=home&closewin=true');
440 $msg = 'delete link #' . $id;
441 if ($this->store
->deleteById($id, $this->user
->getId())) {
442 if (DOWNLOAD_PICTURES
) {
443 remove_directory(ABS_PATH
. $id);
445 $this->messages
->add('s', _('the link has been deleted successfully'));
448 $this->messages
->add('e', _('the link wasn\'t deleted'));
449 $msg = 'error : can\'t delete link #' . $id;
452 Tools
::redirect('?');
455 $this->store
->favoriteById($id, $this->user
->getId());
456 Tools
::logm('mark as favorite link #' . $id);
461 case 'toggle_archive' :
462 $this->store
->archiveById($id, $this->user
->getId());
463 Tools
::logm('archive link #' . $id);
469 $this->store
->archiveAll($this->user
->getId());
470 Tools
::logm('archive all links');
478 $tags = explode(',', $tags);
481 $tags = explode(',', $_POST['value']);
482 $entry_id = $_POST['entry_id'];
484 $entry = $this->store
->retrieveOneById($entry_id, $this->user
->getId());
486 $this->messages
->add('e', _('Article not found!'));
487 Tools
::logm('error : article not found');
490 //get all already set tags to preven duplicates
491 $already_set_tags = array();
492 $entry_tags = $this->store
->retrieveTagsByEntry($entry_id);
493 foreach ($entry_tags as $tag) {
494 $already_set_tags[] = $tag['value'];
496 foreach($tags as $key => $tag_value) {
497 $value = trim($tag_value);
498 if ($value && !in_array($value, $already_set_tags)) {
499 $tag = $this->store
->retrieveTagByValue($value);
503 $tag = $this->store
->createTag($value);
505 if (STORAGE
== 'postgres') {
506 $sequence = 'tags_id_seq';
508 $tag_id = $this->store
->getLastId($sequence);
511 $tag_id = $tag['id'];
514 # we assign the tag to the article
515 $this->store
->setTagToEntry($tag_id, $entry_id);
523 $tag_id = $_GET['tag_id'];
524 $entry = $this->store
->retrieveOneById($id, $this->user
->getId());
526 $this->messages
->add('e', _('Article not found!'));
527 Tools
::logm('error : article not found');
530 $this->store
->removeTagForEntry($id, $tag_id);
538 function displayView($view, $id = 0)
545 $dev_infos = $this->getPocheVersion('dev');
546 $dev = trim($dev_infos[0]);
547 $check_time_dev = date('d-M-Y H:i', $dev_infos[1]);
548 $prod_infos = $this->getPocheVersion('prod');
549 $prod = trim($prod_infos[0]);
550 $check_time_prod = date('d-M-Y H:i', $prod_infos[1]);
551 $compare_dev = version_compare(POCHE
, $dev);
552 $compare_prod = version_compare(POCHE
, $prod);
553 $themes = $this->getInstalledThemes();
554 $languages = $this->getInstalledLanguages();
555 $token = $this->user
->getConfigValue('token');
556 $http_auth = (isset($_SERVER['PHP_AUTH_USER']) || isset($_SERVER['REMOTE_USER'])) ? true : false;
559 'languages' => $languages,
562 'check_time_dev' => $check_time_dev,
563 'check_time_prod' => $check_time_prod,
564 'compare_dev' => $compare_dev,
565 'compare_prod' => $compare_prod,
567 'user_id' => $this->user
->getId(),
568 'http_auth' => $http_auth,
570 Tools
::logm('config view');
574 $entry = $this->store
->retrieveOneById($id, $this->user
->getId());
576 $this->messages
->add('e', _('Article not found!'));
577 Tools
::logm('error : article not found');
580 $tags = $this->store
->retrieveTagsByEntry($id);
588 $token = $this->user
->getConfigValue('token');
589 //if term is set - search tags for this term
590 $term = Tools
::checkVar('term');
591 $tags = $this->store
->retrieveAllTags($this->user
->getId(), $term);
592 if (Tools
::isAjaxRequest()) {
594 foreach ($tags as $tag) {
595 $result[] = $tag['value'];
597 echo json_encode($result);
602 'user_id' => $this->user
->getId(),
608 if (isset($_POST['search'])){
609 $search = $_POST['search'];
610 $tpl_vars['entries'] = $this->store
->search($search);
611 $tpl_vars['nb_results'] = count($tpl_vars['entries']);
615 $entry = $this->store
->retrieveOneById($id, $this->user
->getId());
616 if ($entry != NULL) {
617 Tools
::logm('view link #' . $id);
618 $content = $entry['content'];
619 if (function_exists('tidy_parse_string')) {
620 $tidy = tidy_parse_string($content, array('indent'=>true, 'show-body-only' => true), 'UTF8');
621 $tidy->cleanRepair();
622 $content = $tidy->value
;
626 $flattr = new FlattrItem();
627 $flattr->checkItem($entry['url'], $entry['id']);
630 $tags = $this->store
->retrieveTagsByEntry($entry['id']);
634 'content' => $content,
640 Tools
::logm('error in view call : entry is null');
643 default: # home, favorites, archive and tag views
648 'listmode' => (isset($_COOKIE['listmode']) ? true : false),
651 //if id is given - we retrive entries by tag: id is tag id
653 $tpl_vars['tag'] = $this->store
->retrieveTag($id, $this->user
->getId());
654 $tpl_vars['id'] = intval($id);
657 $count = $this->store
->getEntriesByViewCount($view, $this->user
->getId(), $id);
660 $this->pagination
->set_total($count);
661 $page_links = str_replace(array('previous', 'next'), array(_('previous'), _('next')),
662 $this->pagination
->page_links('?view=' . $view . '&sort=' . $_SESSION['sort'] . (($id)?'&id='.$id:'') . '&' ));
663 $tpl_vars['entries'] = $this->store
->getEntriesByView($view, $this->user
->getId(), $this->pagination
->get_limit(), $id);
664 $tpl_vars['page_links'] = $page_links;
665 $tpl_vars['nb_results'] = $count;
667 Tools
::logm('display ' . $view . ' view');
675 * update the password of the current user.
676 * if MODE_DEMO is TRUE, the password can't be updated.
677 * @todo add the return value
678 * @todo set the new password in function header like this updatePassword($newPassword)
681 public function updatePassword()
684 $this->messages
->add('i', _('in demo mode, you can\'t update your password'));
685 Tools
::logm('in demo mode, you can\'t do this');
686 Tools
::redirect('?view=config');
689 if (isset($_POST['password']) && isset($_POST['password_repeat'])) {
690 if ($_POST['password'] == $_POST['password_repeat'] && $_POST['password'] != "") {
691 $this->messages
->add('s', _('your password has been updated'));
692 $this->store
->updatePassword($this->user
->getId(), Tools
::encodeString($_POST['password'] . $this->user
->getUsername()));
694 Tools
::logm('password updated');
698 $this->messages
->add('e', _('the two fields have to be filled & the password must be the same in the two fields'));
699 Tools
::redirect('?view=config');
705 public function updateTheme()
708 if (empty($_POST['theme'])) {
711 # we are not going to change it to the current theme...
712 if ($_POST['theme'] == $this->getTheme()) {
713 $this->messages
->add('w', _('still using the "' . $this->getTheme() . '" theme!'));
714 Tools
::redirect('?view=config');
717 $themes = $this->getInstalledThemes();
718 $actualTheme = false;
720 foreach (array_keys($themes) as $theme) {
721 if ($theme == $_POST['theme']) {
727 if (! $actualTheme) {
728 $this->messages
->add('e', _('that theme does not seem to be installed'));
729 Tools
::redirect('?view=config');
732 $this->store
->updateUserConfig($this->user
->getId(), 'theme', $_POST['theme']);
733 $this->messages
->add('s', _('you have changed your theme preferences'));
735 $currentConfig = $_SESSION['poche_user']->config
;
736 $currentConfig['theme'] = $_POST['theme'];
738 $_SESSION['poche_user']->setConfig($currentConfig);
742 Tools
::redirect('?view=config');
745 public function updateLanguage()
748 if (empty($_POST['language'])) {
751 # we are not going to change it to the current language...
752 if ($_POST['language'] == $this->getLanguage()) {
753 $this->messages
->add('w', _('still using the "' . $this->getLanguage() . '" language!'));
754 Tools
::redirect('?view=config');
757 $languages = $this->getInstalledLanguages();
758 $actualLanguage = false;
760 foreach ($languages as $language) {
761 if ($language['value'] == $_POST['language']) {
762 $actualLanguage = true;
767 if (! $actualLanguage) {
768 $this->messages
->add('e', _('that language does not seem to be installed'));
769 Tools
::redirect('?view=config');
772 $this->store
->updateUserConfig($this->user
->getId(), 'language', $_POST['language']);
773 $this->messages
->add('s', _('you have changed your language preferences'));
775 $currentConfig = $_SESSION['poche_user']->config
;
776 $currentConfig['language'] = $_POST['language'];
778 $_SESSION['poche_user']->setConfig($currentConfig);
782 Tools
::redirect('?view=config');
785 * get credentials from differents sources
786 * it redirects the user to the $referer link
789 private function credentials() {
790 if(isset($_SERVER['PHP_AUTH_USER'])) {
791 return array($_SERVER['PHP_AUTH_USER'],'php_auth',true);
793 if(!empty($_POST['login']) && !empty($_POST['password'])) {
794 return array($_POST['login'],$_POST['password'],false);
796 if(isset($_SERVER['REMOTE_USER'])) {
797 return array($_SERVER['REMOTE_USER'],'http_auth',true);
800 return array(false,false,false);
804 * checks if login & password are correct and save the user in session.
805 * it redirects the user to the $referer link
806 * @param string $referer the url to redirect after login
807 * @todo add the return value
810 public function login($referer)
812 list($login,$password,$isauthenticated)=$this->credentials();
813 if($login === false || $password === false) {
814 $this->messages
->add('e', _('login failed: you have to fill all fields'));
815 Tools
::logm('login failed');
818 if (!empty($login) && !empty($password)) {
819 $user = $this->store
->login($login, Tools
::encodeString($password . $login), $isauthenticated);
820 if ($user != array()) {
821 # Save login into Session
822 $longlastingsession = isset($_POST['longlastingsession']);
823 $passwordTest = ($isauthenticated) ? $user['password'] : Tools
::encodeString($password . $login);
824 Session
::login($user['username'], $user['password'], $login, $passwordTest, $longlastingsession, array('poche_user' => new User($user)));
825 $this->messages
->add('s', _('welcome to your wallabag'));
826 Tools
::logm('login successful');
827 Tools
::redirect($referer);
829 $this->messages
->add('e', _('login failed: bad login or password'));
830 Tools
::logm('login failed');
836 * log out the poche user. It cleans the session.
837 * @todo add the return value
840 public function logout()
842 $this->user
= array();
844 Tools
::logm('logout');
849 * import from Instapaper. poche needs a ./instapaper-export.html file
850 * @todo add the return value
851 * @param string $targetFile the file used for importing
854 private function importFromInstapaper($targetFile)
856 # TODO gestion des articles favs
857 $html = new simple_html_dom();
858 $html->load_file($targetFile);
859 Tools
::logm('starting import from instapaper');
863 foreach($html->find('ol') as $ul)
865 foreach($ul->find('li') as $li)
868 $url = new Url(base64_encode($a[0]->href
));
869 $this->action('add', $url, 0, TRUE);
872 if (STORAGE
== 'postgres') {
873 $sequence = 'entries_id_seq';
875 $last_id = $this->store
->getLastId($sequence);
876 $this->action('toggle_archive', $url, $last_id, TRUE);
880 # the second <ol> is for read links
884 $unlink = unlink($targetFile);
885 $this->messages
->add('s', _('import from instapaper completed. You have to execute the cron to fetch content.'));
886 Tools
::logm('import from instapaper completed');
891 * import from Pocket. poche needs a ./ril_export.html file
892 * @todo add the return value
893 * @param string $targetFile the file used for importing
896 private function importFromPocket($targetFile)
898 # TODO gestion des articles favs
899 $html = new simple_html_dom();
900 $html->load_file($targetFile);
901 Tools
::logm('starting import from pocket');
905 foreach($html->find('ul') as $ul)
907 foreach($ul->find('li') as $li)
910 $url = new Url(base64_encode($a[0]->href
));
911 $this->action('add', $url, 0, TRUE);
913 if (STORAGE
== 'postgres') {
914 $sequence = 'entries_id_seq';
916 $last_id = $this->store
->getLastId($sequence);
918 $this->action('toggle_archive', $url, $last_id, TRUE);
922 $this->action('add_tag',$url,$last_id,true,false,$tags);
926 # the second <ul> is for read links
930 $unlink = unlink($targetFile);
931 $this->messages
->add('s', _('import from pocket completed. You have to execute the cron to fetch content.'));
932 Tools
::logm('import from pocket completed');
937 * import from Readability. poche needs a ./readability file
938 * @todo add the return value
939 * @param string $targetFile the file used for importing
942 private function importFromReadability($targetFile)
944 # TODO gestion des articles lus / favs
945 $str_data = file_get_contents($targetFile);
946 $data = json_decode($str_data,true);
947 Tools
::logm('starting import from Readability');
949 foreach ($data as $key => $value) {
953 foreach ($value as $item) {
954 foreach ($item as $attr => $value) {
955 if ($attr == 'article__url') {
956 $url = new Url(base64_encode($value));
959 if (STORAGE
== 'postgres') {
960 $sequence = 'entries_id_seq';
962 if ($value == 'true') {
963 if ($attr == 'favorite') {
966 if ($attr == 'archive') {
973 if (!is_null($url) && $url->isCorrect()) {
974 $this->action('add', $url, 0, TRUE);
977 $last_id = $this->store
->getLastId($sequence);
978 $this->action('toggle_fav', $url, $last_id, TRUE);
981 $last_id = $this->store
->getLastId($sequence);
982 $this->action('toggle_archive', $url, $last_id, TRUE);
989 $this->messages
->add('s', _('import from Readability completed. You have to execute the cron to fetch content.'));
990 Tools
::logm('import from Readability completed');
995 * import from Poche exported file
996 * @param string $targetFile the file used for importing
999 private function importFromPoche($targetFile)
1001 $str_data = file_get_contents($targetFile);
1002 $data = json_decode($str_data,true);
1003 Tools
::logm('starting import from Poche');
1007 if (STORAGE
== 'postgres') {
1008 $sequence = 'entries_id_seq';
1012 foreach ($data as $value) {
1014 $url = new Url(base64_encode($value['url']));
1015 $favorite = ($value['is_fav'] == -1);
1016 $archive = ($value['is_read'] == -1);
1018 # we can add the url
1019 if (!is_null($url) && $url->isCorrect()) {
1021 $this->action('add', $url, 0, TRUE);
1025 $last_id = $this->store
->getLastId($sequence);
1026 $this->action('toggle_fav', $url, $last_id, TRUE);
1029 $last_id = $this->store
->getLastId($sequence);
1030 $this->action('toggle_archive', $url, $last_id, TRUE);
1036 unlink($targetFile);
1037 $this->messages
->add('s', _('import from Poche completed. You have to execute the cron to fetch content.'));
1038 Tools
::logm('import from Poche completed');
1043 * import datas into your poche
1044 * @param string $from name of the service to import : pocket, instapaper or readability
1045 * @todo add the return value
1048 public function import($from)
1051 'pocket' => 'importFromPocket',
1052 'readability' => 'importFromReadability',
1053 'instapaper' => 'importFromInstapaper',
1054 'poche' => 'importFromPoche',
1057 if (! isset($providers[$from])) {
1058 $this->messages
->add('e', _('Unknown import provider.'));
1062 $targetFile = CACHE
. '/' . constant(strtoupper($from) . '_FILE');
1064 if (! file_exists($targetFile)) {
1065 $this->messages
->add('e', _('Could not find required "' . $targetFile . '" import file.'));
1069 $this->$providers[$from]($targetFile);
1072 public function uploadFile() {
1073 if(isset($_FILES['file']))
1076 $file = basename($_FILES['file']['name']);
1077 if(move_uploaded_file($_FILES['file']['tmp_name'], $dir . $file)) {
1078 $this->messages
->add('s', _('File uploaded. You can now execute import.'));
1081 $this->messages
->add('e', _('Error while importing file. Do you have access to upload it?'));
1085 Tools
::redirect('?view=config');
1089 * export poche entries in json
1090 * @return json all poche entries
1092 public function export()
1094 $entries = $this->store
->retrieveAll($this->user
->getId());
1095 echo $this->tpl
->render('export.twig', array(
1096 'export' => Tools
::renderJson($entries),
1098 Tools
::logm('export view');
1102 * Checks online the latest version of poche and cache it
1103 * @param string $which 'prod' or 'dev'
1104 * @return string latest $which version
1106 private function getPocheVersion($which = 'prod')
1108 $cache_file = CACHE
. '/' . $which;
1109 $check_time = time();
1111 # checks if the cached version file exists
1112 if (file_exists($cache_file) && (filemtime($cache_file) > (time() - 86400 ))) {
1113 $version = file_get_contents($cache_file);
1114 $check_time = filemtime($cache_file);
1116 $version = file_get_contents('http://static.wallabag.org/versions/' . $which);
1117 file_put_contents($cache_file, $version, LOCK_EX
);
1119 return array($version, $check_time);
1122 public function generateToken()
1124 if (ini_get('open_basedir') === '') {
1125 $token = substr(base64_encode(file_get_contents('/dev/urandom', false, null, 0, 20)), 0, 15);
1128 $token = substr(base64_encode(uniqid(mt_rand(), true)), 0, 20);
1131 $token = str_replace('+', '', $token);
1132 $this->store
->updateUserConfig($this->user
->getId(), 'token', $token);
1133 $currentConfig = $_SESSION['poche_user']->config
;
1134 $currentConfig['token'] = $token;
1135 $_SESSION['poche_user']->setConfig($currentConfig);
1139 public function generateFeeds($token, $user_id, $tag_id, $type = 'home')
1141 $allowed_types = array('home', 'fav', 'archive', 'tag');
1142 $config = $this->store
->getConfigUser($user_id);
1144 if ($config == null) {
1145 die(_('User with this id (' . $user_id . ') does not exist.'));
1148 if (!in_array($type, $allowed_types) ||
1149 $token != $config['token']) {
1150 die(_('Uh, there is a problem while generating feeds.'));
1154 $feed = new FeedWriter(RSS2
);
1155 $feed->setTitle('wallabag — ' . $type . ' feed');
1156 $feed->setLink(Tools
::getPocheUrl());
1157 $feed->setChannelElement('pubDate', date(DATE_RSS
, time()));
1158 $feed->setChannelElement('generator', 'wallabag');
1159 $feed->setDescription('wallabag ' . $type . ' elements');
1161 if ($type == 'tag') {
1162 $entries = $this->store
->retrieveEntriesByTag($tag_id, $user_id);
1165 $entries = $this->store
->getEntriesByView($type, $user_id);
1168 if (count($entries) > 0) {
1169 foreach ($entries as $entry) {
1170 $newItem = $feed->createNewItem();
1171 $newItem->setTitle($entry['title']);
1172 $newItem->setLink($entry['url']);
1173 $newItem->setDate(time());
1174 $newItem->setDescription($entry['content']);
1175 $feed->addItem($newItem);
1179 $feed->genarateFeed();
1183 public function emptyCache() {
1184 $files = new RecursiveIteratorIterator(
1185 new RecursiveDirectoryIterator(CACHE
, RecursiveDirectoryIterator
::SKIP_DOTS
),
1186 RecursiveIteratorIterator
::CHILD_FIRST
1189 foreach ($files as $fileinfo) {
1190 $todo = ($fileinfo->isDir() ? 'rmdir' : 'unlink');
1191 $todo($fileinfo->getRealPath());
1194 Tools
::logm('empty cache');
1195 $this->messages
->add('s', _('Cache deleted.'));