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