]> git.immae.eu Git - github/wallabag/wallabag.git/blame - inc/poche/Poche.class.php
Merge remote-tracking branch 'upstream/dev' into dev
[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) {
41265e07 104 $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 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 {
b4fd2154
MR
351 // Saving and clearing context
352 $REAL = array();
353 foreach( $GLOBALS as $key => $value ) {
354 if( $key != "GLOBALS" && $key != "_SESSION" ) {
355 $GLOBALS[$key] = array();
356 $REAL[$key] = $value;
357 }
358 }
359 // Saving and clearing session
360 $REAL_SESSION = array();
361 foreach( $_SESSION as $key => $value ) {
362 $REAL_SESSION[$key] = $value;
363 unset($_SESSION[$key]);
364 }
365
366 // Running code in different context
367 $scope = function() {
368 extract( func_get_arg(1) );
369 $_GET = $_REQUEST = array(
370 "url" => $url->getUrl(),
371 "max" => 5,
372 "links" => "preserve",
373 "exc" => "",
374 "format" => "json",
375 "submit" => "Create Feed"
f878daeb 376 );
b4fd2154
MR
377 ob_start();
378 require func_get_arg(0);
379 $json = ob_get_flush();
380 return $json;
381 };
382 $json = $scope( "inc/3rdparty/makefulltextfeed.php", array("url" => $url) );
383
384 // Clearing and restoring context
385 foreach( $GLOBALS as $key => $value ) {
386 if( $key != "GLOBALS" && $key != "_SESSION" ) {
387 unset($GLOBALS[$key]);
388 }
389 }
390 foreach( $REAL as $key => $value ) {
391 $GLOBALS[$key] = $value;
392 }
393 // Clearing and restoring session
394 foreach( $_SESSION as $key => $value ) {
395 unset($_SESSION[$key]);
396 }
397 foreach( $REAL_SESSION as $key => $value ) {
398 $_SESSION[$key] = $value;
f878daeb 399 }
f878daeb 400 return json_decode($json, true);
401 }
402
eb1af592
NL
403 /**
404 * Call action (mark as fav, archive, delete, etc.)
405 */
363bc4eb 406 public function action($action, Url $url, $id = 0, $import = FALSE, $autoclose = FALSE)
eb1af592
NL
407 {
408 switch ($action)
409 {
410 case 'add':
f878daeb 411 $content = $this->getPageContent($url);
fa0bfb77 412 $title = ($content['rss']['channel']['item']['title'] != '') ? $content['rss']['channel']['item']['title'] : _('Untitled');
42c80841 413 $body = $content['rss']['channel']['item']['description'];
ec397236 414
488fc63b
MR
415 //search for possible duplicate if not in import mode
416 if (!$import) {
417 $duplicate = $this->store->retrieveOneByURL($url->getUrl(), $this->user->getId());
418 }
419
42c80841 420 if ($this->store->add($url->getUrl(), $title, $body, $this->user->getId())) {
ec397236
NL
421 Tools::logm('add link ' . $url->getUrl());
422 $sequence = '';
423 if (STORAGE == 'postgres') {
424 $sequence = 'entries_id_seq';
eb1af592 425 }
ec397236
NL
426 $last_id = $this->store->getLastId($sequence);
427 if (DOWNLOAD_PICTURES) {
42c80841 428 $content = filtre_picture($body, $url->getUrl(), $last_id);
ec397236
NL
429 Tools::logm('updating content article');
430 $this->store->updateContent($last_id, $content, $this->user->getId());
431 }
488fc63b
MR
432
433 if ($duplicate != NULL) {
434 // 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
435 Tools::logm('link ' . $url->getUrl() . ' is a duplicate');
436 // 1) - preserve tags and favorite, then drop old entry
437 $this->store->reassignTags($duplicate['id'], $last_id);
438 if ($duplicate['is_fav']) {
439 $this->store->favoriteById($last_id, $this->user->getId());
440 }
441 if ($this->store->deleteById($duplicate['id'], $this->user->getId())) {
442 Tools::logm('previous link ' . $url->getUrl() .' entry deleted');
443 }
444 }
445
ec397236
NL
446 if (!$import) {
447 $this->messages->add('s', _('the link has been added successfully'));
eb1af592
NL
448 }
449 }
450 else {
b916bcfc 451 if (!$import) {
ec397236
NL
452 $this->messages->add('e', _('error during insertion : the link wasn\'t added'));
453 Tools::logm('error during insertion : the link wasn\'t added ' . $url->getUrl());
b916bcfc
NL
454 }
455 }
ec397236 456
b916bcfc 457 if (!$import) {
363bc4eb 458 if ($autoclose == TRUE) {
459 Tools::redirect('?view=home');
460 } else {
f616ab60 461 Tools::redirect('?view=home&closewin=true');
363bc4eb 462 }
eb1af592
NL
463 }
464 break;
465 case 'delete':
bc1ee852 466 $msg = 'delete link #' . $id;
8d3275be 467 if ($this->store->deleteById($id, $this->user->getId())) {
eb1af592
NL
468 if (DOWNLOAD_PICTURES) {
469 remove_directory(ABS_PATH . $id);
470 }
6a361945 471 $this->messages->add('s', _('the link has been deleted successfully'));
eb1af592
NL
472 }
473 else {
6a361945 474 $this->messages->add('e', _('the link wasn\'t deleted'));
bc1ee852 475 $msg = 'error : can\'t delete link #' . $id;
eb1af592 476 }
bc1ee852 477 Tools::logm($msg);
985ce3ec 478 Tools::redirect('?');
eb1af592
NL
479 break;
480 case 'toggle_fav' :
8d3275be 481 $this->store->favoriteById($id, $this->user->getId());
eb1af592 482 Tools::logm('mark as favorite link #' . $id);
b916bcfc
NL
483 if (!$import) {
484 Tools::redirect();
485 }
eb1af592
NL
486 break;
487 case 'toggle_archive' :
8d3275be 488 $this->store->archiveById($id, $this->user->getId());
eb1af592 489 Tools::logm('archive link #' . $id);
b916bcfc
NL
490 if (!$import) {
491 Tools::redirect();
492 }
eb1af592 493 break;
f14807de
NL
494 case 'archive_all' :
495 $this->store->archiveAll($this->user->getId());
496 Tools::logm('archive all links');
497 if (!$import) {
498 Tools::redirect();
499 }
500 break;
c432fa16
NL
501 case 'add_tag' :
502 $tags = explode(',', $_POST['value']);
503 $entry_id = $_POST['entry_id'];
b89d5a2b
NL
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 }
c432fa16
NL
510 foreach($tags as $key => $tag_value) {
511 $value = trim($tag_value);
512 $tag = $this->store->retrieveTagByValue($value);
513
514 if (is_null($tag)) {
515 # we create the tag
516 $tag = $this->store->createTag($value);
517 $sequence = '';
518 if (STORAGE == 'postgres') {
519 $sequence = 'tags_id_seq';
520 }
521 $tag_id = $this->store->getLastId($sequence);
522 }
523 else {
524 $tag_id = $tag['id'];
525 }
526
527 # we assign the tag to the article
528 $this->store->setTagToEntry($tag_id, $entry_id);
529 }
530 Tools::redirect();
531 break;
532 case 'remove_tag' :
533 $tag_id = $_GET['tag_id'];
b89d5a2b
NL
534 $entry = $this->store->retrieveOneById($id, $this->user->getId());
535 if (!$entry) {
536 $this->messages->add('e', _('Article not found!'));
537 Tools::logm('error : article not found');
538 Tools::redirect();
539 }
c432fa16
NL
540 $this->store->removeTagForEntry($id, $tag_id);
541 Tools::redirect();
542 break;
eb1af592
NL
543 default:
544 break;
545 }
546 }
547
548 function displayView($view, $id = 0)
549 {
550 $tpl_vars = array();
551
552 switch ($view)
553 {
eb1af592 554 case 'config':
044bf638
NL
555 $dev = trim($this->getPocheVersion('dev'));
556 $prod = trim($this->getPocheVersion('prod'));
031df528
NL
557 $compare_dev = version_compare(POCHE, $dev);
558 $compare_prod = version_compare(POCHE, $prod);
00dbaf90 559 $themes = $this->getInstalledThemes();
5011388f 560 $languages = $this->getInstalledLanguages();
72c20a52 561 $token = $this->user->getConfigValue('token');
1810c13b 562 $http_auth = (isset($_SERVER['PHP_AUTH_USER']) || isset($_SERVER['REMOTE_USER'])) ? true : false;
32520785 563 $tpl_vars = array(
00dbaf90 564 'themes' => $themes,
5011388f 565 'languages' => $languages,
32520785
NL
566 'dev' => $dev,
567 'prod' => $prod,
568 'compare_dev' => $compare_dev,
569 'compare_prod' => $compare_prod,
72c20a52
NL
570 'token' => $token,
571 'user_id' => $this->user->getId(),
df6afaf0 572 'http_auth' => $http_auth,
32520785 573 );
eb1af592
NL
574 Tools::logm('config view');
575 break;
6cab59c3
NL
576 case 'edit-tags':
577 # tags
b89d5a2b
NL
578 $entry = $this->store->retrieveOneById($id, $this->user->getId());
579 if (!$entry) {
580 $this->messages->add('e', _('Article not found!'));
581 Tools::logm('error : article not found');
582 Tools::redirect();
583 }
6cab59c3
NL
584 $tags = $this->store->retrieveTagsByEntry($id);
585 $tpl_vars = array(
c432fa16 586 'entry_id' => $id,
6cab59c3
NL
587 'tags' => $tags,
588 );
589 break;
4886ed6d 590 case 'tag':
b89d5a2b
NL
591 $entries = $this->store->retrieveEntriesByTag($id, $this->user->getId());
592 $tag = $this->store->retrieveTag($id, $this->user->getId());
4886ed6d
NL
593 $tpl_vars = array(
594 'tag' => $tag,
595 'entries' => $entries,
596 );
597 break;
2e2ebe5e 598 case 'tags':
f778e472 599 $token = $this->user->getConfigValue('token');
b89d5a2b 600 $tags = $this->store->retrieveAllTags($this->user->getId());
2e2ebe5e 601 $tpl_vars = array(
f778e472
NL
602 'token' => $token,
603 'user_id' => $this->user->getId(),
2e2ebe5e
NL
604 'tags' => $tags,
605 );
606 break;
eb1af592 607 case 'view':
8d3275be 608 $entry = $this->store->retrieveOneById($id, $this->user->getId());
eb1af592
NL
609 if ($entry != NULL) {
610 Tools::logm('view link #' . $id);
611 $content = $entry['content'];
612 if (function_exists('tidy_parse_string')) {
613 $tidy = tidy_parse_string($content, array('indent'=>true, 'show-body-only' => true), 'UTF8');
614 $tidy->cleanRepair();
615 $content = $tidy->value;
3408ed48 616 }
a3223127 617
3408ed48
NL
618 # flattr checking
619 $flattr = new FlattrItem();
7b171c73
NL
620 $flattr->checkItem($entry['url'], $entry['id']);
621
622 # tags
623 $tags = $this->store->retrieveTagsByEntry($entry['id']);
a3223127 624
3408ed48 625 $tpl_vars = array(
7b171c73
NL
626 'entry' => $entry,
627 'content' => $content,
628 'flattr' => $flattr,
629 'tags' => $tags
3408ed48 630 );
eb1af592
NL
631 }
632 else {
d8d1542e 633 Tools::logm('error in view call : entry is null');
eb1af592
NL
634 }
635 break;
12d9cfbc 636 default: # home, favorites and archive views
8d3275be 637 $entries = $this->store->getEntriesByView($view, $this->user->getId());
eb1af592 638 $tpl_vars = array(
3eb04903
N
639 'entries' => '',
640 'page_links' => '',
7f9f5281 641 'nb_results' => '',
eb1af592 642 );
34d67c83 643
3eb04903
N
644 if (count($entries) > 0) {
645 $this->pagination->set_total(count($entries));
c515ffec
MR
646 $page_links = str_replace(array('previous', 'next'), array(_('previous'), _('next')),
647 $this->pagination->page_links('?view=' . $view . '&sort=' . $_SESSION['sort'] . '&'));
3eb04903
N
648 $datas = $this->store->getEntriesByView($view, $this->user->getId(), $this->pagination->get_limit());
649 $tpl_vars['entries'] = $datas;
650 $tpl_vars['page_links'] = $page_links;
7f9f5281 651 $tpl_vars['nb_results'] = count($entries);
3eb04903 652 }
6a361945 653 Tools::logm('display ' . $view . ' view');
eb1af592
NL
654 break;
655 }
656
657 return $tpl_vars;
658 }
c765c367 659
07ee09f4
NL
660 /**
661 * update the password of the current user.
662 * if MODE_DEMO is TRUE, the password can't be updated.
663 * @todo add the return value
664 * @todo set the new password in function header like this updatePassword($newPassword)
665 * @return boolean
666 */
c765c367
NL
667 public function updatePassword()
668 {
55821e04 669 if (MODE_DEMO) {
8d3275be 670 $this->messages->add('i', _('in demo mode, you can\'t update your password'));
55821e04 671 Tools::logm('in demo mode, you can\'t do this');
6a361945 672 Tools::redirect('?view=config');
55821e04
NL
673 }
674 else {
675 if (isset($_POST['password']) && isset($_POST['password_repeat'])) {
676 if ($_POST['password'] == $_POST['password_repeat'] && $_POST['password'] != "") {
8d3275be
NL
677 $this->messages->add('s', _('your password has been updated'));
678 $this->store->updatePassword($this->user->getId(), Tools::encodeString($_POST['password'] . $this->user->getUsername()));
c765c367 679 Session::logout();
8d3275be 680 Tools::logm('password updated');
c765c367
NL
681 Tools::redirect();
682 }
683 else {
8d3275be 684 $this->messages->add('e', _('the two fields have to be filled & the password must be the same in the two fields'));
6a361945 685 Tools::redirect('?view=config');
c765c367
NL
686 }
687 }
688 }
689 }
00dbaf90
NL
690
691 public function updateTheme()
692 {
693 # no data
694 if (empty($_POST['theme'])) {
695 }
696
697 # we are not going to change it to the current theme...
698 if ($_POST['theme'] == $this->getTheme()) {
699 $this->messages->add('w', _('still using the "' . $this->getTheme() . '" theme!'));
700 Tools::redirect('?view=config');
701 }
702
703 $themes = $this->getInstalledThemes();
704 $actualTheme = false;
705
f4fbfaa7
NL
706 foreach (array_keys($themes) as $theme) {
707 if ($theme == $_POST['theme']) {
00dbaf90
NL
708 $actualTheme = true;
709 break;
710 }
711 }
712
713 if (! $actualTheme) {
714 $this->messages->add('e', _('that theme does not seem to be installed'));
715 Tools::redirect('?view=config');
716 }
717
718 $this->store->updateUserConfig($this->user->getId(), 'theme', $_POST['theme']);
719 $this->messages->add('s', _('you have changed your theme preferences'));
720
721 $currentConfig = $_SESSION['poche_user']->config;
722 $currentConfig['theme'] = $_POST['theme'];
723
724 $_SESSION['poche_user']->setConfig($currentConfig);
725
726 Tools::redirect('?view=config');
727 }
c765c367 728
5011388f
NL
729 public function updateLanguage()
730 {
731 # no data
732 if (empty($_POST['language'])) {
733 }
734
735 # we are not going to change it to the current language...
736 if ($_POST['language'] == $this->getLanguage()) {
737 $this->messages->add('w', _('still using the "' . $this->getLanguage() . '" language!'));
738 Tools::redirect('?view=config');
739 }
740
741 $languages = $this->getInstalledLanguages();
742 $actualLanguage = false;
743
744 foreach ($languages as $language) {
745 if ($language['name'] == $_POST['language']) {
746 $actualLanguage = true;
747 break;
748 }
749 }
750
751 if (! $actualLanguage) {
752 $this->messages->add('e', _('that language does not seem to be installed'));
753 Tools::redirect('?view=config');
754 }
755
756 $this->store->updateUserConfig($this->user->getId(), 'language', $_POST['language']);
757 $this->messages->add('s', _('you have changed your language preferences'));
758
759 $currentConfig = $_SESSION['poche_user']->config;
760 $currentConfig['language'] = $_POST['language'];
761
762 $_SESSION['poche_user']->setConfig($currentConfig);
763
764 Tools::redirect('?view=config');
765 }
766
df6afaf0
DS
767 /**
768 * get credentials from differents sources
769 * it redirects the user to the $referer link
770 * @return array
771 */
1810c13b
NL
772 private function credentials() {
773 if(isset($_SERVER['PHP_AUTH_USER'])) {
6af66b11 774 return array($_SERVER['PHP_AUTH_USER'],'php_auth',true);
1810c13b
NL
775 }
776 if(!empty($_POST['login']) && !empty($_POST['password'])) {
6af66b11 777 return array($_POST['login'],$_POST['password'],false);
1810c13b
NL
778 }
779 if(isset($_SERVER['REMOTE_USER'])) {
6af66b11 780 return array($_SERVER['REMOTE_USER'],'http_auth',true);
1810c13b 781 }
5cfafc61 782
6af66b11
MR
783 return array(false,false,false);
784 }
df6afaf0 785
07ee09f4
NL
786 /**
787 * checks if login & password are correct and save the user in session.
788 * it redirects the user to the $referer link
789 * @param string $referer the url to redirect after login
790 * @todo add the return value
791 * @return boolean
792 */
c765c367
NL
793 public function login($referer)
794 {
6af66b11 795 list($login,$password,$isauthenticated)=$this->credentials();
df6afaf0
DS
796 if($login === false || $password === false) {
797 $this->messages->add('e', _('login failed: you have to fill all fields'));
798 Tools::logm('login failed');
799 Tools::redirect();
800 }
801 if (!empty($login) && !empty($password)) {
6af66b11 802 $user = $this->store->login($login, Tools::encodeString($password . $login), $isauthenticated);
7ce7ec4c
NL
803 if ($user != array()) {
804 # Save login into Session
6af66b11
MR
805 $longlastingsession = isset($_POST['longlastingsession']);
806 $passwordTest = ($isauthenticated) ? $user['password'] : Tools::encodeString($password . $login);
807 Session::login($user['username'], $user['password'], $login, $passwordTest, $longlastingsession, array('poche_user' => new User($user)));
26929c08 808 $this->messages->add('s', _('welcome to your wallabag'));
8d3275be 809 Tools::logm('login successful');
c765c367
NL
810 Tools::redirect($referer);
811 }
8d3275be 812 $this->messages->add('e', _('login failed: bad login or password'));
c765c367
NL
813 Tools::logm('login failed');
814 Tools::redirect();
c765c367
NL
815 }
816 }
817
07ee09f4
NL
818 /**
819 * log out the poche user. It cleans the session.
820 * @todo add the return value
821 * @return boolean
822 */
c765c367
NL
823 public function logout()
824 {
7ce7ec4c 825 $this->user = array();
c765c367 826 Session::logout();
b916bcfc 827 Tools::logm('logout');
c765c367
NL
828 Tools::redirect();
829 }
830
07ee09f4
NL
831 /**
832 * import from Instapaper. poche needs a ./instapaper-export.html file
833 * @todo add the return value
66b6a3b5 834 * @param string $targetFile the file used for importing
07ee09f4
NL
835 * @return boolean
836 */
66b6a3b5 837 private function importFromInstapaper($targetFile)
c765c367 838 {
7f959169 839 # TODO gestion des articles favs
a62788c6 840 $html = new simple_html_dom();
66b6a3b5 841 $html->load_file($targetFile);
b916bcfc 842 Tools::logm('starting import from instapaper');
a62788c6
NL
843
844 $read = 0;
845 $errors = array();
846 foreach($html->find('ol') as $ul)
847 {
848 foreach($ul->find('li') as $li)
849 {
850 $a = $li->find('a');
851 $url = new Url(base64_encode($a[0]->href));
b916bcfc 852 $this->action('add', $url, 0, TRUE);
a62788c6 853 if ($read == '1') {
b916bcfc
NL
854 $sequence = '';
855 if (STORAGE == 'postgres') {
856 $sequence = 'entries_id_seq';
857 }
858 $last_id = $this->store->getLastId($sequence);
859 $this->action('toggle_archive', $url, $last_id, TRUE);
a62788c6
NL
860 }
861 }
7f959169
NL
862
863 # the second <ol> is for read links
a62788c6
NL
864 $read = 1;
865 }
8d3275be 866 $this->messages->add('s', _('import from instapaper completed'));
63c35580
NL
867 Tools::logm('import from instapaper completed');
868 Tools::redirect();
869 }
c765c367 870
07ee09f4
NL
871 /**
872 * import from Pocket. poche needs a ./ril_export.html file
873 * @todo add the return value
66b6a3b5 874 * @param string $targetFile the file used for importing
07ee09f4
NL
875 * @return boolean
876 */
66b6a3b5 877 private function importFromPocket($targetFile)
63c35580 878 {
7f959169 879 # TODO gestion des articles favs
63c35580 880 $html = new simple_html_dom();
66b6a3b5 881 $html->load_file($targetFile);
b916bcfc 882 Tools::logm('starting import from pocket');
63c35580
NL
883
884 $read = 0;
885 $errors = array();
886 foreach($html->find('ul') as $ul)
887 {
888 foreach($ul->find('li') as $li)
c765c367 889 {
63c35580
NL
890 $a = $li->find('a');
891 $url = new Url(base64_encode($a[0]->href));
b916bcfc 892 $this->action('add', $url, 0, TRUE);
63c35580 893 if ($read == '1') {
b916bcfc
NL
894 $sequence = '';
895 if (STORAGE == 'postgres') {
896 $sequence = 'entries_id_seq';
897 }
898 $last_id = $this->store->getLastId($sequence);
899 $this->action('toggle_archive', $url, $last_id, TRUE);
c765c367 900 }
c765c367 901 }
7f959169
NL
902
903 # the second <ul> is for read links
63c35580 904 $read = 1;
c765c367 905 }
8d3275be 906 $this->messages->add('s', _('import from pocket completed'));
63c35580
NL
907 Tools::logm('import from pocket completed');
908 Tools::redirect();
909 }
c765c367 910
07ee09f4
NL
911 /**
912 * import from Readability. poche needs a ./readability file
913 * @todo add the return value
66b6a3b5 914 * @param string $targetFile the file used for importing
07ee09f4
NL
915 * @return boolean
916 */
66b6a3b5 917 private function importFromReadability($targetFile)
63c35580 918 {
7f959169 919 # TODO gestion des articles lus / favs
66b6a3b5 920 $str_data = file_get_contents($targetFile);
63c35580 921 $data = json_decode($str_data,true);
b916bcfc 922 Tools::logm('starting import from Readability');
c0d321c1 923 $count = 0;
63c35580 924 foreach ($data as $key => $value) {
c0d321c1
NL
925 $url = NULL;
926 $favorite = FALSE;
927 $archive = FALSE;
9bc32632
NL
928 foreach ($value as $item) {
929 foreach ($item as $attr => $value) {
930 if ($attr == 'article__url') {
931 $url = new Url(base64_encode($value));
c0d321c1 932 }
9bc32632
NL
933 $sequence = '';
934 if (STORAGE == 'postgres') {
935 $sequence = 'entries_id_seq';
936 }
937 if ($value == 'true') {
938 if ($attr == 'favorite') {
939 $favorite = TRUE;
940 }
941 if ($attr == 'archive') {
942 $archive = TRUE;
943 }
c0d321c1
NL
944 }
945 }
9bc32632
NL
946
947 # we can add the url
948 if (!is_null($url) && $url->isCorrect()) {
949 $this->action('add', $url, 0, TRUE);
950 $count++;
951 if ($favorite) {
952 $last_id = $this->store->getLastId($sequence);
953 $this->action('toggle_fav', $url, $last_id, TRUE);
954 }
955 if ($archive) {
956 $last_id = $this->store->getLastId($sequence);
957 $this->action('toggle_archive', $url, $last_id, TRUE);
958 }
b916bcfc 959 }
c765c367 960 }
c765c367 961 }
c0d321c1 962 $this->messages->add('s', _('import from Readability completed. ' . $count . ' new links.'));
63c35580
NL
963 Tools::logm('import from Readability completed');
964 Tools::redirect();
c765c367
NL
965 }
966
89051914
NL
967 /**
968 * import from Poche exported file
969 * @param string $targetFile the file used for importing
970 * @return boolean
971 */
972 private function importFromPoche($targetFile)
973 {
974 $str_data = file_get_contents($targetFile);
975 $data = json_decode($str_data,true);
976 Tools::logm('starting import from Poche');
977
978
979 $sequence = '';
980 if (STORAGE == 'postgres') {
981 $sequence = 'entries_id_seq';
982 }
983
984 $count = 0;
985 foreach ($data as $value) {
986
987 $url = new Url(base64_encode($value['url']));
988 $favorite = ($value['is_fav'] == -1);
989 $archive = ($value['is_read'] == -1);
990
991 # we can add the url
992 if (!is_null($url) && $url->isCorrect()) {
993
994 $this->action('add', $url, 0, TRUE);
995
996 $count++;
997 if ($favorite) {
998 $last_id = $this->store->getLastId($sequence);
999 $this->action('toggle_fav', $url, $last_id, TRUE);
1000 }
1001 if ($archive) {
1002 $last_id = $this->store->getLastId($sequence);
1003 $this->action('toggle_archive', $url, $last_id, TRUE);
1004 }
1005 }
1006
1007 }
1008 $this->messages->add('s', _('import from Poche completed. ' . $count . ' new links.'));
1009 Tools::logm('import from Poche completed');
1010 Tools::redirect();
1011 }
1012
07ee09f4
NL
1013 /**
1014 * import datas into your poche
1015 * @param string $from name of the service to import : pocket, instapaper or readability
1016 * @todo add the return value
1017 * @return boolean
1018 */
63c35580 1019 public function import($from)
c765c367 1020 {
66b6a3b5
E
1021 $providers = array(
1022 'pocket' => 'importFromPocket',
1023 'readability' => 'importFromReadability',
89051914
NL
1024 'instapaper' => 'importFromInstapaper',
1025 'poche' => 'importFromPoche',
66b6a3b5
E
1026 );
1027
1028 if (! isset($providers[$from])) {
1029 $this->messages->add('e', _('Unknown import provider.'));
1030 Tools::redirect();
63c35580 1031 }
66b6a3b5
E
1032
1033 $targetDefinition = 'IMPORT_' . strtoupper($from) . '_FILE';
1034 $targetFile = constant($targetDefinition);
1035
1036 if (! defined($targetDefinition)) {
1037 $this->messages->add('e', _('Incomplete inc/poche/define.inc.php file, please define "' . $targetDefinition . '".'));
1038 Tools::redirect();
63c35580 1039 }
66b6a3b5
E
1040
1041 if (! file_exists($targetFile)) {
1042 $this->messages->add('e', _('Could not find required "' . $targetFile . '" import file.'));
1043 Tools::redirect();
63c35580 1044 }
66b6a3b5
E
1045
1046 $this->$providers[$from]($targetFile);
63c35580 1047 }
c765c367 1048
07ee09f4
NL
1049 /**
1050 * export poche entries in json
1051 * @return json all poche entries
1052 */
63c35580
NL
1053 public function export()
1054 {
8d3275be 1055 $entries = $this->store->retrieveAll($this->user->getId());
63c35580
NL
1056 echo $this->tpl->render('export.twig', array(
1057 'export' => Tools::renderJson($entries),
1058 ));
1059 Tools::logm('export view');
c765c367 1060 }
32520785 1061
07ee09f4 1062 /**
a3436d4c 1063 * Checks online the latest version of poche and cache it
07ee09f4
NL
1064 * @param string $which 'prod' or 'dev'
1065 * @return string latest $which version
1066 */
32520785
NL
1067 private function getPocheVersion($which = 'prod')
1068 {
1069 $cache_file = CACHE . '/' . $which;
a3436d4c
NL
1070
1071 # checks if the cached version file exists
32520785
NL
1072 if (file_exists($cache_file) && (filemtime($cache_file) > (time() - 86400 ))) {
1073 $version = file_get_contents($cache_file);
1074 } else {
3e0e7e12 1075 $version = file_get_contents('http://static.wallabag.org/versions/' . $which);
32520785
NL
1076 file_put_contents($cache_file, $version, LOCK_EX);
1077 }
1078 return $version;
1079 }
72c20a52
NL
1080
1081 public function generateToken()
1082 {
1083 if (ini_get('open_basedir') === '') {
1084 $token = substr(base64_encode(file_get_contents('/dev/urandom', false, null, 0, 20)), 0, 15);
1085 }
1086 else {
1087 $token = substr(base64_encode(uniqid(mt_rand(), true)), 0, 20);
1088 }
1089
044bf638 1090 $token = str_replace('+', '', $token);
72c20a52
NL
1091 $this->store->updateUserConfig($this->user->getId(), 'token', $token);
1092 $currentConfig = $_SESSION['poche_user']->config;
1093 $currentConfig['token'] = $token;
1094 $_SESSION['poche_user']->setConfig($currentConfig);
1095 }
1096
f778e472 1097 public function generateFeeds($token, $user_id, $tag_id, $type = 'home')
72c20a52 1098 {
f778e472 1099 $allowed_types = array('home', 'fav', 'archive', 'tag');
72c20a52
NL
1100 $config = $this->store->getConfigUser($user_id);
1101
1102 if (!in_array($type, $allowed_types) ||
1103 $token != $config['token']) {
1104 die(_('Uh, there is a problem while generating feeds.'));
1105 }
1106 // Check the token
1107
9e7c840b 1108 $feed = new FeedWriter(RSS2);
2e4440c3 1109 $feed->setTitle('wallabag — ' . $type . ' feed');
72c20a52 1110 $feed->setLink(Tools::getPocheUrl());
9e7c840b 1111 $feed->setChannelElement('updated', date(DATE_RSS , time()));
2e4440c3 1112 $feed->setChannelElement('author', 'wallabag');
72c20a52 1113
f778e472 1114 if ($type == 'tag') {
b89d5a2b 1115 $entries = $this->store->retrieveEntriesByTag($tag_id, $user_id);
f778e472
NL
1116 }
1117 else {
1118 $entries = $this->store->getEntriesByView($type, $user_id);
1119 }
1120
72c20a52
NL
1121 if (count($entries) > 0) {
1122 foreach ($entries as $entry) {
1123 $newItem = $feed->createNewItem();
0b57c682 1124 $newItem->setTitle($entry['title']);
72c20a52
NL
1125 $newItem->setLink(Tools::getPocheUrl() . '?view=view&amp;id=' . $entry['id']);
1126 $newItem->setDate(time());
1127 $newItem->setDescription($entry['content']);
1128 $feed->addItem($newItem);
1129 }
1130 }
1131
1132 $feed->genarateFeed();
1133 exit;
1134 }
6285e57c
NL
1135
1136 public function emptyCache() {
1137 $files = new RecursiveIteratorIterator(
1138 new RecursiveDirectoryIterator(CACHE, RecursiveDirectoryIterator::SKIP_DOTS),
1139 RecursiveIteratorIterator::CHILD_FIRST
1140 );
1141
1142 foreach ($files as $fileinfo) {
1143 $todo = ($fileinfo->isDir() ? 'rmdir' : 'unlink');
1144 $todo($fileinfo->getRealPath());
1145 }
1146
1147 Tools::logm('empty cache');
1148 $this->messages->add('s', _('Cache deleted.'));
1149 Tools::redirect();
1150 }
df6afaf0 1151}