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