3 * wallabag, self hostable application allowing you to not miss any content anymore
6 * @author Nicolas Lœuillet <nicolas@loeuillet.org>
8 * @license http://opensource.org/licenses/MIT see COPYING file
42 public function __construct()
47 private function init()
51 $pocheUser = Session
::getParam('poche_user');
53 if ($pocheUser && $pocheUser != array()) {
54 $this->user
= $pocheUser;
56 // fake user, just for install & login screens
57 $this->user
= new User();
58 $this->user
->setConfig($this->getDefaultConfig());
61 $this->pagination
= new Paginator($this->user
->getConfigValue('pager'), 'p');
62 $this->language
= new Language($this);
63 $this->tpl
= new Template($this);
64 $this->store
= new Database();
65 $this->messages
= new Messages();
66 $this->routing
= new Routing($this);
71 $this->routing
->run();
77 public function createNewUser($username, $password, $email = "", $internalRegistration = false)
79 Tools
::logm('Trying to create a new user...');
80 if (!empty($username) && !empty($password)){
81 $newUsername = filter_var($username, FILTER_SANITIZE_STRING
);
82 $email = filter_var($email, FILTER_SANITIZE_STRING
);
83 if (!$this->store
->userExists($newUsername)){
84 if ($this->store
->install($newUsername, Tools
::encodeString($password . $newUsername), $email)) {
85 if ($email != "") { // if email is filled
86 if (SEND_CONFIRMATION_EMAIL
&& function_exists('mail')) {
88 // if internal registration
89 $body_internal = _('Hi,') . "\r\n\r\n" . sprintf(_('Someone just created a wallabag account for you on %1$s.'), Tools
::getPocheUrl()) .
90 "\r\n\r\n" . sprintf(_('Your login is %1$s.'), $newUsername) ."\r\n\r\n" .
91 _('Note : The password has been chosen by the person who created your account. Get in touch with that person to know your password and change it as soon as possible') . "\r\n\r\n" .
92 _('Have fun with it !') . "\r\n\r\n" .
93 _('This is an automatically generated message, no one will answer if you respond to it.');
95 // if external (public) registration
96 $body = sprintf(_('Hi, %1$s'), $newUsername) . "\r\n\r\n" .
97 sprintf(_('You\'ve just created a wallabag account on %
1$s.'), Tools::getPocheUrl()) .
98 "\r\n\r\n" . _("Have fun with it !");
99 $body = $internalRegistration ? $body_internal : $body;
101 $body = wordwrap($body, 70, "\r\n"); // cut lines with more than 70 caracters (MIME standard)
102 if (mail($email, sprintf(_('Your
new wallabag account on %
1$s'), Tools
::getPocheUrl()), $body,
103 'X-Mailer: PHP/' . phpversion() . "\r\n" .
104 'Content-type: text/plain; charset=UTF-8' . "\r\n" .
105 "From: " . $newUsername . "@" . gethostname() . "\r\n")) {
106 Tools
::logm('The user ' . $newUsername . ' has been emailed');
107 $this->messages
->add('i', sprintf(_('The new user %1$s has been sent an email at %2$s. You may have to check spam folder.'), $newUsername, $email));
110 Tools
::logm('A problem has been encountered while sending an email');
111 $this->messages
->add('e', _('A problem has been encountered while sending an email'));
114 Tools
::logm('The user has been created, but the server did not authorize sending emails');
115 $this->messages
->add('i', _('The server did not authorize sending a confirmation email'));
118 Tools
::logm('The user has been created, but no email was saved, so no confimation email was sent');
119 $this->messages
->add('i', _('The user was created, but no email was sent because email was not filled in'));
121 Tools
::logm('The new user ' . $newUsername . ' has been installed');
122 if (\Session
::isLogged()) {
123 $this->messages
->add('s', sprintf(_('The new user %s has been installed. Do you want to <a href="?logout">logout ?</a>'), $newUsername));
128 Tools
::logm('error during adding new user');
133 $this->messages
->add('e', sprintf(_('Error : An user with the name %s already exists !'), $newUsername));
134 Tools
::logm('An user with the name ' . $newUsername . ' already exists !');
139 Tools
::logm('Password or username were empty');
144 * Delete an existing user
146 public function deleteUser($password)
148 if ($this->store
->listUsers() > 1) {
149 if (Tools
::encodeString($password . $this->user
->getUsername()) == $this->store
->getUserPassword($this->user
->getId())) {
150 $username = $this->user
->getUsername();
151 $this->store
->deleteUserConfig($this->user
->getId());
152 Tools
::logm('The configuration for user '. $username .' has been deleted !');
153 $this->store
->deleteTagsEntriesAndEntries($this->user
->getId());
154 Tools
::logm('The entries for user '. $username .' has been deleted !');
155 $this->store
->deleteUser($this->user
->getId());
156 Tools
::logm('User '. $username .' has been completely deleted !');
158 Tools
::logm('logout');
160 $this->messages
->add('s', sprintf(_('User %s has been successfully deleted !'), $username));
163 Tools
::logm('Bad password !');
164 $this->messages
->add('e', _('Error : The password is wrong !'));
168 Tools
::logm('Only user !');
169 $this->messages
->add('e', _('Error : You are the only user, you cannot delete your account !'));
173 public function getDefaultConfig()
176 'pager' => PAGINATION
,
178 'theme' => DEFAULT_THEME
183 * Call action (mark as fav, archive, delete, etc.)
185 public function action($action, Url
$url, $id = 0, $import = FALSE, $autoclose = FALSE, $tags = null)
190 $content = Tools
::getPageContent($url);
191 $title = ($content['rss']['channel']['item']['title'] != '') ? $content['rss']['channel']['item']['title'] : _('Untitled');
192 $body = $content['rss']['channel']['item']['description'];
194 // clean content from prevent xss attack
195 $purifier = $this->_getPurifier();
196 $title = $purifier->purify($title);
197 $body = $purifier->purify($body);
199 //search for possible duplicate
201 $duplicate = $this->store
->retrieveOneByURL($url->getUrl(), $this->user
->getId());
203 $last_id = $this->store
->add($url->getUrl(), $title, $body, $this->user
->getId());
205 Tools
::logm('add link ' . $url->getUrl());
206 if (DOWNLOAD_PICTURES
) {
207 $content = Picture
::filterPicture($body, $url->getUrl(), $last_id);
208 Tools
::logm('updating content article');
209 $this->store
->updateContent($last_id, $content, $this->user
->getId());
212 if ($duplicate != NULL) {
213 // 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
214 Tools
::logm('link ' . $url->getUrl() . ' is a duplicate');
215 // 1) - preserve tags and favorite, then drop old entry
216 $this->store
->reassignTags($duplicate['id'], $last_id);
217 if ($duplicate['is_fav']) {
218 $this->store
->favoriteById($last_id, $this->user
->getId());
220 if ($this->store
->deleteById($duplicate['id'], $this->user
->getId())) {
221 Tools
::logm('previous link ' . $url->getUrl() .' entry deleted');
225 // if there are tags, add them to the new article
226 if (isset($_GET['tags'])) {
227 $_POST['value'] = $_GET['tags'];
228 $_POST['entry_id'] = $last_id;
229 $this->action('add_tag', $url);
232 $this->messages
->add('s', _('the link has been added successfully'));
235 $this->messages
->add('e', _('error during insertion : the link wasn\'t added'));
236 Tools
::logm('error during insertion : the link wasn\'t added ' . $url->getUrl());
239 if ($autoclose == TRUE) {
240 Tools
::redirect('?view=home&closewin=true');
242 Tools
::redirect('?view=home');
247 if (isset($_GET['search'])) {
248 //when we want to apply a delete to a search
249 $tags = array($_GET['search']);
250 $allentry_ids = $this->store
->search($tags[0], $this->user
->getId());
251 $entry_ids = array();
252 foreach ($allentry_ids as $eachentry) {
253 $entry_ids[] = $eachentry[0];
255 } else { // delete a single article
256 $entry_ids = array($id);
258 foreach($entry_ids as $id) {
259 $msg = 'delete link #' . $id;
260 if ($this->store
->deleteById($id, $this->user
->getId())) {
261 if (DOWNLOAD_PICTURES
) {
262 Picture
::removeDirectory(ABS_PATH
. $id);
264 $this->messages
->add('s', _('the link has been deleted successfully'));
267 $this->messages
->add('e', _('the link wasn\'t deleted'));
268 $msg = 'error : can\'t delete link #' . $id;
272 Tools
::redirect('?');
275 $this->store
->favoriteById($id, $this->user
->getId());
276 Tools
::logm('mark as favorite link #' . $id);
277 if ( Tools
::isAjaxRequest() ) {
285 case 'toggle_archive' :
286 if (isset($_GET['tag_id'])) {
287 //when we want to archive a whole tag
288 $tag_id = $_GET['tag_id'];
289 $allentry_ids = $this->store
->retrieveEntriesByTag($tag_id, $this->user
->getId());
290 $entry_ids = array();
291 foreach ($allentry_ids as $eachentry) {
292 $entry_ids[] = $eachentry[0];
294 } else { //archive a single article
295 $entry_ids = array($id);
297 foreach($entry_ids as $id) {
298 $this->store
->archiveById($id, $this->user
->getId());
299 Tools
::logm('archive link #' . $id);
301 if ( Tools
::isAjaxRequest() ) {
310 $this->store
->archiveAll($this->user
->getId());
311 Tools
::logm('archive all links');
315 if (isset($_GET['search'])) {
316 //when we want to apply a tag to a search
317 $tags = array($_GET['search']);
318 $allentry_ids = $this->store
->search($tags[0], $this->user
->getId());
319 $entry_ids = array();
320 foreach ($allentry_ids as $eachentry) {
321 $entry_ids[] = $eachentry[0];
323 } else { //add a tag to a single article
324 $tags = explode(',', $_POST['value']);
325 $entry_ids = array($_POST['entry_id']);
327 foreach($entry_ids as $entry_id) {
328 $entry = $this->store
->retrieveOneById($entry_id, $this->user
->getId());
330 $this->messages
->add('e', _('Article not found!'));
331 Tools
::logm('error : article not found');
334 //get all already set tags to preven duplicates
335 $already_set_tags = array();
336 $entry_tags = $this->store
->retrieveTagsByEntry($entry_id);
337 foreach ($entry_tags as $tag) {
338 $already_set_tags[] = $tag['value'];
340 foreach($tags as $key => $tag_value) {
341 $value = trim($tag_value);
342 if ($value && !in_array($value, $already_set_tags)) {
343 $tag = $this->store
->retrieveTagByValue($value);
346 $tag = $this->store
->createTag($value);
348 if (STORAGE
== 'postgres') {
349 $sequence = 'tags_id_seq';
351 $tag_id = $this->store
->getLastId($sequence);
354 $tag_id = $tag['id'];
357 # we assign the tag to the article
358 $this->store
->setTagToEntry($tag_id, $entry_id);
362 $this->messages
->add('s', _('The tag has been applied successfully'));
363 Tools
::logm('The tag has been applied successfully');
367 $tag_id = $_GET['tag_id'];
368 $entry = $this->store
->retrieveOneById($id, $this->user
->getId());
370 $this->messages
->add('e', _('Article not found!'));
371 Tools
::logm('error : article not found');
374 $this->store
->removeTagForEntry($id, $tag_id);
375 Tools
::logm('tag entry deleted');
376 if ($this->store
->cleanUnusedTag($tag_id)) {
377 Tools
::logm('tag deleted');
379 $this->messages
->add('s', _('The tag has been successfully deleted'));
383 case 'reload_article' :
384 Tools
::logm('reload article');
386 $entry = $this->store
->retrieveOneById($id, $this->user
->getId());
387 Tools
::logm('reload url ' . $entry['url']);
388 $url = new Url(base64_encode($entry['url']));
389 $this->action('add', $url);
392 /* For some unknown reason I can't get displayView() to work here (it redirects to home view afterwards). So here's a dirty fix which redirects directly to URL */
395 while ($this->store
->retrieveOneById($id,$this->user
->getId()) == null) {
396 $count = $this->store
->getEntriesByViewCount($view, $this->user
->getId());
397 $id = rand(1,$count);
399 Tools
::logm('get a random article');
400 Tools
::redirect('?view=view&id=' . $id);
401 //$this->displayView('view', $id);
408 function displayView($view, $id = 0)
417 $dev_infos = $this->_getPocheVersion('dev');
418 $dev = trim($dev_infos[0]);
419 $check_time_dev = date('d-M-Y H:i', $dev_infos[1]);
420 $prod_infos = $this->_getPocheVersion('prod');
421 $prod = trim($prod_infos[0]);
422 $check_time_prod = date('d-M-Y H:i', $prod_infos[1]);
423 $compare_dev = version_compare(POCHE
, $dev);
424 $compare_prod = version_compare(POCHE
, $prod);
425 $themes = $this->tpl
->getInstalledThemes();
426 $languages = $this->language
->getInstalledLanguages();
427 $token = $this->user
->getConfigValue('token');
428 $http_auth = (isset($_SERVER['PHP_AUTH_USER']) || isset($_SERVER['REMOTE_USER'])) ? true : false;
429 $only_user = ($this->store
->listUsers() > 1) ? false : true;
432 'languages' => $languages,
435 'check_time_dev' => $check_time_dev,
436 'check_time_prod' => $check_time_prod,
437 'compare_dev' => $compare_dev,
438 'compare_prod' => $compare_prod,
440 'user_id' => $this->user
->getId(),
441 'http_auth' => $http_auth,
442 'only_user' => $only_user
444 Tools
::logm('config view');
448 $entry = $this->store
->retrieveOneById($id, $this->user
->getId());
450 $this->messages
->add('e', _('Article not found!'));
451 Tools
::logm('error : article not found');
454 $tags = $this->store
->retrieveTagsByEntry($id);
462 $token = $this->user
->getConfigValue('token');
463 //if term is set - search tags for this term
464 $term = Tools
::checkVar('term');
465 $tags = $this->store
->retrieveAllTags($this->user
->getId(), $term);
466 if (Tools
::isAjaxRequest()) {
468 foreach ($tags as $tag) {
469 $result[] = $tag['value'];
471 echo json_encode($result);
476 'user_id' => $this->user
->getId(),
481 if (isset($_GET['search'])) {
482 $search = filter_var($_GET['search'], FILTER_SANITIZE_STRING
);
483 $tpl_vars['entries'] = $this->store
->search($search, $this->user
->getId());
484 $count = count($tpl_vars['entries']);
485 $this->pagination
->set_total($count);
486 $page_links = str_replace(array('previous', 'next'), array(_('previous'), _('next')),
487 $this->pagination
->page_links('?view=' . $view . '?search=' . $search . '&sort=' . $_SESSION['sort'] . '&' ));
488 $tpl_vars['page_links'] = $page_links;
489 $tpl_vars['nb_results'] = $count;
490 $tpl_vars['searchterm'] = $search;
494 $entry = $this->store
->retrieveOneById($id, $this->user
->getId());
495 if ($entry != NULL) {
496 Tools
::logm('view link #' . $id);
497 $content = $entry['content'];
498 if (function_exists('tidy_parse_string')) {
499 $tidy = tidy_parse_string($content, array('indent'=>true, 'show-body-only' => true), 'UTF8');
500 $tidy->cleanRepair();
501 $content = $tidy->value
;
507 $flattr = new FlattrItem();
508 $flattr->checkItem($entry['url'], $entry['id']);
512 $tags = $this->store
->retrieveTagsByEntry($entry['id']);
516 'content' => $content,
522 Tools
::logm('error in view call : entry is null');
525 default: # home, favorites, archive and tag views
530 'listmode' => (isset($_COOKIE['listmode']) ? true : false),
533 //if id is given - we retrieve entries by tag: id is tag id
535 $tpl_vars['tag'] = $this->store
->retrieveTag($id, $this->user
->getId());
536 $tpl_vars['id'] = intval($id);
539 $count = $this->store
->getEntriesByViewCount($view, $this->user
->getId(), $id);
542 $this->pagination
->set_total($count);
543 $page_links = str_replace(array('previous', 'next'), array(_('previous'), _('next')),
544 $this->pagination
->page_links('?view=' . $view . '&sort=' . $_SESSION['sort'] . (($id)?'&id='.$id:'') . '&' ));
545 $tpl_vars['entries'] = $this->store
->getEntriesByView($view, $this->user
->getId(), $this->pagination
->get_limit(), $id);
546 $tpl_vars['page_links'] = $page_links;
547 $tpl_vars['nb_results'] = $count;
549 Tools
::logm('display ' . $view . ' view');
557 * update the password of the current user.
558 * if MODE_DEMO is TRUE, the password can't be updated.
559 * @todo add the return value
560 * @todo set the new password in function header like this updatePassword($newPassword)
563 public function updatePassword($password, $confirmPassword)
566 $this->messages
->add('i', _('in demo mode, you can\'t update your password'));
567 Tools
::logm('in demo mode, you can\'t do this');
568 Tools
::redirect('?view=config');
571 if (isset($password) && isset($confirmPassword)) {
572 if ($password == $confirmPassword && !empty($password)) {
573 $this->messages
->add('s', _('your password has been updated'));
574 $this->store
->updatePassword($this->user
->getId(), Tools
::encodeString($password . $this->user
->getUsername()));
576 Tools
::logm('password updated');
580 $this->messages
->add('e', _('the two fields have to be filled & the password must be the same in the two fields'));
581 Tools
::redirect('?view=config');
588 * Get credentials from differents sources
589 * It redirects the user to the $referer link
593 private function credentials()
595 if (isset($_SERVER['PHP_AUTH_USER'])) {
596 return array($_SERVER['PHP_AUTH_USER'], 'php_auth', true);
598 if (!empty($_POST['login']) && !empty($_POST['password'])) {
599 return array($_POST['login'], $_POST['password'], false);
601 if (isset($_SERVER['REMOTE_USER'])) {
602 return array($_SERVER['REMOTE_USER'], 'http_auth', true);
605 return array(false, false, false);
609 * checks if login & password are correct and save the user in session.
610 * it redirects the user to the $referer link
611 * @param string $referer the url to redirect after login
612 * @todo add the return value
615 public function login($referer)
617 list($login,$password,$isauthenticated)=$this->credentials();
618 if($login === false || $password === false) {
619 $this->messages
->add('e', _('login failed: you have to fill all fields'));
620 Tools
::logm('login failed');
623 if (!empty($login) && !empty($password)) {
624 $user = $this->store
->login($login, Tools
::encodeString($password . $login), $isauthenticated);
625 if ($user != array()) {
626 # Save login into Session
627 $longlastingsession = isset($_POST['longlastingsession']);
628 $passwordTest = ($isauthenticated) ? $user['password'] : Tools
::encodeString($password . $login);
629 Session
::login($user['username'], $user['password'], $login, $passwordTest, $longlastingsession, array('poche_user' => new User($user)));
632 $language = $user['config']['language'];
633 @putenv('LC_ALL=' . $language);
634 setlocale(LC_ALL
, $language);
635 bindtextdomain($language, LOCALE
);
636 textdomain($language);
638 $this->messages
->add('s', _('welcome to your wallabag'));
639 Tools
::logm('login successful');
640 Tools
::redirect($referer);
642 $this->messages
->add('e', _('login failed: bad login or password'));
643 // log login failure in web server log to allow fail2ban usage
644 error_log('user '.$login.' authentication failure');
645 Tools
::logm('login failed');
651 * log out the poche user. It cleans the session.
652 * @todo add the return value
655 public function logout()
657 $this->user
= array();
659 Tools
::logm('logout');
664 * import datas into your wallabag
668 public function import() {
670 if ( isset($_FILES['file']) && $_FILES['file']['tmp_name'] ) {
671 Tools
::logm('Import stated: parsing file');
673 // assume, that file is in json format
674 $str_data = file_get_contents($_FILES['file']['tmp_name']);
675 $data = json_decode($str_data, true);
677 if ( $data === null ) {
678 //not json - assume html
679 $html = new simple_html_dom();
680 $html->load_file($_FILES['file']['tmp_name']);
683 foreach (array('ol','ul') as $list) {
684 foreach ($html->find($list) as $ul) {
685 foreach ($ul->find('li') as $li) {
688 $tmpEntry['url'] = $a[0]->href
;
689 $tmpEntry['tags'] = $a[0]->tags
;
690 $tmpEntry['is_read'] = $read;
691 if ($tmpEntry['url']) {
695 # the second <ol/ul> is for read links
696 $read = ((sizeof($data) && $read)?0:1);
701 // for readability structure
703 foreach($data as $record) {
704 if (is_array($record)) {
706 foreach($record as $record2) {
707 if (is_array($record2)) {
714 $urlsInserted = array(); //urls of articles inserted
715 foreach($data as $record) {
716 $url = trim(isset($record['article__url']) ? $record['article__url'] : (isset($record['url']) ? $record['url'] : ''));
717 if ($url and !in_array($url, $urlsInserted)) {
718 $title = (isset($record['title']) ? $record['title'] : _('Untitled - Import - ') . '</a> <a href="./?import">' . _('click to finish import') . '</a><a>');
719 $body = (isset($record['content']) ? $record['content'] : '');
720 $isRead = (isset($record['is_read']) ? intval($record['is_read']) : (isset($record['archive']) ? intval($record['archive']) : 0));
721 $isFavorite = (isset($record['is_fav']) ? intval($record['is_fav']) : (isset($record['favorite']) ? intval($record['favorite']) : 0));
725 $id = $this->store
->add($url, $title, $body, $this->user
->getId() , $isFavorite, $isRead);
727 $urlsInserted[] = $url; //add
728 if (isset($record['tags']) && trim($record['tags'])) {
730 $tags = explode(',', $record['tags']);
731 foreach($tags as $tag) {
733 $tag_id = $this->store
->retrieveTagByValue($tag);
735 $this->store
->setTagToEntry($tag_id['id'], $entry_id);
737 $this->store
->createTag($tag);
738 $tag_id = $this->store
->retrieveTagByValue($tag);
739 $this->store
->setTagToEntry($tag_id['id'], $entry_id);
748 $i = sizeof($urlsInserted);
750 $this->messages
->add('s', _('Articles inserted: ') . $i . _('. Please note, that some may be marked as "read".'));
753 Tools
::logm('Import of articles finished: '.$i.' articles added (w/o content if not provided).');
756 $this->messages
->add('s', _('Did you forget to select a file?'));
758 // file parsing finished here
759 // now download article contents if any
760 // check if we need to download any content
762 $recordsDownloadRequired = $this->store
->retrieveUnfetchedEntriesCount($this->user
->getId());
764 if ($recordsDownloadRequired == 0) {
766 // nothing to download
768 $this->messages
->add('s', _('Import finished.'));
769 Tools
::logm('Import finished completely');
774 // if just inserted - don't download anything, download will start in next reload
776 if (!isset($_FILES['file'])) {
778 // download next batch
780 Tools
::logm('Fetching next batch of articles...');
781 $items = $this->store
->retrieveUnfetchedEntries($this->user
->getId() , IMPORT_LIMIT
);
782 $purifier = $this->_getPurifier();
783 foreach($items as $item) {
784 $url = new Url(base64_encode($item['url']));
785 if( $url->isCorrect() )
787 Tools
::logm('Fetching article ' . $item['id']);
788 $content = Tools
::getPageContent($url);
789 $title = (($content['rss']['channel']['item']['title'] != '') ? $content['rss']['channel']['item']['title'] : _('Untitled'));
790 $body = (($content['rss']['channel']['item']['description'] != '') ? $content['rss']['channel']['item']['description'] : _('Undefined'));
792 // clean content to prevent xss attack
794 $title = $purifier->purify($title);
795 $body = $purifier->purify($body);
796 $this->store
->updateContentAndTitle($item['id'], $title, $body, $this->user
->getId());
797 Tools
::logm('Article ' . $item['id'] . ' updated.');
800 Tools
::logm('Unvalid URL (' . $item['url'] .') to fetch for article ' . $item['id']);
807 'includeImport' => true,
809 'recordsDownloadRequired' => $recordsDownloadRequired,
810 'recordsUnderDownload' => IMPORT_LIMIT
,
811 'delay' => IMPORT_DELAY
* 1000
817 * export poche entries in json
818 * @return json all poche entries
820 public function export()
822 $filename = "wallabag-export-".$this->user
->getId()."-".date("Y-m-d").".json";
823 header('Content-Disposition: attachment; filename='.$filename);
825 $entries = $this->store
->retrieveAll($this->user
->getId());
826 echo $this->tpl
->render('export.twig', array(
827 'export' => Tools
::renderJson($entries),
829 Tools
::logm('export view');
833 * Checks online the latest version of poche and cache it
834 * @param string $which 'prod' or 'dev'
835 * @return string latest $which version
837 private function _getPocheVersion($which = 'prod') {
838 $cache_file = CACHE
. '/' . $which;
839 $check_time = time();
841 # checks if the cached version file exists
842 if (file_exists($cache_file) && (filemtime($cache_file) > (time() - 86400 ))) {
843 $version = file_get_contents($cache_file);
844 $check_time = filemtime($cache_file);
846 $version = file_get_contents('http://static.wallabag.org/versions/' . $which);
847 file_put_contents($cache_file, $version, LOCK_EX
);
849 return array($version, $check_time);
853 * Update token for current user
855 public function updateToken()
857 $token = Tools
::generateToken();
858 $this->store
->updateUserConfig($this->user
->getId(), 'token', $token);
859 $currentConfig = $_SESSION['poche_user']->config
;
860 $currentConfig['token'] = $token;
861 $_SESSION['poche_user']->setConfig($currentConfig);
866 * Generate RSS feeds for current user
870 * @param $tag_id if $type is 'tag', the id of the tag to generate feed for
871 * @param string $type the type of feed to generate
872 * @param int $limit the maximum number of items (0 means all)
874 public function generateFeeds($token, $user_id, $tag_id, $type = 'home', $limit = 0)
876 $allowed_types = array('home', 'fav', 'archive', 'tag');
877 $config = $this->store
->getConfigUser($user_id);
879 if ($config == null) {
880 die(sprintf(_('User with this id (%d) does not exist.'), $user_id));
883 if (!in_array($type, $allowed_types) || !isset($config['token']) || $token != $config['token']) {
884 die(_('Uh, there is a problem while generating feed. Wrong token used?'));
887 $feed = new FeedWriter(RSS2
);
888 $feed->setTitle('wallabag — ' . $type . ' feed');
889 $feed->setLink(Tools
::getPocheUrl());
890 $feed->setChannelElement('pubDate', date(DATE_RSS
, time()));
891 $feed->setChannelElement('generator', 'wallabag');
892 $feed->setDescription('wallabag ' . $type . ' elements');
894 if ($type == 'tag') {
895 $entries = $this->store
->retrieveEntriesByTag($tag_id, $user_id);
898 $entries = $this->store
->getEntriesByView($type, $user_id);
901 // if $limit is set to zero, use all entries
903 $limit = count($entries);
905 if (count($entries) > 0) {
906 for ($i = 0; $i < min(count($entries), $limit); $i++
) {
907 $entry = $entries[$i];
908 $newItem = $feed->createNewItem();
909 $newItem->setTitle($entry['title']);
910 $newItem->setSource(Tools
::getPocheUrl() . '?view=view&id=' . $entry['id']);
911 $newItem->setLink($entry['url']);
912 $newItem->setDate(time());
913 $newItem->setDescription($entry['content']);
914 $feed->addItem($newItem);
918 $feed->genarateFeed();
925 * Returns new purifier object with actual config
927 private function _getPurifier()
929 $config = HTMLPurifier_Config
::createDefault();
930 $config->set('Cache.SerializerPath', CACHE
);
931 $config->set('HTML.SafeIframe', true);
933 //allow YouTube, Vimeo and dailymotion videos
934 $config->set('URI.SafeIframeRegexp', '%^(https?:)?//(www\.youtube(?:-nocookie)?\.com/embed/|player\.vimeo\.com/video/|www\.dailymotion\.com/embed/video/)%');
936 return new HTMLPurifier($config);