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