]> git.immae.eu Git - github/wallabag/wallabag.git/blob - inc/poche/Poche.class.php
working on registration support
[github/wallabag/wallabag.git] / inc / poche / Poche.class.php
1 <?php
2 /**
3 * wallabag, self hostable application allowing you to not miss any content anymore
4 *
5 * @category wallabag
6 * @author Nicolas Lœuillet <nicolas@loeuillet.org>
7 * @copyright 2013
8 * @license http://opensource.org/licenses/MIT see COPYING file
9 */
10
11 class Poche
12 {
13 /**
14 * @var User
15 */
16 public $user;
17 /**
18 * @var Database
19 */
20 public $store;
21 /**
22 * @var Template
23 */
24 public $tpl;
25 /**
26 * @var Language
27 */
28 public $language;
29 /**
30 * @var Routing
31 */
32 public $routing;
33 /**
34 * @var Messages
35 */
36 public $messages;
37 /**
38 * @var Paginator
39 */
40 public $pagination;
41
42 public function __construct()
43 {
44 $this->init();
45 }
46
47 private function init()
48 {
49 Tools::initPhp();
50
51 $pocheUser = Session::getParam('poche_user');
52
53 if ($pocheUser && $pocheUser != array()) {
54 $this->user = $pocheUser;
55 } else {
56 // fake user, just for install & login screens
57 $this->user = new User();
58 $this->user->setConfig($this->getDefaultConfig());
59 }
60
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);
67 }
68
69 public function run()
70 {
71 $this->routing->run();
72 }
73
74 /**
75 * Creates a new user
76 */
77 public function createNewUser($username, $password, $email = "")
78 {
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 Tools::logm('The new user ' . $newUsername . ' has been installed');
86 $this->messages->add('s', sprintf(_('The new user %s has been installed. Do you want to <a href="?logout">logout ?</a>'), $newUsername));
87 Tools::redirect();
88 }
89 else {
90 Tools::logm('error during adding new user');
91 Tools::redirect();
92 }
93 }
94 else {
95 $this->messages->add('e', sprintf(_('Error : An user with the name %s already exists !'), $newUsername));
96 Tools::logm('An user with the name ' . $newUsername . ' already exists !');
97 Tools::redirect();
98 }
99 }
100 else {
101 Tools::logm('Password or username were empty');
102 }
103 }
104
105 /**
106 * Delete an existing user
107 */
108 public function deleteUser($password)
109 {
110 if ($this->store->listUsers() > 1) {
111 if (Tools::encodeString($password . $this->user->getUsername()) == $this->store->getUserPassword($this->user->getId())) {
112 $username = $this->user->getUsername();
113 $this->store->deleteUserConfig($this->user->getId());
114 Tools::logm('The configuration for user '. $username .' has been deleted !');
115 $this->store->deleteTagsEntriesAndEntries($this->user->getId());
116 Tools::logm('The entries for user '. $username .' has been deleted !');
117 $this->store->deleteUser($this->user->getId());
118 Tools::logm('User '. $username .' has been completely deleted !');
119 Session::logout();
120 Tools::logm('logout');
121 Tools::redirect();
122 $this->messages->add('s', sprintf(_('User %s has been successfully deleted !'), $username));
123 }
124 else {
125 Tools::logm('Bad password !');
126 $this->messages->add('e', _('Error : The password is wrong !'));
127 }
128 }
129 else {
130 Tools::logm('Only user !');
131 $this->messages->add('e', _('Error : You are the only user, you cannot delete your account !'));
132 }
133 }
134
135 public function getDefaultConfig()
136 {
137 return array(
138 'pager' => PAGINATION,
139 'language' => LANG,
140 'theme' => DEFAULT_THEME
141 );
142 }
143
144 /**
145 * Call action (mark as fav, archive, delete, etc.)
146 */
147 public function action($action, Url $url, $id = 0, $import = FALSE, $autoclose = FALSE, $tags = null)
148 {
149 switch ($action)
150 {
151 case 'add':
152 $content = Tools::getPageContent($url);
153 $title = ($content['rss']['channel']['item']['title'] != '') ? $content['rss']['channel']['item']['title'] : _('Untitled');
154 $body = $content['rss']['channel']['item']['description'];
155
156 // clean content from prevent xss attack
157 $purifier = $this->_getPurifier();
158 $title = $purifier->purify($title);
159 $body = $purifier->purify($body);
160
161 //search for possible duplicate
162 $duplicate = NULL;
163 $duplicate = $this->store->retrieveOneByURL($url->getUrl(), $this->user->getId());
164
165 $last_id = $this->store->add($url->getUrl(), $title, $body, $this->user->getId());
166 if ( $last_id ) {
167 Tools::logm('add link ' . $url->getUrl());
168 if (DOWNLOAD_PICTURES) {
169 $content = Picture::filterPicture($body, $url->getUrl(), $last_id);
170 Tools::logm('updating content article');
171 $this->store->updateContent($last_id, $content, $this->user->getId());
172 }
173
174 if ($duplicate != NULL) {
175 // 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
176 Tools::logm('link ' . $url->getUrl() . ' is a duplicate');
177 // 1) - preserve tags and favorite, then drop old entry
178 $this->store->reassignTags($duplicate['id'], $last_id);
179 if ($duplicate['is_fav']) {
180 $this->store->favoriteById($last_id, $this->user->getId());
181 }
182 if ($this->store->deleteById($duplicate['id'], $this->user->getId())) {
183 Tools::logm('previous link ' . $url->getUrl() .' entry deleted');
184 }
185 }
186
187 // if there are tags, add them to the new article
188 if (isset($_GET['tags'])) {
189 $_POST['value'] = $_GET['tags'];
190 $_POST['entry_id'] = $last_id;
191 $this->action('add_tag', $url);
192 }
193
194 $this->messages->add('s', _('the link has been added successfully'));
195 }
196 else {
197 $this->messages->add('e', _('error during insertion : the link wasn\'t added'));
198 Tools::logm('error during insertion : the link wasn\'t added ' . $url->getUrl());
199 }
200
201 if ($autoclose == TRUE) {
202 Tools::redirect('?view=home');
203 } else {
204 Tools::redirect('?view=home&closewin=true');
205 }
206 return $last_id;
207 break;
208 case 'delete':
209 if (isset($_GET['search'])) {
210 //when we want to apply a delete to a search
211 $tags = array($_GET['search']);
212 $allentry_ids = $this->store->search($tags[0], $this->user->getId());
213 $entry_ids = array();
214 foreach ($allentry_ids as $eachentry) {
215 $entry_ids[] = $eachentry[0];
216 }
217 } else { // delete a single article
218 $entry_ids = array($id);
219 }
220 foreach($entry_ids as $id) {
221 $msg = 'delete link #' . $id;
222 if ($this->store->deleteById($id, $this->user->getId())) {
223 if (DOWNLOAD_PICTURES) {
224 Picture::removeDirectory(ABS_PATH . $id);
225 }
226 $this->messages->add('s', _('the link has been deleted successfully'));
227 }
228 else {
229 $this->messages->add('e', _('the link wasn\'t deleted'));
230 $msg = 'error : can\'t delete link #' . $id;
231 }
232 Tools::logm($msg);
233 }
234 Tools::redirect('?');
235 break;
236 case 'toggle_fav' :
237 $this->store->favoriteById($id, $this->user->getId());
238 Tools::logm('mark as favorite link #' . $id);
239 if ( Tools::isAjaxRequest() ) {
240 echo 1;
241 exit;
242 }
243 else {
244 Tools::redirect();
245 }
246 break;
247 case 'toggle_archive' :
248 if (isset($_GET['tag_id'])) {
249 //when we want to archive a whole tag
250 $tag_id = $_GET['tag_id'];
251 $allentry_ids = $this->store->retrieveEntriesByTag($tag_id, $this->user->getId());
252 $entry_ids = array();
253 foreach ($allentry_ids as $eachentry) {
254 $entry_ids[] = $eachentry[0];
255 }
256 } else { //archive a single article
257 $entry_ids = array($id);
258 }
259 foreach($entry_ids as $id) {
260 $this->store->archiveById($id, $this->user->getId());
261 Tools::logm('archive link #' . $id);
262 }
263 if ( Tools::isAjaxRequest() ) {
264 echo 1;
265 exit;
266 }
267 else {
268 Tools::redirect();
269 }
270 break;
271 case 'archive_all' :
272 $this->store->archiveAll($this->user->getId());
273 Tools::logm('archive all links');
274 Tools::redirect();
275 break;
276 case 'add_tag' :
277 if (isset($_GET['search'])) {
278 //when we want to apply a tag to a search
279 $tags = array($_GET['search']);
280 $allentry_ids = $this->store->search($tags[0], $this->user->getId());
281 $entry_ids = array();
282 foreach ($allentry_ids as $eachentry) {
283 $entry_ids[] = $eachentry[0];
284 }
285 } else { //add a tag to a single article
286 $tags = explode(',', $_POST['value']);
287 $entry_ids = array($_POST['entry_id']);
288 }
289 foreach($entry_ids as $entry_id) {
290 $entry = $this->store->retrieveOneById($entry_id, $this->user->getId());
291 if (!$entry) {
292 $this->messages->add('e', _('Article not found!'));
293 Tools::logm('error : article not found');
294 Tools::redirect();
295 }
296 //get all already set tags to preven duplicates
297 $already_set_tags = array();
298 $entry_tags = $this->store->retrieveTagsByEntry($entry_id);
299 foreach ($entry_tags as $tag) {
300 $already_set_tags[] = $tag['value'];
301 }
302 foreach($tags as $key => $tag_value) {
303 $value = trim($tag_value);
304 if ($value && !in_array($value, $already_set_tags)) {
305 $tag = $this->store->retrieveTagByValue($value);
306 if (is_null($tag)) {
307 # we create the tag
308 $tag = $this->store->createTag($value);
309 $sequence = '';
310 if (STORAGE == 'postgres') {
311 $sequence = 'tags_id_seq';
312 }
313 $tag_id = $this->store->getLastId($sequence);
314 }
315 else {
316 $tag_id = $tag['id'];
317 }
318
319 # we assign the tag to the article
320 $this->store->setTagToEntry($tag_id, $entry_id);
321 }
322 }
323 }
324 $this->messages->add('s', _('The tag has been applied successfully'));
325 Tools::logm('The tag has been applied successfully');
326 Tools::redirect();
327 break;
328 case 'remove_tag' :
329 $tag_id = $_GET['tag_id'];
330 $entry = $this->store->retrieveOneById($id, $this->user->getId());
331 if (!$entry) {
332 $this->messages->add('e', _('Article not found!'));
333 Tools::logm('error : article not found');
334 Tools::redirect();
335 }
336 $this->store->removeTagForEntry($id, $tag_id);
337 Tools::logm('tag entry deleted');
338 if ($this->store->cleanUnusedTag($tag_id)) {
339 Tools::logm('tag deleted');
340 }
341 $this->messages->add('s', _('The tag has been successfully deleted'));
342 Tools::redirect();
343 break;
344 default:
345 break;
346 }
347 }
348
349 function displayView($view, $id = 0)
350 {
351 $tpl_vars = array();
352
353 switch ($view)
354 {
355 case 'about':
356 break;
357 case 'config':
358 $dev_infos = $this->_getPocheVersion('dev');
359 $dev = trim($dev_infos[0]);
360 $check_time_dev = date('d-M-Y H:i', $dev_infos[1]);
361 $prod_infos = $this->_getPocheVersion('prod');
362 $prod = trim($prod_infos[0]);
363 $check_time_prod = date('d-M-Y H:i', $prod_infos[1]);
364 $compare_dev = version_compare(POCHE, $dev);
365 $compare_prod = version_compare(POCHE, $prod);
366 $themes = $this->tpl->getInstalledThemes();
367 $languages = $this->language->getInstalledLanguages();
368 $token = $this->user->getConfigValue('token');
369 $http_auth = (isset($_SERVER['PHP_AUTH_USER']) || isset($_SERVER['REMOTE_USER'])) ? true : false;
370 $only_user = ($this->store->listUsers() > 1) ? false : true;
371 $tpl_vars = array(
372 'themes' => $themes,
373 'languages' => $languages,
374 'dev' => $dev,
375 'prod' => $prod,
376 'check_time_dev' => $check_time_dev,
377 'check_time_prod' => $check_time_prod,
378 'compare_dev' => $compare_dev,
379 'compare_prod' => $compare_prod,
380 'token' => $token,
381 'user_id' => $this->user->getId(),
382 'http_auth' => $http_auth,
383 'only_user' => $only_user
384 );
385 Tools::logm('config view');
386 break;
387 case 'edit-tags':
388 # tags
389 $entry = $this->store->retrieveOneById($id, $this->user->getId());
390 if (!$entry) {
391 $this->messages->add('e', _('Article not found!'));
392 Tools::logm('error : article not found');
393 Tools::redirect();
394 }
395 $tags = $this->store->retrieveTagsByEntry($id);
396 $tpl_vars = array(
397 'entry_id' => $id,
398 'tags' => $tags,
399 'entry' => $entry,
400 );
401 break;
402 case 'tags':
403 $token = $this->user->getConfigValue('token');
404 //if term is set - search tags for this term
405 $term = Tools::checkVar('term');
406 $tags = $this->store->retrieveAllTags($this->user->getId(), $term);
407 if (Tools::isAjaxRequest()) {
408 $result = array();
409 foreach ($tags as $tag) {
410 $result[] = $tag['value'];
411 }
412 echo json_encode($result);
413 exit;
414 }
415 $tpl_vars = array(
416 'token' => $token,
417 'user_id' => $this->user->getId(),
418 'tags' => $tags,
419 );
420 break;
421 case 'search':
422 if (isset($_GET['search'])) {
423 $search = filter_var($_GET['search'], FILTER_SANITIZE_STRING);
424 $tpl_vars['entries'] = $this->store->search($search, $this->user->getId());
425 $count = count($tpl_vars['entries']);
426 $this->pagination->set_total($count);
427 $page_links = str_replace(array('previous', 'next'), array(_('previous'), _('next')),
428 $this->pagination->page_links('?view=' . $view . '?search=' . $search . '&sort=' . $_SESSION['sort'] . '&' ));
429 $tpl_vars['page_links'] = $page_links;
430 $tpl_vars['nb_results'] = $count;
431 $tpl_vars['searchterm'] = $search;
432 }
433 break;
434 case 'view':
435 $entry = $this->store->retrieveOneById($id, $this->user->getId());
436 if ($entry != NULL) {
437 Tools::logm('view link #' . $id);
438 $content = $entry['content'];
439 if (function_exists('tidy_parse_string')) {
440 $tidy = tidy_parse_string($content, array('indent'=>true, 'show-body-only' => true), 'UTF8');
441 $tidy->cleanRepair();
442 $content = $tidy->value;
443 }
444
445 # flattr checking
446 $flattr = NULL;
447 if (FLATTR) {
448 $flattr = new FlattrItem();
449 $flattr->checkItem($entry['url'], $entry['id']);
450 }
451
452 # tags
453 $tags = $this->store->retrieveTagsByEntry($entry['id']);
454
455 $tpl_vars = array(
456 'entry' => $entry,
457 'content' => $content,
458 'flattr' => $flattr,
459 'tags' => $tags
460 );
461 }
462 else {
463 Tools::logm('error in view call : entry is null');
464 }
465 break;
466 default: # home, favorites, archive and tag views
467 $tpl_vars = array(
468 'entries' => '',
469 'page_links' => '',
470 'nb_results' => '',
471 'listmode' => (isset($_COOKIE['listmode']) ? true : false),
472 );
473
474 //if id is given - we retrieve entries by tag: id is tag id
475 if ($id) {
476 $tpl_vars['tag'] = $this->store->retrieveTag($id, $this->user->getId());
477 $tpl_vars['id'] = intval($id);
478 }
479
480 $count = $this->store->getEntriesByViewCount($view, $this->user->getId(), $id);
481
482 if ($count > 0) {
483 $this->pagination->set_total($count);
484 $page_links = str_replace(array('previous', 'next'), array(_('previous'), _('next')),
485 $this->pagination->page_links('?view=' . $view . '&sort=' . $_SESSION['sort'] . (($id)?'&id='.$id:'') . '&' ));
486 $tpl_vars['entries'] = $this->store->getEntriesByView($view, $this->user->getId(), $this->pagination->get_limit(), $id);
487 $tpl_vars['page_links'] = $page_links;
488 $tpl_vars['nb_results'] = $count;
489 }
490 Tools::logm('display ' . $view . ' view');
491 break;
492 }
493
494 return $tpl_vars;
495 }
496
497 /**
498 * update the password of the current user.
499 * if MODE_DEMO is TRUE, the password can't be updated.
500 * @todo add the return value
501 * @todo set the new password in function header like this updatePassword($newPassword)
502 * @return boolean
503 */
504 public function updatePassword($password, $confirmPassword)
505 {
506 if (MODE_DEMO) {
507 $this->messages->add('i', _('in demo mode, you can\'t update your password'));
508 Tools::logm('in demo mode, you can\'t do this');
509 Tools::redirect('?view=config');
510 }
511 else {
512 if (isset($password) && isset($confirmPassword)) {
513 if ($password == $confirmPassword && !empty($password)) {
514 $this->messages->add('s', _('your password has been updated'));
515 $this->store->updatePassword($this->user->getId(), Tools::encodeString($password . $this->user->getUsername()));
516 Session::logout();
517 Tools::logm('password updated');
518 Tools::redirect();
519 }
520 else {
521 $this->messages->add('e', _('the two fields have to be filled & the password must be the same in the two fields'));
522 Tools::redirect('?view=config');
523 }
524 }
525 }
526 }
527
528 /**
529 * Get credentials from differents sources
530 * It redirects the user to the $referer link
531 *
532 * @return array
533 */
534 private function credentials()
535 {
536 if (isset($_SERVER['PHP_AUTH_USER'])) {
537 return array($_SERVER['PHP_AUTH_USER'], 'php_auth', true);
538 }
539 if (!empty($_POST['login']) && !empty($_POST['password'])) {
540 return array($_POST['login'], $_POST['password'], false);
541 }
542 if (isset($_SERVER['REMOTE_USER'])) {
543 return array($_SERVER['REMOTE_USER'], 'http_auth', true);
544 }
545
546 return array(false, false, false);
547 }
548
549 /**
550 * checks if login & password are correct and save the user in session.
551 * it redirects the user to the $referer link
552 * @param string $referer the url to redirect after login
553 * @todo add the return value
554 * @return boolean
555 */
556 public function login($referer)
557 {
558 list($login,$password,$isauthenticated)=$this->credentials();
559 if($login === false || $password === false) {
560 $this->messages->add('e', _('login failed: you have to fill all fields'));
561 Tools::logm('login failed');
562 Tools::redirect();
563 }
564 if (!empty($login) && !empty($password)) {
565 $user = $this->store->login($login, Tools::encodeString($password . $login), $isauthenticated);
566 if ($user != array()) {
567 # Save login into Session
568 $longlastingsession = isset($_POST['longlastingsession']);
569 $passwordTest = ($isauthenticated) ? $user['password'] : Tools::encodeString($password . $login);
570 Session::login($user['username'], $user['password'], $login, $passwordTest, $longlastingsession, array('poche_user' => new User($user)));
571
572 # reload l10n
573 $language = $user['config']['language'];
574 @putenv('LC_ALL=' . $language);
575 setlocale(LC_ALL, $language);
576 bindtextdomain($language, LOCALE);
577 textdomain($language);
578
579 $this->messages->add('s', _('welcome to your wallabag'));
580 Tools::logm('login successful');
581 Tools::redirect($referer);
582 }
583 $this->messages->add('e', _('login failed: bad login or password'));
584 // log login failure in web server log to allow fail2ban usage
585 error_log('user '.$login.' authentication failure');
586 Tools::logm('login failed');
587 Tools::redirect();
588 }
589 }
590
591 /**
592 * log out the poche user. It cleans the session.
593 * @todo add the return value
594 * @return boolean
595 */
596 public function logout()
597 {
598 $this->user = array();
599 Session::logout();
600 Tools::logm('logout');
601 Tools::redirect();
602 }
603
604 /**
605 * import datas into your wallabag
606 * @return boolean
607 */
608
609 public function import() {
610
611 if ( isset($_FILES['file']) && $_FILES['file']['tmp_name'] ) {
612 Tools::logm('Import stated: parsing file');
613
614 // assume, that file is in json format
615 $str_data = file_get_contents($_FILES['file']['tmp_name']);
616 $data = json_decode($str_data, true);
617
618 if ( $data === null ) {
619 //not json - assume html
620 $html = new simple_html_dom();
621 $html->load_file($_FILES['file']['tmp_name']);
622 $data = array();
623 $read = 0;
624 foreach (array('ol','ul') as $list) {
625 foreach ($html->find($list) as $ul) {
626 foreach ($ul->find('li') as $li) {
627 $tmpEntry = array();
628 $a = $li->find('a');
629 $tmpEntry['url'] = $a[0]->href;
630 $tmpEntry['tags'] = $a[0]->tags;
631 $tmpEntry['is_read'] = $read;
632 if ($tmpEntry['url']) {
633 $data[] = $tmpEntry;
634 }
635 }
636 # the second <ol/ul> is for read links
637 $read = ((sizeof($data) && $read)?0:1);
638 }
639 }
640 }
641
642 // for readability structure
643
644 foreach($data as $record) {
645 if (is_array($record)) {
646 $data[] = $record;
647 foreach($record as $record2) {
648 if (is_array($record2)) {
649 $data[] = $record2;
650 }
651 }
652 }
653 }
654
655 $urlsInserted = array(); //urls of articles inserted
656 foreach($data as $record) {
657 $url = trim(isset($record['article__url']) ? $record['article__url'] : (isset($record['url']) ? $record['url'] : ''));
658 if ($url and !in_array($url, $urlsInserted)) {
659 $title = (isset($record['title']) ? $record['title'] : _('Untitled - Import - ') . '</a> <a href="./?import">' . _('click to finish import') . '</a><a>');
660 $body = (isset($record['content']) ? $record['content'] : '');
661 $isRead = (isset($record['is_read']) ? intval($record['is_read']) : (isset($record['archive']) ? intval($record['archive']) : 0));
662 $isFavorite = (isset($record['is_fav']) ? intval($record['is_fav']) : (isset($record['favorite']) ? intval($record['favorite']) : 0));
663
664 // insert new record
665
666 $id = $this->store->add($url, $title, $body, $this->user->getId() , $isFavorite, $isRead);
667 if ($id) {
668 $urlsInserted[] = $url; //add
669 if (isset($record['tags']) && trim($record['tags'])) {
670
671 $tags = explode(',', $record['tags']);
672 foreach($tags as $tag) {
673 $entry_id = $id;
674 $tag_id = $this->store->retrieveTagByValue($tag);
675 if ($tag_id) {
676 $this->store->setTagToEntry($tag_id['id'], $entry_id);
677 } else {
678 $this->store->createTag($tag);
679 $tag_id = $this->store->retrieveTagByValue($tag);
680 $this->store->setTagToEntry($tag_id['id'], $entry_id);
681 }
682 }
683
684 }
685 }
686 }
687 }
688
689 $i = sizeof($urlsInserted);
690 if ($i > 0) {
691 $this->messages->add('s', _('Articles inserted: ') . $i . _('. Please note, that some may be marked as "read".'));
692 }
693
694 Tools::logm('Import of articles finished: '.$i.' articles added (w/o content if not provided).');
695 }
696 else {
697 $this->messages->add('s', _('Did you forget to select a file?'));
698 }
699 // file parsing finished here
700 // now download article contents if any
701 // check if we need to download any content
702
703 $recordsDownloadRequired = $this->store->retrieveUnfetchedEntriesCount($this->user->getId());
704
705 if ($recordsDownloadRequired == 0) {
706
707 // nothing to download
708
709 $this->messages->add('s', _('Import finished.'));
710 Tools::logm('Import finished completely');
711 Tools::redirect();
712 }
713 else {
714
715 // if just inserted - don't download anything, download will start in next reload
716
717 if (!isset($_FILES['file'])) {
718
719 // download next batch
720
721 Tools::logm('Fetching next batch of articles...');
722 $items = $this->store->retrieveUnfetchedEntries($this->user->getId() , IMPORT_LIMIT);
723 $purifier = $this->_getPurifier();
724 foreach($items as $item) {
725 $url = new Url(base64_encode($item['url']));
726 Tools::logm('Fetching article ' . $item['id']);
727 $content = Tools::getPageContent($url);
728 $title = (($content['rss']['channel']['item']['title'] != '') ? $content['rss']['channel']['item']['title'] : _('Untitled'));
729 $body = (($content['rss']['channel']['item']['description'] != '') ? $content['rss']['channel']['item']['description'] : _('Undefined'));
730
731 // clean content to prevent xss attack
732
733 $title = $purifier->purify($title);
734 $body = $purifier->purify($body);
735 $this->store->updateContentAndTitle($item['id'], $title, $body, $this->user->getId());
736 Tools::logm('Article ' . $item['id'] . ' updated.');
737 }
738 }
739 }
740
741 return array(
742 'includeImport' => true,
743 'import' => array(
744 'recordsDownloadRequired' => $recordsDownloadRequired,
745 'recordsUnderDownload' => IMPORT_LIMIT,
746 'delay' => IMPORT_DELAY * 1000
747 )
748 );
749 }
750
751 /**
752 * export poche entries in json
753 * @return json all poche entries
754 */
755 public function export()
756 {
757 $filename = "wallabag-export-".$this->user->getId()."-".date("Y-m-d").".json";
758 header('Content-Disposition: attachment; filename='.$filename);
759
760 $entries = $this->store->retrieveAll($this->user->getId());
761 echo $this->tpl->render('export.twig', array(
762 'export' => Tools::renderJson($entries),
763 ));
764 Tools::logm('export view');
765 }
766
767 /**
768 * Checks online the latest version of poche and cache it
769 * @param string $which 'prod' or 'dev'
770 * @return string latest $which version
771 */
772 private function _getPocheVersion($which = 'prod') {
773 $cache_file = CACHE . '/' . $which;
774 $check_time = time();
775
776 # checks if the cached version file exists
777 if (file_exists($cache_file) && (filemtime($cache_file) > (time() - 86400 ))) {
778 $version = file_get_contents($cache_file);
779 $check_time = filemtime($cache_file);
780 } else {
781 $version = file_get_contents('http://static.wallabag.org/versions/' . $which);
782 file_put_contents($cache_file, $version, LOCK_EX);
783 }
784 return array($version, $check_time);
785 }
786
787 /**
788 * Update token for current user
789 */
790 public function updateToken()
791 {
792 $token = Tools::generateToken();
793 $this->store->updateUserConfig($this->user->getId(), 'token', $token);
794 $currentConfig = $_SESSION['poche_user']->config;
795 $currentConfig['token'] = $token;
796 $_SESSION['poche_user']->setConfig($currentConfig);
797 Tools::redirect();
798 }
799
800 /**
801 * Generate RSS feeds for current user
802 *
803 * @param $token
804 * @param $user_id
805 * @param $tag_id if $type is 'tag', the id of the tag to generate feed for
806 * @param string $type the type of feed to generate
807 * @param int $limit the maximum number of items (0 means all)
808 */
809 public function generateFeeds($token, $user_id, $tag_id, $type = 'home', $limit = 0)
810 {
811 $allowed_types = array('home', 'fav', 'archive', 'tag');
812 $config = $this->store->getConfigUser($user_id);
813
814 if ($config == null) {
815 die(sprintf(_('User with this id (%d) does not exist.'), $user_id));
816 }
817
818 if (!in_array($type, $allowed_types) || !isset($config['token']) || $token != $config['token']) {
819 die(_('Uh, there is a problem while generating feed. Wrong token used?'));
820 }
821
822 $feed = new FeedWriter(RSS2);
823 $feed->setTitle('wallabag — ' . $type . ' feed');
824 $feed->setLink(Tools::getPocheUrl());
825 $feed->setChannelElement('pubDate', date(DATE_RSS , time()));
826 $feed->setChannelElement('generator', 'wallabag');
827 $feed->setDescription('wallabag ' . $type . ' elements');
828
829 if ($type == 'tag') {
830 $entries = $this->store->retrieveEntriesByTag($tag_id, $user_id);
831 }
832 else {
833 $entries = $this->store->getEntriesByView($type, $user_id);
834 }
835
836 // if $limit is set to zero, use all entries
837 if (0 == $limit) {
838 $limit = count($entries);
839 }
840 if (count($entries) > 0) {
841 for ($i = 0; $i < min(count($entries), $limit); $i++) {
842 $entry = $entries[$i];
843 $newItem = $feed->createNewItem();
844 $newItem->setTitle($entry['title']);
845 $newItem->setSource(Tools::getPocheUrl() . '?view=view&amp;id=' . $entry['id']);
846 $newItem->setLink($entry['url']);
847 $newItem->setDate(time());
848 $newItem->setDescription($entry['content']);
849 $feed->addItem($newItem);
850 }
851 }
852
853 $feed->genarateFeed();
854 exit;
855 }
856
857
858
859 /**
860 * Returns new purifier object with actual config
861 */
862 private function _getPurifier()
863 {
864 $config = HTMLPurifier_Config::createDefault();
865 $config->set('Cache.SerializerPath', CACHE);
866 $config->set('HTML.SafeIframe', true);
867
868 //allow YouTube, Vimeo and dailymotion videos
869 $config->set('URI.SafeIframeRegexp', '%^(https?:)?//(www\.youtube(?:-nocookie)?\.com/embed/|player\.vimeo\.com/video/|www\.dailymotion\.com/embed/video/)%');
870
871 return new HTMLPurifier($config);
872 }
873
874
875 }