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