]> git.immae.eu Git - github/wallabag/wallabag.git/blob - inc/poche/Poche.class.php
Fixed Multi-user system
[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 public function createNewUser() {
246 if (isset($_GET['newuser'])){
247 if ($_POST['newusername'] != "" && $_POST['password4newuser'] != ""){
248 $newusername = filter_var($_POST['newusername'], FILTER_SANITIZE_STRING);
249 if (!$this->store->userExists($newusername)){
250 if ($this->store->install($newusername, Tools::encodeString($_POST['password4newuser'] . $newusername))) {
251 Tools::logm('The new user '.$newusername.' has been installed');
252 $this->messages->add('s', sprintf(_('The new user %s has been installed. Do you want to <a href="?logout">logout ?</a>'),$newusername));
253 Tools::redirect();
254 }
255 else {
256 Tools::logm('error during adding new user');
257 Tools::redirect();
258 }
259 }
260 else {
261 $this->messages->add('e', sprintf(_('Error : An user with the name %s already exists !'),$newusername));
262 Tools::logm('An user with the name '.$newusername.' already exists !');
263 Tools::redirect();
264 }
265 }
266 }
267 }
268
269 public function deleteUser(){
270 if (isset($_GET['deluser'])){
271 if ($this->store->listUsers() > 1) {
272 if (Tools::encodeString($_POST['password4deletinguser'].$this->user->getUsername()) == $this->store->getUserPassword($this->user->getId())) {
273 $username = $this->user->getUsername();
274 $this->store->deleteUserConfig($this->user->getId());
275 Tools::logm('The configuration for user '. $username .' has been deleted !');
276 $this->store->deleteTagsEntriesAndEntries($this->user->getId());
277 Tools::logm('The entries for user '. $username .' has been deleted !');
278 $this->store->deleteUser($this->user->getId());
279 Tools::logm('User '. $username .' has been completely deleted !');
280 Session::logout();
281 Tools::logm('logout');
282 Tools::redirect();
283 $this->messages->add('s', sprintf(_('User %s has been successfully deleted !'),$newusername));
284 }
285 else {
286 Tools::logm('Bad password !');
287 $this->messages->add('e', _('Error : The password is wrong !'));
288 }
289 }
290 else {
291 Tools::logm('Only user !');
292 $this->messages->add('e', _('Error : You are the only user, you cannot delete your account !'));
293 }
294 }
295 }
296
297 private function install()
298 {
299 Tools::logm('poche still not installed');
300 echo $this->tpl->render('install.twig', array(
301 'token' => Session::getToken(),
302 'theme' => $this->getTheme(),
303 'poche_url' => Tools::getPocheUrl()
304 ));
305 if (isset($_GET['install'])) {
306 if (($_POST['password'] == $_POST['password_repeat'])
307 && $_POST['password'] != "" && $_POST['login'] != "") {
308 # let's rock, install poche baby !
309 if ($this->store->install($_POST['login'], Tools::encodeString($_POST['password'] . $_POST['login'])))
310 {
311 Session::logout();
312 Tools::logm('poche is now installed');
313 Tools::redirect();
314 }
315 }
316 else {
317 Tools::logm('error during installation');
318 Tools::redirect();
319 }
320 }
321 exit();
322 }
323
324 public function getTheme() {
325 return $this->currentTheme;
326 }
327
328 /**
329 * Provides theme information by parsing theme.ini file if present in the theme's root directory.
330 * In all cases, the following data will be returned:
331 * - name: theme's name, or key if the theme is unnamed,
332 * - current: boolean informing if the theme is the current user theme.
333 *
334 * @param string $theme Theme key (directory name)
335 * @return array|boolean Theme information, or false if the theme doesn't exist.
336 */
337 public function getThemeInfo($theme) {
338 if (!is_dir(THEME . '/' . $theme)) {
339 return false;
340 }
341
342 $themeIniFile = THEME . '/' . $theme . '/theme.ini';
343 $themeInfo = array();
344
345 if (is_file($themeIniFile) && is_readable($themeIniFile)) {
346 $themeInfo = parse_ini_file($themeIniFile);
347 }
348
349 if ($themeInfo === false) {
350 $themeInfo = array();
351 }
352 if (!isset($themeInfo['name'])) {
353 $themeInfo['name'] = $theme;
354 }
355 $themeInfo['current'] = ($theme === $this->getTheme());
356
357 return $themeInfo;
358 }
359
360 public function getInstalledThemes() {
361 $handle = opendir(THEME);
362 $themes = array();
363
364 while (($theme = readdir($handle)) !== false) {
365 # Themes are stored in a directory, so all directory names are themes
366 # @todo move theme installation data to database
367 if (!is_dir(THEME . '/' . $theme) || in_array($theme, array('.', '..'))) {
368 continue;
369 }
370
371 $themes[$theme] = $this->getThemeInfo($theme);
372 }
373
374 ksort($themes);
375
376 return $themes;
377 }
378
379 public function getLanguage() {
380 return $this->currentLanguage;
381 }
382
383 public function getInstalledLanguages() {
384 $handle = opendir(LOCALE);
385 $languages = array();
386
387 while (($language = readdir($handle)) !== false) {
388 # Languages are stored in a directory, so all directory names are languages
389 # @todo move language installation data to database
390 if (! is_dir(LOCALE . '/' . $language) || in_array($language, array('..', '.', 'tools'))) {
391 continue;
392 }
393
394 $current = false;
395
396 if ($language === $this->getLanguage()) {
397 $current = true;
398 }
399
400 $languages[] = array('name' => (isset($this->language_names[$language]) ? $this->language_names[$language] : $language), 'value' => $language, 'current' => $current);
401 }
402
403 return $languages;
404 }
405
406 public function getDefaultConfig()
407 {
408 return array(
409 'pager' => PAGINATION,
410 'language' => LANG,
411 'theme' => DEFAULT_THEME
412 );
413 }
414
415 /**
416 * Call action (mark as fav, archive, delete, etc.)
417 */
418 public function action($action, Url $url, $id = 0, $import = FALSE, $autoclose = FALSE, $tags = null)
419 {
420 switch ($action)
421 {
422 case 'add':
423 $content = Tools::getPageContent($url);
424 $title = ($content['rss']['channel']['item']['title'] != '') ? $content['rss']['channel']['item']['title'] : _('Untitled');
425 $body = $content['rss']['channel']['item']['description'];
426
427 // clean content from prevent xss attack
428 $purifier = $this->getPurifier();
429 $title = $purifier->purify($title);
430 $body = $purifier->purify($body);
431
432 //search for possible duplicate
433 $duplicate = NULL;
434 $duplicate = $this->store->retrieveOneByURL($url->getUrl(), $this->user->getId());
435
436 $last_id = $this->store->add($url->getUrl(), $title, $body, $this->user->getId());
437 if ( $last_id ) {
438 Tools::logm('add link ' . $url->getUrl());
439 if (DOWNLOAD_PICTURES) {
440 $content = filtre_picture($body, $url->getUrl(), $last_id);
441 Tools::logm('updating content article');
442 $this->store->updateContent($last_id, $content, $this->user->getId());
443 }
444
445 if ($duplicate != NULL) {
446 // 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
447 Tools::logm('link ' . $url->getUrl() . ' is a duplicate');
448 // 1) - preserve tags and favorite, then drop old entry
449 $this->store->reassignTags($duplicate['id'], $last_id);
450 if ($duplicate['is_fav']) {
451 $this->store->favoriteById($last_id, $this->user->getId());
452 }
453 if ($this->store->deleteById($duplicate['id'], $this->user->getId())) {
454 Tools::logm('previous link ' . $url->getUrl() .' entry deleted');
455 }
456 }
457
458 $this->messages->add('s', _('the link has been added successfully'));
459 }
460 else {
461 $this->messages->add('e', _('error during insertion : the link wasn\'t added'));
462 Tools::logm('error during insertion : the link wasn\'t added ' . $url->getUrl());
463 }
464
465 if ($autoclose == TRUE) {
466 Tools::redirect('?view=home');
467 } else {
468 Tools::redirect('?view=home&closewin=true');
469 }
470 break;
471 case 'delete':
472 $msg = 'delete link #' . $id;
473 if ($this->store->deleteById($id, $this->user->getId())) {
474 if (DOWNLOAD_PICTURES) {
475 remove_directory(ABS_PATH . $id);
476 }
477 $this->messages->add('s', _('the link has been deleted successfully'));
478 }
479 else {
480 $this->messages->add('e', _('the link wasn\'t deleted'));
481 $msg = 'error : can\'t delete link #' . $id;
482 }
483 Tools::logm($msg);
484 Tools::redirect('?');
485 break;
486 case 'toggle_fav' :
487 $this->store->favoriteById($id, $this->user->getId());
488 Tools::logm('mark as favorite link #' . $id);
489 Tools::redirect();
490 break;
491 case 'toggle_archive' :
492 $this->store->archiveById($id, $this->user->getId());
493 Tools::logm('archive link #' . $id);
494 Tools::redirect();
495 break;
496 case 'archive_all' :
497 $this->store->archiveAll($this->user->getId());
498 Tools::logm('archive all links');
499 Tools::redirect();
500 break;
501 case 'add_tag' :
502 $tags = explode(',', $_POST['value']);
503 $entry_id = $_POST['entry_id'];
504 $entry = $this->store->retrieveOneById($entry_id, $this->user->getId());
505 if (!$entry) {
506 $this->messages->add('e', _('Article not found!'));
507 Tools::logm('error : article not found');
508 Tools::redirect();
509 }
510 //get all already set tags to preven duplicates
511 $already_set_tags = array();
512 $entry_tags = $this->store->retrieveTagsByEntry($entry_id);
513 foreach ($entry_tags as $tag) {
514 $already_set_tags[] = $tag['value'];
515 }
516 foreach($tags as $key => $tag_value) {
517 $value = trim($tag_value);
518 if ($value && !in_array($value, $already_set_tags)) {
519 $tag = $this->store->retrieveTagByValue($value);
520
521 if (is_null($tag)) {
522 # we create the tag
523 $tag = $this->store->createTag($value);
524 $sequence = '';
525 if (STORAGE == 'postgres') {
526 $sequence = 'tags_id_seq';
527 }
528 $tag_id = $this->store->getLastId($sequence);
529 }
530 else {
531 $tag_id = $tag['id'];
532 }
533
534 # we assign the tag to the article
535 $this->store->setTagToEntry($tag_id, $entry_id);
536 }
537 }
538 Tools::redirect();
539 break;
540 case 'remove_tag' :
541 $tag_id = $_GET['tag_id'];
542 $entry = $this->store->retrieveOneById($id, $this->user->getId());
543 if (!$entry) {
544 $this->messages->add('e', _('Article not found!'));
545 Tools::logm('error : article not found');
546 Tools::redirect();
547 }
548 $this->store->removeTagForEntry($id, $tag_id);
549 Tools::redirect();
550 break;
551 default:
552 break;
553 }
554 }
555
556 function displayView($view, $id = 0)
557 {
558 $tpl_vars = array();
559
560 switch ($view)
561 {
562 case 'config':
563 $dev_infos = $this->getPocheVersion('dev');
564 $dev = trim($dev_infos[0]);
565 $check_time_dev = date('d-M-Y H:i', $dev_infos[1]);
566 $prod_infos = $this->getPocheVersion('prod');
567 $prod = trim($prod_infos[0]);
568 $check_time_prod = date('d-M-Y H:i', $prod_infos[1]);
569 $compare_dev = version_compare(POCHE, $dev);
570 $compare_prod = version_compare(POCHE, $prod);
571 $themes = $this->getInstalledThemes();
572 $languages = $this->getInstalledLanguages();
573 $token = $this->user->getConfigValue('token');
574 $http_auth = (isset($_SERVER['PHP_AUTH_USER']) || isset($_SERVER['REMOTE_USER'])) ? true : false;
575 $only_user = ($this->store->listUsers() > 1) ? false : true;
576 $tpl_vars = array(
577 'themes' => $themes,
578 'languages' => $languages,
579 'dev' => $dev,
580 'prod' => $prod,
581 'check_time_dev' => $check_time_dev,
582 'check_time_prod' => $check_time_prod,
583 'compare_dev' => $compare_dev,
584 'compare_prod' => $compare_prod,
585 'token' => $token,
586 'user_id' => $this->user->getId(),
587 'http_auth' => $http_auth,
588 'only_user' => $only_user
589 );
590 Tools::logm('config view');
591 break;
592 case 'edit-tags':
593 # tags
594 $entry = $this->store->retrieveOneById($id, $this->user->getId());
595 if (!$entry) {
596 $this->messages->add('e', _('Article not found!'));
597 Tools::logm('error : article not found');
598 Tools::redirect();
599 }
600 $tags = $this->store->retrieveTagsByEntry($id);
601 $tpl_vars = array(
602 'entry_id' => $id,
603 'tags' => $tags,
604 'entry' => $entry,
605 );
606 break;
607 case 'tags':
608 $token = $this->user->getConfigValue('token');
609 //if term is set - search tags for this term
610 $term = Tools::checkVar('term');
611 $tags = $this->store->retrieveAllTags($this->user->getId(), $term);
612 if (Tools::isAjaxRequest()) {
613 $result = array();
614 foreach ($tags as $tag) {
615 $result[] = $tag['value'];
616 }
617 echo json_encode($result);
618 exit;
619 }
620 $tpl_vars = array(
621 'token' => $token,
622 'user_id' => $this->user->getId(),
623 'tags' => $tags,
624 );
625 break;
626 case 'search':
627 if (isset($_GET['search'])) {
628 $search = filter_var($_GET['search'], FILTER_SANITIZE_STRING);
629 $tpl_vars['entries'] = $this->store->search($search, $this->user->getId());
630 $count = count($tpl_vars['entries']);
631 $this->pagination->set_total($count);
632 $page_links = str_replace(array('previous', 'next'), array(_('previous'), _('next')),
633 $this->pagination->page_links('?view=' . $view . '?search=' . $search . '&sort=' . $_SESSION['sort'] . '&' ));
634 $tpl_vars['page_links'] = $page_links;
635 $tpl_vars['nb_results'] = $count;
636 $tpl_vars['search_term'] = $search;
637 }
638 break;
639 case 'view':
640 $entry = $this->store->retrieveOneById($id, $this->user->getId());
641 if ($entry != NULL) {
642 Tools::logm('view link #' . $id);
643 $content = $entry['content'];
644 if (function_exists('tidy_parse_string')) {
645 $tidy = tidy_parse_string($content, array('indent'=>true, 'show-body-only' => true), 'UTF8');
646 $tidy->cleanRepair();
647 $content = $tidy->value;
648 }
649
650 # flattr checking
651 $flattr = new FlattrItem();
652 $flattr->checkItem($entry['url'], $entry['id']);
653
654 # tags
655 $tags = $this->store->retrieveTagsByEntry($entry['id']);
656
657 $tpl_vars = array(
658 'entry' => $entry,
659 'content' => $content,
660 'flattr' => $flattr,
661 'tags' => $tags
662 );
663 }
664 else {
665 Tools::logm('error in view call : entry is null');
666 }
667 break;
668 default: # home, favorites, archive and tag views
669 $tpl_vars = array(
670 'entries' => '',
671 'page_links' => '',
672 'nb_results' => '',
673 'listmode' => (isset($_COOKIE['listmode']) ? true : false),
674 );
675
676 //if id is given - we retrive entries by tag: id is tag id
677 if ($id) {
678 $tpl_vars['tag'] = $this->store->retrieveTag($id, $this->user->getId());
679 $tpl_vars['id'] = intval($id);
680 }
681
682 $count = $this->store->getEntriesByViewCount($view, $this->user->getId(), $id);
683
684 if ($count > 0) {
685 $this->pagination->set_total($count);
686 $page_links = str_replace(array('previous', 'next'), array(_('previous'), _('next')),
687 $this->pagination->page_links('?view=' . $view . '&sort=' . $_SESSION['sort'] . (($id)?'&id='.$id:'') . '&' ));
688 $tpl_vars['entries'] = $this->store->getEntriesByView($view, $this->user->getId(), $this->pagination->get_limit(), $id);
689 $tpl_vars['page_links'] = $page_links;
690 $tpl_vars['nb_results'] = $count;
691 }
692 Tools::logm('display ' . $view . ' view');
693 break;
694 }
695
696 return $tpl_vars;
697 }
698
699 /**
700 * update the password of the current user.
701 * if MODE_DEMO is TRUE, the password can't be updated.
702 * @todo add the return value
703 * @todo set the new password in function header like this updatePassword($newPassword)
704 * @return boolean
705 */
706 public function updatePassword()
707 {
708 if (MODE_DEMO) {
709 $this->messages->add('i', _('in demo mode, you can\'t update your password'));
710 Tools::logm('in demo mode, you can\'t do this');
711 Tools::redirect('?view=config');
712 }
713 else {
714 if (isset($_POST['password']) && isset($_POST['password_repeat'])) {
715 if ($_POST['password'] == $_POST['password_repeat'] && $_POST['password'] != "") {
716 $this->messages->add('s', _('your password has been updated'));
717 $this->store->updatePassword($this->user->getId(), Tools::encodeString($_POST['password'] . $this->user->getUsername()));
718 Session::logout();
719 Tools::logm('password updated');
720 Tools::redirect();
721 }
722 else {
723 $this->messages->add('e', _('the two fields have to be filled & the password must be the same in the two fields'));
724 Tools::redirect('?view=config');
725 }
726 }
727 }
728 }
729
730 public function updateTheme()
731 {
732 # no data
733 if (empty($_POST['theme'])) {
734 }
735
736 # we are not going to change it to the current theme...
737 if ($_POST['theme'] == $this->getTheme()) {
738 $this->messages->add('w', _('still using the "' . $this->getTheme() . '" theme!'));
739 Tools::redirect('?view=config');
740 }
741
742 $themes = $this->getInstalledThemes();
743 $actualTheme = false;
744
745 foreach (array_keys($themes) as $theme) {
746 if ($theme == $_POST['theme']) {
747 $actualTheme = true;
748 break;
749 }
750 }
751
752 if (! $actualTheme) {
753 $this->messages->add('e', _('that theme does not seem to be installed'));
754 Tools::redirect('?view=config');
755 }
756
757 $this->store->updateUserConfig($this->user->getId(), 'theme', $_POST['theme']);
758 $this->messages->add('s', _('you have changed your theme preferences'));
759
760 $currentConfig = $_SESSION['poche_user']->config;
761 $currentConfig['theme'] = $_POST['theme'];
762
763 $_SESSION['poche_user']->setConfig($currentConfig);
764
765 $this->emptyCache();
766
767 Tools::redirect('?view=config');
768 }
769
770 public function updateLanguage()
771 {
772 # no data
773 if (empty($_POST['language'])) {
774 }
775
776 # we are not going to change it to the current language...
777 if ($_POST['language'] == $this->getLanguage()) {
778 $this->messages->add('w', _('still using the "' . $this->getLanguage() . '" language!'));
779 Tools::redirect('?view=config');
780 }
781
782 $languages = $this->getInstalledLanguages();
783 $actualLanguage = false;
784
785 foreach ($languages as $language) {
786 if ($language['value'] == $_POST['language']) {
787 $actualLanguage = true;
788 break;
789 }
790 }
791
792 if (! $actualLanguage) {
793 $this->messages->add('e', _('that language does not seem to be installed'));
794 Tools::redirect('?view=config');
795 }
796
797 $this->store->updateUserConfig($this->user->getId(), 'language', $_POST['language']);
798 $this->messages->add('s', _('you have changed your language preferences'));
799
800 $currentConfig = $_SESSION['poche_user']->config;
801 $currentConfig['language'] = $_POST['language'];
802
803 $_SESSION['poche_user']->setConfig($currentConfig);
804
805 $this->emptyCache();
806
807 Tools::redirect('?view=config');
808 }
809 /**
810 * get credentials from differents sources
811 * it redirects the user to the $referer link
812 * @return array
813 */
814 private function credentials() {
815 if(isset($_SERVER['PHP_AUTH_USER'])) {
816 return array($_SERVER['PHP_AUTH_USER'],'php_auth',true);
817 }
818 if(!empty($_POST['login']) && !empty($_POST['password'])) {
819 return array($_POST['login'],$_POST['password'],false);
820 }
821 if(isset($_SERVER['REMOTE_USER'])) {
822 return array($_SERVER['REMOTE_USER'],'http_auth',true);
823 }
824
825 return array(false,false,false);
826 }
827
828 /**
829 * checks if login & password are correct and save the user in session.
830 * it redirects the user to the $referer link
831 * @param string $referer the url to redirect after login
832 * @todo add the return value
833 * @return boolean
834 */
835 public function login($referer)
836 {
837 list($login,$password,$isauthenticated)=$this->credentials();
838 if($login === false || $password === false) {
839 $this->messages->add('e', _('login failed: you have to fill all fields'));
840 Tools::logm('login failed');
841 Tools::redirect();
842 }
843 if (!empty($login) && !empty($password)) {
844 $user = $this->store->login($login, Tools::encodeString($password . $login), $isauthenticated);
845 if ($user != array()) {
846 # Save login into Session
847 $longlastingsession = isset($_POST['longlastingsession']);
848 $passwordTest = ($isauthenticated) ? $user['password'] : Tools::encodeString($password . $login);
849 Session::login($user['username'], $user['password'], $login, $passwordTest, $longlastingsession, array('poche_user' => new User($user)));
850 $this->messages->add('s', _('welcome to your wallabag'));
851 Tools::logm('login successful');
852 Tools::redirect($referer);
853 }
854 $this->messages->add('e', _('login failed: bad login or password'));
855 Tools::logm('login failed');
856 Tools::redirect();
857 }
858 }
859
860 /**
861 * log out the poche user. It cleans the session.
862 * @todo add the return value
863 * @return boolean
864 */
865 public function logout()
866 {
867 $this->user = array();
868 Session::logout();
869 Tools::logm('logout');
870 Tools::redirect();
871 }
872
873 /**
874 * import datas into your poche
875 * @return boolean
876 */
877 public function import() {
878
879 if (!defined('IMPORT_LIMIT')) {
880 define('IMPORT_LIMIT', 5);
881 }
882 if (!defined('IMPORT_DELAY')) {
883 define('IMPORT_DELAY', 5);
884 }
885
886 if ( isset($_FILES['file']) ) {
887 Tools::logm('Import stated: parsing file');
888
889 // assume, that file is in json format
890 $str_data = file_get_contents($_FILES['file']['tmp_name']);
891 $data = json_decode($str_data, true);
892
893 if ( $data === null ) {
894 //not json - assume html
895 $html = new simple_html_dom();
896 $html->load_file($_FILES['file']['tmp_name']);
897 $data = array();
898 $read = 0;
899 foreach (array('ol','ul') as $list) {
900 foreach ($html->find($list) as $ul) {
901 foreach ($ul->find('li') as $li) {
902 $tmpEntry = array();
903 $a = $li->find('a');
904 $tmpEntry['url'] = $a[0]->href;
905 $tmpEntry['tags'] = $a[0]->tags;
906 $tmpEntry['is_read'] = $read;
907 if ($tmpEntry['url']) {
908 $data[] = $tmpEntry;
909 }
910 }
911 # the second <ol/ul> is for read links
912 $read = ((sizeof($data) && $read)?0:1);
913 }
914 }
915 }
916
917 //for readability structure
918 foreach ($data as $record) {
919 if (is_array($record)) {
920 $data[] = $record;
921 foreach ($record as $record2) {
922 if (is_array($record2)) {
923 $data[] = $record2;
924 }
925 }
926 }
927 }
928
929 $urlsInserted = array(); //urls of articles inserted
930 foreach ($data as $record) {
931 $url = trim( isset($record['article__url']) ? $record['article__url'] : (isset($record['url']) ? $record['url'] : '') );
932 if ( $url and !in_array($url, $urlsInserted) ) {
933 $title = (isset($record['title']) ? $record['title'] : _('Untitled - Import - ').'</a> <a href="./?import">'._('click to finish import').'</a><a>');
934 $body = (isset($record['content']) ? $record['content'] : '');
935 $isRead = (isset($record['is_read']) ? intval($record['is_read']) : (isset($record['archive'])?intval($record['archive']):0));
936 $isFavorite = (isset($record['is_fav']) ? intval($record['is_fav']) : (isset($record['favorite'])?intval($record['favorite']):0) );
937 //insert new record
938 $id = $this->store->add($url, $title, $body, $this->user->getId(), $isFavorite, $isRead);
939 if ( $id ) {
940 $urlsInserted[] = $url; //add
941
942 if ( isset($record['tags']) && trim($record['tags']) ) {
943 //@TODO: set tags
944
945 }
946 }
947 }
948 }
949
950 $i = sizeof($urlsInserted);
951 if ( $i > 0 ) {
952 $this->messages->add('s', _('Articles inserted: ').$i._('. Please note, that some may be marked as "read".'));
953 }
954 Tools::logm('Import of articles finished: '.$i.' articles added (w/o content if not provided).');
955 }
956 //file parsing finished here
957
958 //now download article contents if any
959
960 //check if we need to download any content
961 $recordsDownloadRequired = $this->store->retrieveUnfetchedEntriesCount($this->user->getId());
962 if ( $recordsDownloadRequired == 0 ) {
963 //nothing to download
964 $this->messages->add('s', _('Import finished.'));
965 Tools::logm('Import finished completely');
966 Tools::redirect();
967 }
968 else {
969 //if just inserted - don't download anything, download will start in next reload
970 if ( !isset($_FILES['file']) ) {
971 //download next batch
972 Tools::logm('Fetching next batch of articles...');
973 $items = $this->store->retrieveUnfetchedEntries($this->user->getId(), IMPORT_LIMIT);
974
975 $purifier = $this->getPurifier();
976
977 foreach ($items as $item) {
978 $url = new Url(base64_encode($item['url']));
979 Tools::logm('Fetching article '.$item['id']);
980 $content = Tools::getPageContent($url);
981
982 $title = (($content['rss']['channel']['item']['title'] != '') ? $content['rss']['channel']['item']['title'] : _('Untitled'));
983 $body = (($content['rss']['channel']['item']['description'] != '') ? $content['rss']['channel']['item']['description'] : _('Undefined'));
984
985 //clean content to prevent xss attack
986 $title = $purifier->purify($title);
987 $body = $purifier->purify($body);
988
989 $this->store->updateContentAndTitle($item['id'], $title, $body, $this->user->getId());
990 Tools::logm('Article '.$item['id'].' updated.');
991 }
992
993 }
994 }
995
996 return array('includeImport'=>true, 'import'=>array('recordsDownloadRequired'=>$recordsDownloadRequired, 'recordsUnderDownload'=> IMPORT_LIMIT, 'delay'=> IMPORT_DELAY * 1000) );
997 }
998
999 /**
1000 * export poche entries in json
1001 * @return json all poche entries
1002 */
1003 public function export() {
1004 $filename = "wallabag-export-".$this->user->getId()."-".date("Y-m-d").".json";
1005 header('Content-Disposition: attachment; filename='.$filename);
1006
1007 $entries = $this->store->retrieveAll($this->user->getId());
1008 echo $this->tpl->render('export.twig', array(
1009 'export' => Tools::renderJson($entries),
1010 ));
1011 Tools::logm('export view');
1012 }
1013
1014 /**
1015 * Checks online the latest version of poche and cache it
1016 * @param string $which 'prod' or 'dev'
1017 * @return string latest $which version
1018 */
1019 private function getPocheVersion($which = 'prod') {
1020 $cache_file = CACHE . '/' . $which;
1021 $check_time = time();
1022
1023 # checks if the cached version file exists
1024 if (file_exists($cache_file) && (filemtime($cache_file) > (time() - 86400 ))) {
1025 $version = file_get_contents($cache_file);
1026 $check_time = filemtime($cache_file);
1027 } else {
1028 $version = file_get_contents('http://static.wallabag.org/versions/' . $which);
1029 file_put_contents($cache_file, $version, LOCK_EX);
1030 }
1031 return array($version, $check_time);
1032 }
1033
1034 public function generateToken()
1035 {
1036 if (ini_get('open_basedir') === '') {
1037 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
1038 echo 'This is a server using Windows!';
1039 // alternative to /dev/urandom for Windows
1040 $token = substr(base64_encode(uniqid(mt_rand(), true)), 0, 20);
1041 } else {
1042 $token = substr(base64_encode(file_get_contents('/dev/urandom', false, null, 0, 20)), 0, 15);
1043 }
1044 }
1045 else {
1046 $token = substr(base64_encode(uniqid(mt_rand(), true)), 0, 20);
1047 }
1048
1049 $token = str_replace('+', '', $token);
1050 $this->store->updateUserConfig($this->user->getId(), 'token', $token);
1051 $currentConfig = $_SESSION['poche_user']->config;
1052 $currentConfig['token'] = $token;
1053 $_SESSION['poche_user']->setConfig($currentConfig);
1054 Tools::redirect();
1055 }
1056
1057 public function generateFeeds($token, $user_id, $tag_id, $type = 'home')
1058 {
1059 $allowed_types = array('home', 'fav', 'archive', 'tag');
1060 $config = $this->store->getConfigUser($user_id);
1061
1062 if ($config == null) {
1063 die(_('User with this id (' . $user_id . ') does not exist.'));
1064 }
1065
1066 if (!in_array($type, $allowed_types) ||
1067 $token != $config['token']) {
1068 die(_('Uh, there is a problem while generating feeds.'));
1069 }
1070 // Check the token
1071
1072 $feed = new FeedWriter(RSS2);
1073 $feed->setTitle('wallabag — ' . $type . ' feed');
1074 $feed->setLink(Tools::getPocheUrl());
1075 $feed->setChannelElement('pubDate', date(DATE_RSS , time()));
1076 $feed->setChannelElement('generator', 'wallabag');
1077 $feed->setDescription('wallabag ' . $type . ' elements');
1078
1079 if ($type == 'tag') {
1080 $entries = $this->store->retrieveEntriesByTag($tag_id, $user_id);
1081 }
1082 else {
1083 $entries = $this->store->getEntriesByView($type, $user_id);
1084 }
1085
1086 if (count($entries) > 0) {
1087 foreach ($entries as $entry) {
1088 $newItem = $feed->createNewItem();
1089 $newItem->setTitle($entry['title']);
1090 $newItem->setSource(Tools::getPocheUrl() . '?view=view&amp;id=' . $entry['id']);
1091 $newItem->setLink($entry['url']);
1092 $newItem->setDate(time());
1093 $newItem->setDescription($entry['content']);
1094 $feed->addItem($newItem);
1095 }
1096 }
1097
1098 $feed->genarateFeed();
1099 exit;
1100 }
1101
1102 public function emptyCache() {
1103 $files = new RecursiveIteratorIterator(
1104 new RecursiveDirectoryIterator(CACHE, RecursiveDirectoryIterator::SKIP_DOTS),
1105 RecursiveIteratorIterator::CHILD_FIRST
1106 );
1107
1108 foreach ($files as $fileinfo) {
1109 $todo = ($fileinfo->isDir() ? 'rmdir' : 'unlink');
1110 $todo($fileinfo->getRealPath());
1111 }
1112
1113 Tools::logm('empty cache');
1114 $this->messages->add('s', _('Cache deleted.'));
1115 Tools::redirect();
1116 }
1117
1118 /**
1119 * return new purifier object with actual config
1120 */
1121 protected function getPurifier() {
1122 $config = HTMLPurifier_Config::createDefault();
1123 $config->set('Cache.SerializerPath', CACHE);
1124 $config->set('HTML.SafeIframe', true);
1125 $config->set('URI.SafeIframeRegexp', '%^(https?:)?//(www\.youtube(?:-nocookie)?\.com/embed/|player\.vimeo\.com/video/)%'); //allow YouTube and Vimeo$purifier = new HTMLPurifier($config);
1126
1127 return new HTMLPurifier($config);
1128 }
1129 }