]> git.immae.eu Git - github/wallabag/wallabag.git/blob - inc/poche/Poche.class.php
a lot of refactoring: tag action is now handled by home view and uses sorting and...
[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://www.wtfpl.net/ see COPYING file
9 */
10
11 class Poche
12 {
13 public static $canRenderTemplates = true;
14 public static $configFileAvailable = true;
15
16 public $user;
17 public $store;
18 public $tpl;
19 public $messages;
20 public $pagination;
21
22 private $currentTheme = '';
23 private $currentLanguage = '';
24 private $notInstalledMessage = array();
25
26 public function __construct()
27 {
28 if ($this->configFileIsAvailable()) {
29 $this->init();
30 }
31
32 if ($this->themeIsInstalled()) {
33 $this->initTpl();
34 }
35
36 if ($this->systemIsInstalled()) {
37 $this->store = new Database();
38 $this->messages = new Messages();
39 # installation
40 if (! $this->store->isInstalled()) {
41 $this->install();
42 }
43 $this->store->checkTags();
44 }
45 }
46
47 private function init()
48 {
49 Tools::initPhp();
50 Session::$sessionName = 'poche';
51 Session::init();
52
53 if (isset($_SESSION['poche_user']) && $_SESSION['poche_user'] != array()) {
54 $this->user = $_SESSION['poche_user'];
55 } else {
56 # fake user, just for install & login screens
57 $this->user = new User();
58 $this->user->setConfig($this->getDefaultConfig());
59 }
60
61 # l10n
62 $language = $this->user->getConfigValue('language');
63 putenv('LC_ALL=' . $language);
64 setlocale(LC_ALL, $language);
65 bindtextdomain($language, LOCALE);
66 textdomain($language);
67
68 # Pagination
69 $this->pagination = new Paginator($this->user->getConfigValue('pager'), 'p');
70
71 # Set up theme
72 $themeDirectory = $this->user->getConfigValue('theme');
73
74 if ($themeDirectory === false) {
75 $themeDirectory = DEFAULT_THEME;
76 }
77
78 $this->currentTheme = $themeDirectory;
79
80 # Set up language
81 $languageDirectory = $this->user->getConfigValue('language');
82
83 if ($languageDirectory === false) {
84 $languageDirectory = DEFAULT_THEME;
85 }
86
87 $this->currentLanguage = $languageDirectory;
88 }
89
90 public function configFileIsAvailable() {
91 if (! self::$configFileAvailable) {
92 $this->notInstalledMessage[] = 'You have to rename inc/poche/config.inc.php.new to inc/poche/config.inc.php.';
93
94 return false;
95 }
96
97 return true;
98 }
99
100 public function themeIsInstalled() {
101 $passTheme = TRUE;
102 # Twig is an absolute requirement for Poche to function. Abort immediately if the Composer installer hasn't been run yet
103 if (! self::$canRenderTemplates) {
104 $this->notInstalledMessage[] = 'Twig does not seem to be installed. Please initialize the Composer installation to automatically fetch dependencies. You can also download <a href="http://wllbg.org/vendor">vendor.zip</a> and extract it in your wallabag folder.';
105 $passTheme = FALSE;
106 }
107
108 if (! is_writable(CACHE)) {
109 $this->notInstalledMessage[] = 'You don\'t have write access on cache directory.';
110
111 self::$canRenderTemplates = false;
112
113 $passTheme = FALSE;
114 }
115
116 # Check if the selected theme and its requirements are present
117 $theme = $this->getTheme();
118
119 if ($theme != '' && ! is_dir(THEME . '/' . $theme)) {
120 $this->notInstalledMessage[] = 'The currently selected theme (' . $theme . ') does not seem to be properly installed (Missing directory: ' . THEME . '/' . $theme . ')';
121
122 self::$canRenderTemplates = false;
123
124 $passTheme = FALSE;
125 }
126
127 $themeInfo = $this->getThemeInfo($theme);
128 if (isset($themeInfo['requirements']) && is_array($themeInfo['requirements'])) {
129 foreach ($themeInfo['requirements'] as $requiredTheme) {
130 if (! is_dir(THEME . '/' . $requiredTheme)) {
131 $this->notInstalledMessage[] = 'The required "' . $requiredTheme . '" theme is missing for the current theme (' . $theme . ')';
132
133 self::$canRenderTemplates = false;
134
135 $passTheme = FALSE;
136 }
137 }
138 }
139
140 if (!$passTheme) {
141 return FALSE;
142 }
143
144
145 return true;
146 }
147
148 /**
149 * all checks before installation.
150 * @todo move HTML to template
151 * @return boolean
152 */
153 public function systemIsInstalled()
154 {
155 $msg = TRUE;
156
157 $configSalt = defined('SALT') ? constant('SALT') : '';
158
159 if (empty($configSalt)) {
160 $this->notInstalledMessage[] = 'You have not yet filled in the SALT value in the config.inc.php file.';
161 $msg = FALSE;
162 }
163 if (STORAGE == 'sqlite' && ! file_exists(STORAGE_SQLITE)) {
164 Tools::logm('sqlite file doesn\'t exist');
165 $this->notInstalledMessage[] = 'sqlite file doesn\'t exist, you can find it in install folder. Copy it in /db folder.';
166 $msg = FALSE;
167 }
168 if (is_dir(ROOT . '/install') && ! DEBUG_POCHE) {
169 $this->notInstalledMessage[] = 'you have to delete the /install folder before using poche.';
170 $msg = FALSE;
171 }
172 if (STORAGE == 'sqlite' && ! is_writable(STORAGE_SQLITE)) {
173 Tools::logm('you don\'t have write access on sqlite file');
174 $this->notInstalledMessage[] = 'You don\'t have write access on sqlite file.';
175 $msg = FALSE;
176 }
177
178 if (! $msg) {
179 return false;
180 }
181
182 return true;
183 }
184
185 public function getNotInstalledMessage() {
186 return $this->notInstalledMessage;
187 }
188
189 private function initTpl()
190 {
191 $loaderChain = new Twig_Loader_Chain();
192 $theme = $this->getTheme();
193
194 # add the current theme as first to the loader chain so Twig will look there first for overridden template files
195 try {
196 $loaderChain->addLoader(new Twig_Loader_Filesystem(THEME . '/' . $theme));
197 } catch (Twig_Error_Loader $e) {
198 # @todo isInstalled() should catch this, inject Twig later
199 die('The currently selected theme (' . $theme . ') does not seem to be properly installed (' . THEME . '/' . $theme .' is missing)');
200 }
201
202 # add all required themes to the loader chain
203 $themeInfo = $this->getThemeInfo($theme);
204 if (isset($themeInfo['requirements']) && is_array($themeInfo['requirements'])) {
205 foreach ($themeInfo['requirements'] as $requiredTheme) {
206 try {
207 $loaderChain->addLoader(new Twig_Loader_Filesystem(THEME . '/' . $requiredTheme));
208 } catch (Twig_Error_Loader $e) {
209 # @todo isInstalled() should catch this, inject Twig later
210 die('The required "' . $requiredTheme . '" theme is missing for the current theme (' . $theme . ')');
211 }
212 }
213 }
214
215 if (DEBUG_POCHE) {
216 $twigParams = array();
217 } else {
218 $twigParams = array('cache' => CACHE);
219 }
220
221 $this->tpl = new Twig_Environment($loaderChain, $twigParams);
222 $this->tpl->addExtension(new Twig_Extensions_Extension_I18n());
223
224 # filter to display domain name of an url
225 $filter = new Twig_SimpleFilter('getDomain', 'Tools::getDomain');
226 $this->tpl->addFilter($filter);
227
228 # filter for reading time
229 $filter = new Twig_SimpleFilter('getReadingTime', 'Tools::getReadingTime');
230 $this->tpl->addFilter($filter);
231 }
232
233 private function install()
234 {
235 Tools::logm('poche still not installed');
236 echo $this->tpl->render('install.twig', array(
237 'token' => Session::getToken(),
238 'theme' => $this->getTheme(),
239 'poche_url' => Tools::getPocheUrl()
240 ));
241 if (isset($_GET['install'])) {
242 if (($_POST['password'] == $_POST['password_repeat'])
243 && $_POST['password'] != "" && $_POST['login'] != "") {
244 # let's rock, install poche baby !
245 if ($this->store->install($_POST['login'], Tools::encodeString($_POST['password'] . $_POST['login'])))
246 {
247 Session::logout();
248 Tools::logm('poche is now installed');
249 Tools::redirect();
250 }
251 }
252 else {
253 Tools::logm('error during installation');
254 Tools::redirect();
255 }
256 }
257 exit();
258 }
259
260 public function getTheme() {
261 return $this->currentTheme;
262 }
263
264 /**
265 * Provides theme information by parsing theme.ini file if present in the theme's root directory.
266 * In all cases, the following data will be returned:
267 * - name: theme's name, or key if the theme is unnamed,
268 * - current: boolean informing if the theme is the current user theme.
269 *
270 * @param string $theme Theme key (directory name)
271 * @return array|boolean Theme information, or false if the theme doesn't exist.
272 */
273 public function getThemeInfo($theme) {
274 if (!is_dir(THEME . '/' . $theme)) {
275 return false;
276 }
277
278 $themeIniFile = THEME . '/' . $theme . '/theme.ini';
279 $themeInfo = array();
280
281 if (is_file($themeIniFile) && is_readable($themeIniFile)) {
282 $themeInfo = parse_ini_file($themeIniFile);
283 }
284
285 if ($themeInfo === false) {
286 $themeInfo = array();
287 }
288 if (!isset($themeInfo['name'])) {
289 $themeInfo['name'] = $theme;
290 }
291 $themeInfo['current'] = ($theme === $this->getTheme());
292
293 return $themeInfo;
294 }
295
296 public function getInstalledThemes() {
297 $handle = opendir(THEME);
298 $themes = array();
299
300 while (($theme = readdir($handle)) !== false) {
301 # Themes are stored in a directory, so all directory names are themes
302 # @todo move theme installation data to database
303 if (!is_dir(THEME . '/' . $theme) || in_array($theme, array('.', '..'))) {
304 continue;
305 }
306
307 $themes[$theme] = $this->getThemeInfo($theme);
308 }
309
310 return $themes;
311 }
312
313 public function getLanguage() {
314 return $this->currentLanguage;
315 }
316
317 public function getInstalledLanguages() {
318 $handle = opendir(LOCALE);
319 $languages = array();
320
321 while (($language = readdir($handle)) !== false) {
322 # Languages are stored in a directory, so all directory names are languages
323 # @todo move language installation data to database
324 if (! is_dir(LOCALE . '/' . $language) || in_array($language, array('..', '.'))) {
325 continue;
326 }
327
328 $current = false;
329
330 if ($language === $this->getLanguage()) {
331 $current = true;
332 }
333
334 $languages[] = array('name' => $language, 'current' => $current);
335 }
336
337 return $languages;
338 }
339
340 public function getDefaultConfig()
341 {
342 return array(
343 'pager' => PAGINATION,
344 'language' => LANG,
345 'theme' => DEFAULT_THEME
346 );
347 }
348
349 protected function getPageContent(Url $url)
350 {
351 // Saving and clearing context
352 $REAL = array();
353 foreach( $GLOBALS as $key => $value ) {
354 if( $key != "GLOBALS" && $key != "_SESSION" ) {
355 $GLOBALS[$key] = array();
356 $REAL[$key] = $value;
357 }
358 }
359 // Saving and clearing session
360 $REAL_SESSION = array();
361 foreach( $_SESSION as $key => $value ) {
362 $REAL_SESSION[$key] = $value;
363 unset($_SESSION[$key]);
364 }
365
366 // Running code in different context
367 $scope = function() {
368 extract( func_get_arg(1) );
369 $_GET = $_REQUEST = array(
370 "url" => $url->getUrl(),
371 "max" => 5,
372 "links" => "preserve",
373 "exc" => "",
374 "format" => "json",
375 "submit" => "Create Feed"
376 );
377 ob_start();
378 require func_get_arg(0);
379 $json = ob_get_flush();
380 return $json;
381 };
382 $json = $scope( "inc/3rdparty/makefulltextfeed.php", array("url" => $url) );
383
384 // Clearing and restoring context
385 foreach( $GLOBALS as $key => $value ) {
386 if( $key != "GLOBALS" && $key != "_SESSION" ) {
387 unset($GLOBALS[$key]);
388 }
389 }
390 foreach( $REAL as $key => $value ) {
391 $GLOBALS[$key] = $value;
392 }
393 // Clearing and restoring session
394 foreach( $_SESSION as $key => $value ) {
395 unset($_SESSION[$key]);
396 }
397 foreach( $REAL_SESSION as $key => $value ) {
398 $_SESSION[$key] = $value;
399 }
400 return json_decode($json, true);
401 }
402
403 /**
404 * Call action (mark as fav, archive, delete, etc.)
405 */
406 public function action($action, Url $url, $id = 0, $import = FALSE, $autoclose = FALSE)
407 {
408 switch ($action)
409 {
410 case 'add':
411 $content = $this->getPageContent($url);
412 $title = ($content['rss']['channel']['item']['title'] != '') ? $content['rss']['channel']['item']['title'] : _('Untitled');
413 $body = $content['rss']['channel']['item']['description'];
414
415 //search for possible duplicate if not in import mode
416 if (!$import) {
417 $duplicate = $this->store->retrieveOneByURL($url->getUrl(), $this->user->getId());
418 }
419
420 if ($this->store->add($url->getUrl(), $title, $body, $this->user->getId())) {
421 Tools::logm('add link ' . $url->getUrl());
422 $sequence = '';
423 if (STORAGE == 'postgres') {
424 $sequence = 'entries_id_seq';
425 }
426 $last_id = $this->store->getLastId($sequence);
427 if (DOWNLOAD_PICTURES) {
428 $content = filtre_picture($body, $url->getUrl(), $last_id);
429 Tools::logm('updating content article');
430 $this->store->updateContent($last_id, $content, $this->user->getId());
431 }
432
433 if ($duplicate != NULL) {
434 // 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
435 Tools::logm('link ' . $url->getUrl() . ' is a duplicate');
436 // 1) - preserve tags and favorite, then drop old entry
437 $this->store->reassignTags($duplicate['id'], $last_id);
438 if ($duplicate['is_fav']) {
439 $this->store->favoriteById($last_id, $this->user->getId());
440 }
441 if ($this->store->deleteById($duplicate['id'], $this->user->getId())) {
442 Tools::logm('previous link ' . $url->getUrl() .' entry deleted');
443 }
444 }
445
446 if (!$import) {
447 $this->messages->add('s', _('the link has been added successfully'));
448 }
449 }
450 else {
451 if (!$import) {
452 $this->messages->add('e', _('error during insertion : the link wasn\'t added'));
453 Tools::logm('error during insertion : the link wasn\'t added ' . $url->getUrl());
454 }
455 }
456
457 if (!$import) {
458 if ($autoclose == TRUE) {
459 Tools::redirect('?view=home');
460 } else {
461 Tools::redirect('?view=home&closewin=true');
462 }
463 }
464 break;
465 case 'delete':
466 $msg = 'delete link #' . $id;
467 if ($this->store->deleteById($id, $this->user->getId())) {
468 if (DOWNLOAD_PICTURES) {
469 remove_directory(ABS_PATH . $id);
470 }
471 $this->messages->add('s', _('the link has been deleted successfully'));
472 }
473 else {
474 $this->messages->add('e', _('the link wasn\'t deleted'));
475 $msg = 'error : can\'t delete link #' . $id;
476 }
477 Tools::logm($msg);
478 Tools::redirect('?');
479 break;
480 case 'toggle_fav' :
481 $this->store->favoriteById($id, $this->user->getId());
482 Tools::logm('mark as favorite link #' . $id);
483 if (!$import) {
484 Tools::redirect();
485 }
486 break;
487 case 'toggle_archive' :
488 $this->store->archiveById($id, $this->user->getId());
489 Tools::logm('archive link #' . $id);
490 if (!$import) {
491 Tools::redirect();
492 }
493 break;
494 case 'archive_all' :
495 $this->store->archiveAll($this->user->getId());
496 Tools::logm('archive all links');
497 if (!$import) {
498 Tools::redirect();
499 }
500 break;
501 case 'add_tag' :
502 $tags = explode(',', $_POST['value']);
503 $entry_id = $_POST['entry_id'];
504 $entry = $this->store->retrieveOneById($entry_id, $this->user->getId());
505 if (!$entry) {
506 $this->messages->add('e', _('Article not found!'));
507 Tools::logm('error : article not found');
508 Tools::redirect();
509 }
510 foreach($tags as $key => $tag_value) {
511 $value = trim($tag_value);
512 $tag = $this->store->retrieveTagByValue($value);
513
514 if (is_null($tag)) {
515 # we create the tag
516 $tag = $this->store->createTag($value);
517 $sequence = '';
518 if (STORAGE == 'postgres') {
519 $sequence = 'tags_id_seq';
520 }
521 $tag_id = $this->store->getLastId($sequence);
522 }
523 else {
524 $tag_id = $tag['id'];
525 }
526
527 # we assign the tag to the article
528 $this->store->setTagToEntry($tag_id, $entry_id);
529 }
530 Tools::redirect();
531 break;
532 case 'remove_tag' :
533 $tag_id = $_GET['tag_id'];
534 $entry = $this->store->retrieveOneById($id, $this->user->getId());
535 if (!$entry) {
536 $this->messages->add('e', _('Article not found!'));
537 Tools::logm('error : article not found');
538 Tools::redirect();
539 }
540 $this->store->removeTagForEntry($id, $tag_id);
541 Tools::redirect();
542 break;
543 default:
544 break;
545 }
546 }
547
548 function displayView($view, $id = 0)
549 {
550 $tpl_vars = array();
551
552 switch ($view)
553 {
554 case 'config':
555 $dev = trim($this->getPocheVersion('dev'));
556 $prod = trim($this->getPocheVersion('prod'));
557 $compare_dev = version_compare(POCHE, $dev);
558 $compare_prod = version_compare(POCHE, $prod);
559 $themes = $this->getInstalledThemes();
560 $languages = $this->getInstalledLanguages();
561 $token = $this->user->getConfigValue('token');
562 $http_auth = (isset($_SERVER['PHP_AUTH_USER']) || isset($_SERVER['REMOTE_USER'])) ? true : false;
563 $tpl_vars = array(
564 'themes' => $themes,
565 'languages' => $languages,
566 'dev' => $dev,
567 'prod' => $prod,
568 'compare_dev' => $compare_dev,
569 'compare_prod' => $compare_prod,
570 'token' => $token,
571 'user_id' => $this->user->getId(),
572 'http_auth' => $http_auth,
573 );
574 Tools::logm('config view');
575 break;
576 case 'edit-tags':
577 # tags
578 $entry = $this->store->retrieveOneById($id, $this->user->getId());
579 if (!$entry) {
580 $this->messages->add('e', _('Article not found!'));
581 Tools::logm('error : article not found');
582 Tools::redirect();
583 }
584 $tags = $this->store->retrieveTagsByEntry($id);
585 $tpl_vars = array(
586 'entry_id' => $id,
587 'tags' => $tags,
588 'entry' => $entry,
589 );
590 break;
591 case 'tags':
592 $token = $this->user->getConfigValue('token');
593 $tags = $this->store->retrieveAllTags($this->user->getId());
594 $tpl_vars = array(
595 'token' => $token,
596 'user_id' => $this->user->getId(),
597 'tags' => $tags,
598 );
599 break;
600 case 'view':
601 $entry = $this->store->retrieveOneById($id, $this->user->getId());
602 if ($entry != NULL) {
603 Tools::logm('view link #' . $id);
604 $content = $entry['content'];
605 if (function_exists('tidy_parse_string')) {
606 $tidy = tidy_parse_string($content, array('indent'=>true, 'show-body-only' => true), 'UTF8');
607 $tidy->cleanRepair();
608 $content = $tidy->value;
609 }
610
611 # flattr checking
612 $flattr = new FlattrItem();
613 $flattr->checkItem($entry['url'], $entry['id']);
614
615 # tags
616 $tags = $this->store->retrieveTagsByEntry($entry['id']);
617
618 $tpl_vars = array(
619 'entry' => $entry,
620 'content' => $content,
621 'flattr' => $flattr,
622 'tags' => $tags
623 );
624 }
625 else {
626 Tools::logm('error in view call : entry is null');
627 }
628 break;
629 default: # home, favorites, archive and tag views
630 $tpl_vars = array(
631 'entries' => '',
632 'page_links' => '',
633 'nb_results' => '',
634 );
635
636 //if id is given - we retrive entries by tag: id is tag id
637 if ($id) {
638 $tpl_vars['tag'] = $this->store->retrieveTag($id, $this->user->getId());
639 $tpl_vars['id'] = intval($id);
640 }
641
642 $count = $this->store->getEntriesByViewCount($view, $this->user->getId(), $id);
643
644 if ($count > 0) {
645 $this->pagination->set_total($count);
646 $page_links = str_replace(array('previous', 'next'), array(_('previous'), _('next')),
647 $this->pagination->page_links('?view=' . $view . '&sort=' . $_SESSION['sort'] . (($id)?'&id='.$id:'') . '&' ));
648 $tpl_vars['entries'] = $this->store->getEntriesByView($view, $this->user->getId(), $this->pagination->get_limit(), $id);
649 $tpl_vars['page_links'] = $page_links;
650 $tpl_vars['nb_results'] = $count;
651 }
652 Tools::logm('display ' . $view . ' view');
653 break;
654 }
655
656 return $tpl_vars;
657 }
658
659 /**
660 * update the password of the current user.
661 * if MODE_DEMO is TRUE, the password can't be updated.
662 * @todo add the return value
663 * @todo set the new password in function header like this updatePassword($newPassword)
664 * @return boolean
665 */
666 public function updatePassword()
667 {
668 if (MODE_DEMO) {
669 $this->messages->add('i', _('in demo mode, you can\'t update your password'));
670 Tools::logm('in demo mode, you can\'t do this');
671 Tools::redirect('?view=config');
672 }
673 else {
674 if (isset($_POST['password']) && isset($_POST['password_repeat'])) {
675 if ($_POST['password'] == $_POST['password_repeat'] && $_POST['password'] != "") {
676 $this->messages->add('s', _('your password has been updated'));
677 $this->store->updatePassword($this->user->getId(), Tools::encodeString($_POST['password'] . $this->user->getUsername()));
678 Session::logout();
679 Tools::logm('password updated');
680 Tools::redirect();
681 }
682 else {
683 $this->messages->add('e', _('the two fields have to be filled & the password must be the same in the two fields'));
684 Tools::redirect('?view=config');
685 }
686 }
687 }
688 }
689
690 public function updateTheme()
691 {
692 # no data
693 if (empty($_POST['theme'])) {
694 }
695
696 # we are not going to change it to the current theme...
697 if ($_POST['theme'] == $this->getTheme()) {
698 $this->messages->add('w', _('still using the "' . $this->getTheme() . '" theme!'));
699 Tools::redirect('?view=config');
700 }
701
702 $themes = $this->getInstalledThemes();
703 $actualTheme = false;
704
705 foreach (array_keys($themes) as $theme) {
706 if ($theme == $_POST['theme']) {
707 $actualTheme = true;
708 break;
709 }
710 }
711
712 if (! $actualTheme) {
713 $this->messages->add('e', _('that theme does not seem to be installed'));
714 Tools::redirect('?view=config');
715 }
716
717 $this->store->updateUserConfig($this->user->getId(), 'theme', $_POST['theme']);
718 $this->messages->add('s', _('you have changed your theme preferences'));
719
720 $currentConfig = $_SESSION['poche_user']->config;
721 $currentConfig['theme'] = $_POST['theme'];
722
723 $_SESSION['poche_user']->setConfig($currentConfig);
724
725 Tools::redirect('?view=config');
726 }
727
728 public function updateLanguage()
729 {
730 # no data
731 if (empty($_POST['language'])) {
732 }
733
734 # we are not going to change it to the current language...
735 if ($_POST['language'] == $this->getLanguage()) {
736 $this->messages->add('w', _('still using the "' . $this->getLanguage() . '" language!'));
737 Tools::redirect('?view=config');
738 }
739
740 $languages = $this->getInstalledLanguages();
741 $actualLanguage = false;
742
743 foreach ($languages as $language) {
744 if ($language['name'] == $_POST['language']) {
745 $actualLanguage = true;
746 break;
747 }
748 }
749
750 if (! $actualLanguage) {
751 $this->messages->add('e', _('that language does not seem to be installed'));
752 Tools::redirect('?view=config');
753 }
754
755 $this->store->updateUserConfig($this->user->getId(), 'language', $_POST['language']);
756 $this->messages->add('s', _('you have changed your language preferences'));
757
758 $currentConfig = $_SESSION['poche_user']->config;
759 $currentConfig['language'] = $_POST['language'];
760
761 $_SESSION['poche_user']->setConfig($currentConfig);
762
763 Tools::redirect('?view=config');
764 }
765
766 /**
767 * get credentials from differents sources
768 * it redirects the user to the $referer link
769 * @return array
770 */
771 private function credentials() {
772 if(isset($_SERVER['PHP_AUTH_USER'])) {
773 return array($_SERVER['PHP_AUTH_USER'],'php_auth',true);
774 }
775 if(!empty($_POST['login']) && !empty($_POST['password'])) {
776 return array($_POST['login'],$_POST['password'],false);
777 }
778 if(isset($_SERVER['REMOTE_USER'])) {
779 return array($_SERVER['REMOTE_USER'],'http_auth',true);
780 }
781
782 return array(false,false,false);
783 }
784
785 /**
786 * checks if login & password are correct and save the user in session.
787 * it redirects the user to the $referer link
788 * @param string $referer the url to redirect after login
789 * @todo add the return value
790 * @return boolean
791 */
792 public function login($referer)
793 {
794 list($login,$password,$isauthenticated)=$this->credentials();
795 if($login === false || $password === false) {
796 $this->messages->add('e', _('login failed: you have to fill all fields'));
797 Tools::logm('login failed');
798 Tools::redirect();
799 }
800 if (!empty($login) && !empty($password)) {
801 $user = $this->store->login($login, Tools::encodeString($password . $login), $isauthenticated);
802 if ($user != array()) {
803 # Save login into Session
804 $longlastingsession = isset($_POST['longlastingsession']);
805 $passwordTest = ($isauthenticated) ? $user['password'] : Tools::encodeString($password . $login);
806 Session::login($user['username'], $user['password'], $login, $passwordTest, $longlastingsession, array('poche_user' => new User($user)));
807 $this->messages->add('s', _('welcome to your wallabag'));
808 Tools::logm('login successful');
809 Tools::redirect($referer);
810 }
811 $this->messages->add('e', _('login failed: bad login or password'));
812 Tools::logm('login failed');
813 Tools::redirect();
814 }
815 }
816
817 /**
818 * log out the poche user. It cleans the session.
819 * @todo add the return value
820 * @return boolean
821 */
822 public function logout()
823 {
824 $this->user = array();
825 Session::logout();
826 Tools::logm('logout');
827 Tools::redirect();
828 }
829
830 /**
831 * import from Instapaper. poche needs a ./instapaper-export.html file
832 * @todo add the return value
833 * @param string $targetFile the file used for importing
834 * @return boolean
835 */
836 private function importFromInstapaper($targetFile)
837 {
838 # TODO gestion des articles favs
839 $html = new simple_html_dom();
840 $html->load_file($targetFile);
841 Tools::logm('starting import from instapaper');
842
843 $read = 0;
844 $errors = array();
845 foreach($html->find('ol') as $ul)
846 {
847 foreach($ul->find('li') as $li)
848 {
849 $a = $li->find('a');
850 $url = new Url(base64_encode($a[0]->href));
851 $this->action('add', $url, 0, TRUE);
852 if ($read == '1') {
853 $sequence = '';
854 if (STORAGE == 'postgres') {
855 $sequence = 'entries_id_seq';
856 }
857 $last_id = $this->store->getLastId($sequence);
858 $this->action('toggle_archive', $url, $last_id, TRUE);
859 }
860 }
861
862 # the second <ol> is for read links
863 $read = 1;
864 }
865 $this->messages->add('s', _('import from instapaper completed'));
866 Tools::logm('import from instapaper completed');
867 Tools::redirect();
868 }
869
870 /**
871 * import from Pocket. poche needs a ./ril_export.html file
872 * @todo add the return value
873 * @param string $targetFile the file used for importing
874 * @return boolean
875 */
876 private function importFromPocket($targetFile)
877 {
878 # TODO gestion des articles favs
879 $html = new simple_html_dom();
880 $html->load_file($targetFile);
881 Tools::logm('starting import from pocket');
882
883 $read = 0;
884 $errors = array();
885 foreach($html->find('ul') as $ul)
886 {
887 foreach($ul->find('li') as $li)
888 {
889 $a = $li->find('a');
890 $url = new Url(base64_encode($a[0]->href));
891 $this->action('add', $url, 0, TRUE);
892 if ($read == '1') {
893 $sequence = '';
894 if (STORAGE == 'postgres') {
895 $sequence = 'entries_id_seq';
896 }
897 $last_id = $this->store->getLastId($sequence);
898 $this->action('toggle_archive', $url, $last_id, TRUE);
899 }
900 }
901
902 # the second <ul> is for read links
903 $read = 1;
904 }
905 $this->messages->add('s', _('import from pocket completed'));
906 Tools::logm('import from pocket completed');
907 Tools::redirect();
908 }
909
910 /**
911 * import from Readability. poche needs a ./readability file
912 * @todo add the return value
913 * @param string $targetFile the file used for importing
914 * @return boolean
915 */
916 private function importFromReadability($targetFile)
917 {
918 # TODO gestion des articles lus / favs
919 $str_data = file_get_contents($targetFile);
920 $data = json_decode($str_data,true);
921 Tools::logm('starting import from Readability');
922 $count = 0;
923 foreach ($data as $key => $value) {
924 $url = NULL;
925 $favorite = FALSE;
926 $archive = FALSE;
927 foreach ($value as $item) {
928 foreach ($item as $attr => $value) {
929 if ($attr == 'article__url') {
930 $url = new Url(base64_encode($value));
931 }
932 $sequence = '';
933 if (STORAGE == 'postgres') {
934 $sequence = 'entries_id_seq';
935 }
936 if ($value == 'true') {
937 if ($attr == 'favorite') {
938 $favorite = TRUE;
939 }
940 if ($attr == 'archive') {
941 $archive = TRUE;
942 }
943 }
944 }
945
946 # we can add the url
947 if (!is_null($url) && $url->isCorrect()) {
948 $this->action('add', $url, 0, TRUE);
949 $count++;
950 if ($favorite) {
951 $last_id = $this->store->getLastId($sequence);
952 $this->action('toggle_fav', $url, $last_id, TRUE);
953 }
954 if ($archive) {
955 $last_id = $this->store->getLastId($sequence);
956 $this->action('toggle_archive', $url, $last_id, TRUE);
957 }
958 }
959 }
960 }
961 $this->messages->add('s', _('import from Readability completed. ' . $count . ' new links.'));
962 Tools::logm('import from Readability completed');
963 Tools::redirect();
964 }
965
966 /**
967 * import from Poche exported file
968 * @param string $targetFile the file used for importing
969 * @return boolean
970 */
971 private function importFromPoche($targetFile)
972 {
973 $str_data = file_get_contents($targetFile);
974 $data = json_decode($str_data,true);
975 Tools::logm('starting import from Poche');
976
977
978 $sequence = '';
979 if (STORAGE == 'postgres') {
980 $sequence = 'entries_id_seq';
981 }
982
983 $count = 0;
984 foreach ($data as $value) {
985
986 $url = new Url(base64_encode($value['url']));
987 $favorite = ($value['is_fav'] == -1);
988 $archive = ($value['is_read'] == -1);
989
990 # we can add the url
991 if (!is_null($url) && $url->isCorrect()) {
992
993 $this->action('add', $url, 0, TRUE);
994
995 $count++;
996 if ($favorite) {
997 $last_id = $this->store->getLastId($sequence);
998 $this->action('toggle_fav', $url, $last_id, TRUE);
999 }
1000 if ($archive) {
1001 $last_id = $this->store->getLastId($sequence);
1002 $this->action('toggle_archive', $url, $last_id, TRUE);
1003 }
1004 }
1005
1006 }
1007 $this->messages->add('s', _('import from Poche completed. ' . $count . ' new links.'));
1008 Tools::logm('import from Poche completed');
1009 Tools::redirect();
1010 }
1011
1012 /**
1013 * import datas into your poche
1014 * @param string $from name of the service to import : pocket, instapaper or readability
1015 * @todo add the return value
1016 * @return boolean
1017 */
1018 public function import($from)
1019 {
1020 $providers = array(
1021 'pocket' => 'importFromPocket',
1022 'readability' => 'importFromReadability',
1023 'instapaper' => 'importFromInstapaper',
1024 'poche' => 'importFromPoche',
1025 );
1026
1027 if (! isset($providers[$from])) {
1028 $this->messages->add('e', _('Unknown import provider.'));
1029 Tools::redirect();
1030 }
1031
1032 $targetDefinition = 'IMPORT_' . strtoupper($from) . '_FILE';
1033 $targetFile = constant($targetDefinition);
1034
1035 if (! defined($targetDefinition)) {
1036 $this->messages->add('e', _('Incomplete inc/poche/define.inc.php file, please define "' . $targetDefinition . '".'));
1037 Tools::redirect();
1038 }
1039
1040 if (! file_exists($targetFile)) {
1041 $this->messages->add('e', _('Could not find required "' . $targetFile . '" import file.'));
1042 Tools::redirect();
1043 }
1044
1045 $this->$providers[$from]($targetFile);
1046 }
1047
1048 /**
1049 * export poche entries in json
1050 * @return json all poche entries
1051 */
1052 public function export()
1053 {
1054 $entries = $this->store->retrieveAll($this->user->getId());
1055 echo $this->tpl->render('export.twig', array(
1056 'export' => Tools::renderJson($entries),
1057 ));
1058 Tools::logm('export view');
1059 }
1060
1061 /**
1062 * Checks online the latest version of poche and cache it
1063 * @param string $which 'prod' or 'dev'
1064 * @return string latest $which version
1065 */
1066 private function getPocheVersion($which = 'prod')
1067 {
1068 $cache_file = CACHE . '/' . $which;
1069
1070 # checks if the cached version file exists
1071 if (file_exists($cache_file) && (filemtime($cache_file) > (time() - 86400 ))) {
1072 $version = file_get_contents($cache_file);
1073 } else {
1074 $version = file_get_contents('http://static.wallabag.org/versions/' . $which);
1075 file_put_contents($cache_file, $version, LOCK_EX);
1076 }
1077 return $version;
1078 }
1079
1080 public function generateToken()
1081 {
1082 if (ini_get('open_basedir') === '') {
1083 $token = substr(base64_encode(file_get_contents('/dev/urandom', false, null, 0, 20)), 0, 15);
1084 }
1085 else {
1086 $token = substr(base64_encode(uniqid(mt_rand(), true)), 0, 20);
1087 }
1088
1089 $token = str_replace('+', '', $token);
1090 $this->store->updateUserConfig($this->user->getId(), 'token', $token);
1091 $currentConfig = $_SESSION['poche_user']->config;
1092 $currentConfig['token'] = $token;
1093 $_SESSION['poche_user']->setConfig($currentConfig);
1094 }
1095
1096 public function generateFeeds($token, $user_id, $tag_id, $type = 'home')
1097 {
1098 $allowed_types = array('home', 'fav', 'archive', 'tag');
1099 $config = $this->store->getConfigUser($user_id);
1100
1101 if (!in_array($type, $allowed_types) ||
1102 $token != $config['token']) {
1103 die(_('Uh, there is a problem while generating feeds.'));
1104 }
1105 // Check the token
1106
1107 $feed = new FeedWriter(RSS2);
1108 $feed->setTitle('wallabag — ' . $type . ' feed');
1109 $feed->setLink(Tools::getPocheUrl());
1110 $feed->setChannelElement('updated', date(DATE_RSS , time()));
1111 $feed->setChannelElement('author', 'wallabag');
1112
1113 if ($type == 'tag') {
1114 $entries = $this->store->retrieveEntriesByTag($tag_id, $user_id);
1115 }
1116 else {
1117 $entries = $this->store->getEntriesByView($type, $user_id);
1118 }
1119
1120 if (count($entries) > 0) {
1121 foreach ($entries as $entry) {
1122 $newItem = $feed->createNewItem();
1123 $newItem->setTitle($entry['title']);
1124 $newItem->setLink(Tools::getPocheUrl() . '?view=view&amp;id=' . $entry['id']);
1125 $newItem->setDate(time());
1126 $newItem->setDescription($entry['content']);
1127 $feed->addItem($newItem);
1128 }
1129 }
1130
1131 $feed->genarateFeed();
1132 exit;
1133 }
1134
1135 public function emptyCache() {
1136 $files = new RecursiveIteratorIterator(
1137 new RecursiveDirectoryIterator(CACHE, RecursiveDirectoryIterator::SKIP_DOTS),
1138 RecursiveIteratorIterator::CHILD_FIRST
1139 );
1140
1141 foreach ($files as $fileinfo) {
1142 $todo = ($fileinfo->isDir() ? 'rmdir' : 'unlink');
1143 $todo($fileinfo->getRealPath());
1144 }
1145
1146 Tools::logm('empty cache');
1147 $this->messages->add('s', _('Cache deleted.'));
1148 Tools::redirect();
1149 }
1150 }