]> git.immae.eu Git - github/wallabag/wallabag.git/blame - inc/poche/Poche.class.php
bug fix #430 - welcome to your wallabag
[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
00dbaf90 26 public function __construct()
eb1af592 27 {
9d3b88b3
NL
28 if ($this->configFileIsAvailable()) {
29 $this->init();
00dbaf90
NL
30 }
31
9d3b88b3
NL
32 if ($this->themeIsInstalled()) {
33 $this->initTpl();
00dbaf90
NL
34 }
35
9d3b88b3
NL
36 if ($this->systemIsInstalled()) {
37 $this->store = new Database();
38 $this->messages = new Messages();
39 # installation
40 if (! $this->store->isInstalled()) {
41 $this->install();
42 }
5cfafc61 43 $this->store->checkTags();
eb1af592 44 }
eb1af592 45 }
00dbaf90
NL
46
47 private function init()
48 {
49 Tools::initPhp();
50 Session::$sessionName = 'poche';
51 Session::init();
eb1af592 52
00dbaf90
NL
53 if (isset($_SESSION['poche_user']) && $_SESSION['poche_user'] != array()) {
54 $this->user = $_SESSION['poche_user'];
55 } else {
56 # fake user, just for install & login screens
57 $this->user = new User();
58 $this->user->setConfig($this->getDefaultConfig());
59 }
60
61 # l10n
62 $language = $this->user->getConfigValue('language');
63 putenv('LC_ALL=' . $language);
64 setlocale(LC_ALL, $language);
65 bindtextdomain($language, LOCALE);
66 textdomain($language);
67
68 # Pagination
69 $this->pagination = new Paginator($this->user->getConfigValue('pager'), 'p');
70
71 # Set up theme
72 $themeDirectory = $this->user->getConfigValue('theme');
73
74 if ($themeDirectory === false) {
75 $themeDirectory = DEFAULT_THEME;
76 }
77
78 $this->currentTheme = $themeDirectory;
5011388f
NL
79
80 # Set up language
81 $languageDirectory = $this->user->getConfigValue('language');
82
83 if ($languageDirectory === false) {
84 $languageDirectory = DEFAULT_THEME;
85 }
86
87 $this->currentLanguage = $languageDirectory;
00dbaf90
NL
88 }
89
90 public function configFileIsAvailable() {
91 if (! self::$configFileAvailable) {
9d3b88b3 92 $this->notInstalledMessage[] = 'You have to rename inc/poche/config.inc.php.new to inc/poche/config.inc.php.';
00dbaf90
NL
93
94 return false;
95 }
96
97 return true;
98 }
99
100 public function themeIsInstalled() {
9d3b88b3 101 $passTheme = TRUE;
00dbaf90
NL
102 # Twig is an absolute requirement for Poche to function. Abort immediately if the Composer installer hasn't been run yet
103 if (! self::$canRenderTemplates) {
3e0e7e12 104 $this->notInstalledMessage[] = 'Twig does not seem to be installed. Please initialize the Composer installation to automatically fetch dependencies. Have a look at <a href="http://doc.wallabag.org/doku.php?id=users:begin:install">the documentation.</a>';
9d3b88b3 105 $passTheme = FALSE;
00dbaf90 106 }
7f17a38d
NL
107
108 if (! is_writable(CACHE)) {
9d3b88b3 109 $this->notInstalledMessage[] = 'You don\'t have write access on cache directory.';
7f17a38d
NL
110
111 self::$canRenderTemplates = false;
112
9d3b88b3 113 $passTheme = FALSE;
7f17a38d 114 }
00dbaf90
NL
115
116 # Check if the selected theme and its requirements are present
f4fbfaa7
NL
117 $theme = $this->getTheme();
118
119 if ($theme != '' && ! is_dir(THEME . '/' . $theme)) {
120 $this->notInstalledMessage[] = 'The currently selected theme (' . $theme . ') does not seem to be properly installed (Missing directory: ' . THEME . '/' . $theme . ')';
00dbaf90
NL
121
122 self::$canRenderTemplates = false;
123
9d3b88b3 124 $passTheme = FALSE;
00dbaf90
NL
125 }
126
f4fbfaa7
NL
127 $themeInfo = $this->getThemeInfo($theme);
128 if (isset($themeInfo['requirements']) && is_array($themeInfo['requirements'])) {
129 foreach ($themeInfo['requirements'] as $requiredTheme) {
130 if (! is_dir(THEME . '/' . $requiredTheme)) {
131 $this->notInstalledMessage[] = 'The required "' . $requiredTheme . '" theme is missing for the current theme (' . $theme . ')';
00dbaf90 132
f4fbfaa7 133 self::$canRenderTemplates = false;
00dbaf90 134
f4fbfaa7
NL
135 $passTheme = FALSE;
136 }
00dbaf90
NL
137 }
138 }
9d3b88b3
NL
139
140 if (!$passTheme) {
141 return FALSE;
142 }
143
00dbaf90
NL
144
145 return true;
146 }
147
4a291288
NL
148 /**
149 * all checks before installation.
00dbaf90 150 * @todo move HTML to template
4a291288
NL
151 * @return boolean
152 */
00dbaf90 153 public function systemIsInstalled()
eb1af592 154 {
9d3b88b3 155 $msg = TRUE;
00dbaf90
NL
156
157 $configSalt = defined('SALT') ? constant('SALT') : '';
158
159 if (empty($configSalt)) {
9d3b88b3
NL
160 $this->notInstalledMessage[] = 'You have not yet filled in the SALT value in the config.inc.php file.';
161 $msg = FALSE;
162 }
163 if (STORAGE == 'sqlite' && ! file_exists(STORAGE_SQLITE)) {
00dbaf90 164 Tools::logm('sqlite file doesn\'t exist');
9d3b88b3
NL
165 $this->notInstalledMessage[] = 'sqlite file doesn\'t exist, you can find it in install folder. Copy it in /db folder.';
166 $msg = FALSE;
167 }
168 if (is_dir(ROOT . '/install') && ! DEBUG_POCHE) {
169 $this->notInstalledMessage[] = 'you have to delete the /install folder before using poche.';
170 $msg = FALSE;
171 }
172 if (STORAGE == 'sqlite' && ! is_writable(STORAGE_SQLITE)) {
bb5a7d9e 173 Tools::logm('you don\'t have write access on sqlite file');
9d3b88b3
NL
174 $this->notInstalledMessage[] = 'You don\'t have write access on sqlite file.';
175 $msg = FALSE;
bb5a7d9e 176 }
00dbaf90 177
9d3b88b3 178 if (! $msg) {
00dbaf90 179 return false;
8d3275be 180 }
7ce7ec4c 181
00dbaf90
NL
182 return true;
183 }
184
185 public function getNotInstalledMessage() {
186 return $this->notInstalledMessage;
4a291288 187 }
eb1af592 188
4a291288
NL
189 private function initTpl()
190 {
00dbaf90 191 $loaderChain = new Twig_Loader_Chain();
f4fbfaa7 192 $theme = $this->getTheme();
00dbaf90
NL
193
194 # add the current theme as first to the loader chain so Twig will look there first for overridden template files
195 try {
f4fbfaa7 196 $loaderChain->addLoader(new Twig_Loader_Filesystem(THEME . '/' . $theme));
00dbaf90
NL
197 } catch (Twig_Error_Loader $e) {
198 # @todo isInstalled() should catch this, inject Twig later
f4fbfaa7 199 die('The currently selected theme (' . $theme . ') does not seem to be properly installed (' . THEME . '/' . $theme .' is missing)');
00dbaf90
NL
200 }
201
202 # add all required themes to the loader chain
f4fbfaa7
NL
203 $themeInfo = $this->getThemeInfo($theme);
204 if (isset($themeInfo['requirements']) && is_array($themeInfo['requirements'])) {
205 foreach ($themeInfo['requirements'] as $requiredTheme) {
206 try {
207 $loaderChain->addLoader(new Twig_Loader_Filesystem(THEME . '/' . $requiredTheme));
208 } catch (Twig_Error_Loader $e) {
209 # @todo isInstalled() should catch this, inject Twig later
210 die('The required "' . $requiredTheme . '" theme is missing for the current theme (' . $theme . ')');
211 }
00dbaf90
NL
212 }
213 }
214
bc1ee852 215 if (DEBUG_POCHE) {
f4fbfaa7 216 $twigParams = array();
00dbaf90 217 } else {
f4fbfaa7 218 $twigParams = array('cache' => CACHE);
bc1ee852 219 }
00dbaf90 220
f4fbfaa7 221 $this->tpl = new Twig_Environment($loaderChain, $twigParams);
eb1af592 222 $this->tpl->addExtension(new Twig_Extensions_Extension_I18n());
00dbaf90 223
55821e04
NL
224 # filter to display domain name of an url
225 $filter = new Twig_SimpleFilter('getDomain', 'Tools::getDomain');
226 $this->tpl->addFilter($filter);
eb1af592 227
d9178758
NL
228 # filter for reading time
229 $filter = new Twig_SimpleFilter('getReadingTime', 'Tools::getReadingTime');
230 $this->tpl->addFilter($filter);
eb1af592
NL
231 }
232
f4fbfaa7 233 private function install()
eb1af592
NL
234 {
235 Tools::logm('poche still not installed');
236 echo $this->tpl->render('install.twig', array(
00dbaf90
NL
237 'token' => Session::getToken(),
238 'theme' => $this->getTheme(),
239 'poche_url' => Tools::getPocheUrl()
eb1af592
NL
240 ));
241 if (isset($_GET['install'])) {
242 if (($_POST['password'] == $_POST['password_repeat'])
243 && $_POST['password'] != "" && $_POST['login'] != "") {
244 # let's rock, install poche baby !
bb5a7d9e
NL
245 if ($this->store->install($_POST['login'], Tools::encodeString($_POST['password'] . $_POST['login'])))
246 {
247 Session::logout();
248 Tools::logm('poche is now installed');
249 Tools::redirect();
250 }
6a361945
NL
251 }
252 else {
253 Tools::logm('error during installation');
eb1af592
NL
254 Tools::redirect();
255 }
256 }
257 exit();
258 }
00dbaf90
NL
259
260 public function getTheme() {
261 return $this->currentTheme;
262 }
5011388f 263
f4fbfaa7
NL
264 /**
265 * Provides theme information by parsing theme.ini file if present in the theme's root directory.
266 * In all cases, the following data will be returned:
267 * - name: theme's name, or key if the theme is unnamed,
268 * - current: boolean informing if the theme is the current user theme.
269 *
270 * @param string $theme Theme key (directory name)
271 * @return array|boolean Theme information, or false if the theme doesn't exist.
272 */
273 public function getThemeInfo($theme) {
274 if (!is_dir(THEME . '/' . $theme)) {
275 return false;
276 }
277
278 $themeIniFile = THEME . '/' . $theme . '/theme.ini';
279 $themeInfo = array();
280
281 if (is_file($themeIniFile) && is_readable($themeIniFile)) {
282 $themeInfo = parse_ini_file($themeIniFile);
283 }
284
285 if ($themeInfo === false) {
286 $themeInfo = array();
287 }
288 if (!isset($themeInfo['name'])) {
289 $themeInfo['name'] = $theme;
290 }
291 $themeInfo['current'] = ($theme === $this->getTheme());
292
293 return $themeInfo;
5011388f 294 }
00dbaf90
NL
295
296 public function getInstalledThemes() {
297 $handle = opendir(THEME);
298 $themes = array();
f4fbfaa7 299
00dbaf90
NL
300 while (($theme = readdir($handle)) !== false) {
301 # Themes are stored in a directory, so all directory names are themes
302 # @todo move theme installation data to database
f4fbfaa7 303 if (!is_dir(THEME . '/' . $theme) || in_array($theme, array('.', '..'))) {
00dbaf90
NL
304 continue;
305 }
f4fbfaa7
NL
306
307 $themes[$theme] = $this->getThemeInfo($theme);
00dbaf90 308 }
f4fbfaa7 309
00dbaf90
NL
310 return $themes;
311 }
eb1af592 312
f4fbfaa7
NL
313 public function getLanguage() {
314 return $this->currentLanguage;
315 }
316
5011388f
NL
317 public function getInstalledLanguages() {
318 $handle = opendir(LOCALE);
319 $languages = array();
320
321 while (($language = readdir($handle)) !== false) {
322 # Languages are stored in a directory, so all directory names are languages
323 # @todo move language installation data to database
324 if (! is_dir(LOCALE . '/' . $language) || in_array($language, array('..', '.'))) {
325 continue;
326 }
327
328 $current = false;
329
330 if ($language === $this->getLanguage()) {
331 $current = true;
332 }
333
334 $languages[] = array('name' => $language, 'current' => $current);
335 }
336
337 return $languages;
338 }
339
8d3275be 340 public function getDefaultConfig()
00dbaf90 341 {
8d3275be
NL
342 return array(
343 'pager' => PAGINATION,
344 'language' => LANG,
00dbaf90
NL
345 'theme' => DEFAULT_THEME
346 );
8d3275be
NL
347 }
348
f878daeb 349 protected function getPageContent(Url $url)
350 {
351 $options = array('http' => array('user_agent' => 'poche'));
352 if (isset($_SERVER['AUTH_TYPE']) && "basic" === strtolower($_SERVER['AUTH_TYPE'])) {
353 $options['http']['header'] = sprintf(
354 "Authorization: Basic %s",
355 base64_encode(
356 sprintf('%s:%s', $_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW'])
357 )
358 );
359 }
360 $context = stream_context_create($options);
361 $json = file_get_contents(Tools::getPocheUrl() . '/inc/3rdparty/makefulltextfeed.php?url='.urlencode($url->getUrl()).'&max=5&links=preserve&exc=&format=json&submit=Create+Feed', false, $context);
362 return json_decode($json, true);
363 }
364
eb1af592
NL
365 /**
366 * Call action (mark as fav, archive, delete, etc.)
367 */
363bc4eb 368 public function action($action, Url $url, $id = 0, $import = FALSE, $autoclose = FALSE)
eb1af592
NL
369 {
370 switch ($action)
371 {
372 case 'add':
f878daeb 373 $content = $this->getPageContent($url);
42c80841
NL
374 $title = $content['rss']['channel']['item']['title'];
375 $body = $content['rss']['channel']['item']['description'];
ec397236 376
42c80841 377 if ($this->store->add($url->getUrl(), $title, $body, $this->user->getId())) {
ec397236
NL
378 Tools::logm('add link ' . $url->getUrl());
379 $sequence = '';
380 if (STORAGE == 'postgres') {
381 $sequence = 'entries_id_seq';
eb1af592 382 }
ec397236
NL
383 $last_id = $this->store->getLastId($sequence);
384 if (DOWNLOAD_PICTURES) {
42c80841 385 $content = filtre_picture($body, $url->getUrl(), $last_id);
ec397236
NL
386 Tools::logm('updating content article');
387 $this->store->updateContent($last_id, $content, $this->user->getId());
388 }
389 if (!$import) {
390 $this->messages->add('s', _('the link has been added successfully'));
eb1af592
NL
391 }
392 }
393 else {
b916bcfc 394 if (!$import) {
ec397236
NL
395 $this->messages->add('e', _('error during insertion : the link wasn\'t added'));
396 Tools::logm('error during insertion : the link wasn\'t added ' . $url->getUrl());
b916bcfc
NL
397 }
398 }
ec397236 399
b916bcfc 400 if (!$import) {
363bc4eb 401 if ($autoclose == TRUE) {
402 Tools::redirect('?view=home');
403 } else {
f616ab60 404 Tools::redirect('?view=home&closewin=true');
363bc4eb 405 }
eb1af592
NL
406 }
407 break;
408 case 'delete':
bc1ee852 409 $msg = 'delete link #' . $id;
8d3275be 410 if ($this->store->deleteById($id, $this->user->getId())) {
eb1af592
NL
411 if (DOWNLOAD_PICTURES) {
412 remove_directory(ABS_PATH . $id);
413 }
6a361945 414 $this->messages->add('s', _('the link has been deleted successfully'));
eb1af592
NL
415 }
416 else {
6a361945 417 $this->messages->add('e', _('the link wasn\'t deleted'));
bc1ee852 418 $msg = 'error : can\'t delete link #' . $id;
eb1af592 419 }
bc1ee852 420 Tools::logm($msg);
985ce3ec 421 Tools::redirect('?');
eb1af592
NL
422 break;
423 case 'toggle_fav' :
8d3275be 424 $this->store->favoriteById($id, $this->user->getId());
eb1af592 425 Tools::logm('mark as favorite link #' . $id);
b916bcfc
NL
426 if (!$import) {
427 Tools::redirect();
428 }
eb1af592
NL
429 break;
430 case 'toggle_archive' :
8d3275be 431 $this->store->archiveById($id, $this->user->getId());
eb1af592 432 Tools::logm('archive link #' . $id);
b916bcfc
NL
433 if (!$import) {
434 Tools::redirect();
435 }
eb1af592 436 break;
c432fa16
NL
437 case 'add_tag' :
438 $tags = explode(',', $_POST['value']);
439 $entry_id = $_POST['entry_id'];
440 foreach($tags as $key => $tag_value) {
441 $value = trim($tag_value);
442 $tag = $this->store->retrieveTagByValue($value);
443
444 if (is_null($tag)) {
445 # we create the tag
446 $tag = $this->store->createTag($value);
447 $sequence = '';
448 if (STORAGE == 'postgres') {
449 $sequence = 'tags_id_seq';
450 }
451 $tag_id = $this->store->getLastId($sequence);
452 }
453 else {
454 $tag_id = $tag['id'];
455 }
456
457 # we assign the tag to the article
458 $this->store->setTagToEntry($tag_id, $entry_id);
459 }
460 Tools::redirect();
461 break;
462 case 'remove_tag' :
463 $tag_id = $_GET['tag_id'];
464 $this->store->removeTagForEntry($id, $tag_id);
465 Tools::redirect();
466 break;
eb1af592
NL
467 default:
468 break;
469 }
470 }
471
472 function displayView($view, $id = 0)
473 {
474 $tpl_vars = array();
475
476 switch ($view)
477 {
eb1af592 478 case 'config':
044bf638
NL
479 $dev = trim($this->getPocheVersion('dev'));
480 $prod = trim($this->getPocheVersion('prod'));
031df528
NL
481 $compare_dev = version_compare(POCHE, $dev);
482 $compare_prod = version_compare(POCHE, $prod);
00dbaf90 483 $themes = $this->getInstalledThemes();
5011388f 484 $languages = $this->getInstalledLanguages();
72c20a52 485 $token = $this->user->getConfigValue('token');
1810c13b 486 $http_auth = (isset($_SERVER['PHP_AUTH_USER']) || isset($_SERVER['REMOTE_USER'])) ? true : false;
32520785 487 $tpl_vars = array(
00dbaf90 488 'themes' => $themes,
5011388f 489 'languages' => $languages,
32520785
NL
490 'dev' => $dev,
491 'prod' => $prod,
492 'compare_dev' => $compare_dev,
493 'compare_prod' => $compare_prod,
72c20a52
NL
494 'token' => $token,
495 'user_id' => $this->user->getId(),
df6afaf0 496 'http_auth' => $http_auth,
32520785 497 );
eb1af592
NL
498 Tools::logm('config view');
499 break;
6cab59c3
NL
500 case 'edit-tags':
501 # tags
502 $tags = $this->store->retrieveTagsByEntry($id);
503 $tpl_vars = array(
c432fa16 504 'entry_id' => $id,
6cab59c3
NL
505 'tags' => $tags,
506 );
507 break;
4886ed6d
NL
508 case 'tag':
509 $entries = $this->store->retrieveEntriesByTag($id);
510 $tag = $this->store->retrieveTag($id);
511 $tpl_vars = array(
512 'tag' => $tag,
513 'entries' => $entries,
514 );
515 break;
2e2ebe5e 516 case 'tags':
f778e472 517 $token = $this->user->getConfigValue('token');
2e2ebe5e
NL
518 $tags = $this->store->retrieveAllTags();
519 $tpl_vars = array(
f778e472
NL
520 'token' => $token,
521 'user_id' => $this->user->getId(),
2e2ebe5e
NL
522 'tags' => $tags,
523 );
524 break;
eb1af592 525 case 'view':
8d3275be 526 $entry = $this->store->retrieveOneById($id, $this->user->getId());
eb1af592
NL
527 if ($entry != NULL) {
528 Tools::logm('view link #' . $id);
529 $content = $entry['content'];
530 if (function_exists('tidy_parse_string')) {
531 $tidy = tidy_parse_string($content, array('indent'=>true, 'show-body-only' => true), 'UTF8');
532 $tidy->cleanRepair();
533 $content = $tidy->value;
3408ed48 534 }
a3223127 535
3408ed48
NL
536 # flattr checking
537 $flattr = new FlattrItem();
7b171c73
NL
538 $flattr->checkItem($entry['url'], $entry['id']);
539
540 # tags
541 $tags = $this->store->retrieveTagsByEntry($entry['id']);
a3223127 542
3408ed48 543 $tpl_vars = array(
7b171c73
NL
544 'entry' => $entry,
545 'content' => $content,
546 'flattr' => $flattr,
547 'tags' => $tags
3408ed48 548 );
eb1af592
NL
549 }
550 else {
d8d1542e 551 Tools::logm('error in view call : entry is null');
eb1af592
NL
552 }
553 break;
12d9cfbc 554 default: # home, favorites and archive views
8d3275be 555 $entries = $this->store->getEntriesByView($view, $this->user->getId());
eb1af592 556 $tpl_vars = array(
3eb04903
N
557 'entries' => '',
558 'page_links' => '',
7f9f5281 559 'nb_results' => '',
eb1af592 560 );
34d67c83 561
3eb04903
N
562 if (count($entries) > 0) {
563 $this->pagination->set_total(count($entries));
564 $page_links = $this->pagination->page_links('?view=' . $view . '&sort=' . $_SESSION['sort'] . '&');
565 $datas = $this->store->getEntriesByView($view, $this->user->getId(), $this->pagination->get_limit());
566 $tpl_vars['entries'] = $datas;
567 $tpl_vars['page_links'] = $page_links;
7f9f5281 568 $tpl_vars['nb_results'] = count($entries);
3eb04903 569 }
6a361945 570 Tools::logm('display ' . $view . ' view');
eb1af592
NL
571 break;
572 }
573
574 return $tpl_vars;
575 }
c765c367 576
07ee09f4
NL
577 /**
578 * update the password of the current user.
579 * if MODE_DEMO is TRUE, the password can't be updated.
580 * @todo add the return value
581 * @todo set the new password in function header like this updatePassword($newPassword)
582 * @return boolean
583 */
c765c367
NL
584 public function updatePassword()
585 {
55821e04 586 if (MODE_DEMO) {
8d3275be 587 $this->messages->add('i', _('in demo mode, you can\'t update your password'));
55821e04 588 Tools::logm('in demo mode, you can\'t do this');
6a361945 589 Tools::redirect('?view=config');
55821e04
NL
590 }
591 else {
592 if (isset($_POST['password']) && isset($_POST['password_repeat'])) {
593 if ($_POST['password'] == $_POST['password_repeat'] && $_POST['password'] != "") {
8d3275be
NL
594 $this->messages->add('s', _('your password has been updated'));
595 $this->store->updatePassword($this->user->getId(), Tools::encodeString($_POST['password'] . $this->user->getUsername()));
c765c367 596 Session::logout();
8d3275be 597 Tools::logm('password updated');
c765c367
NL
598 Tools::redirect();
599 }
600 else {
8d3275be 601 $this->messages->add('e', _('the two fields have to be filled & the password must be the same in the two fields'));
6a361945 602 Tools::redirect('?view=config');
c765c367
NL
603 }
604 }
605 }
606 }
00dbaf90
NL
607
608 public function updateTheme()
609 {
610 # no data
611 if (empty($_POST['theme'])) {
612 }
613
614 # we are not going to change it to the current theme...
615 if ($_POST['theme'] == $this->getTheme()) {
616 $this->messages->add('w', _('still using the "' . $this->getTheme() . '" theme!'));
617 Tools::redirect('?view=config');
618 }
619
620 $themes = $this->getInstalledThemes();
621 $actualTheme = false;
622
f4fbfaa7
NL
623 foreach (array_keys($themes) as $theme) {
624 if ($theme == $_POST['theme']) {
00dbaf90
NL
625 $actualTheme = true;
626 break;
627 }
628 }
629
630 if (! $actualTheme) {
631 $this->messages->add('e', _('that theme does not seem to be installed'));
632 Tools::redirect('?view=config');
633 }
634
635 $this->store->updateUserConfig($this->user->getId(), 'theme', $_POST['theme']);
636 $this->messages->add('s', _('you have changed your theme preferences'));
637
638 $currentConfig = $_SESSION['poche_user']->config;
639 $currentConfig['theme'] = $_POST['theme'];
640
641 $_SESSION['poche_user']->setConfig($currentConfig);
642
643 Tools::redirect('?view=config');
644 }
c765c367 645
5011388f
NL
646 public function updateLanguage()
647 {
648 # no data
649 if (empty($_POST['language'])) {
650 }
651
652 # we are not going to change it to the current language...
653 if ($_POST['language'] == $this->getLanguage()) {
654 $this->messages->add('w', _('still using the "' . $this->getLanguage() . '" language!'));
655 Tools::redirect('?view=config');
656 }
657
658 $languages = $this->getInstalledLanguages();
659 $actualLanguage = false;
660
661 foreach ($languages as $language) {
662 if ($language['name'] == $_POST['language']) {
663 $actualLanguage = true;
664 break;
665 }
666 }
667
668 if (! $actualLanguage) {
669 $this->messages->add('e', _('that language does not seem to be installed'));
670 Tools::redirect('?view=config');
671 }
672
673 $this->store->updateUserConfig($this->user->getId(), 'language', $_POST['language']);
674 $this->messages->add('s', _('you have changed your language preferences'));
675
676 $currentConfig = $_SESSION['poche_user']->config;
677 $currentConfig['language'] = $_POST['language'];
678
679 $_SESSION['poche_user']->setConfig($currentConfig);
680
681 Tools::redirect('?view=config');
682 }
683
df6afaf0
DS
684 /**
685 * get credentials from differents sources
686 * it redirects the user to the $referer link
687 * @return array
688 */
1810c13b
NL
689 private function credentials() {
690 if(isset($_SERVER['PHP_AUTH_USER'])) {
6af66b11 691 return array($_SERVER['PHP_AUTH_USER'],'php_auth',true);
1810c13b
NL
692 }
693 if(!empty($_POST['login']) && !empty($_POST['password'])) {
6af66b11 694 return array($_POST['login'],$_POST['password'],false);
1810c13b
NL
695 }
696 if(isset($_SERVER['REMOTE_USER'])) {
6af66b11 697 return array($_SERVER['REMOTE_USER'],'http_auth',true);
1810c13b 698 }
5cfafc61 699
6af66b11
MR
700 return array(false,false,false);
701 }
df6afaf0 702
07ee09f4
NL
703 /**
704 * checks if login & password are correct and save the user in session.
705 * it redirects the user to the $referer link
706 * @param string $referer the url to redirect after login
707 * @todo add the return value
708 * @return boolean
709 */
c765c367
NL
710 public function login($referer)
711 {
6af66b11 712 list($login,$password,$isauthenticated)=$this->credentials();
df6afaf0
DS
713 if($login === false || $password === false) {
714 $this->messages->add('e', _('login failed: you have to fill all fields'));
715 Tools::logm('login failed');
716 Tools::redirect();
717 }
718 if (!empty($login) && !empty($password)) {
6af66b11 719 $user = $this->store->login($login, Tools::encodeString($password . $login), $isauthenticated);
7ce7ec4c
NL
720 if ($user != array()) {
721 # Save login into Session
6af66b11
MR
722 $longlastingsession = isset($_POST['longlastingsession']);
723 $passwordTest = ($isauthenticated) ? $user['password'] : Tools::encodeString($password . $login);
724 Session::login($user['username'], $user['password'], $login, $passwordTest, $longlastingsession, array('poche_user' => new User($user)));
26929c08 725 $this->messages->add('s', _('welcome to your wallabag'));
8d3275be 726 Tools::logm('login successful');
c765c367
NL
727 Tools::redirect($referer);
728 }
8d3275be 729 $this->messages->add('e', _('login failed: bad login or password'));
c765c367
NL
730 Tools::logm('login failed');
731 Tools::redirect();
c765c367
NL
732 }
733 }
734
07ee09f4
NL
735 /**
736 * log out the poche user. It cleans the session.
737 * @todo add the return value
738 * @return boolean
739 */
c765c367
NL
740 public function logout()
741 {
7ce7ec4c 742 $this->user = array();
c765c367 743 Session::logout();
b916bcfc 744 Tools::logm('logout');
c765c367
NL
745 Tools::redirect();
746 }
747
07ee09f4
NL
748 /**
749 * import from Instapaper. poche needs a ./instapaper-export.html file
750 * @todo add the return value
66b6a3b5 751 * @param string $targetFile the file used for importing
07ee09f4
NL
752 * @return boolean
753 */
66b6a3b5 754 private function importFromInstapaper($targetFile)
c765c367 755 {
7f959169 756 # TODO gestion des articles favs
a62788c6 757 $html = new simple_html_dom();
66b6a3b5 758 $html->load_file($targetFile);
b916bcfc 759 Tools::logm('starting import from instapaper');
a62788c6
NL
760
761 $read = 0;
762 $errors = array();
763 foreach($html->find('ol') as $ul)
764 {
765 foreach($ul->find('li') as $li)
766 {
767 $a = $li->find('a');
768 $url = new Url(base64_encode($a[0]->href));
b916bcfc 769 $this->action('add', $url, 0, TRUE);
a62788c6 770 if ($read == '1') {
b916bcfc
NL
771 $sequence = '';
772 if (STORAGE == 'postgres') {
773 $sequence = 'entries_id_seq';
774 }
775 $last_id = $this->store->getLastId($sequence);
776 $this->action('toggle_archive', $url, $last_id, TRUE);
a62788c6
NL
777 }
778 }
7f959169
NL
779
780 # the second <ol> is for read links
a62788c6
NL
781 $read = 1;
782 }
8d3275be 783 $this->messages->add('s', _('import from instapaper completed'));
63c35580
NL
784 Tools::logm('import from instapaper completed');
785 Tools::redirect();
786 }
c765c367 787
07ee09f4
NL
788 /**
789 * import from Pocket. poche needs a ./ril_export.html file
790 * @todo add the return value
66b6a3b5 791 * @param string $targetFile the file used for importing
07ee09f4
NL
792 * @return boolean
793 */
66b6a3b5 794 private function importFromPocket($targetFile)
63c35580 795 {
7f959169 796 # TODO gestion des articles favs
63c35580 797 $html = new simple_html_dom();
66b6a3b5 798 $html->load_file($targetFile);
b916bcfc 799 Tools::logm('starting import from pocket');
63c35580
NL
800
801 $read = 0;
802 $errors = array();
803 foreach($html->find('ul') as $ul)
804 {
805 foreach($ul->find('li') as $li)
c765c367 806 {
63c35580
NL
807 $a = $li->find('a');
808 $url = new Url(base64_encode($a[0]->href));
b916bcfc 809 $this->action('add', $url, 0, TRUE);
63c35580 810 if ($read == '1') {
b916bcfc
NL
811 $sequence = '';
812 if (STORAGE == 'postgres') {
813 $sequence = 'entries_id_seq';
814 }
815 $last_id = $this->store->getLastId($sequence);
816 $this->action('toggle_archive', $url, $last_id, TRUE);
c765c367 817 }
c765c367 818 }
7f959169
NL
819
820 # the second <ul> is for read links
63c35580 821 $read = 1;
c765c367 822 }
8d3275be 823 $this->messages->add('s', _('import from pocket completed'));
63c35580
NL
824 Tools::logm('import from pocket completed');
825 Tools::redirect();
826 }
c765c367 827
07ee09f4
NL
828 /**
829 * import from Readability. poche needs a ./readability file
830 * @todo add the return value
66b6a3b5 831 * @param string $targetFile the file used for importing
07ee09f4
NL
832 * @return boolean
833 */
66b6a3b5 834 private function importFromReadability($targetFile)
63c35580 835 {
7f959169 836 # TODO gestion des articles lus / favs
66b6a3b5 837 $str_data = file_get_contents($targetFile);
63c35580 838 $data = json_decode($str_data,true);
b916bcfc 839 Tools::logm('starting import from Readability');
c0d321c1 840 $count = 0;
63c35580 841 foreach ($data as $key => $value) {
c0d321c1
NL
842 $url = NULL;
843 $favorite = FALSE;
844 $archive = FALSE;
9bc32632
NL
845 foreach ($value as $item) {
846 foreach ($item as $attr => $value) {
847 if ($attr == 'article__url') {
848 $url = new Url(base64_encode($value));
c0d321c1 849 }
9bc32632
NL
850 $sequence = '';
851 if (STORAGE == 'postgres') {
852 $sequence = 'entries_id_seq';
853 }
854 if ($value == 'true') {
855 if ($attr == 'favorite') {
856 $favorite = TRUE;
857 }
858 if ($attr == 'archive') {
859 $archive = TRUE;
860 }
c0d321c1
NL
861 }
862 }
9bc32632
NL
863
864 # we can add the url
865 if (!is_null($url) && $url->isCorrect()) {
866 $this->action('add', $url, 0, TRUE);
867 $count++;
868 if ($favorite) {
869 $last_id = $this->store->getLastId($sequence);
870 $this->action('toggle_fav', $url, $last_id, TRUE);
871 }
872 if ($archive) {
873 $last_id = $this->store->getLastId($sequence);
874 $this->action('toggle_archive', $url, $last_id, TRUE);
875 }
b916bcfc 876 }
c765c367 877 }
c765c367 878 }
c0d321c1 879 $this->messages->add('s', _('import from Readability completed. ' . $count . ' new links.'));
63c35580
NL
880 Tools::logm('import from Readability completed');
881 Tools::redirect();
c765c367
NL
882 }
883
89051914
NL
884 /**
885 * import from Poche exported file
886 * @param string $targetFile the file used for importing
887 * @return boolean
888 */
889 private function importFromPoche($targetFile)
890 {
891 $str_data = file_get_contents($targetFile);
892 $data = json_decode($str_data,true);
893 Tools::logm('starting import from Poche');
894
895
896 $sequence = '';
897 if (STORAGE == 'postgres') {
898 $sequence = 'entries_id_seq';
899 }
900
901 $count = 0;
902 foreach ($data as $value) {
903
904 $url = new Url(base64_encode($value['url']));
905 $favorite = ($value['is_fav'] == -1);
906 $archive = ($value['is_read'] == -1);
907
908 # we can add the url
909 if (!is_null($url) && $url->isCorrect()) {
910
911 $this->action('add', $url, 0, TRUE);
912
913 $count++;
914 if ($favorite) {
915 $last_id = $this->store->getLastId($sequence);
916 $this->action('toggle_fav', $url, $last_id, TRUE);
917 }
918 if ($archive) {
919 $last_id = $this->store->getLastId($sequence);
920 $this->action('toggle_archive', $url, $last_id, TRUE);
921 }
922 }
923
924 }
925 $this->messages->add('s', _('import from Poche completed. ' . $count . ' new links.'));
926 Tools::logm('import from Poche completed');
927 Tools::redirect();
928 }
929
07ee09f4
NL
930 /**
931 * import datas into your poche
932 * @param string $from name of the service to import : pocket, instapaper or readability
933 * @todo add the return value
934 * @return boolean
935 */
63c35580 936 public function import($from)
c765c367 937 {
66b6a3b5
E
938 $providers = array(
939 'pocket' => 'importFromPocket',
940 'readability' => 'importFromReadability',
89051914
NL
941 'instapaper' => 'importFromInstapaper',
942 'poche' => 'importFromPoche',
66b6a3b5
E
943 );
944
945 if (! isset($providers[$from])) {
946 $this->messages->add('e', _('Unknown import provider.'));
947 Tools::redirect();
63c35580 948 }
66b6a3b5
E
949
950 $targetDefinition = 'IMPORT_' . strtoupper($from) . '_FILE';
951 $targetFile = constant($targetDefinition);
952
953 if (! defined($targetDefinition)) {
954 $this->messages->add('e', _('Incomplete inc/poche/define.inc.php file, please define "' . $targetDefinition . '".'));
955 Tools::redirect();
63c35580 956 }
66b6a3b5
E
957
958 if (! file_exists($targetFile)) {
959 $this->messages->add('e', _('Could not find required "' . $targetFile . '" import file.'));
960 Tools::redirect();
63c35580 961 }
66b6a3b5
E
962
963 $this->$providers[$from]($targetFile);
63c35580 964 }
c765c367 965
07ee09f4
NL
966 /**
967 * export poche entries in json
968 * @return json all poche entries
969 */
63c35580
NL
970 public function export()
971 {
8d3275be 972 $entries = $this->store->retrieveAll($this->user->getId());
63c35580
NL
973 echo $this->tpl->render('export.twig', array(
974 'export' => Tools::renderJson($entries),
975 ));
976 Tools::logm('export view');
c765c367 977 }
32520785 978
07ee09f4 979 /**
a3436d4c 980 * Checks online the latest version of poche and cache it
07ee09f4
NL
981 * @param string $which 'prod' or 'dev'
982 * @return string latest $which version
983 */
32520785
NL
984 private function getPocheVersion($which = 'prod')
985 {
986 $cache_file = CACHE . '/' . $which;
a3436d4c
NL
987
988 # checks if the cached version file exists
32520785
NL
989 if (file_exists($cache_file) && (filemtime($cache_file) > (time() - 86400 ))) {
990 $version = file_get_contents($cache_file);
991 } else {
3e0e7e12 992 $version = file_get_contents('http://static.wallabag.org/versions/' . $which);
32520785
NL
993 file_put_contents($cache_file, $version, LOCK_EX);
994 }
995 return $version;
996 }
72c20a52
NL
997
998 public function generateToken()
999 {
1000 if (ini_get('open_basedir') === '') {
1001 $token = substr(base64_encode(file_get_contents('/dev/urandom', false, null, 0, 20)), 0, 15);
1002 }
1003 else {
1004 $token = substr(base64_encode(uniqid(mt_rand(), true)), 0, 20);
1005 }
1006
044bf638 1007 $token = str_replace('+', '', $token);
72c20a52
NL
1008 $this->store->updateUserConfig($this->user->getId(), 'token', $token);
1009 $currentConfig = $_SESSION['poche_user']->config;
1010 $currentConfig['token'] = $token;
1011 $_SESSION['poche_user']->setConfig($currentConfig);
1012 }
1013
f778e472 1014 public function generateFeeds($token, $user_id, $tag_id, $type = 'home')
72c20a52 1015 {
f778e472 1016 $allowed_types = array('home', 'fav', 'archive', 'tag');
72c20a52
NL
1017 $config = $this->store->getConfigUser($user_id);
1018
1019 if (!in_array($type, $allowed_types) ||
1020 $token != $config['token']) {
1021 die(_('Uh, there is a problem while generating feeds.'));
1022 }
1023 // Check the token
1024
9e7c840b 1025 $feed = new FeedWriter(RSS2);
72c20a52
NL
1026 $feed->setTitle('poche - ' . $type . ' feed');
1027 $feed->setLink(Tools::getPocheUrl());
9e7c840b 1028 $feed->setChannelElement('updated', date(DATE_RSS , time()));
72c20a52
NL
1029 $feed->setChannelElement('author', 'poche');
1030
f778e472
NL
1031 if ($type == 'tag') {
1032 $entries = $this->store->retrieveEntriesByTag($tag_id);
1033 }
1034 else {
1035 $entries = $this->store->getEntriesByView($type, $user_id);
1036 }
1037
72c20a52
NL
1038 if (count($entries) > 0) {
1039 foreach ($entries as $entry) {
1040 $newItem = $feed->createNewItem();
0b57c682 1041 $newItem->setTitle($entry['title']);
72c20a52
NL
1042 $newItem->setLink(Tools::getPocheUrl() . '?view=view&amp;id=' . $entry['id']);
1043 $newItem->setDate(time());
1044 $newItem->setDescription($entry['content']);
1045 $feed->addItem($newItem);
1046 }
1047 }
1048
1049 $feed->genarateFeed();
1050 exit;
1051 }
df6afaf0 1052}