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