]> git.immae.eu Git - github/wallabag/wallabag.git/blob - inc/poche/Poche.class.php
753bd7f077619959a08cc68355f8706d2d695bb6
[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 $options = array('http' => array('user_agent' => 'poche'));
352 if (isset($_SERVER['AUTH_TYPE']) && "basic" === strtolower($_SERVER['AUTH_TYPE'])) {
353 $options['http']['header'] = sprintf(
354 "Authorization: Basic %s",
355 base64_encode(
356 sprintf('%s:%s', $_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW'])
357 )
358 );
359 }
360 $context = stream_context_create($options);
361 $json = file_get_contents(Tools::getPocheUrl() . '/inc/3rdparty/makefulltextfeed.php?url='.urlencode($url->getUrl()).'&max=5&links=preserve&exc=&format=json&submit=Create+Feed', false, $context);
362 return json_decode($json, true);
363 }
364
365 /**
366 * Call action (mark as fav, archive, delete, etc.)
367 */
368 public function action($action, Url $url, $id = 0, $import = FALSE, $autoclose = FALSE)
369 {
370 switch ($action)
371 {
372 case 'add':
373 $content = $this->getPageContent($url);
374 $title = ($content['rss']['channel']['item']['title'] != '') ? $content['rss']['channel']['item']['title'] : _('Untitled');
375 $body = $content['rss']['channel']['item']['description'];
376
377 //search for possible duplicate if not in import mode
378 if (!$import) {
379 $duplicate = $this->store->retrieveOneByURL($url->getUrl(), $this->user->getId());
380 }
381
382 if ($this->store->add($url->getUrl(), $title, $body, $this->user->getId())) {
383 Tools::logm('add link ' . $url->getUrl());
384 $sequence = '';
385 if (STORAGE == 'postgres') {
386 $sequence = 'entries_id_seq';
387 }
388 $last_id = $this->store->getLastId($sequence);
389 if (DOWNLOAD_PICTURES) {
390 $content = filtre_picture($body, $url->getUrl(), $last_id);
391 Tools::logm('updating content article');
392 $this->store->updateContent($last_id, $content, $this->user->getId());
393 }
394
395 if ($duplicate != NULL) {
396 // 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
397 Tools::logm('link ' . $url->getUrl() . ' is a duplicate');
398 // 1) - preserve tags and favorite, then drop old entry
399 $this->store->reassignTags($duplicate['id'], $last_id);
400 if ($duplicate['is_fav']) {
401 $this->store->favoriteById($last_id, $this->user->getId());
402 }
403 if ($this->store->deleteById($duplicate['id'], $this->user->getId())) {
404 Tools::logm('previous link ' . $url->getUrl() .' entry deleted');
405 }
406 }
407
408 if (!$import) {
409 $this->messages->add('s', _('the link has been added successfully'));
410 }
411 }
412 else {
413 if (!$import) {
414 $this->messages->add('e', _('error during insertion : the link wasn\'t added'));
415 Tools::logm('error during insertion : the link wasn\'t added ' . $url->getUrl());
416 }
417 }
418
419 if (!$import) {
420 if ($autoclose == TRUE) {
421 Tools::redirect('?view=home');
422 } else {
423 Tools::redirect('?view=home&closewin=true');
424 }
425 }
426 break;
427 case 'delete':
428 $msg = 'delete link #' . $id;
429 if ($this->store->deleteById($id, $this->user->getId())) {
430 if (DOWNLOAD_PICTURES) {
431 remove_directory(ABS_PATH . $id);
432 }
433 $this->messages->add('s', _('the link has been deleted successfully'));
434 }
435 else {
436 $this->messages->add('e', _('the link wasn\'t deleted'));
437 $msg = 'error : can\'t delete link #' . $id;
438 }
439 Tools::logm($msg);
440 Tools::redirect('?');
441 break;
442 case 'toggle_fav' :
443 $this->store->favoriteById($id, $this->user->getId());
444 Tools::logm('mark as favorite link #' . $id);
445 if (!$import) {
446 Tools::redirect();
447 }
448 break;
449 case 'toggle_archive' :
450 $this->store->archiveById($id, $this->user->getId());
451 Tools::logm('archive link #' . $id);
452 if (!$import) {
453 Tools::redirect();
454 }
455 break;
456 case 'archive_all' :
457 $this->store->archiveAll($this->user->getId());
458 Tools::logm('archive all links');
459 if (!$import) {
460 Tools::redirect();
461 }
462 break;
463 case 'add_tag' :
464 $tags = explode(',', $_POST['value']);
465 $entry_id = $_POST['entry_id'];
466 $entry = $this->store->retrieveOneById($entry_id, $this->user->getId());
467 if (!$entry) {
468 $this->messages->add('e', _('Article not found!'));
469 Tools::logm('error : article not found');
470 Tools::redirect();
471 }
472 foreach($tags as $key => $tag_value) {
473 $value = trim($tag_value);
474 $tag = $this->store->retrieveTagByValue($value);
475
476 if (is_null($tag)) {
477 # we create the tag
478 $tag = $this->store->createTag($value);
479 $sequence = '';
480 if (STORAGE == 'postgres') {
481 $sequence = 'tags_id_seq';
482 }
483 $tag_id = $this->store->getLastId($sequence);
484 }
485 else {
486 $tag_id = $tag['id'];
487 }
488
489 # we assign the tag to the article
490 $this->store->setTagToEntry($tag_id, $entry_id);
491 }
492 Tools::redirect();
493 break;
494 case 'remove_tag' :
495 $tag_id = $_GET['tag_id'];
496 $entry = $this->store->retrieveOneById($id, $this->user->getId());
497 if (!$entry) {
498 $this->messages->add('e', _('Article not found!'));
499 Tools::logm('error : article not found');
500 Tools::redirect();
501 }
502 $this->store->removeTagForEntry($id, $tag_id);
503 Tools::redirect();
504 break;
505 default:
506 break;
507 }
508 }
509
510 function displayView($view, $id = 0)
511 {
512 $tpl_vars = array();
513
514 switch ($view)
515 {
516 case 'config':
517 $dev = trim($this->getPocheVersion('dev'));
518 $prod = trim($this->getPocheVersion('prod'));
519 $compare_dev = version_compare(POCHE, $dev);
520 $compare_prod = version_compare(POCHE, $prod);
521 $themes = $this->getInstalledThemes();
522 $languages = $this->getInstalledLanguages();
523 $token = $this->user->getConfigValue('token');
524 $http_auth = (isset($_SERVER['PHP_AUTH_USER']) || isset($_SERVER['REMOTE_USER'])) ? true : false;
525 $tpl_vars = array(
526 'themes' => $themes,
527 'languages' => $languages,
528 'dev' => $dev,
529 'prod' => $prod,
530 'compare_dev' => $compare_dev,
531 'compare_prod' => $compare_prod,
532 'token' => $token,
533 'user_id' => $this->user->getId(),
534 'http_auth' => $http_auth,
535 );
536 Tools::logm('config view');
537 break;
538 case 'edit-tags':
539 # tags
540 $entry = $this->store->retrieveOneById($id, $this->user->getId());
541 if (!$entry) {
542 $this->messages->add('e', _('Article not found!'));
543 Tools::logm('error : article not found');
544 Tools::redirect();
545 }
546 $tags = $this->store->retrieveTagsByEntry($id);
547 $tpl_vars = array(
548 'entry_id' => $id,
549 'tags' => $tags,
550 );
551 break;
552 case 'tag':
553 $entries = $this->store->retrieveEntriesByTag($id, $this->user->getId());
554 $tag = $this->store->retrieveTag($id, $this->user->getId());
555 $tpl_vars = array(
556 'tag' => $tag,
557 'entries' => $entries,
558 );
559 break;
560 case 'tags':
561 $token = $this->user->getConfigValue('token');
562 $tags = $this->store->retrieveAllTags($this->user->getId());
563 $tpl_vars = array(
564 'token' => $token,
565 'user_id' => $this->user->getId(),
566 'tags' => $tags,
567 );
568 break;
569 case 'view':
570 $entry = $this->store->retrieveOneById($id, $this->user->getId());
571 if ($entry != NULL) {
572 Tools::logm('view link #' . $id);
573 $content = $entry['content'];
574 if (function_exists('tidy_parse_string')) {
575 $tidy = tidy_parse_string($content, array('indent'=>true, 'show-body-only' => true), 'UTF8');
576 $tidy->cleanRepair();
577 $content = $tidy->value;
578 }
579
580 # flattr checking
581 $flattr = new FlattrItem();
582 $flattr->checkItem($entry['url'], $entry['id']);
583
584 # tags
585 $tags = $this->store->retrieveTagsByEntry($entry['id']);
586
587 $tpl_vars = array(
588 'entry' => $entry,
589 'content' => $content,
590 'flattr' => $flattr,
591 'tags' => $tags
592 );
593 }
594 else {
595 Tools::logm('error in view call : entry is null');
596 }
597 break;
598 default: # home, favorites and archive views
599 $entries = $this->store->getEntriesByView($view, $this->user->getId());
600 $tpl_vars = array(
601 'entries' => '',
602 'page_links' => '',
603 'nb_results' => '',
604 );
605
606 if (count($entries) > 0) {
607 $this->pagination->set_total(count($entries));
608 $page_links = str_replace(array('previous', 'next'), array(_('previous'), _('next')),
609 $this->pagination->page_links('?view=' . $view . '&sort=' . $_SESSION['sort'] . '&'));
610 $datas = $this->store->getEntriesByView($view, $this->user->getId(), $this->pagination->get_limit());
611 $tpl_vars['entries'] = $datas;
612 $tpl_vars['page_links'] = $page_links;
613 $tpl_vars['nb_results'] = count($entries);
614 }
615 Tools::logm('display ' . $view . ' view');
616 break;
617 }
618
619 return $tpl_vars;
620 }
621
622 /**
623 * update the password of the current user.
624 * if MODE_DEMO is TRUE, the password can't be updated.
625 * @todo add the return value
626 * @todo set the new password in function header like this updatePassword($newPassword)
627 * @return boolean
628 */
629 public function updatePassword()
630 {
631 if (MODE_DEMO) {
632 $this->messages->add('i', _('in demo mode, you can\'t update your password'));
633 Tools::logm('in demo mode, you can\'t do this');
634 Tools::redirect('?view=config');
635 }
636 else {
637 if (isset($_POST['password']) && isset($_POST['password_repeat'])) {
638 if ($_POST['password'] == $_POST['password_repeat'] && $_POST['password'] != "") {
639 $this->messages->add('s', _('your password has been updated'));
640 $this->store->updatePassword($this->user->getId(), Tools::encodeString($_POST['password'] . $this->user->getUsername()));
641 Session::logout();
642 Tools::logm('password updated');
643 Tools::redirect();
644 }
645 else {
646 $this->messages->add('e', _('the two fields have to be filled & the password must be the same in the two fields'));
647 Tools::redirect('?view=config');
648 }
649 }
650 }
651 }
652
653 public function updateTheme()
654 {
655 # no data
656 if (empty($_POST['theme'])) {
657 }
658
659 # we are not going to change it to the current theme...
660 if ($_POST['theme'] == $this->getTheme()) {
661 $this->messages->add('w', _('still using the "' . $this->getTheme() . '" theme!'));
662 Tools::redirect('?view=config');
663 }
664
665 $themes = $this->getInstalledThemes();
666 $actualTheme = false;
667
668 foreach (array_keys($themes) as $theme) {
669 if ($theme == $_POST['theme']) {
670 $actualTheme = true;
671 break;
672 }
673 }
674
675 if (! $actualTheme) {
676 $this->messages->add('e', _('that theme does not seem to be installed'));
677 Tools::redirect('?view=config');
678 }
679
680 $this->store->updateUserConfig($this->user->getId(), 'theme', $_POST['theme']);
681 $this->messages->add('s', _('you have changed your theme preferences'));
682
683 $currentConfig = $_SESSION['poche_user']->config;
684 $currentConfig['theme'] = $_POST['theme'];
685
686 $_SESSION['poche_user']->setConfig($currentConfig);
687
688 Tools::redirect('?view=config');
689 }
690
691 public function updateLanguage()
692 {
693 # no data
694 if (empty($_POST['language'])) {
695 }
696
697 # we are not going to change it to the current language...
698 if ($_POST['language'] == $this->getLanguage()) {
699 $this->messages->add('w', _('still using the "' . $this->getLanguage() . '" language!'));
700 Tools::redirect('?view=config');
701 }
702
703 $languages = $this->getInstalledLanguages();
704 $actualLanguage = false;
705
706 foreach ($languages as $language) {
707 if ($language['name'] == $_POST['language']) {
708 $actualLanguage = true;
709 break;
710 }
711 }
712
713 if (! $actualLanguage) {
714 $this->messages->add('e', _('that language does not seem to be installed'));
715 Tools::redirect('?view=config');
716 }
717
718 $this->store->updateUserConfig($this->user->getId(), 'language', $_POST['language']);
719 $this->messages->add('s', _('you have changed your language preferences'));
720
721 $currentConfig = $_SESSION['poche_user']->config;
722 $currentConfig['language'] = $_POST['language'];
723
724 $_SESSION['poche_user']->setConfig($currentConfig);
725
726 Tools::redirect('?view=config');
727 }
728
729 /**
730 * get credentials from differents sources
731 * it redirects the user to the $referer link
732 * @return array
733 */
734 private function credentials() {
735 if(isset($_SERVER['PHP_AUTH_USER'])) {
736 return array($_SERVER['PHP_AUTH_USER'],'php_auth',true);
737 }
738 if(!empty($_POST['login']) && !empty($_POST['password'])) {
739 return array($_POST['login'],$_POST['password'],false);
740 }
741 if(isset($_SERVER['REMOTE_USER'])) {
742 return array($_SERVER['REMOTE_USER'],'http_auth',true);
743 }
744
745 return array(false,false,false);
746 }
747
748 /**
749 * checks if login & password are correct and save the user in session.
750 * it redirects the user to the $referer link
751 * @param string $referer the url to redirect after login
752 * @todo add the return value
753 * @return boolean
754 */
755 public function login($referer)
756 {
757 list($login,$password,$isauthenticated)=$this->credentials();
758 if($login === false || $password === false) {
759 $this->messages->add('e', _('login failed: you have to fill all fields'));
760 Tools::logm('login failed');
761 Tools::redirect();
762 }
763 if (!empty($login) && !empty($password)) {
764 $user = $this->store->login($login, Tools::encodeString($password . $login), $isauthenticated);
765 if ($user != array()) {
766 # Save login into Session
767 $longlastingsession = isset($_POST['longlastingsession']);
768 $passwordTest = ($isauthenticated) ? $user['password'] : Tools::encodeString($password . $login);
769 Session::login($user['username'], $user['password'], $login, $passwordTest, $longlastingsession, array('poche_user' => new User($user)));
770 $this->messages->add('s', _('welcome to your wallabag'));
771 Tools::logm('login successful');
772 Tools::redirect($referer);
773 }
774 $this->messages->add('e', _('login failed: bad login or password'));
775 Tools::logm('login failed');
776 Tools::redirect();
777 }
778 }
779
780 /**
781 * log out the poche user. It cleans the session.
782 * @todo add the return value
783 * @return boolean
784 */
785 public function logout()
786 {
787 $this->user = array();
788 Session::logout();
789 Tools::logm('logout');
790 Tools::redirect();
791 }
792
793 /**
794 * import from Instapaper. poche needs a ./instapaper-export.html file
795 * @todo add the return value
796 * @param string $targetFile the file used for importing
797 * @return boolean
798 */
799 private function importFromInstapaper($targetFile)
800 {
801 # TODO gestion des articles favs
802 $html = new simple_html_dom();
803 $html->load_file($targetFile);
804 Tools::logm('starting import from instapaper');
805
806 $read = 0;
807 $errors = array();
808 foreach($html->find('ol') as $ul)
809 {
810 foreach($ul->find('li') as $li)
811 {
812 $a = $li->find('a');
813 $url = new Url(base64_encode($a[0]->href));
814 $this->action('add', $url, 0, TRUE);
815 if ($read == '1') {
816 $sequence = '';
817 if (STORAGE == 'postgres') {
818 $sequence = 'entries_id_seq';
819 }
820 $last_id = $this->store->getLastId($sequence);
821 $this->action('toggle_archive', $url, $last_id, TRUE);
822 }
823 }
824
825 # the second <ol> is for read links
826 $read = 1;
827 }
828 $this->messages->add('s', _('import from instapaper completed'));
829 Tools::logm('import from instapaper completed');
830 Tools::redirect();
831 }
832
833 /**
834 * import from Pocket. poche needs a ./ril_export.html file
835 * @todo add the return value
836 * @param string $targetFile the file used for importing
837 * @return boolean
838 */
839 private function importFromPocket($targetFile)
840 {
841 # TODO gestion des articles favs
842 $html = new simple_html_dom();
843 $html->load_file($targetFile);
844 Tools::logm('starting import from pocket');
845
846 $read = 0;
847 $errors = array();
848 foreach($html->find('ul') as $ul)
849 {
850 foreach($ul->find('li') as $li)
851 {
852 $a = $li->find('a');
853 $url = new Url(base64_encode($a[0]->href));
854 $this->action('add', $url, 0, TRUE);
855 if ($read == '1') {
856 $sequence = '';
857 if (STORAGE == 'postgres') {
858 $sequence = 'entries_id_seq';
859 }
860 $last_id = $this->store->getLastId($sequence);
861 $this->action('toggle_archive', $url, $last_id, TRUE);
862 }
863 }
864
865 # the second <ul> is for read links
866 $read = 1;
867 }
868 $this->messages->add('s', _('import from pocket completed'));
869 Tools::logm('import from pocket completed');
870 Tools::redirect();
871 }
872
873 /**
874 * import from Readability. poche needs a ./readability file
875 * @todo add the return value
876 * @param string $targetFile the file used for importing
877 * @return boolean
878 */
879 private function importFromReadability($targetFile)
880 {
881 # TODO gestion des articles lus / favs
882 $str_data = file_get_contents($targetFile);
883 $data = json_decode($str_data,true);
884 Tools::logm('starting import from Readability');
885 $count = 0;
886 foreach ($data as $key => $value) {
887 $url = NULL;
888 $favorite = FALSE;
889 $archive = FALSE;
890 foreach ($value as $item) {
891 foreach ($item as $attr => $value) {
892 if ($attr == 'article__url') {
893 $url = new Url(base64_encode($value));
894 }
895 $sequence = '';
896 if (STORAGE == 'postgres') {
897 $sequence = 'entries_id_seq';
898 }
899 if ($value == 'true') {
900 if ($attr == 'favorite') {
901 $favorite = TRUE;
902 }
903 if ($attr == 'archive') {
904 $archive = TRUE;
905 }
906 }
907 }
908
909 # we can add the url
910 if (!is_null($url) && $url->isCorrect()) {
911 $this->action('add', $url, 0, TRUE);
912 $count++;
913 if ($favorite) {
914 $last_id = $this->store->getLastId($sequence);
915 $this->action('toggle_fav', $url, $last_id, TRUE);
916 }
917 if ($archive) {
918 $last_id = $this->store->getLastId($sequence);
919 $this->action('toggle_archive', $url, $last_id, TRUE);
920 }
921 }
922 }
923 }
924 $this->messages->add('s', _('import from Readability completed. ' . $count . ' new links.'));
925 Tools::logm('import from Readability completed');
926 Tools::redirect();
927 }
928
929 /**
930 * import from Poche exported file
931 * @param string $targetFile the file used for importing
932 * @return boolean
933 */
934 private function importFromPoche($targetFile)
935 {
936 $str_data = file_get_contents($targetFile);
937 $data = json_decode($str_data,true);
938 Tools::logm('starting import from Poche');
939
940
941 $sequence = '';
942 if (STORAGE == 'postgres') {
943 $sequence = 'entries_id_seq';
944 }
945
946 $count = 0;
947 foreach ($data as $value) {
948
949 $url = new Url(base64_encode($value['url']));
950 $favorite = ($value['is_fav'] == -1);
951 $archive = ($value['is_read'] == -1);
952
953 # we can add the url
954 if (!is_null($url) && $url->isCorrect()) {
955
956 $this->action('add', $url, 0, TRUE);
957
958 $count++;
959 if ($favorite) {
960 $last_id = $this->store->getLastId($sequence);
961 $this->action('toggle_fav', $url, $last_id, TRUE);
962 }
963 if ($archive) {
964 $last_id = $this->store->getLastId($sequence);
965 $this->action('toggle_archive', $url, $last_id, TRUE);
966 }
967 }
968
969 }
970 $this->messages->add('s', _('import from Poche completed. ' . $count . ' new links.'));
971 Tools::logm('import from Poche completed');
972 Tools::redirect();
973 }
974
975 /**
976 * import datas into your poche
977 * @param string $from name of the service to import : pocket, instapaper or readability
978 * @todo add the return value
979 * @return boolean
980 */
981 public function import($from)
982 {
983 $providers = array(
984 'pocket' => 'importFromPocket',
985 'readability' => 'importFromReadability',
986 'instapaper' => 'importFromInstapaper',
987 'poche' => 'importFromPoche',
988 );
989
990 if (! isset($providers[$from])) {
991 $this->messages->add('e', _('Unknown import provider.'));
992 Tools::redirect();
993 }
994
995 $targetDefinition = 'IMPORT_' . strtoupper($from) . '_FILE';
996 $targetFile = constant($targetDefinition);
997
998 if (! defined($targetDefinition)) {
999 $this->messages->add('e', _('Incomplete inc/poche/define.inc.php file, please define "' . $targetDefinition . '".'));
1000 Tools::redirect();
1001 }
1002
1003 if (! file_exists($targetFile)) {
1004 $this->messages->add('e', _('Could not find required "' . $targetFile . '" import file.'));
1005 Tools::redirect();
1006 }
1007
1008 $this->$providers[$from]($targetFile);
1009 }
1010
1011 /**
1012 * export poche entries in json
1013 * @return json all poche entries
1014 */
1015 public function export()
1016 {
1017 $entries = $this->store->retrieveAll($this->user->getId());
1018 echo $this->tpl->render('export.twig', array(
1019 'export' => Tools::renderJson($entries),
1020 ));
1021 Tools::logm('export view');
1022 }
1023
1024 /**
1025 * Checks online the latest version of poche and cache it
1026 * @param string $which 'prod' or 'dev'
1027 * @return string latest $which version
1028 */
1029 private function getPocheVersion($which = 'prod')
1030 {
1031 $cache_file = CACHE . '/' . $which;
1032
1033 # checks if the cached version file exists
1034 if (file_exists($cache_file) && (filemtime($cache_file) > (time() - 86400 ))) {
1035 $version = file_get_contents($cache_file);
1036 } else {
1037 $version = file_get_contents('http://static.wallabag.org/versions/' . $which);
1038 file_put_contents($cache_file, $version, LOCK_EX);
1039 }
1040 return $version;
1041 }
1042
1043 public function generateToken()
1044 {
1045 if (ini_get('open_basedir') === '') {
1046 $token = substr(base64_encode(file_get_contents('/dev/urandom', false, null, 0, 20)), 0, 15);
1047 }
1048 else {
1049 $token = substr(base64_encode(uniqid(mt_rand(), true)), 0, 20);
1050 }
1051
1052 $token = str_replace('+', '', $token);
1053 $this->store->updateUserConfig($this->user->getId(), 'token', $token);
1054 $currentConfig = $_SESSION['poche_user']->config;
1055 $currentConfig['token'] = $token;
1056 $_SESSION['poche_user']->setConfig($currentConfig);
1057 }
1058
1059 public function generateFeeds($token, $user_id, $tag_id, $type = 'home')
1060 {
1061 $allowed_types = array('home', 'fav', 'archive', 'tag');
1062 $config = $this->store->getConfigUser($user_id);
1063
1064 if (!in_array($type, $allowed_types) ||
1065 $token != $config['token']) {
1066 die(_('Uh, there is a problem while generating feeds.'));
1067 }
1068 // Check the token
1069
1070 $feed = new FeedWriter(RSS2);
1071 $feed->setTitle('wallabag — ' . $type . ' feed');
1072 $feed->setLink(Tools::getPocheUrl());
1073 $feed->setChannelElement('updated', date(DATE_RSS , time()));
1074 $feed->setChannelElement('author', 'wallabag');
1075
1076 if ($type == 'tag') {
1077 $entries = $this->store->retrieveEntriesByTag($tag_id, $user_id);
1078 }
1079 else {
1080 $entries = $this->store->getEntriesByView($type, $user_id);
1081 }
1082
1083 if (count($entries) > 0) {
1084 foreach ($entries as $entry) {
1085 $newItem = $feed->createNewItem();
1086 $newItem->setTitle($entry['title']);
1087 $newItem->setLink(Tools::getPocheUrl() . '?view=view&amp;id=' . $entry['id']);
1088 $newItem->setDate(time());
1089 $newItem->setDescription($entry['content']);
1090 $feed->addItem($newItem);
1091 }
1092 }
1093
1094 $feed->genarateFeed();
1095 exit;
1096 }
1097
1098 public function emptyCache() {
1099 $files = new RecursiveIteratorIterator(
1100 new RecursiveDirectoryIterator(CACHE, RecursiveDirectoryIterator::SKIP_DOTS),
1101 RecursiveIteratorIterator::CHILD_FIRST
1102 );
1103
1104 foreach ($files as $fileinfo) {
1105 $todo = ($fileinfo->isDir() ? 'rmdir' : 'unlink');
1106 $todo($fileinfo->getRealPath());
1107 }
1108
1109 Tools::logm('empty cache');
1110 $this->messages->add('s', _('Cache deleted.'));
1111 Tools::redirect();
1112 }
1113 }