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