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