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 = "Hi, " . $newUsername . "\r\n\r\nYou've just created a wallabag account on " . Tools
::getPocheUrl() . ".\r\nHave fun with it !";
97 $body = $internalRegistration ? $body_internal : $body;
99 $body = wordwrap($body, 70, "\r\n"); // cut lines with more than 70 caracters (MIME standard)
100 if (mail($email, sprintf(_('Your new wallabag account on %1$s'), Tools::getPocheUrl()), $body,
101 'X
-Mailer
: PHP
/' . phpversion() . "\r\n" .
102 'Content
-type
: text
/plain
; charset
=UTF
-8' . "\r\n" .
103 "From: " . $newUsername . "@" . gethostname() . "\r\n")) {
104 Tools::logm('The user
' . $newUsername . ' has been emailed
');
105 $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));
108 Tools::logm('A problem has been encountered
while sending an email
');
109 $this->messages->add('e
', _('A problem has been encountered
while sending an email
'));
112 Tools::logm('The user has been created
, but the server did not authorize sending emails
');
113 $this->messages->add('i
', _('The server did not authorize sending a confirmation email
'));
116 Tools::logm('The user has been created
, but no email was saved
, so no confimation email was sent
');
117 $this->messages->add('i
', _('The user was created
, but no email was sent because email was not filled in
'));
119 Tools::logm('The
new user
' . $newUsername . ' has been installed
');
120 $this->messages->add('s
', sprintf(_('The
new user %s has been installed
. Do you want to
<a href
="?logout">logout
?</a
>'), $newUsername));
124 Tools::logm('error during adding
new user
');
129 $this->messages->add('e
', sprintf(_('Error
: An user with the name %s already exists
!'), $newUsername));
130 Tools::logm('An user with the name
' . $newUsername . ' already exists
!');
135 Tools::logm('Password
or username were
empty');
140 * Delete an existing user
142 public function deleteUser($password)
144 if ($this->store->listUsers() > 1) {
145 if (Tools::encodeString($password . $this->user->getUsername()) == $this->store->getUserPassword($this->user->getId())) {
146 $username = $this->user->getUsername();
147 $this->store->deleteUserConfig($this->user->getId());
148 Tools::logm('The configuration
for user
'. $username .' has been deleted
!');
149 $this->store->deleteTagsEntriesAndEntries($this->user->getId());
150 Tools::logm('The entries
for user
'. $username .' has been deleted
!');
151 $this->store->deleteUser($this->user->getId());
152 Tools::logm('User
'. $username .' has been completely deleted
!');
154 Tools::logm('logout
');
156 $this->messages->add('s
', sprintf(_('User %s has been successfully deleted
!'), $username));
159 Tools::logm('Bad password
!');
160 $this->messages->add('e
', _('Error
: The password is wrong
!'));
164 Tools::logm('Only user
!');
165 $this->messages->add('e
', _('Error
: You are the only user
, you cannot delete your account
!'));
169 public function getDefaultConfig()
172 'pager
' => PAGINATION,
174 'theme
' => DEFAULT_THEME
179 * Call action (mark as fav, archive, delete, etc.)
181 public function action($action, Url $url, $id = 0, $import = FALSE, $autoclose = FALSE, $tags = null)
186 $content = Tools::getPageContent($url);
187 $title = ($content['rss
']['channel
']['item
']['title
'] != '') ? $content['rss
']['channel
']['item
']['title
'] : _('Untitled
');
188 $body = $content['rss
']['channel
']['item
']['description
'];
190 // clean content from prevent xss attack
191 $purifier = $this->_getPurifier();
192 $title = $purifier->purify($title);
193 $body = $purifier->purify($body);
195 //search for possible duplicate
197 $duplicate = $this->store->retrieveOneByURL($url->getUrl(), $this->user->getId());
199 $last_id = $this->store->add($url->getUrl(), $title, $body, $this->user->getId());
201 Tools::logm('add link
' . $url->getUrl());
202 if (DOWNLOAD_PICTURES) {
203 $content = Picture::filterPicture($body, $url->getUrl(), $last_id);
204 Tools::logm('updating content article
');
205 $this->store->updateContent($last_id, $content, $this->user->getId());
208 if ($duplicate != NULL) {
209 // 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
210 Tools::logm('link
' . $url->getUrl() . ' is a duplicate
');
211 // 1) - preserve tags and favorite, then drop old entry
212 $this->store->reassignTags($duplicate['id
'], $last_id);
213 if ($duplicate['is_fav
']) {
214 $this->store->favoriteById($last_id, $this->user->getId());
216 if ($this->store->deleteById($duplicate['id
'], $this->user->getId())) {
217 Tools::logm('previous link
' . $url->getUrl() .' entry deleted
');
221 // if there are tags, add them to the new article
222 if (isset($_GET['tags
'])) {
223 $_POST['value
'] = $_GET['tags
'];
224 $_POST['entry_id
'] = $last_id;
225 $this->action('add_tag
', $url);
228 $this->messages->add('s
', _('the link has been added successfully
'));
231 $this->messages->add('e
', _('error during insertion
: the link wasn\'t added
'));
232 Tools::logm('error during insertion
: the link wasn\'t added
' . $url->getUrl());
235 if ($autoclose == TRUE) {
236 Tools::redirect('?view
=home
&closewin
=true');
238 Tools::redirect('?view
=home
');
243 if (isset($_GET['search
'])) {
244 //when we want to apply a delete to a search
245 $tags = array($_GET['search
']);
246 $allentry_ids = $this->store->search($tags[0], $this->user->getId());
247 $entry_ids = array();
248 foreach ($allentry_ids as $eachentry) {
249 $entry_ids[] = $eachentry[0];
251 } else { // delete a single article
252 $entry_ids = array($id);
254 foreach($entry_ids as $id) {
255 $msg = 'delete link
#' . $id;
256 if ($this->store
->deleteById($id, $this->user
->getId())) {
257 if (DOWNLOAD_PICTURES
) {
258 Picture
::removeDirectory(ABS_PATH
. $id);
260 $this->messages
->add('s', _('the link has been deleted successfully'));
263 $this->messages
->add('e', _('the link wasn\'t deleted'));
264 $msg = 'error : can\'t delete link #' . $id;
268 Tools
::redirect('?');
271 $this->store
->favoriteById($id, $this->user
->getId());
272 Tools
::logm('mark as favorite link #' . $id);
273 if ( Tools
::isAjaxRequest() ) {
281 case 'toggle_archive' :
282 if (isset($_GET['tag_id'])) {
283 //when we want to archive a whole tag
284 $tag_id = $_GET['tag_id'];
285 $allentry_ids = $this->store
->retrieveEntriesByTag($tag_id, $this->user
->getId());
286 $entry_ids = array();
287 foreach ($allentry_ids as $eachentry) {
288 $entry_ids[] = $eachentry[0];
290 } else { //archive a single article
291 $entry_ids = array($id);
293 foreach($entry_ids as $id) {
294 $this->store
->archiveById($id, $this->user
->getId());
295 Tools
::logm('archive link #' . $id);
297 if ( Tools
::isAjaxRequest() ) {
306 $this->store
->archiveAll($this->user
->getId());
307 Tools
::logm('archive all links');
311 if (isset($_GET['search'])) {
312 //when we want to apply a tag to a search
313 $tags = array($_GET['search']);
314 $allentry_ids = $this->store
->search($tags[0], $this->user
->getId());
315 $entry_ids = array();
316 foreach ($allentry_ids as $eachentry) {
317 $entry_ids[] = $eachentry[0];
319 } else { //add a tag to a single article
320 $tags = explode(',', $_POST['value']);
321 $entry_ids = array($_POST['entry_id']);
323 foreach($entry_ids as $entry_id) {
324 $entry = $this->store
->retrieveOneById($entry_id, $this->user
->getId());
326 $this->messages
->add('e', _('Article not found!'));
327 Tools
::logm('error : article not found');
330 //get all already set tags to preven duplicates
331 $already_set_tags = array();
332 $entry_tags = $this->store
->retrieveTagsByEntry($entry_id);
333 foreach ($entry_tags as $tag) {
334 $already_set_tags[] = $tag['value'];
336 foreach($tags as $key => $tag_value) {
337 $value = trim($tag_value);
338 if ($value && !in_array($value, $already_set_tags)) {
339 $tag = $this->store
->retrieveTagByValue($value);
342 $tag = $this->store
->createTag($value);
344 if (STORAGE
== 'postgres') {
345 $sequence = 'tags_id_seq';
347 $tag_id = $this->store
->getLastId($sequence);
350 $tag_id = $tag['id'];
353 # we assign the tag to the article
354 $this->store
->setTagToEntry($tag_id, $entry_id);
358 $this->messages
->add('s', _('The tag has been applied successfully'));
359 Tools
::logm('The tag has been applied successfully');
363 $tag_id = $_GET['tag_id'];
364 $entry = $this->store
->retrieveOneById($id, $this->user
->getId());
366 $this->messages
->add('e', _('Article not found!'));
367 Tools
::logm('error : article not found');
370 $this->store
->removeTagForEntry($id, $tag_id);
371 Tools
::logm('tag entry deleted');
372 if ($this->store
->cleanUnusedTag($tag_id)) {
373 Tools
::logm('tag deleted');
375 $this->messages
->add('s', _('The tag has been successfully deleted'));
379 case 'reload_article' :
380 Tools
::logm('reload article');
382 $entry = $this->store
->retrieveOneById($id, $this->user
->getId());
383 Tools
::logm('reload url ' . $entry['url']);
384 $url = new Url(base64_encode($entry['url']));
385 $this->action('add', $url);
388 /* 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 */
391 while ($this->store
->retrieveOneById($id,$this->user
->getId()) == null) {
392 $count = $this->store
->getEntriesByViewCount($view, $this->user
->getId());
393 $id = rand(1,$count);
395 Tools
::logm('get a random article');
396 Tools
::redirect('?view=view&id=' . $id);
397 //$this->displayView('view', $id);
404 function displayView($view, $id = 0)
413 $dev_infos = $this->_getPocheVersion('dev');
414 $dev = trim($dev_infos[0]);
415 $check_time_dev = date('d-M-Y H:i', $dev_infos[1]);
416 $prod_infos = $this->_getPocheVersion('prod');
417 $prod = trim($prod_infos[0]);
418 $check_time_prod = date('d-M-Y H:i', $prod_infos[1]);
419 $compare_dev = version_compare(POCHE
, $dev);
420 $compare_prod = version_compare(POCHE
, $prod);
421 $themes = $this->tpl
->getInstalledThemes();
422 $languages = $this->language
->getInstalledLanguages();
423 $token = $this->user
->getConfigValue('token');
424 $http_auth = (isset($_SERVER['PHP_AUTH_USER']) || isset($_SERVER['REMOTE_USER'])) ? true : false;
425 $only_user = ($this->store
->listUsers() > 1) ? false : true;
428 'languages' => $languages,
431 'check_time_dev' => $check_time_dev,
432 'check_time_prod' => $check_time_prod,
433 'compare_dev' => $compare_dev,
434 'compare_prod' => $compare_prod,
436 'user_id' => $this->user
->getId(),
437 'http_auth' => $http_auth,
438 'only_user' => $only_user
440 Tools
::logm('config view');
444 $entry = $this->store
->retrieveOneById($id, $this->user
->getId());
446 $this->messages
->add('e', _('Article not found!'));
447 Tools
::logm('error : article not found');
450 $tags = $this->store
->retrieveTagsByEntry($id);
458 $token = $this->user
->getConfigValue('token');
459 //if term is set - search tags for this term
460 $term = Tools
::checkVar('term');
461 $tags = $this->store
->retrieveAllTags($this->user
->getId(), $term);
462 if (Tools
::isAjaxRequest()) {
464 foreach ($tags as $tag) {
465 $result[] = $tag['value'];
467 echo json_encode($result);
472 'user_id' => $this->user
->getId(),
477 if (isset($_GET['search'])) {
478 $search = filter_var($_GET['search'], FILTER_SANITIZE_STRING
);
479 $tpl_vars['entries'] = $this->store
->search($search, $this->user
->getId());
480 $count = count($tpl_vars['entries']);
481 $this->pagination
->set_total($count);
482 $page_links = str_replace(array('previous', 'next'), array(_('previous'), _('next')),
483 $this->pagination
->page_links('?view=' . $view . '?search=' . $search . '&sort=' . $_SESSION['sort'] . '&' ));
484 $tpl_vars['page_links'] = $page_links;
485 $tpl_vars['nb_results'] = $count;
486 $tpl_vars['searchterm'] = $search;
490 $entry = $this->store
->retrieveOneById($id, $this->user
->getId());
491 if ($entry != NULL) {
492 Tools
::logm('view link #' . $id);
493 $content = $entry['content'];
494 if (function_exists('tidy_parse_string')) {
495 $tidy = tidy_parse_string($content, array('indent'=>true, 'show-body-only' => true), 'UTF8');
496 $tidy->cleanRepair();
497 $content = $tidy->value
;
503 $flattr = new FlattrItem();
504 $flattr->checkItem($entry['url'], $entry['id']);
508 $tags = $this->store
->retrieveTagsByEntry($entry['id']);
512 'content' => $content,
518 Tools
::logm('error in view call : entry is null');
521 default: # home, favorites, archive and tag views
526 'listmode' => (isset($_COOKIE['listmode']) ? true : false),
529 //if id is given - we retrieve entries by tag: id is tag id
531 $tpl_vars['tag'] = $this->store
->retrieveTag($id, $this->user
->getId());
532 $tpl_vars['id'] = intval($id);
535 $count = $this->store
->getEntriesByViewCount($view, $this->user
->getId(), $id);
538 $this->pagination
->set_total($count);
539 $page_links = str_replace(array('previous', 'next'), array(_('previous'), _('next')),
540 $this->pagination
->page_links('?view=' . $view . '&sort=' . $_SESSION['sort'] . (($id)?'&id='.$id:'') . '&' ));
541 $tpl_vars['entries'] = $this->store
->getEntriesByView($view, $this->user
->getId(), $this->pagination
->get_limit(), $id);
542 $tpl_vars['page_links'] = $page_links;
543 $tpl_vars['nb_results'] = $count;
545 Tools
::logm('display ' . $view . ' view');
553 * update the password of the current user.
554 * if MODE_DEMO is TRUE, the password can't be updated.
555 * @todo add the return value
556 * @todo set the new password in function header like this updatePassword($newPassword)
559 public function updatePassword($password, $confirmPassword)
562 $this->messages
->add('i', _('in demo mode, you can\'t update your password'));
563 Tools
::logm('in demo mode, you can\'t do this');
564 Tools
::redirect('?view=config');
567 if (isset($password) && isset($confirmPassword)) {
568 if ($password == $confirmPassword && !empty($password)) {
569 $this->messages
->add('s', _('your password has been updated'));
570 $this->store
->updatePassword($this->user
->getId(), Tools
::encodeString($password . $this->user
->getUsername()));
572 Tools
::logm('password updated');
576 $this->messages
->add('e', _('the two fields have to be filled & the password must be the same in the two fields'));
577 Tools
::redirect('?view=config');
584 * Get credentials from differents sources
585 * It redirects the user to the $referer link
589 private function credentials()
591 if (isset($_SERVER['PHP_AUTH_USER'])) {
592 return array($_SERVER['PHP_AUTH_USER'], 'php_auth', true);
594 if (!empty($_POST['login']) && !empty($_POST['password'])) {
595 return array($_POST['login'], $_POST['password'], false);
597 if (isset($_SERVER['REMOTE_USER'])) {
598 return array($_SERVER['REMOTE_USER'], 'http_auth', true);
601 return array(false, false, false);
605 * checks if login & password are correct and save the user in session.
606 * it redirects the user to the $referer link
607 * @param string $referer the url to redirect after login
608 * @todo add the return value
611 public function login($referer)
613 list($login,$password,$isauthenticated)=$this->credentials();
614 if($login === false || $password === false) {
615 $this->messages
->add('e', _('login failed: you have to fill all fields'));
616 Tools
::logm('login failed');
619 if (!empty($login) && !empty($password)) {
620 $user = $this->store
->login($login, Tools
::encodeString($password . $login), $isauthenticated);
621 if ($user != array()) {
622 # Save login into Session
623 $longlastingsession = isset($_POST['longlastingsession']);
624 $passwordTest = ($isauthenticated) ? $user['password'] : Tools
::encodeString($password . $login);
625 Session
::login($user['username'], $user['password'], $login, $passwordTest, $longlastingsession, array('poche_user' => new User($user)));
628 $language = $user['config']['language'];
629 @putenv('LC_ALL=' . $language);
630 setlocale(LC_ALL
, $language);
631 bindtextdomain($language, LOCALE
);
632 textdomain($language);
634 $this->messages
->add('s', _('welcome to your wallabag'));
635 Tools
::logm('login successful');
636 Tools
::redirect($referer);
638 $this->messages
->add('e', _('login failed: bad login or password'));
639 // log login failure in web server log to allow fail2ban usage
640 error_log('user '.$login.' authentication failure');
641 Tools
::logm('login failed');
647 * log out the poche user. It cleans the session.
648 * @todo add the return value
651 public function logout()
653 $this->user
= array();
655 Tools
::logm('logout');
660 * import datas into your wallabag
664 public function import() {
666 if ( isset($_FILES['file']) && $_FILES['file']['tmp_name'] ) {
667 Tools
::logm('Import stated: parsing file');
669 // assume, that file is in json format
670 $str_data = file_get_contents($_FILES['file']['tmp_name']);
671 $data = json_decode($str_data, true);
673 if ( $data === null ) {
674 //not json - assume html
675 $html = new simple_html_dom();
676 $html->load_file($_FILES['file']['tmp_name']);
679 foreach (array('ol','ul') as $list) {
680 foreach ($html->find($list) as $ul) {
681 foreach ($ul->find('li') as $li) {
684 $tmpEntry['url'] = $a[0]->href
;
685 $tmpEntry['tags'] = $a[0]->tags
;
686 $tmpEntry['is_read'] = $read;
687 if ($tmpEntry['url']) {
691 # the second <ol/ul> is for read links
692 $read = ((sizeof($data) && $read)?0:1);
697 // for readability structure
699 foreach($data as $record) {
700 if (is_array($record)) {
702 foreach($record as $record2) {
703 if (is_array($record2)) {
710 $urlsInserted = array(); //urls of articles inserted
711 foreach($data as $record) {
712 $url = trim(isset($record['article__url']) ? $record['article__url'] : (isset($record['url']) ? $record['url'] : ''));
713 if ($url and !in_array($url, $urlsInserted)) {
714 $title = (isset($record['title']) ? $record['title'] : _('Untitled - Import - ') . '</a> <a href="./?import">' . _('click to finish import') . '</a><a>');
715 $body = (isset($record['content']) ? $record['content'] : '');
716 $isRead = (isset($record['is_read']) ? intval($record['is_read']) : (isset($record['archive']) ? intval($record['archive']) : 0));
717 $isFavorite = (isset($record['is_fav']) ? intval($record['is_fav']) : (isset($record['favorite']) ? intval($record['favorite']) : 0));
721 $id = $this->store
->add($url, $title, $body, $this->user
->getId() , $isFavorite, $isRead);
723 $urlsInserted[] = $url; //add
724 if (isset($record['tags']) && trim($record['tags'])) {
726 $tags = explode(',', $record['tags']);
727 foreach($tags as $tag) {
729 $tag_id = $this->store
->retrieveTagByValue($tag);
731 $this->store
->setTagToEntry($tag_id['id'], $entry_id);
733 $this->store
->createTag($tag);
734 $tag_id = $this->store
->retrieveTagByValue($tag);
735 $this->store
->setTagToEntry($tag_id['id'], $entry_id);
744 $i = sizeof($urlsInserted);
746 $this->messages
->add('s', _('Articles inserted: ') . $i . _('. Please note, that some may be marked as "read".'));
749 Tools
::logm('Import of articles finished: '.$i.' articles added (w/o content if not provided).');
752 $this->messages
->add('s', _('Did you forget to select a file?'));
754 // file parsing finished here
755 // now download article contents if any
756 // check if we need to download any content
758 $recordsDownloadRequired = $this->store
->retrieveUnfetchedEntriesCount($this->user
->getId());
760 if ($recordsDownloadRequired == 0) {
762 // nothing to download
764 $this->messages
->add('s', _('Import finished.'));
765 Tools
::logm('Import finished completely');
770 // if just inserted - don't download anything, download will start in next reload
772 if (!isset($_FILES['file'])) {
774 // download next batch
776 Tools
::logm('Fetching next batch of articles...');
777 $items = $this->store
->retrieveUnfetchedEntries($this->user
->getId() , IMPORT_LIMIT
);
778 $purifier = $this->_getPurifier();
779 foreach($items as $item) {
780 $url = new Url(base64_encode($item['url']));
781 if( $url->isCorrect() )
783 Tools
::logm('Fetching article ' . $item['id']);
784 $content = Tools
::getPageContent($url);
785 $title = (($content['rss']['channel']['item']['title'] != '') ? $content['rss']['channel']['item']['title'] : _('Untitled'));
786 $body = (($content['rss']['channel']['item']['description'] != '') ? $content['rss']['channel']['item']['description'] : _('Undefined'));
788 // clean content to prevent xss attack
790 $title = $purifier->purify($title);
791 $body = $purifier->purify($body);
792 $this->store
->updateContentAndTitle($item['id'], $title, $body, $this->user
->getId());
793 Tools
::logm('Article ' . $item['id'] . ' updated.');
796 Tools
::logm('Unvalid URL (' . $item['url'] .') to fetch for article ' . $item['id']);
803 'includeImport' => true,
805 'recordsDownloadRequired' => $recordsDownloadRequired,
806 'recordsUnderDownload' => IMPORT_LIMIT
,
807 'delay' => IMPORT_DELAY
* 1000
813 * export poche entries in json
814 * @return json all poche entries
816 public function export()
818 $filename = "wallabag-export-".$this->user
->getId()."-".date("Y-m-d").".json";
819 header('Content-Disposition: attachment; filename='.$filename);
821 $entries = $this->store
->retrieveAll($this->user
->getId());
822 echo $this->tpl
->render('export.twig', array(
823 'export' => Tools
::renderJson($entries),
825 Tools
::logm('export view');
829 * Checks online the latest version of poche and cache it
830 * @param string $which 'prod' or 'dev'
831 * @return string latest $which version
833 private function _getPocheVersion($which = 'prod') {
834 $cache_file = CACHE
. '/' . $which;
835 $check_time = time();
837 # checks if the cached version file exists
838 if (file_exists($cache_file) && (filemtime($cache_file) > (time() - 86400 ))) {
839 $version = file_get_contents($cache_file);
840 $check_time = filemtime($cache_file);
842 $version = file_get_contents('http://static.wallabag.org/versions/' . $which);
843 file_put_contents($cache_file, $version, LOCK_EX
);
845 return array($version, $check_time);
849 * Update token for current user
851 public function updateToken()
853 $token = Tools
::generateToken();
854 $this->store
->updateUserConfig($this->user
->getId(), 'token', $token);
855 $currentConfig = $_SESSION['poche_user']->config
;
856 $currentConfig['token'] = $token;
857 $_SESSION['poche_user']->setConfig($currentConfig);
862 * Generate RSS feeds for current user
866 * @param $tag_id if $type is 'tag', the id of the tag to generate feed for
867 * @param string $type the type of feed to generate
868 * @param int $limit the maximum number of items (0 means all)
870 public function generateFeeds($token, $user_id, $tag_id, $type = 'home', $limit = 0)
872 $allowed_types = array('home', 'fav', 'archive', 'tag');
873 $config = $this->store
->getConfigUser($user_id);
875 if ($config == null) {
876 die(sprintf(_('User with this id (%d) does not exist.'), $user_id));
879 if (!in_array($type, $allowed_types) || !isset($config['token']) || $token != $config['token']) {
880 die(_('Uh, there is a problem while generating feed. Wrong token used?'));
883 $feed = new FeedWriter(RSS2
);
884 $feed->setTitle('wallabag — ' . $type . ' feed');
885 $feed->setLink(Tools
::getPocheUrl());
886 $feed->setChannelElement('pubDate', date(DATE_RSS
, time()));
887 $feed->setChannelElement('generator', 'wallabag');
888 $feed->setDescription('wallabag ' . $type . ' elements');
890 if ($type == 'tag') {
891 $entries = $this->store
->retrieveEntriesByTag($tag_id, $user_id);
894 $entries = $this->store
->getEntriesByView($type, $user_id);
897 // if $limit is set to zero, use all entries
899 $limit = count($entries);
901 if (count($entries) > 0) {
902 for ($i = 0; $i < min(count($entries), $limit); $i++
) {
903 $entry = $entries[$i];
904 $newItem = $feed->createNewItem();
905 $newItem->setTitle($entry['title']);
906 $newItem->setSource(Tools
::getPocheUrl() . '?view=view&id=' . $entry['id']);
907 $newItem->setLink($entry['url']);
908 $newItem->setDate(time());
909 $newItem->setDescription($entry['content']);
910 $feed->addItem($newItem);
914 $feed->genarateFeed();
921 * Returns new purifier object with actual config
923 private function _getPurifier()
925 $config = HTMLPurifier_Config
::createDefault();
926 $config->set('Cache.SerializerPath', CACHE
);
927 $config->set('HTML.SafeIframe', true);
929 //allow YouTube, Vimeo and dailymotion videos
930 $config->set('URI.SafeIframeRegexp', '%^(https?:)?//(www\.youtube(?:-nocookie)?\.com/embed/|player\.vimeo\.com/video/|www\.dailymotion\.com/embed/video/)%');
932 return new HTMLPurifier($config);