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