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 from config screen
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 !");
100 $body = $internalRegistration ? $body_internal : $body;
102 $body = wordwrap($body, 70, "\r\n"); // cut lines with more than 70 caracters (MIME standard)
103 if (mail($email, sprintf(_('Your
new wallabag account on %
1$s'), Tools
::getPocheUrl()), $body,
104 'X-Mailer: PHP/' . phpversion() . "\r\n" .
105 'Content-type: text/plain; charset=UTF-8' . "\r\n" .
106 "From: " . $newUsername . "@" . gethostname() . "\r\n")) {
107 Tools
::logm('The user ' . $newUsername . ' has been emailed');
108 $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));
109 Tools
::redirect('?');
112 Tools
::logm('A problem has been encountered while sending an email');
113 $this->messages
->add('e', _('A problem has been encountered while sending an email'));
116 Tools
::logm('The user has been created, but the server did not authorize sending emails');
117 $this->messages
->add('i', _('The server did not authorize sending a confirmation email, but the user was created.'));
120 Tools
::logm('The user has been created, but no email was saved, so no confimation email was sent');
121 $this->messages
->add('i', _('The user was created, but no email was sent because email was not filled in'));
123 Tools
::logm('The new user ' . $newUsername . ' has been installed');
124 if (\Session
::isLogged()) {
125 $this->messages
->add('s', sprintf(_('The new user %s has been installed. Do you want to <a href="?logout">logout ?</a>'), $newUsername));
130 Tools
::logm('error during adding new user');
135 $this->messages
->add('e', sprintf(_('Error : An user with the name %s already exists !'), $newUsername));
136 Tools
::logm('An user with the name ' . $newUsername . ' already exists !');
141 Tools
::logm('Password or username were empty');
146 * Delete an existing user
148 public function deleteUser($password)
150 if ($this->store
->listUsers() > 1) {
151 if (Tools
::encodeString($password . $this->user
->getUsername()) == $this->store
->getUserPassword($this->user
->getId())) {
152 $username = $this->user
->getUsername();
153 $this->store
->deleteUserConfig($this->user
->getId());
154 Tools
::logm('The configuration for user '. $username .' has been deleted !');
155 $this->store
->deleteTagsEntriesAndEntries($this->user
->getId());
156 Tools
::logm('The entries for user '. $username .' has been deleted !');
157 $this->store
->deleteUser($this->user
->getId());
158 Tools
::logm('User '. $username .' has been completely deleted !');
160 Tools
::logm('logout');
162 $this->messages
->add('s', sprintf(_('User %s has been successfully deleted !'), $username));
165 Tools
::logm('Bad password !');
166 $this->messages
->add('e', _('Error : The password is wrong !'));
170 Tools
::logm('Only user !');
171 $this->messages
->add('e', _('Error : You are the only user, you cannot delete your account !'));
175 public function getDefaultConfig()
178 'pager' => PAGINATION
,
180 'theme' => DEFAULT_THEME
185 * Call action (mark as fav, archive, delete, etc.)
187 public function action($action, Url
$url, $id = 0, $import = FALSE, $autoclose = FALSE, $tags = null)
192 $content = Tools
::getPageContent($url);
193 $title = ($content['rss']['channel']['item']['title'] != '') ? $content['rss']['channel']['item']['title'] : parse_url($url, PHP_URL_HOST
);
194 $body = $content['rss']['channel']['item']['description'];
196 // clean content from prevent xss attack
197 $purifier = $this->_getPurifier();
198 $title = $purifier->purify($title);
199 $body = $purifier->purify($body);
201 //search for possible duplicate
203 $clean_url = $url->getUrl();
205 // Clean URL to remove parameters from feedburner and all this stuff. Taken from Shaarli.
206 $i=strpos($clean_url,'&utm_source='); if ($i!==false) $clean_url=substr($clean_url,0,$i);
207 $i=strpos($clean_url,'?utm_source='); if ($i!==false) $clean_url=substr($clean_url,0,$i);
208 $i=strpos($clean_url,'#xtor=RSS-'); if ($i!==false) $clean_url=substr($clean_url,0,$i);
210 $duplicate = $this->store
->retrieveOneByURL($clean_url, $this->user
->getId());
212 $last_id = $this->store
->add($clean_url, $title, $body, $this->user
->getId());
214 Tools
::logm('add link ' . $clean_url);
215 if (DOWNLOAD_PICTURES
) {
216 $content = Picture
::filterPicture($body, $clean_url, $last_id);
217 Tools
::logm('updating content article');
218 $this->store
->updateContent($last_id, $content, $this->user
->getId());
221 if ($duplicate != NULL) {
222 // 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
223 Tools
::logm('link ' . $clean_url . ' is a duplicate');
224 // 1) - preserve tags and favorite, then drop old entry
225 $this->store
->reassignTags($duplicate['id'], $last_id);
226 if ($duplicate['is_fav']) {
227 $this->store
->favoriteById($last_id, $this->user
->getId());
229 if ($this->store
->deleteById($duplicate['id'], $this->user
->getId())) {
230 Tools
::logm('previous link ' . $clean_url .' entry deleted');
234 // if there are tags, add them to the new article
235 if (isset($_GET['tags'])) {
236 $_POST['value'] = $_GET['tags'];
237 $_POST['entry_id'] = $last_id;
238 $this->action('add_tag', $url);
241 $this->messages
->add('s', _('the link has been added successfully'));
244 $this->messages
->add('e', _('error during insertion : the link wasn\'t added'));
245 Tools
::logm('error during insertion : the link wasn\'t added ' . $clean_url);
248 if ($autoclose == TRUE) {
249 Tools
::redirect('?view=home&closewin=true');
251 Tools
::redirect('?view=home');
256 if (isset($_GET['search'])) {
257 //when we want to apply a delete to a search
258 $tags = array($_GET['search']);
259 $allentry_ids = $this->store
->search($tags[0], $this->user
->getId());
260 $entry_ids = array();
261 foreach ($allentry_ids as $eachentry) {
262 $entry_ids[] = $eachentry[0];
264 } else { // delete a single article
265 $entry_ids = array($id);
267 foreach($entry_ids as $id) {
268 $msg = 'delete link #' . $id;
270 // deleting tags and tags_entries
271 $tags = $this->store
->retrieveTagsByEntry($id);
272 foreach ($tags as $tag) {
273 $this->store
->removeTagForEntry($id, $tag['id']);
274 $this->store
->cleanUnusedTag($tag['id']);
278 if ($this->store
->deleteById($id, $this->user
->getId())) {
279 if (DOWNLOAD_PICTURES
) {
280 Picture
::removeDirectory(ABS_PATH
. $id);
282 $this->messages
->add('s', _('the link has been deleted successfully'));
285 $this->messages
->add('e', _('the link wasn\'t deleted'));
286 $msg = 'error : can\'t delete link #' . $id;
290 Tools
::redirect('?');
293 $this->store
->favoriteById($id, $this->user
->getId());
294 Tools
::logm('mark as favorite link #' . $id);
295 if ( Tools
::isAjaxRequest() ) {
303 case 'toggle_archive' :
304 if (isset($_GET['tag_id'])) {
305 //when we want to archive a whole tag
306 $tag_id = $_GET['tag_id'];
307 $allentry_ids = $this->store
->retrieveEntriesByTag($tag_id, $this->user
->getId());
308 $entry_ids = array();
309 foreach ($allentry_ids as $eachentry) {
310 $entry_ids[] = $eachentry[0];
312 } else { //archive a single article
313 $entry_ids = array($id);
315 foreach($entry_ids as $id) {
316 $this->store
->archiveById($id, $this->user
->getId());
317 Tools
::logm('archive link #' . $id);
319 if ( Tools
::isAjaxRequest() ) {
326 case 'archive_and_next' :
327 $nextid = $this->store
->getPreviousArticle($id, $this->user
->getId());
328 $this->store
->archiveById($id, $this->user
->getId());
329 Tools
::logm('archive link #' . $id);
330 Tools
::redirect('?view=view&id=' . $nextid);
333 $this->store
->archiveAll($this->user
->getId());
334 Tools
::logm('archive all links');
338 if (isset($_GET['search'])) {
339 //when we want to apply a tag to a search
340 $tags = array($_GET['search']);
341 $allentry_ids = $this->store
->search($tags[0], $this->user
->getId());
342 $entry_ids = array();
343 foreach ($allentry_ids as $eachentry) {
344 $entry_ids[] = $eachentry[0];
346 } else { //add a tag to a single article
347 $tags = explode(',', $_POST['value']);
348 $entry_ids = array($_POST['entry_id']);
350 foreach($entry_ids as $entry_id) {
351 $entry = $this->store
->retrieveOneById($entry_id, $this->user
->getId());
353 $this->messages
->add('e', _('Article not found!'));
354 Tools
::logm('error : article not found');
357 //get all already set tags to preven duplicates
358 $already_set_tags = array();
359 $entry_tags = $this->store
->retrieveTagsByEntry($entry_id);
360 foreach ($entry_tags as $tag) {
361 $already_set_tags[] = $tag['value'];
363 foreach($tags as $key => $tag_value) {
364 $value = trim($tag_value);
365 if ($value && !in_array($value, $already_set_tags)) {
366 $tag = $this->store
->retrieveTagByValue($value);
369 $tag = $this->store
->createTag($value);
371 if (STORAGE
== 'postgres') {
372 $sequence = 'tags_id_seq';
374 $tag_id = $this->store
->getLastId($sequence);
377 $tag_id = $tag['id'];
380 # we assign the tag to the article
381 $this->store
->setTagToEntry($tag_id, $entry_id);
385 $this->messages
->add('s', _('The tag has been applied successfully'));
386 Tools
::logm('The tag has been applied successfully');
390 $tag_id = $_GET['tag_id'];
391 $entry = $this->store
->retrieveOneById($id, $this->user
->getId());
393 $this->messages
->add('e', _('Article not found!'));
394 Tools
::logm('error : article not found');
397 $this->store
->removeTagForEntry($id, $tag_id);
398 Tools
::logm('tag entry deleted');
399 if ($this->store
->cleanUnusedTag($tag_id)) {
400 Tools
::logm('tag deleted');
402 $this->messages
->add('s', _('The tag has been successfully deleted'));
406 case 'reload_article' :
407 Tools
::logm('reload article');
409 $entry = $this->store
->retrieveOneById($id, $this->user
->getId());
410 Tools
::logm('reload url ' . $entry['url']);
411 $url = new Url(base64_encode($entry['url']));
412 $this->action('add', $url);
415 /* 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 */
417 Tools
::logm('get a random article');
418 $view = $_GET['view'];
419 if ($this->store
->getRandomId($this->user
->getId(),$view)) {
420 $id_array = $this->store
->getRandomId($this->user
->getId(),$view);
422 Tools
::redirect('?view=view&id=' . $id[0]);
423 Tools
::logm('got the article with id ' . $id[0]);
431 function displayView($view, $id = 0)
440 $dev_infos = $this->_getPocheVersion('dev');
441 $dev = trim($dev_infos[0]);
442 $check_time_dev = date('d-M-Y H:i', $dev_infos[1]);
443 $prod_infos = $this->_getPocheVersion('prod');
444 $prod = trim($prod_infos[0]);
445 $check_time_prod = date('d-M-Y H:i', $prod_infos[1]);
446 $compare_dev = version_compare(POCHE
, $dev);
447 $compare_prod = version_compare(POCHE
, $prod);
448 $themes = $this->tpl
->getInstalledThemes();
449 $languages = $this->language
->getInstalledLanguages();
450 $token = $this->user
->getConfigValue('token');
451 $http_auth = isset($_SERVER['REMOTE_USER']);
452 $only_user = ($this->store
->listUsers() > 1) ? false : true;
453 $https = substr(Tools
::getPocheUrl(), 0, 5) == 'https';
456 'languages' => $languages,
459 'check_time_dev' => $check_time_dev,
460 'check_time_prod' => $check_time_prod,
461 'compare_dev' => $compare_dev,
462 'compare_prod' => $compare_prod,
464 'user_id' => $this->user
->getId(),
465 'http_auth' => $http_auth,
466 'only_user' => $only_user,
469 Tools
::logm('config view');
473 $entry = $this->store
->retrieveOneById($id, $this->user
->getId());
475 $this->messages
->add('e', _('Article not found!'));
476 Tools
::logm('error : article not found');
479 $tags = $this->store
->retrieveTagsByEntry($id);
480 $all_tags = $this->store
->retrieveAllTags($this->user
->getId());
482 foreach ($all_tags as $eachtag) { // search for the most times a tag is present
483 if ($eachtag["entriescount"] > $maximus) $maximus = $eachtag["entriescount"];
485 foreach ($all_tags as $key => $eachtag) { // get the percentage of presence of each tag
486 $percent = floor(($eachtag["entriescount"] / $maximus) * 100);
488 if ($percent < 20): // assign a css class, depending on the number of entries count
489 $cssclass = 'smallesttag';
490 elseif ($percent >= 20 and $percent < 40):
491 $cssclass = 'smalltag';
492 elseif ($percent >= 40 and $percent < 60):
493 $cssclass = 'mediumtag';
494 elseif ($percent >= 60 and $percent < 80):
495 $cssclass = 'largetag';
497 $cssclass = 'largesttag';
499 $all_tags[$key]['cssclass'] = $cssclass;
504 'alltags' => $all_tags,
509 $token = $this->user
->getConfigValue('token');
510 //if term is set - search tags for this term
511 $term = Tools
::checkVar('term');
512 $tags = $this->store
->retrieveAllTags($this->user
->getId(), $term);
513 if (Tools
::isAjaxRequest()) {
515 foreach ($tags as $tag) {
516 $result[] = $tag['value'];
518 echo json_encode($result);
523 'user_id' => $this->user
->getId(),
528 if (isset($_GET['search'])) {
529 $search = filter_var($_GET['search'], FILTER_SANITIZE_STRING
);
530 $tpl_vars['entries'] = $this->store
->search($search, $this->user
->getId());
531 $count = count($tpl_vars['entries']);
532 $this->pagination
->set_total($count);
533 $page_links = str_replace(array('previous', 'next'), array(_('previous'), _('next')),
534 $this->pagination
->page_links('?view=' . $view . '?search=' . $search . '&sort=' . $_SESSION['sort'] . '&' ));
535 $tpl_vars['page_links'] = $page_links;
536 $tpl_vars['nb_results'] = $count;
537 $tpl_vars['searchterm'] = $search;
541 $entry = $this->store
->retrieveOneById($id, $this->user
->getId());
542 if ($entry != NULL) {
543 Tools
::logm('view link #' . $id);
544 $content = $entry['content'];
545 if (function_exists('tidy_parse_string')) {
546 $tidy = tidy_parse_string($content, array('indent'=>true, 'show-body-only' => true), 'UTF8');
547 $tidy->cleanRepair();
548 $content = $tidy->value
;
554 $flattr = new FlattrItem();
555 $flattr->checkItem($entry['url'], $entry['id']);
560 $previous_id = $this->store
->getPreviousArticle($id, $this->user
->getId());
562 $next_id = $this->store
->getNextArticle($id, $this->user
->getId());
564 if ($this->store
->retrieveOneById($previous_id, $this->user
->getId())) {
567 if ($this->store
->retrieveOneById($next_id, $this->user
->getId())) {
570 $navigate = array('previous' => $previous, 'previousid' => $previous_id, 'next' => $next, 'nextid' => $next_id);
573 $tags = $this->store
->retrieveTagsByEntry($entry['id']);
577 'content' => $content,
580 'navigate' => $navigate
584 Tools
::logm('error in view call : entry is null');
587 default: # home, favorites, archive and tag views
592 'listmode' => (isset($_COOKIE['listmode']) ? true : false),
596 //if id is given - we retrieve entries by tag: id is tag id
598 $tpl_vars['tag'] = $this->store
->retrieveTag($id, $this->user
->getId());
599 $tpl_vars['id'] = intval($id);
602 $count = $this->store
->getEntriesByViewCount($view, $this->user
->getId(), $id);
604 if ($count && $count > 0) {
605 $this->pagination
->set_total($count);
606 $page_links = str_replace(array('previous', 'next'), array(_('previous'), _('next')),
607 $this->pagination
->page_links('?view=' . $view . '&sort=' . $_SESSION['sort'] . (($id)?'&id='.$id:'') . '&' ));
608 $tpl_vars['entries'] = $this->store
->getEntriesByView($view, $this->user
->getId(), $this->pagination
->get_limit(), $id);
609 $tpl_vars['page_links'] = $page_links;
610 $tpl_vars['nb_results'] = $count;
612 Tools
::logm('display ' . $view . ' view');
620 * update the password of the current user.
621 * if MODE_DEMO is TRUE, the password can't be updated.
622 * @todo add the return value
623 * @todo set the new password in function header like this updatePassword($newPassword)
626 public function updatePassword($password, $confirmPassword)
629 $this->messages
->add('i', _('in demo mode, you can\'t update your password'));
630 Tools
::logm('in demo mode, you can\'t do this');
631 Tools
::redirect('?view=config');
634 if (isset($password) && isset($confirmPassword)) {
635 if ($password == $confirmPassword && !empty($password)) {
636 $this->messages
->add('s', _('your password has been updated'));
637 $this->store
->updatePassword($this->user
->getId(), Tools
::encodeString($password . $this->user
->getUsername()));
639 Tools
::logm('password updated');
643 $this->messages
->add('e', _('the two fields have to be filled & the password must be the same in the two fields'));
644 Tools
::redirect('?view=config');
651 * Get credentials from differents sources
652 * It redirects the user to the $referer link
656 private function credentials()
658 if (!empty($_POST['login']) && !empty($_POST['password'])) {
659 return array($_POST['login'], $_POST['password'], false);
661 if (isset($_SERVER['REMOTE_USER'])) {
662 return array($_SERVER['REMOTE_USER'], 'http_auth', true);
665 return array(false, false, false);
669 * checks if login & password are correct and save the user in session.
670 * it redirects the user to the $referer link
671 * @param string $referer the url to redirect after login
672 * @todo add the return value
675 public function login($referer)
677 list($login,$password,$isauthenticated)=$this->credentials();
678 if($login === false || $password === false) {
679 $this->messages
->add('e', _('login failed: you have to fill all fields'));
680 Tools
::logm('login failed');
683 if (!empty($login) && !empty($password)) {
684 $user = $this->store
->login($login, Tools
::encodeString($password . $login), $isauthenticated);
685 if ($user != array()) {
686 # Save login into Session
687 $longlastingsession = isset($_POST['longlastingsession']);
688 $passwordTest = ($isauthenticated) ? $user['password'] : Tools
::encodeString($password . $login);
689 Session
::login($user['username'], $user['password'], $login, $passwordTest, $longlastingsession, array('poche_user' => new User($user)));
692 $language = $user['config']['language'];
693 @putenv('LC_ALL=' . $language);
694 setlocale(LC_ALL
, $language);
695 bindtextdomain($language, LOCALE
);
696 textdomain($language);
697 bind_textdomain_codeset($language, 'UTF-8');
699 $this->messages
->add('s', _('welcome to your wallabag'));
700 Tools
::logm('login successful');
701 Tools
::redirect($referer);
703 $this->messages
->add('e', _('login failed: bad login or password'));
704 // log login failure in web server log to allow fail2ban usage
705 error_log('user '.$login.' authentication failure');
706 Tools
::logm('login failed');
712 * log out the poche user. It cleans the session.
713 * @todo add the return value
716 public function logout()
718 $this->user
= array();
720 Tools
::logm('logout');
725 * import datas into your wallabag
729 public function import() {
731 if ( isset($_FILES['file']) && $_FILES['file']['tmp_name'] ) {
732 Tools
::logm('Import stated: parsing file');
734 // assume, that file is in json format
735 $str_data = file_get_contents($_FILES['file']['tmp_name']);
736 $data = json_decode($str_data, true);
738 if ( $data === null ) {
739 //not json - assume html
740 $html = new simple_html_dom();
741 $html->load_file($_FILES['file']['tmp_name']);
745 if (Tools
::get_doctype($html)->innertext
== "<!DOCTYPE NETSCAPE-Bookmark-file-1>") {
746 // Firefox-bookmarks HTML
747 foreach (array('DL','ul') as $list) {
748 foreach ($html->find($list) as $ul) {
749 foreach ($ul->find('DT') as $li) {
752 $tmpEntry['url'] = $a[0]->href
;
753 $tmpEntry['tags'] = $a[0]->tags
;
754 $tmpEntry['is_read'] = $read;
755 if ($tmpEntry['url']) {
759 # the second <ol/ul> is for read links
760 $read = ((sizeof($data) && $read)?0:1);
765 foreach (array('ol','ul') as $list) {
766 foreach ($html->find($list) as $ul) {
767 foreach ($ul->find('li') as $li) {
770 $tmpEntry['url'] = $a[0]->href
;
771 $tmpEntry['tags'] = $a[0]->tags
;
772 $tmpEntry['is_read'] = $read;
773 if ($tmpEntry['url']) {
777 # the second <ol/ul> is for read links
778 $read = ((sizeof($data) && $read)?0:1);
784 // for readability structure
786 foreach($data as $record) {
787 if (is_array($record)) {
789 foreach($record as $record2) {
790 if (is_array($record2)) {
797 $urlsInserted = array(); //urls of articles inserted
798 foreach($data as $record) {
799 $url = trim(isset($record['article__url']) ? $record['article__url'] : (isset($record['url']) ? $record['url'] : ''));
800 if (filter_var($url, FILTER_VALIDATE_URL
) and !in_array($url, $urlsInserted)) {
801 $title = (isset($record['title']) ? $record['title'] : _('Untitled - Import - ') . '</a> <a href="./?import">' . _('click to finish import') . '</a><a>');
802 $body = (isset($record['content']) ? $record['content'] : '');
803 $isRead = (isset($record['is_read']) ? intval($record['is_read']) : (isset($record['archive']) ? intval($record['archive']) : 0));
804 $isFavorite = (isset($record['is_fav']) ? intval($record['is_fav']) : (isset($record['favorite']) ? intval($record['favorite']) : 0));
808 $id = $this->store
->add($url, $title, $body, $this->user
->getId() , $isFavorite, $isRead);
810 $urlsInserted[] = $url; //add
811 if (isset($record['tags']) && trim($record['tags'])) {
813 $tags = explode(',', $record['tags']);
814 foreach($tags as $tag) {
816 $tag_id = $this->store
->retrieveTagByValue($tag);
818 $this->store
->setTagToEntry($tag_id['id'], $entry_id);
820 $this->store
->createTag($tag);
821 $tag_id = $this->store
->retrieveTagByValue($tag);
822 $this->store
->setTagToEntry($tag_id['id'], $entry_id);
831 $i = sizeof($urlsInserted);
833 $this->messages
->add('s', _('Articles inserted: ') . $i . _('. Please note, that some may be marked as "read".'));
836 Tools
::logm('Import of articles finished: '.$i.' articles added (w/o content if not provided).');
839 $this->messages
->add('e', _('Did you forget to select a file?'));
841 // file parsing finished here
842 // now download article contents if any
843 // check if we need to download any content
845 $recordsDownloadRequired = $this->store
->retrieveUnfetchedEntriesCount($this->user
->getId());
847 if ($recordsDownloadRequired == 0) {
849 // nothing to download
851 $this->messages
->add('s', _('Import finished.'));
852 Tools
::logm('Import finished completely');
857 // if just inserted - don't download anything, download will start in next reload
859 if (!isset($_FILES['file'])) {
861 // download next batch
863 Tools
::logm('Fetching next batch of articles...');
864 $items = $this->store
->retrieveUnfetchedEntries($this->user
->getId() , IMPORT_LIMIT
);
865 $purifier = $this->_getPurifier();
866 foreach($items as $item) {
867 $url = new Url(base64_encode($item['url']));
868 if( $url->isCorrect() )
870 Tools
::logm('Fetching article ' . $item['id']);
871 $content = Tools
::getPageContent($url);
872 $title = (($content['rss']['channel']['item']['title'] != '') ? $content['rss']['channel']['item']['title'] : _('Untitled'));
873 $body = (($content['rss']['channel']['item']['description'] != '') ? $content['rss']['channel']['item']['description'] : _('Undefined'));
875 // clean content to prevent xss attack
877 $title = $purifier->purify($title);
878 $body = $purifier->purify($body);
879 $this->store
->updateContentAndTitle($item['id'], $title, $body, $this->user
->getId());
880 Tools
::logm('Article ' . $item['id'] . ' updated.');
883 Tools
::logm('Unvalid URL (' . $item['url'] .') to fetch for article ' . $item['id']);
890 'includeImport' => true,
892 'recordsDownloadRequired' => $recordsDownloadRequired,
893 'recordsUnderDownload' => IMPORT_LIMIT
,
894 'delay' => IMPORT_DELAY
* 1000
900 * export poche entries in json
901 * @return json all poche entries
903 public function export()
905 $filename = "wallabag-export-".$this->user
->getId()."-".date("Y-m-d").".json";
906 header('Content-Disposition: attachment; filename='.$filename);
908 $entries = $this->store
->retrieveAllWithTags($this->user
->getId());
910 echo $this->tpl
->render('export.twig', array(
911 'export' => Tools
::renderJson($entries),
913 Tools
::logm('export view');
915 Tools
::logm('error accessing database while exporting');
920 * Checks online the latest version of poche and cache it
921 * @param string $which 'prod' or 'dev'
922 * @return string latest $which version
924 private function _getPocheVersion($which = 'prod') {
925 $cache_file = CACHE
. '/' . $which;
926 $check_time = time();
928 # checks if the cached version file exists
929 if (file_exists($cache_file) && (filemtime($cache_file) > (time() - 86400 ))) {
930 $version = file_get_contents($cache_file);
931 $check_time = filemtime($cache_file);
933 $version = file_get_contents('http://static.wallabag.org/versions/' . $which);
934 file_put_contents($cache_file, $version, LOCK_EX
);
936 return array($version, $check_time);
940 * Update token for current user
942 public function updateToken()
944 $token = Tools
::generateToken();
945 $this->store
->updateUserConfig($this->user
->getId(), 'token', $token);
946 $currentConfig = $_SESSION['poche_user']->config
;
947 $currentConfig['token'] = $token;
948 $_SESSION['poche_user']->setConfig($currentConfig);
953 * Generate RSS feeds for current user
957 * @param $tag_id if $type is 'tag', the id of the tag to generate feed for
958 * @param string $type the type of feed to generate
959 * @param int $limit the maximum number of items (0 means all)
961 public function generateFeeds($token, $user_id, $tag_id, $type = 'home', $limit = 0)
963 $allowed_types = array('home', 'fav', 'archive', 'tag');
964 $config = $this->store
->getConfigUser($user_id);
966 if ($config == null) {
967 die(sprintf(_('User with this id (%d) does not exist.'), $user_id));
970 if (!in_array($type, $allowed_types) || !isset($config['token']) || $token != $config['token']) {
971 die(_('Uh, there is a problem while generating feed. Wrong token used?'));
974 $feed = new FeedWriter(RSS2
);
975 $feed->setTitle('wallabag — ' . $type . ' feed');
976 $feed->setLink(Tools
::getPocheUrl());
977 $feed->setChannelElement('pubDate', date(DATE_RSS
, time()));
978 $feed->setChannelElement('generator', 'wallabag');
979 $feed->setDescription('wallabag ' . $type . ' elements');
981 if ($type == 'tag') {
982 $entries = $this->store
->retrieveEntriesByTag($tag_id, $user_id);
985 $entries = $this->store
->getEntriesByView($type, $user_id);
988 // if $limit is set to zero, use all entries
990 $limit = count($entries);
992 if ($entries && count($entries) > 0) {
993 for ($i = 0; $i < min(count($entries), $limit); $i++
) {
994 $entry = $entries[$i];
995 $newItem = $feed->createNewItem();
996 $newItem->setTitle($entry['title']);
997 $newItem->setSource(Tools
::getPocheUrl() . '?view=view&id=' . $entry['id']);
998 $newItem->setLink($entry['url']);
999 $newItem->setDate(time());
1000 $newItem->setDescription($entry['content']);
1001 $feed->addItem($newItem);
1006 Tools
::logm("database error while generating feeds");
1008 $feed->genarateFeed();
1015 * Returns new purifier object with actual config
1017 private function _getPurifier()
1019 $config = HTMLPurifier_Config
::createDefault();
1020 $config->set('Cache.SerializerPath', CACHE
);
1021 $config->set('HTML.SafeIframe', true);
1023 //allow YouTube, Vimeo and dailymotion videos
1024 $config->set('URI.SafeIframeRegexp', '%^(https?:)?//(www\.youtube(?:-nocookie)?\.com/embed/|player\.vimeo\.com/video/|www\.dailymotion\.com/embed/video/)%');
1026 return new HTMLPurifier($config);