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