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