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