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