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)
371 $content = Tools
::getPageContent($url);
372 $title = ($content['rss']['channel']['item']['title'] != '') ? $content['rss']['channel']['item']['title'] : _('Untitled');
373 $body = $content['rss']['channel']['item']['description'];
375 // clean content from prevent xss attack
376 $purifier = $this->getPurifier();
377 $title = $purifier->purify($title);
378 $body = $purifier->purify($body);
380 //search for possible duplicate
382 $duplicate = $this->store
->retrieveOneByURL($url->getUrl(), $this->user
->getId());
384 $last_id = $this->store
->add($url->getUrl(), $title, $body, $this->user
->getId());
386 Tools
::logm('add link ' . $url->getUrl());
387 if (DOWNLOAD_PICTURES
) {
388 $content = filtre_picture($body, $url->getUrl(), $last_id);
389 Tools
::logm('updating content article');
390 $this->store
->updateContent($last_id, $content, $this->user
->getId());
393 if ($duplicate != NULL) {
394 // 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
395 Tools
::logm('link ' . $url->getUrl() . ' is a duplicate');
396 // 1) - preserve tags and favorite, then drop old entry
397 $this->store
->reassignTags($duplicate['id'], $last_id);
398 if ($duplicate['is_fav']) {
399 $this->store
->favoriteById($last_id, $this->user
->getId());
401 if ($this->store
->deleteById($duplicate['id'], $this->user
->getId())) {
402 Tools
::logm('previous link ' . $url->getUrl() .' entry deleted');
406 $this->messages
->add('s', _('the link has been added successfully'));
409 $this->messages
->add('e', _('error during insertion : the link wasn\'t added'));
410 Tools
::logm('error during insertion : the link wasn\'t added ' . $url->getUrl());
413 if ($autoclose == TRUE) {
414 Tools
::redirect('?view=home');
416 Tools
::redirect('?view=home&closewin=true');
420 $msg = 'delete link #' . $id;
421 if ($this->store
->deleteById($id, $this->user
->getId())) {
422 if (DOWNLOAD_PICTURES
) {
423 remove_directory(ABS_PATH
. $id);
425 $this->messages
->add('s', _('the link has been deleted successfully'));
428 $this->messages
->add('e', _('the link wasn\'t deleted'));
429 $msg = 'error : can\'t delete link #' . $id;
432 Tools
::redirect('?');
435 $this->store
->favoriteById($id, $this->user
->getId());
436 Tools
::logm('mark as favorite link #' . $id);
439 case 'toggle_archive' :
440 $this->store
->archiveById($id, $this->user
->getId());
441 Tools
::logm('archive link #' . $id);
445 $this->store
->archiveAll($this->user
->getId());
446 Tools
::logm('archive all links');
450 $tags = explode(',', $_POST['value']);
451 $entry_id = $_POST['entry_id'];
452 $entry = $this->store
->retrieveOneById($entry_id, $this->user
->getId());
454 $this->messages
->add('e', _('Article not found!'));
455 Tools
::logm('error : article not found');
458 //get all already set tags to preven duplicates
459 $already_set_tags = array();
460 $entry_tags = $this->store
->retrieveTagsByEntry($entry_id);
461 foreach ($entry_tags as $tag) {
462 $already_set_tags[] = $tag['value'];
464 foreach($tags as $key => $tag_value) {
465 $value = trim($tag_value);
466 if ($value && !in_array($value, $already_set_tags)) {
467 $tag = $this->store
->retrieveTagByValue($value);
471 $tag = $this->store
->createTag($value);
473 if (STORAGE
== 'postgres') {
474 $sequence = 'tags_id_seq';
476 $tag_id = $this->store
->getLastId($sequence);
479 $tag_id = $tag['id'];
482 # we assign the tag to the article
483 $this->store
->setTagToEntry($tag_id, $entry_id);
489 $tag_id = $_GET['tag_id'];
490 $entry = $this->store
->retrieveOneById($id, $this->user
->getId());
492 $this->messages
->add('e', _('Article not found!'));
493 Tools
::logm('error : article not found');
496 $this->store
->removeTagForEntry($id, $tag_id);
504 function displayView($view, $id = 0)
511 $dev_infos = $this->getPocheVersion('dev');
512 $dev = trim($dev_infos[0]);
513 $check_time_dev = date('d-M-Y H:i', $dev_infos[1]);
514 $prod_infos = $this->getPocheVersion('prod');
515 $prod = trim($prod_infos[0]);
516 $check_time_prod = date('d-M-Y H:i', $prod_infos[1]);
517 $compare_dev = version_compare(POCHE
, $dev);
518 $compare_prod = version_compare(POCHE
, $prod);
519 $themes = $this->getInstalledThemes();
520 $languages = $this->getInstalledLanguages();
521 $token = $this->user
->getConfigValue('token');
522 $http_auth = (isset($_SERVER['PHP_AUTH_USER']) || isset($_SERVER['REMOTE_USER'])) ? true : false;
525 'languages' => $languages,
528 'check_time_dev' => $check_time_dev,
529 'check_time_prod' => $check_time_prod,
530 'compare_dev' => $compare_dev,
531 'compare_prod' => $compare_prod,
533 'user_id' => $this->user
->getId(),
534 'http_auth' => $http_auth,
536 Tools
::logm('config view');
540 $entry = $this->store
->retrieveOneById($id, $this->user
->getId());
542 $this->messages
->add('e', _('Article not found!'));
543 Tools
::logm('error : article not found');
546 $tags = $this->store
->retrieveTagsByEntry($id);
554 $token = $this->user
->getConfigValue('token');
555 //if term is set - search tags for this term
556 $term = Tools
::checkVar('term');
557 $tags = $this->store
->retrieveAllTags($this->user
->getId(), $term);
558 if (Tools
::isAjaxRequest()) {
560 foreach ($tags as $tag) {
561 $result[] = $tag['value'];
563 echo json_encode($result);
568 'user_id' => $this->user
->getId(),
573 if (isset($_GET['search'])) {
574 $search = filter_var($_GET['search'], FILTER_SANITIZE_STRING
);
575 $tpl_vars['entries'] = $this->store
->search($search, $this->user
->getId());
576 $count = count($tpl_vars['entries']);
577 $this->pagination
->set_total($count);
578 $page_links = str_replace(array('previous', 'next'), array(_('previous'), _('next')),
579 $this->pagination
->page_links('?view=' . $view . '?search=' . $search . '&sort=' . $_SESSION['sort'] . '&' ));
580 $tpl_vars['page_links'] = $page_links;
581 $tpl_vars['nb_results'] = $count;
582 $tpl_vars['search_term'] = $search;
586 $entry = $this->store
->retrieveOneById($id, $this->user
->getId());
587 if ($entry != NULL) {
588 Tools
::logm('view link #' . $id);
589 $content = $entry['content'];
590 if (function_exists('tidy_parse_string')) {
591 $tidy = tidy_parse_string($content, array('indent'=>true, 'show-body-only' => true), 'UTF8');
592 $tidy->cleanRepair();
593 $content = $tidy->value
;
597 $flattr = new FlattrItem();
598 $flattr->checkItem($entry['url'], $entry['id']);
601 $tags = $this->store
->retrieveTagsByEntry($entry['id']);
605 'content' => $content,
611 Tools
::logm('error in view call : entry is null');
614 default: # home, favorites, archive and tag views
619 'listmode' => (isset($_COOKIE['listmode']) ? true : false),
622 //if id is given - we retrive entries by tag: id is tag id
624 $tpl_vars['tag'] = $this->store
->retrieveTag($id, $this->user
->getId());
625 $tpl_vars['id'] = intval($id);
628 $count = $this->store
->getEntriesByViewCount($view, $this->user
->getId(), $id);
631 $this->pagination
->set_total($count);
632 $page_links = str_replace(array('previous', 'next'), array(_('previous'), _('next')),
633 $this->pagination
->page_links('?view=' . $view . '&sort=' . $_SESSION['sort'] . (($id)?'&id='.$id:'') . '&' ));
634 $tpl_vars['entries'] = $this->store
->getEntriesByView($view, $this->user
->getId(), $this->pagination
->get_limit(), $id);
635 $tpl_vars['page_links'] = $page_links;
636 $tpl_vars['nb_results'] = $count;
638 Tools
::logm('display ' . $view . ' view');
646 * update the password of the current user.
647 * if MODE_DEMO is TRUE, the password can't be updated.
648 * @todo add the return value
649 * @todo set the new password in function header like this updatePassword($newPassword)
652 public function updatePassword()
655 $this->messages
->add('i', _('in demo mode, you can\'t update your password'));
656 Tools
::logm('in demo mode, you can\'t do this');
657 Tools
::redirect('?view=config');
660 if (isset($_POST['password']) && isset($_POST['password_repeat'])) {
661 if ($_POST['password'] == $_POST['password_repeat'] && $_POST['password'] != "") {
662 $this->messages
->add('s', _('your password has been updated'));
663 $this->store
->updatePassword($this->user
->getId(), Tools
::encodeString($_POST['password'] . $this->user
->getUsername()));
665 Tools
::logm('password updated');
669 $this->messages
->add('e', _('the two fields have to be filled & the password must be the same in the two fields'));
670 Tools
::redirect('?view=config');
676 public function updateTheme()
679 if (empty($_POST['theme'])) {
682 # we are not going to change it to the current theme...
683 if ($_POST['theme'] == $this->getTheme()) {
684 $this->messages
->add('w', _('still using the "' . $this->getTheme() . '" theme!'));
685 Tools
::redirect('?view=config');
688 $themes = $this->getInstalledThemes();
689 $actualTheme = false;
691 foreach (array_keys($themes) as $theme) {
692 if ($theme == $_POST['theme']) {
698 if (! $actualTheme) {
699 $this->messages
->add('e', _('that theme does not seem to be installed'));
700 Tools
::redirect('?view=config');
703 $this->store
->updateUserConfig($this->user
->getId(), 'theme', $_POST['theme']);
704 $this->messages
->add('s', _('you have changed your theme preferences'));
706 $currentConfig = $_SESSION['poche_user']->config
;
707 $currentConfig['theme'] = $_POST['theme'];
709 $_SESSION['poche_user']->setConfig($currentConfig);
713 Tools
::redirect('?view=config');
716 public function updateLanguage()
719 if (empty($_POST['language'])) {
722 # we are not going to change it to the current language...
723 if ($_POST['language'] == $this->getLanguage()) {
724 $this->messages
->add('w', _('still using the "' . $this->getLanguage() . '" language!'));
725 Tools
::redirect('?view=config');
728 $languages = $this->getInstalledLanguages();
729 $actualLanguage = false;
731 foreach ($languages as $language) {
732 if ($language['value'] == $_POST['language']) {
733 $actualLanguage = true;
738 if (! $actualLanguage) {
739 $this->messages
->add('e', _('that language does not seem to be installed'));
740 Tools
::redirect('?view=config');
743 $this->store
->updateUserConfig($this->user
->getId(), 'language', $_POST['language']);
744 $this->messages
->add('s', _('you have changed your language preferences'));
746 $currentConfig = $_SESSION['poche_user']->config
;
747 $currentConfig['language'] = $_POST['language'];
749 $_SESSION['poche_user']->setConfig($currentConfig);
753 Tools
::redirect('?view=config');
756 * get credentials from differents sources
757 * it redirects the user to the $referer link
760 private function credentials() {
761 if(isset($_SERVER['PHP_AUTH_USER'])) {
762 return array($_SERVER['PHP_AUTH_USER'],'php_auth',true);
764 if(!empty($_POST['login']) && !empty($_POST['password'])) {
765 return array($_POST['login'],$_POST['password'],false);
767 if(isset($_SERVER['REMOTE_USER'])) {
768 return array($_SERVER['REMOTE_USER'],'http_auth',true);
771 return array(false,false,false);
775 * checks if login & password are correct and save the user in session.
776 * it redirects the user to the $referer link
777 * @param string $referer the url to redirect after login
778 * @todo add the return value
781 public function login($referer)
783 list($login,$password,$isauthenticated)=$this->credentials();
784 if($login === false || $password === false) {
785 $this->messages
->add('e', _('login failed: you have to fill all fields'));
786 Tools
::logm('login failed');
789 if (!empty($login) && !empty($password)) {
790 $user = $this->store
->login($login, Tools
::encodeString($password . $login), $isauthenticated);
791 if ($user != array()) {
792 # Save login into Session
793 $longlastingsession = isset($_POST['longlastingsession']);
794 $passwordTest = ($isauthenticated) ? $user['password'] : Tools
::encodeString($password . $login);
795 Session
::login($user['username'], $user['password'], $login, $passwordTest, $longlastingsession, array('poche_user' => new User($user)));
796 $this->messages
->add('s', _('welcome to your wallabag'));
797 Tools
::logm('login successful');
798 Tools
::redirect($referer);
800 $this->messages
->add('e', _('login failed: bad login or password'));
801 Tools
::logm('login failed');
807 * log out the poche user. It cleans the session.
808 * @todo add the return value
811 public function logout()
813 $this->user
= array();
815 Tools
::logm('logout');
820 * import datas into your poche
823 public function import() {
825 if (!defined('IMPORT_LIMIT')) {
826 define('IMPORT_LIMIT', 5);
828 if (!defined('IMPORT_DELAY')) {
829 define('IMPORT_DELAY', 5);
832 if ( isset($_FILES['file']) ) {
833 Tools
::logm('Import stated: parsing file');
835 // assume, that file is in json format
836 $str_data = file_get_contents($_FILES['file']['tmp_name']);
837 $data = json_decode($str_data, true);
839 if ( $data === null ) {
840 //not json - assume html
841 $html = new simple_html_dom();
842 $html->load_file($_FILES['file']['tmp_name']);
845 foreach (array('ol','ul') as $list) {
846 foreach ($html->find($list) as $ul) {
847 foreach ($ul->find('li') as $li) {
850 $tmpEntry['url'] = $a[0]->href
;
851 $tmpEntry['tags'] = $a[0]->tags
;
852 $tmpEntry['is_read'] = $read;
853 if ($tmpEntry['url']) {
857 # the second <ol/ul> is for read links
858 $read = ((sizeof($data) && $read)?0:1);
863 //for readability structure
864 foreach ($data as $record) {
865 if (is_array($record)) {
867 foreach ($record as $record2) {
868 if (is_array($record2)) {
875 $urlsInserted = array(); //urls of articles inserted
876 foreach ($data as $record) {
877 $url = trim( isset($record['article__url']) ? $record['article__url'] : (isset($record['url']) ? $record['url'] : '') );
878 if ( $url and !in_array($url, $urlsInserted) ) {
879 $title = (isset($record['title']) ? $record['title'] : _('Untitled - Import - ').'</a> <a href="./?import">'._('click to finish import').'</a><a>');
880 $body = (isset($record['content']) ? $record['content'] : '');
881 $isRead = (isset($record['is_read']) ? intval($record['is_read']) : (isset($record['archive'])?intval($record['archive']):0));
882 $isFavorite = (isset($record['is_fav']) ? intval($record['is_fav']) : (isset($record['favorite'])?intval($record['favorite']):0) );
884 $id = $this->store
->add($url, $title, $body, $this->user
->getId(), $isFavorite, $isRead);
886 $urlsInserted[] = $url; //add
888 if ( isset($record['tags']) && trim($record['tags']) ) {
896 $i = sizeof($urlsInserted);
898 $this->messages
->add('s', _('Articles inserted: ').$i._('. Please note, that some may be marked as "read".'));
900 Tools
::logm('Import of articles finished: '.$i.' articles added (w/o content if not provided).');
902 //file parsing finished here
904 //now download article contents if any
906 //check if we need to download any content
907 $recordsDownloadRequired = $this->store
->retrieveUnfetchedEntriesCount($this->user
->getId());
908 if ( $recordsDownloadRequired == 0 ) {
909 //nothing to download
910 $this->messages
->add('s', _('Import finished.'));
911 Tools
::logm('Import finished completely');
915 //if just inserted - don't download anything, download will start in next reload
916 if ( !isset($_FILES['file']) ) {
917 //download next batch
918 Tools
::logm('Fetching next batch of articles...');
919 $items = $this->store
->retrieveUnfetchedEntries($this->user
->getId(), IMPORT_LIMIT
);
921 $purifier = $this->getPurifier();
923 foreach ($items as $item) {
924 $url = new Url(base64_encode($item['url']));
925 Tools
::logm('Fetching article '.$item['id']);
926 $content = Tools
::getPageContent($url);
928 $title = (($content['rss']['channel']['item']['title'] != '') ? $content['rss']['channel']['item']['title'] : _('Untitled'));
929 $body = (($content['rss']['channel']['item']['description'] != '') ? $content['rss']['channel']['item']['description'] : _('Undefined'));
931 //clean content to prevent xss attack
932 $title = $purifier->purify($title);
933 $body = $purifier->purify($body);
935 $this->store
->updateContentAndTitle($item['id'], $title, $body, $this->user
->getId());
936 Tools
::logm('Article '.$item['id'].' updated.');
942 return array('includeImport'=>true, 'import'=>array('recordsDownloadRequired'=>$recordsDownloadRequired, 'recordsUnderDownload'=> IMPORT_LIMIT
, 'delay'=> IMPORT_DELAY
* 1000) );
946 * export poche entries in json
947 * @return json all poche entries
949 public function export() {
950 $filename = "wallabag-export-".$this->user
->getId()."-".date("Y-m-d").".json";
951 header('Content-Disposition: attachment; filename='.$filename);
953 $entries = $this->store
->retrieveAll($this->user
->getId());
954 echo $this->tpl
->render('export.twig', array(
955 'export' => Tools
::renderJson($entries),
957 Tools
::logm('export view');
961 * Checks online the latest version of poche and cache it
962 * @param string $which 'prod' or 'dev'
963 * @return string latest $which version
965 private function getPocheVersion($which = 'prod') {
966 $cache_file = CACHE
. '/' . $which;
967 $check_time = time();
969 # checks if the cached version file exists
970 if (file_exists($cache_file) && (filemtime($cache_file) > (time() - 86400 ))) {
971 $version = file_get_contents($cache_file);
972 $check_time = filemtime($cache_file);
974 $version = file_get_contents('http://static.wallabag.org/versions/' . $which);
975 file_put_contents($cache_file, $version, LOCK_EX
);
977 return array($version, $check_time);
980 public function generateToken()
982 if (ini_get('open_basedir') === '') {
983 if (strtoupper(substr(PHP_OS
, 0, 3)) === 'WIN') {
984 echo 'This is a server using Windows!';
985 // alternative to /dev/urandom for Windows
986 $token = substr(base64_encode(uniqid(mt_rand(), true)), 0, 20);
988 $token = substr(base64_encode(file_get_contents('/dev/urandom', false, null, 0, 20)), 0, 15);
992 $token = substr(base64_encode(uniqid(mt_rand(), true)), 0, 20);
995 $token = str_replace('+', '', $token);
996 $this->store
->updateUserConfig($this->user
->getId(), 'token', $token);
997 $currentConfig = $_SESSION['poche_user']->config
;
998 $currentConfig['token'] = $token;
999 $_SESSION['poche_user']->setConfig($currentConfig);
1003 public function generateFeeds($token, $user_id, $tag_id, $type = 'home')
1005 $allowed_types = array('home', 'fav', 'archive', 'tag');
1006 $config = $this->store
->getConfigUser($user_id);
1008 if ($config == null) {
1009 die(_('User with this id (' . $user_id . ') does not exist.'));
1012 if (!in_array($type, $allowed_types) ||
1013 $token != $config['token']) {
1014 die(_('Uh, there is a problem while generating feeds.'));
1018 $feed = new FeedWriter(RSS2
);
1019 $feed->setTitle('wallabag — ' . $type . ' feed');
1020 $feed->setLink(Tools
::getPocheUrl());
1021 $feed->setChannelElement('pubDate', date(DATE_RSS
, time()));
1022 $feed->setChannelElement('generator', 'wallabag');
1023 $feed->setDescription('wallabag ' . $type . ' elements');
1025 if ($type == 'tag') {
1026 $entries = $this->store
->retrieveEntriesByTag($tag_id, $user_id);
1029 $entries = $this->store
->getEntriesByView($type, $user_id);
1032 if (count($entries) > 0) {
1033 foreach ($entries as $entry) {
1034 $newItem = $feed->createNewItem();
1035 $newItem->setTitle($entry['title']);
1036 $newItem->setSource(Tools
::getPocheUrl() . '?view=view&id=' . $entry['id']);
1037 $newItem->setLink($entry['url']);
1038 $newItem->setDate(time());
1039 $newItem->setDescription($entry['content']);
1040 $feed->addItem($newItem);
1044 $feed->genarateFeed();
1048 public function emptyCache() {
1049 $files = new RecursiveIteratorIterator(
1050 new RecursiveDirectoryIterator(CACHE
, RecursiveDirectoryIterator
::SKIP_DOTS
),
1051 RecursiveIteratorIterator
::CHILD_FIRST
1054 foreach ($files as $fileinfo) {
1055 $todo = ($fileinfo->isDir() ? 'rmdir' : 'unlink');
1056 $todo($fileinfo->getRealPath());
1059 Tools
::logm('empty cache');
1060 $this->messages
->add('s', _('Cache deleted.'));
1065 * return new purifier object with actual config
1067 protected function getPurifier() {
1068 $config = HTMLPurifier_Config
::createDefault();
1069 $config->set('Cache.SerializerPath', CACHE
);
1070 $config->set('HTML.SafeIframe', true);
1071 $config->set('URI.SafeIframeRegexp', '%^(https?:)?//(www\.youtube(?:-nocookie)?\.com/embed/|player\.vimeo\.com/video/)%'); //allow YouTube and Vimeo$purifier = new HTMLPurifier($config);
1073 return new HTMLPurifier($config);