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