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