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