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