]> git.immae.eu Git - github/wallabag/wallabag.git/blob - inc/poche/Poche.class.php
Important fixes for search engine (thx @mariroz)
[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 = filter_var($_GET['search'], FILTER_SANITIZE_STRING);
610 $tpl_vars['entries'] = $this->store->search($search,$this->user->getId());
611 $count = count($tpl_vars['entries']);
612 $this->pagination->set_total($count);
613 $page_links = str_replace(array('previous', 'next'), array(_('previous'), _('next')),
614 $this->pagination->page_links('?view=' . $view . '?search=' . $search . '&sort=' . $_SESSION['sort'] . '&' ));
615 $tpl_vars['page_links'] = $page_links;
616 $tpl_vars['nb_results'] = $count;
617 $tpl_vars['search_term'] = $search;
618 }
619 break;
620 case 'view':
621 $entry = $this->store->retrieveOneById($id, $this->user->getId());
622 if ($entry != NULL) {
623 Tools::logm('view link #' . $id);
624 $content = $entry['content'];
625 if (function_exists('tidy_parse_string')) {
626 $tidy = tidy_parse_string($content, array('indent'=>true, 'show-body-only' => true), 'UTF8');
627 $tidy->cleanRepair();
628 $content = $tidy->value;
629 }
630
631 # flattr checking
632 $flattr = new FlattrItem();
633 $flattr->checkItem($entry['url'], $entry['id']);
634
635 # tags
636 $tags = $this->store->retrieveTagsByEntry($entry['id']);
637
638 $tpl_vars = array(
639 'entry' => $entry,
640 'content' => $content,
641 'flattr' => $flattr,
642 'tags' => $tags
643 );
644 }
645 else {
646 Tools::logm('error in view call : entry is null');
647 }
648 break;
649 default: # home, favorites, archive and tag views
650 $tpl_vars = array(
651 'entries' => '',
652 'page_links' => '',
653 'nb_results' => '',
654 'listmode' => (isset($_COOKIE['listmode']) ? true : false),
655 );
656
657 //if id is given - we retrive entries by tag: id is tag id
658 if ($id) {
659 $tpl_vars['tag'] = $this->store->retrieveTag($id, $this->user->getId());
660 $tpl_vars['id'] = intval($id);
661 }
662
663 $count = $this->store->getEntriesByViewCount($view, $this->user->getId(), $id);
664
665 if ($count > 0) {
666 $this->pagination->set_total($count);
667 $page_links = str_replace(array('previous', 'next'), array(_('previous'), _('next')),
668 $this->pagination->page_links('?view=' . $view . '&sort=' . $_SESSION['sort'] . (($id)?'&id='.$id:'') . '&' ));
669 $tpl_vars['entries'] = $this->store->getEntriesByView($view, $this->user->getId(), $this->pagination->get_limit(), $id);
670 $tpl_vars['page_links'] = $page_links;
671 $tpl_vars['nb_results'] = $count;
672 }
673 Tools::logm('display ' . $view . ' view');
674 break;
675 }
676
677 return $tpl_vars;
678 }
679
680 /**
681 * update the password of the current user.
682 * if MODE_DEMO is TRUE, the password can't be updated.
683 * @todo add the return value
684 * @todo set the new password in function header like this updatePassword($newPassword)
685 * @return boolean
686 */
687 public function updatePassword()
688 {
689 if (MODE_DEMO) {
690 $this->messages->add('i', _('in demo mode, you can\'t update your password'));
691 Tools::logm('in demo mode, you can\'t do this');
692 Tools::redirect('?view=config');
693 }
694 else {
695 if (isset($_POST['password']) && isset($_POST['password_repeat'])) {
696 if ($_POST['password'] == $_POST['password_repeat'] && $_POST['password'] != "") {
697 $this->messages->add('s', _('your password has been updated'));
698 $this->store->updatePassword($this->user->getId(), Tools::encodeString($_POST['password'] . $this->user->getUsername()));
699 Session::logout();
700 Tools::logm('password updated');
701 Tools::redirect();
702 }
703 else {
704 $this->messages->add('e', _('the two fields have to be filled & the password must be the same in the two fields'));
705 Tools::redirect('?view=config');
706 }
707 }
708 }
709 }
710
711 public function updateTheme()
712 {
713 # no data
714 if (empty($_POST['theme'])) {
715 }
716
717 # we are not going to change it to the current theme...
718 if ($_POST['theme'] == $this->getTheme()) {
719 $this->messages->add('w', _('still using the "' . $this->getTheme() . '" theme!'));
720 Tools::redirect('?view=config');
721 }
722
723 $themes = $this->getInstalledThemes();
724 $actualTheme = false;
725
726 foreach (array_keys($themes) as $theme) {
727 if ($theme == $_POST['theme']) {
728 $actualTheme = true;
729 break;
730 }
731 }
732
733 if (! $actualTheme) {
734 $this->messages->add('e', _('that theme does not seem to be installed'));
735 Tools::redirect('?view=config');
736 }
737
738 $this->store->updateUserConfig($this->user->getId(), 'theme', $_POST['theme']);
739 $this->messages->add('s', _('you have changed your theme preferences'));
740
741 $currentConfig = $_SESSION['poche_user']->config;
742 $currentConfig['theme'] = $_POST['theme'];
743
744 $_SESSION['poche_user']->setConfig($currentConfig);
745
746 $this->emptyCache();
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 $this->emptyCache();
787
788 Tools::redirect('?view=config');
789 }
790 /**
791 * get credentials from differents sources
792 * it redirects the user to the $referer link
793 * @return array
794 */
795 private function credentials() {
796 if(isset($_SERVER['PHP_AUTH_USER'])) {
797 return array($_SERVER['PHP_AUTH_USER'],'php_auth',true);
798 }
799 if(!empty($_POST['login']) && !empty($_POST['password'])) {
800 return array($_POST['login'],$_POST['password'],false);
801 }
802 if(isset($_SERVER['REMOTE_USER'])) {
803 return array($_SERVER['REMOTE_USER'],'http_auth',true);
804 }
805
806 return array(false,false,false);
807 }
808
809 /**
810 * checks if login & password are correct and save the user in session.
811 * it redirects the user to the $referer link
812 * @param string $referer the url to redirect after login
813 * @todo add the return value
814 * @return boolean
815 */
816 public function login($referer)
817 {
818 list($login,$password,$isauthenticated)=$this->credentials();
819 if($login === false || $password === false) {
820 $this->messages->add('e', _('login failed: you have to fill all fields'));
821 Tools::logm('login failed');
822 Tools::redirect();
823 }
824 if (!empty($login) && !empty($password)) {
825 $user = $this->store->login($login, Tools::encodeString($password . $login), $isauthenticated);
826 if ($user != array()) {
827 # Save login into Session
828 $longlastingsession = isset($_POST['longlastingsession']);
829 $passwordTest = ($isauthenticated) ? $user['password'] : Tools::encodeString($password . $login);
830 Session::login($user['username'], $user['password'], $login, $passwordTest, $longlastingsession, array('poche_user' => new User($user)));
831 $this->messages->add('s', _('welcome to your wallabag'));
832 Tools::logm('login successful');
833 Tools::redirect($referer);
834 }
835 $this->messages->add('e', _('login failed: bad login or password'));
836 Tools::logm('login failed');
837 Tools::redirect();
838 }
839 }
840
841 /**
842 * log out the poche user. It cleans the session.
843 * @todo add the return value
844 * @return boolean
845 */
846 public function logout()
847 {
848 $this->user = array();
849 Session::logout();
850 Tools::logm('logout');
851 Tools::redirect();
852 }
853
854 /**
855 * import from Instapaper. poche needs a ./instapaper-export.html file
856 * @todo add the return value
857 * @param string $targetFile the file used for importing
858 * @return boolean
859 */
860 private function importFromInstapaper($targetFile)
861 {
862 # TODO gestion des articles favs
863 $html = new simple_html_dom();
864 $html->load_file($targetFile);
865 Tools::logm('starting import from instapaper');
866
867 $read = 0;
868 $errors = array();
869 foreach($html->find('ol') as $ul)
870 {
871 foreach($ul->find('li') as $li)
872 {
873 $a = $li->find('a');
874 $url = new Url(base64_encode($a[0]->href));
875 $this->action('add', $url, 0, TRUE);
876 if ($read == '1') {
877 $sequence = '';
878 if (STORAGE == 'postgres') {
879 $sequence = 'entries_id_seq';
880 }
881 $last_id = $this->store->getLastId($sequence);
882 $this->action('toggle_archive', $url, $last_id, TRUE);
883 }
884 }
885
886 # the second <ol> is for read links
887 $read = 1;
888 }
889
890 $unlink = unlink($targetFile);
891 $this->messages->add('s', _('import from instapaper completed. You have to execute the cron to fetch content.'));
892 Tools::logm('import from instapaper completed');
893 Tools::redirect();
894 }
895
896 /**
897 * import from Pocket. poche needs a ./ril_export.html file
898 * @todo add the return value
899 * @param string $targetFile the file used for importing
900 * @return boolean
901 */
902 private function importFromPocket($targetFile)
903 {
904 # TODO gestion des articles favs
905 $html = new simple_html_dom();
906 $html->load_file($targetFile);
907 Tools::logm('starting import from pocket');
908
909 $read = 0;
910 $errors = array();
911 foreach($html->find('ul') as $ul)
912 {
913 foreach($ul->find('li') as $li)
914 {
915 $a = $li->find('a');
916 $url = new Url(base64_encode($a[0]->href));
917 $this->action('add', $url, 0, TRUE);
918 $sequence = '';
919 if (STORAGE == 'postgres') {
920 $sequence = 'entries_id_seq';
921 }
922 $last_id = $this->store->getLastId($sequence);
923 if ($read == '1') {
924 $this->action('toggle_archive', $url, $last_id, TRUE);
925 }
926 $tags = $a[0]->tags;
927 if(!empty($tags)) {
928 $this->action('add_tag',$url,$last_id,true,false,$tags);
929 }
930 }
931
932 # the second <ul> is for read links
933 $read = 1;
934 }
935
936 $unlink = unlink($targetFile);
937 $this->messages->add('s', _('import from pocket completed. You have to execute the cron to fetch content.'));
938 Tools::logm('import from pocket completed');
939 Tools::redirect();
940 }
941
942 /**
943 * import from Readability. poche needs a ./readability file
944 * @todo add the return value
945 * @param string $targetFile the file used for importing
946 * @return boolean
947 */
948 private function importFromReadability($targetFile)
949 {
950 # TODO gestion des articles lus / favs
951 $str_data = file_get_contents($targetFile);
952 $data = json_decode($str_data,true);
953 Tools::logm('starting import from Readability');
954 $count = 0;
955 foreach ($data as $key => $value) {
956 $url = NULL;
957 $favorite = FALSE;
958 $archive = FALSE;
959 foreach ($value as $item) {
960 foreach ($item as $attr => $value) {
961 if ($attr == 'article__url') {
962 $url = new Url(base64_encode($value));
963 }
964 $sequence = '';
965 if (STORAGE == 'postgres') {
966 $sequence = 'entries_id_seq';
967 }
968 if ($value == 'true') {
969 if ($attr == 'favorite') {
970 $favorite = TRUE;
971 }
972 if ($attr == 'archive') {
973 $archive = TRUE;
974 }
975 }
976 }
977
978 # we can add the url
979 if (!is_null($url) && $url->isCorrect()) {
980 $this->action('add', $url, 0, TRUE);
981 $count++;
982 if ($favorite) {
983 $last_id = $this->store->getLastId($sequence);
984 $this->action('toggle_fav', $url, $last_id, TRUE);
985 }
986 if ($archive) {
987 $last_id = $this->store->getLastId($sequence);
988 $this->action('toggle_archive', $url, $last_id, TRUE);
989 }
990 }
991 }
992 }
993
994 unlink($targetFile);
995 $this->messages->add('s', _('import from Readability completed. You have to execute the cron to fetch content.'));
996 Tools::logm('import from Readability completed');
997 Tools::redirect();
998 }
999
1000 /**
1001 * import from Poche exported file
1002 * @param string $targetFile the file used for importing
1003 * @return boolean
1004 */
1005 private function importFromPoche($targetFile)
1006 {
1007 $str_data = file_get_contents($targetFile);
1008 $data = json_decode($str_data,true);
1009 Tools::logm('starting import from Poche');
1010
1011
1012 $sequence = '';
1013 if (STORAGE == 'postgres') {
1014 $sequence = 'entries_id_seq';
1015 }
1016
1017 $count = 0;
1018 foreach ($data as $value) {
1019
1020 $url = new Url(base64_encode($value['url']));
1021 $favorite = ($value['is_fav'] == -1);
1022 $archive = ($value['is_read'] == -1);
1023
1024 # we can add the url
1025 if (!is_null($url) && $url->isCorrect()) {
1026
1027 $this->action('add', $url, 0, TRUE);
1028
1029 $count++;
1030 if ($favorite) {
1031 $last_id = $this->store->getLastId($sequence);
1032 $this->action('toggle_fav', $url, $last_id, TRUE);
1033 }
1034 if ($archive) {
1035 $last_id = $this->store->getLastId($sequence);
1036 $this->action('toggle_archive', $url, $last_id, TRUE);
1037 }
1038 }
1039
1040 }
1041
1042 unlink($targetFile);
1043 $this->messages->add('s', _('import from Poche completed. You have to execute the cron to fetch content.'));
1044 Tools::logm('import from Poche completed');
1045 Tools::redirect();
1046 }
1047
1048 /**
1049 * import datas into your poche
1050 * @param string $from name of the service to import : pocket, instapaper or readability
1051 * @todo add the return value
1052 * @return boolean
1053 */
1054 public function import($from)
1055 {
1056 $providers = array(
1057 'pocket' => 'importFromPocket',
1058 'readability' => 'importFromReadability',
1059 'instapaper' => 'importFromInstapaper',
1060 'poche' => 'importFromPoche',
1061 );
1062
1063 if (! isset($providers[$from])) {
1064 $this->messages->add('e', _('Unknown import provider.'));
1065 Tools::redirect();
1066 }
1067
1068 $targetFile = CACHE . '/' . constant(strtoupper($from) . '_FILE');
1069
1070 if (! file_exists($targetFile)) {
1071 $this->messages->add('e', _('Could not find required "' . $targetFile . '" import file.'));
1072 Tools::redirect();
1073 }
1074
1075 $this->$providers[$from]($targetFile);
1076 }
1077
1078 public function uploadFile() {
1079 if(isset($_FILES['file']))
1080 {
1081 $dir = CACHE . '/';
1082 $file = basename($_FILES['file']['name']);
1083 if(move_uploaded_file($_FILES['file']['tmp_name'], $dir . $file)) {
1084 $this->messages->add('s', _('File uploaded. You can now execute import.'));
1085 }
1086 else {
1087 $this->messages->add('e', _('Error while importing file. Do you have access to upload it?'));
1088 }
1089 }
1090
1091 Tools::redirect('?view=config');
1092 }
1093
1094 /**
1095 * export poche entries in json
1096 * @return json all poche entries
1097 */
1098 public function export()
1099 {
1100 $filename = "wallabag-export-".$this->user->getId()."-".date("Y-m-d").".json";
1101 header('Content-Disposition: attachment; filename='.$filename);
1102
1103 $entries = $this->store->retrieveAll($this->user->getId());
1104 echo $this->tpl->render('export.twig', array(
1105 'export' => Tools::renderJson($entries),
1106 ));
1107 Tools::logm('export view');
1108 }
1109
1110 /**
1111 * Checks online the latest version of poche and cache it
1112 * @param string $which 'prod' or 'dev'
1113 * @return string latest $which version
1114 */
1115 private function getPocheVersion($which = 'prod')
1116 {
1117 $cache_file = CACHE . '/' . $which;
1118 $check_time = time();
1119
1120 # checks if the cached version file exists
1121 if (file_exists($cache_file) && (filemtime($cache_file) > (time() - 86400 ))) {
1122 $version = file_get_contents($cache_file);
1123 $check_time = filemtime($cache_file);
1124 } else {
1125 $version = file_get_contents('http://static.wallabag.org/versions/' . $which);
1126 file_put_contents($cache_file, $version, LOCK_EX);
1127 }
1128 return array($version, $check_time);
1129 }
1130
1131 public function generateToken()
1132 {
1133 if (ini_get('open_basedir') === '') {
1134 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
1135 echo 'This is a server using Windows!';
1136 // alternative to /dev/urandom for Windows
1137 $token = substr(base64_encode(uniqid(mt_rand(), true)), 0, 20);
1138 } else {
1139 $token = substr(base64_encode(file_get_contents('/dev/urandom', false, null, 0, 20)), 0, 15);
1140 }
1141 }
1142 else {
1143 $token = substr(base64_encode(uniqid(mt_rand(), true)), 0, 20);
1144 }
1145
1146 $token = str_replace('+', '', $token);
1147 $this->store->updateUserConfig($this->user->getId(), 'token', $token);
1148 $currentConfig = $_SESSION['poche_user']->config;
1149 $currentConfig['token'] = $token;
1150 $_SESSION['poche_user']->setConfig($currentConfig);
1151 Tools::redirect();
1152 }
1153
1154 public function generateFeeds($token, $user_id, $tag_id, $type = 'home')
1155 {
1156 $allowed_types = array('home', 'fav', 'archive', 'tag');
1157 $config = $this->store->getConfigUser($user_id);
1158
1159 if ($config == null) {
1160 die(_('User with this id (' . $user_id . ') does not exist.'));
1161 }
1162
1163 if (!in_array($type, $allowed_types) ||
1164 $token != $config['token']) {
1165 die(_('Uh, there is a problem while generating feeds.'));
1166 }
1167 // Check the token
1168
1169 $feed = new FeedWriter(RSS2);
1170 $feed->setTitle('wallabag — ' . $type . ' feed');
1171 $feed->setLink(Tools::getPocheUrl());
1172 $feed->setChannelElement('pubDate', date(DATE_RSS , time()));
1173 $feed->setChannelElement('generator', 'wallabag');
1174 $feed->setDescription('wallabag ' . $type . ' elements');
1175
1176 if ($type == 'tag') {
1177 $entries = $this->store->retrieveEntriesByTag($tag_id, $user_id);
1178 }
1179 else {
1180 $entries = $this->store->getEntriesByView($type, $user_id);
1181 }
1182
1183 if (count($entries) > 0) {
1184 foreach ($entries as $entry) {
1185 $newItem = $feed->createNewItem();
1186 $newItem->setTitle($entry['title']);
1187 $newItem->setLink($entry['url']);
1188 $newItem->setDate(time());
1189 $newItem->setDescription($entry['content']);
1190 $feed->addItem($newItem);
1191 }
1192 }
1193
1194 $feed->genarateFeed();
1195 exit;
1196 }
1197
1198 public function emptyCache() {
1199 $files = new RecursiveIteratorIterator(
1200 new RecursiveDirectoryIterator(CACHE, RecursiveDirectoryIterator::SKIP_DOTS),
1201 RecursiveIteratorIterator::CHILD_FIRST
1202 );
1203
1204 foreach ($files as $fileinfo) {
1205 $todo = ($fileinfo->isDir() ? 'rmdir' : 'unlink');
1206 $todo($fileinfo->getRealPath());
1207 }
1208
1209 Tools::logm('empty cache');
1210 $this->messages->add('s', _('Cache deleted.'));
1211 Tools::redirect();
1212 }
1213 }