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