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