]> git.immae.eu Git - github/wallabag/wallabag.git/blob - inc/poche/Poche.class.php
merge
[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
341 case 'reload_article' :
342 Tools::logm('reload article');
343 $id = $_GET['id'];
344 $entry = $this->store->retrieveOneById($id, $this->user->getId());
345 Tools::logm('reload url ' . $entry['url']);
346 $url = new Url(base64_encode($entry['url']));
347 $this->action('add', $url);
348 break;
349
350 /* 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 */
351 case 'random':
352 $count = $this->store->getEntriesByViewCount($view, $this->user->getId());
353 $id = rand(1,$count);
354 Tools::logm('get a random article');
355 Tools::redirect('?view=view&id=' . $id);
356 //$this->displayView('view', $id);
357 break;
358 default:
359 break;
360 }
361 }
362
363 function displayView($view, $id = 0)
364 {
365 $tpl_vars = array();
366
367 switch ($view)
368 {
369 case 'about':
370 break;
371 case 'config':
372 $dev_infos = $this->_getPocheVersion('dev');
373 $dev = trim($dev_infos[0]);
374 $check_time_dev = date('d-M-Y H:i', $dev_infos[1]);
375 $prod_infos = $this->_getPocheVersion('prod');
376 $prod = trim($prod_infos[0]);
377 $check_time_prod = date('d-M-Y H:i', $prod_infos[1]);
378 $compare_dev = version_compare(POCHE, $dev);
379 $compare_prod = version_compare(POCHE, $prod);
380 $themes = $this->tpl->getInstalledThemes();
381 $languages = $this->language->getInstalledLanguages();
382 $token = $this->user->getConfigValue('token');
383 $http_auth = (isset($_SERVER['PHP_AUTH_USER']) || isset($_SERVER['REMOTE_USER'])) ? true : false;
384 $only_user = ($this->store->listUsers() > 1) ? false : true;
385 $tpl_vars = array(
386 'themes' => $themes,
387 'languages' => $languages,
388 'dev' => $dev,
389 'prod' => $prod,
390 'check_time_dev' => $check_time_dev,
391 'check_time_prod' => $check_time_prod,
392 'compare_dev' => $compare_dev,
393 'compare_prod' => $compare_prod,
394 'token' => $token,
395 'user_id' => $this->user->getId(),
396 'http_auth' => $http_auth,
397 'only_user' => $only_user
398 );
399 Tools::logm('config view');
400 break;
401 case 'edit-tags':
402 # tags
403 $entry = $this->store->retrieveOneById($id, $this->user->getId());
404 if (!$entry) {
405 $this->messages->add('e', _('Article not found!'));
406 Tools::logm('error : article not found');
407 Tools::redirect();
408 }
409 $tags = $this->store->retrieveTagsByEntry($id);
410 $tpl_vars = array(
411 'entry_id' => $id,
412 'tags' => $tags,
413 'entry' => $entry,
414 );
415 break;
416 case 'tags':
417 $token = $this->user->getConfigValue('token');
418 //if term is set - search tags for this term
419 $term = Tools::checkVar('term');
420 $tags = $this->store->retrieveAllTags($this->user->getId(), $term);
421 if (Tools::isAjaxRequest()) {
422 $result = array();
423 foreach ($tags as $tag) {
424 $result[] = $tag['value'];
425 }
426 echo json_encode($result);
427 exit;
428 }
429 $tpl_vars = array(
430 'token' => $token,
431 'user_id' => $this->user->getId(),
432 'tags' => $tags,
433 );
434 break;
435 case 'search':
436 if (isset($_GET['search'])) {
437 $search = filter_var($_GET['search'], FILTER_SANITIZE_STRING);
438 $tpl_vars['entries'] = $this->store->search($search, $this->user->getId());
439 $count = count($tpl_vars['entries']);
440 $this->pagination->set_total($count);
441 $page_links = str_replace(array('previous', 'next'), array(_('previous'), _('next')),
442 $this->pagination->page_links('?view=' . $view . '?search=' . $search . '&sort=' . $_SESSION['sort'] . '&' ));
443 $tpl_vars['page_links'] = $page_links;
444 $tpl_vars['nb_results'] = $count;
445 $tpl_vars['searchterm'] = $search;
446 }
447 break;
448 case 'view':
449 $entry = $this->store->retrieveOneById($id, $this->user->getId());
450 if ($entry != NULL) {
451 Tools::logm('view link #' . $id);
452 $content = $entry['content'];
453 if (function_exists('tidy_parse_string')) {
454 $tidy = tidy_parse_string($content, array('indent'=>true, 'show-body-only' => true), 'UTF8');
455 $tidy->cleanRepair();
456 $content = $tidy->value;
457 }
458
459 # flattr checking
460 $flattr = NULL;
461 if (FLATTR) {
462 $flattr = new FlattrItem();
463 $flattr->checkItem($entry['url'], $entry['id']);
464 }
465
466 # tags
467 $tags = $this->store->retrieveTagsByEntry($entry['id']);
468
469 $tpl_vars = array(
470 'entry' => $entry,
471 'content' => $content,
472 'flattr' => $flattr,
473 'tags' => $tags
474 );
475 }
476 else {
477 Tools::logm('error in view call : entry is null');
478 }
479 break;
480 default: # home, favorites, archive and tag views
481 $tpl_vars = array(
482 'entries' => '',
483 'page_links' => '',
484 'nb_results' => '',
485 'listmode' => (isset($_COOKIE['listmode']) ? true : false),
486 );
487
488 //if id is given - we retrieve entries by tag: id is tag id
489 if ($id) {
490 $tpl_vars['tag'] = $this->store->retrieveTag($id, $this->user->getId());
491 $tpl_vars['id'] = intval($id);
492 }
493
494 $count = $this->store->getEntriesByViewCount($view, $this->user->getId(), $id);
495
496 if ($count > 0) {
497 $this->pagination->set_total($count);
498 $page_links = str_replace(array('previous', 'next'), array(_('previous'), _('next')),
499 $this->pagination->page_links('?view=' . $view . '&sort=' . $_SESSION['sort'] . (($id)?'&id='.$id:'') . '&' ));
500 $tpl_vars['entries'] = $this->store->getEntriesByView($view, $this->user->getId(), $this->pagination->get_limit(), $id);
501 $tpl_vars['page_links'] = $page_links;
502 $tpl_vars['nb_results'] = $count;
503 }
504 Tools::logm('display ' . $view . ' view');
505 break;
506 }
507
508 return $tpl_vars;
509 }
510
511 /**
512 * update the password of the current user.
513 * if MODE_DEMO is TRUE, the password can't be updated.
514 * @todo add the return value
515 * @todo set the new password in function header like this updatePassword($newPassword)
516 * @return boolean
517 */
518 public function updatePassword($password, $confirmPassword)
519 {
520 if (MODE_DEMO) {
521 $this->messages->add('i', _('in demo mode, you can\'t update your password'));
522 Tools::logm('in demo mode, you can\'t do this');
523 Tools::redirect('?view=config');
524 }
525 else {
526 if (isset($password) && isset($confirmPassword)) {
527 if ($password == $confirmPassword && !empty($password)) {
528 $this->messages->add('s', _('your password has been updated'));
529 $this->store->updatePassword($this->user->getId(), Tools::encodeString($password . $this->user->getUsername()));
530 Session::logout();
531 Tools::logm('password updated');
532 Tools::redirect();
533 }
534 else {
535 $this->messages->add('e', _('the two fields have to be filled & the password must be the same in the two fields'));
536 Tools::redirect('?view=config');
537 }
538 }
539 }
540 }
541
542 /**
543 * Get credentials from differents sources
544 * It redirects the user to the $referer link
545 *
546 * @return array
547 */
548 private function credentials()
549 {
550 if (isset($_SERVER['PHP_AUTH_USER'])) {
551 return array($_SERVER['PHP_AUTH_USER'], 'php_auth', true);
552 }
553 if (!empty($_POST['login']) && !empty($_POST['password'])) {
554 return array($_POST['login'], $_POST['password'], false);
555 }
556 if (isset($_SERVER['REMOTE_USER'])) {
557 return array($_SERVER['REMOTE_USER'], 'http_auth', true);
558 }
559
560 return array(false, false, false);
561 }
562
563 /**
564 * checks if login & password are correct and save the user in session.
565 * it redirects the user to the $referer link
566 * @param string $referer the url to redirect after login
567 * @todo add the return value
568 * @return boolean
569 */
570 public function login($referer)
571 {
572 list($login,$password,$isauthenticated)=$this->credentials();
573 if($login === false || $password === false) {
574 $this->messages->add('e', _('login failed: you have to fill all fields'));
575 Tools::logm('login failed');
576 Tools::redirect();
577 }
578 if (!empty($login) && !empty($password)) {
579 $user = $this->store->login($login, Tools::encodeString($password . $login), $isauthenticated);
580 if ($user != array()) {
581 # Save login into Session
582 $longlastingsession = isset($_POST['longlastingsession']);
583 $passwordTest = ($isauthenticated) ? $user['password'] : Tools::encodeString($password . $login);
584 Session::login($user['username'], $user['password'], $login, $passwordTest, $longlastingsession, array('poche_user' => new User($user)));
585
586 # reload l10n
587 $language = $user['config']['language'];
588 @putenv('LC_ALL=' . $language);
589 setlocale(LC_ALL, $language);
590 bindtextdomain($language, LOCALE);
591 textdomain($language);
592
593 $this->messages->add('s', _('welcome to your wallabag'));
594 Tools::logm('login successful');
595 Tools::redirect($referer);
596 }
597 $this->messages->add('e', _('login failed: bad login or password'));
598 // log login failure in web server log to allow fail2ban usage
599 error_log('user '.$login.' authentication failure');
600 Tools::logm('login failed');
601 Tools::redirect();
602 }
603 }
604
605 /**
606 * log out the poche user. It cleans the session.
607 * @todo add the return value
608 * @return boolean
609 */
610 public function logout()
611 {
612 $this->user = array();
613 Session::logout();
614 Tools::logm('logout');
615 Tools::redirect();
616 }
617
618 /**
619 * import datas into your wallabag
620 * @return boolean
621 */
622
623 public function import() {
624
625 if ( isset($_FILES['file']) && $_FILES['file']['tmp_name'] ) {
626 Tools::logm('Import stated: parsing file');
627
628 // assume, that file is in json format
629 $str_data = file_get_contents($_FILES['file']['tmp_name']);
630 $data = json_decode($str_data, true);
631
632 if ( $data === null ) {
633 //not json - assume html
634 $html = new simple_html_dom();
635 $html->load_file($_FILES['file']['tmp_name']);
636 $data = array();
637 $read = 0;
638 foreach (array('ol','ul') as $list) {
639 foreach ($html->find($list) as $ul) {
640 foreach ($ul->find('li') as $li) {
641 $tmpEntry = array();
642 $a = $li->find('a');
643 $tmpEntry['url'] = $a[0]->href;
644 $tmpEntry['tags'] = $a[0]->tags;
645 $tmpEntry['is_read'] = $read;
646 if ($tmpEntry['url']) {
647 $data[] = $tmpEntry;
648 }
649 }
650 # the second <ol/ul> is for read links
651 $read = ((sizeof($data) && $read)?0:1);
652 }
653 }
654 }
655
656 // for readability structure
657
658 foreach($data as $record) {
659 if (is_array($record)) {
660 $data[] = $record;
661 foreach($record as $record2) {
662 if (is_array($record2)) {
663 $data[] = $record2;
664 }
665 }
666 }
667 }
668
669 $urlsInserted = array(); //urls of articles inserted
670 foreach($data as $record) {
671 $url = trim(isset($record['article__url']) ? $record['article__url'] : (isset($record['url']) ? $record['url'] : ''));
672 if ($url and !in_array($url, $urlsInserted)) {
673 $title = (isset($record['title']) ? $record['title'] : _('Untitled - Import - ') . '</a> <a href="./?import">' . _('click to finish import') . '</a><a>');
674 $body = (isset($record['content']) ? $record['content'] : '');
675 $isRead = (isset($record['is_read']) ? intval($record['is_read']) : (isset($record['archive']) ? intval($record['archive']) : 0));
676 $isFavorite = (isset($record['is_fav']) ? intval($record['is_fav']) : (isset($record['favorite']) ? intval($record['favorite']) : 0));
677
678 // insert new record
679
680 $id = $this->store->add($url, $title, $body, $this->user->getId() , $isFavorite, $isRead);
681 if ($id) {
682 $urlsInserted[] = $url; //add
683 if (isset($record['tags']) && trim($record['tags'])) {
684
685 $tags = explode(',', $record['tags']);
686 foreach($tags as $tag) {
687 $entry_id = $id;
688 $tag_id = $this->store->retrieveTagByValue($tag);
689 if ($tag_id) {
690 $this->store->setTagToEntry($tag_id['id'], $entry_id);
691 } else {
692 $this->store->createTag($tag);
693 $tag_id = $this->store->retrieveTagByValue($tag);
694 $this->store->setTagToEntry($tag_id['id'], $entry_id);
695 }
696 }
697
698 }
699 }
700 }
701 }
702
703 $i = sizeof($urlsInserted);
704 if ($i > 0) {
705 $this->messages->add('s', _('Articles inserted: ') . $i . _('. Please note, that some may be marked as "read".'));
706 }
707
708 Tools::logm('Import of articles finished: '.$i.' articles added (w/o content if not provided).');
709 }
710 else {
711 $this->messages->add('s', _('Did you forget to select a file?'));
712 }
713 // file parsing finished here
714 // now download article contents if any
715 // check if we need to download any content
716
717 $recordsDownloadRequired = $this->store->retrieveUnfetchedEntriesCount($this->user->getId());
718
719 if ($recordsDownloadRequired == 0) {
720
721 // nothing to download
722
723 $this->messages->add('s', _('Import finished.'));
724 Tools::logm('Import finished completely');
725 Tools::redirect();
726 }
727 else {
728
729 // if just inserted - don't download anything, download will start in next reload
730
731 if (!isset($_FILES['file'])) {
732
733 // download next batch
734
735 Tools::logm('Fetching next batch of articles...');
736 $items = $this->store->retrieveUnfetchedEntries($this->user->getId() , IMPORT_LIMIT);
737 $purifier = $this->_getPurifier();
738 foreach($items as $item) {
739 $url = new Url(base64_encode($item['url']));
740 Tools::logm('Fetching article ' . $item['id']);
741 $content = Tools::getPageContent($url);
742 $title = (($content['rss']['channel']['item']['title'] != '') ? $content['rss']['channel']['item']['title'] : _('Untitled'));
743 $body = (($content['rss']['channel']['item']['description'] != '') ? $content['rss']['channel']['item']['description'] : _('Undefined'));
744
745 // clean content to prevent xss attack
746
747 $title = $purifier->purify($title);
748 $body = $purifier->purify($body);
749 $this->store->updateContentAndTitle($item['id'], $title, $body, $this->user->getId());
750 Tools::logm('Article ' . $item['id'] . ' updated.');
751 }
752 }
753 }
754
755 return array(
756 'includeImport' => true,
757 'import' => array(
758 'recordsDownloadRequired' => $recordsDownloadRequired,
759 'recordsUnderDownload' => IMPORT_LIMIT,
760 'delay' => IMPORT_DELAY * 1000
761 )
762 );
763 }
764
765 /**
766 * export poche entries in json
767 * @return json all poche entries
768 */
769 public function export()
770 {
771 $filename = "wallabag-export-".$this->user->getId()."-".date("Y-m-d").".json";
772 header('Content-Disposition: attachment; filename='.$filename);
773
774 $entries = $this->store->retrieveAll($this->user->getId());
775 echo $this->tpl->render('export.twig', array(
776 'export' => Tools::renderJson($entries),
777 ));
778 Tools::logm('export view');
779 }
780
781 /**
782 * Checks online the latest version of poche and cache it
783 * @param string $which 'prod' or 'dev'
784 * @return string latest $which version
785 */
786 private function _getPocheVersion($which = 'prod') {
787 $cache_file = CACHE . '/' . $which;
788 $check_time = time();
789
790 # checks if the cached version file exists
791 if (file_exists($cache_file) && (filemtime($cache_file) > (time() - 86400 ))) {
792 $version = file_get_contents($cache_file);
793 $check_time = filemtime($cache_file);
794 } else {
795 $version = file_get_contents('http://static.wallabag.org/versions/' . $which);
796 file_put_contents($cache_file, $version, LOCK_EX);
797 }
798 return array($version, $check_time);
799 }
800
801 /**
802 * Update token for current user
803 */
804 public function updateToken()
805 {
806 $token = Tools::generateToken();
807 $this->store->updateUserConfig($this->user->getId(), 'token', $token);
808 $currentConfig = $_SESSION['poche_user']->config;
809 $currentConfig['token'] = $token;
810 $_SESSION['poche_user']->setConfig($currentConfig);
811 Tools::redirect();
812 }
813
814 /**
815 * Generate RSS feeds for current user
816 *
817 * @param $token
818 * @param $user_id
819 * @param $tag_id if $type is 'tag', the id of the tag to generate feed for
820 * @param string $type the type of feed to generate
821 * @param int $limit the maximum number of items (0 means all)
822 */
823 public function generateFeeds($token, $user_id, $tag_id, $type = 'home', $limit = 0)
824 {
825 $allowed_types = array('home', 'fav', 'archive', 'tag');
826 $config = $this->store->getConfigUser($user_id);
827
828 if ($config == null) {
829 die(sprintf(_('User with this id (%d) does not exist.'), $user_id));
830 }
831
832 if (!in_array($type, $allowed_types) || !isset($config['token']) || $token != $config['token']) {
833 die(_('Uh, there is a problem while generating feed. Wrong token used?'));
834 }
835
836 $feed = new FeedWriter(RSS2);
837 $feed->setTitle('wallabag — ' . $type . ' feed');
838 $feed->setLink(Tools::getPocheUrl());
839 $feed->setChannelElement('pubDate', date(DATE_RSS , time()));
840 $feed->setChannelElement('generator', 'wallabag');
841 $feed->setDescription('wallabag ' . $type . ' elements');
842
843 if ($type == 'tag') {
844 $entries = $this->store->retrieveEntriesByTag($tag_id, $user_id);
845 }
846 else {
847 $entries = $this->store->getEntriesByView($type, $user_id);
848 }
849
850 // if $limit is set to zero, use all entries
851 if (0 == $limit) {
852 $limit = count($entries);
853 }
854 if (count($entries) > 0) {
855 for ($i = 0; $i < min(count($entries), $limit); $i++) {
856 $entry = $entries[$i];
857 $newItem = $feed->createNewItem();
858 $newItem->setTitle($entry['title']);
859 $newItem->setSource(Tools::getPocheUrl() . '?view=view&amp;id=' . $entry['id']);
860 $newItem->setLink($entry['url']);
861 $newItem->setDate(time());
862 $newItem->setDescription($entry['content']);
863 $feed->addItem($newItem);
864 }
865 }
866
867 $feed->genarateFeed();
868 exit;
869 }
870
871
872
873 /**
874 * Returns new purifier object with actual config
875 */
876 private function _getPurifier()
877 {
878 $config = HTMLPurifier_Config::createDefault();
879 $config->set('Cache.SerializerPath', CACHE);
880 $config->set('HTML.SafeIframe', true);
881
882 //allow YouTube, Vimeo and dailymotion videos
883 $config->set('URI.SafeIframeRegexp', '%^(https?:)?//(www\.youtube(?:-nocookie)?\.com/embed/|player\.vimeo\.com/video/|www\.dailymotion\.com/embed/video/)%');
884
885 return new HTMLPurifier($config);
886 }
887
888
889 }