]> git.immae.eu Git - github/wallabag/wallabag.git/blob - inc/poche/Poche.class.php
Sort themes alphabetically in config list
[github/wallabag/wallabag.git] / inc / poche / Poche.class.php
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
11 class Poche
12 {
13 public static $canRenderTemplates = true;
14 public static $configFileAvailable = true;
15
16 public $user;
17 public $store;
18 public $tpl;
19 public $messages;
20 public $pagination;
21
22 private $currentTheme = '';
23 private $notInstalledMessage = '';
24
25 # @todo make this dynamic (actually install themes and save them in the database including author information et cetera)
26 private $installedThemes = array(
27 'default' => array('requires' => array()),
28 'dark' => array('requires' => array('default')),
29 'dmagenta' => array('requires' => array('default')),
30 'solarized' => array('requires' => array('default')),
31 'solarized-dark' => array('requires' => array('default'))
32 );
33
34 public function __construct()
35 {
36 if (! $this->configFileIsAvailable()) {
37 return;
38 }
39
40 $this->init();
41
42 if (! $this->themeIsInstalled()) {
43 return;
44 }
45
46 $this->initTpl();
47
48 if (! $this->systemIsInstalled()) {
49 return;
50 }
51
52 $this->store = new Database();
53 $this->messages = new Messages();
54
55 # installation
56 if (! $this->store->isInstalled()) {
57 $this->install();
58 }
59 }
60
61 private function init()
62 {
63 Tools::initPhp();
64 Session::$sessionName = 'poche';
65 Session::init();
66
67 if (isset($_SESSION['poche_user']) && $_SESSION['poche_user'] != array()) {
68 $this->user = $_SESSION['poche_user'];
69 } else {
70 # fake user, just for install & login screens
71 $this->user = new User();
72 $this->user->setConfig($this->getDefaultConfig());
73 }
74
75 # l10n
76 $language = $this->user->getConfigValue('language');
77 putenv('LC_ALL=' . $language);
78 setlocale(LC_ALL, $language);
79 bindtextdomain($language, LOCALE);
80 textdomain($language);
81
82 # Pagination
83 $this->pagination = new Paginator($this->user->getConfigValue('pager'), 'p');
84
85 # Set up theme
86 $themeDirectory = $this->user->getConfigValue('theme');
87
88 if ($themeDirectory === false) {
89 $themeDirectory = DEFAULT_THEME;
90 }
91
92 $this->currentTheme = $themeDirectory;
93 }
94
95 public function configFileIsAvailable() {
96 if (! self::$configFileAvailable) {
97 $this->notInstalledMessage = 'You have to rename <strong>inc/poche/config.inc.php.new</strong> to <strong>inc/poche/config.inc.php</strong>.';
98
99 return false;
100 }
101
102 return true;
103 }
104
105 public function themeIsInstalled() {
106 # Twig is an absolute requirement for Poche to function. Abort immediately if the Composer installer hasn't been run yet
107 if (! self::$canRenderTemplates) {
108 $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>';
109
110 return false;
111 }
112
113 if (! is_writable(CACHE)) {
114 $this->notInstalledMessage = '<h1>error</h1><p>You don\'t have write access on cache directory.</p>';
115
116 self::$canRenderTemplates = false;
117
118 return false;
119 }
120
121 # Check if the selected theme and its requirements are present
122 if (! is_dir(THEME . '/' . $this->getTheme())) {
123 $this->notInstalledMessage = 'The currently selected theme (' . $this->getTheme() . ') does not seem to be properly installed (Missing directory: ' . THEME . '/' . $this->getTheme() . ')';
124
125 self::$canRenderTemplates = false;
126
127 return false;
128 }
129
130 foreach ($this->installedThemes[$this->getTheme()]['requires'] as $requiredTheme) {
131 if (! is_dir(THEME . '/' . $requiredTheme)) {
132 $this->notInstalledMessage = 'The required "' . $requiredTheme . '" theme is missing for the current theme (' . $this->getTheme() . ')';
133
134 self::$canRenderTemplates = false;
135
136 return false;
137 }
138 }
139
140 return true;
141 }
142
143 /**
144 * all checks before installation.
145 * @todo move HTML to template
146 * @return boolean
147 */
148 public function systemIsInstalled()
149 {
150 $msg = '';
151
152 $configSalt = defined('SALT') ? constant('SALT') : '';
153
154 if (empty($configSalt)) {
155 $msg = '<h1>error</h1><p>You have not yet filled in the SALT value in the config.inc.php file.</p>';
156 } else if (STORAGE == 'sqlite' && ! file_exists(STORAGE_SQLITE)) {
157 Tools::logm('sqlite file doesn\'t exist');
158 $msg = '<h1>error</h1><p>sqlite file doesn\'t exist, you can find it in install folder. Copy it in /db folder.</p>';
159 } else if (is_dir(ROOT . '/install') && ! DEBUG_POCHE) {
160 $msg = '<h1>install folder</h1><p>you have to delete the /install folder before using poche.</p>';
161 } else if (STORAGE == 'sqlite' && ! is_writable(STORAGE_SQLITE)) {
162 Tools::logm('you don\'t have write access on sqlite file');
163 $msg = '<h1>error</h1><p>You don\'t have write access on sqlite file.</p>';
164 }
165
166 if (! empty($msg)) {
167 $this->notInstalledMessage = $msg;
168
169 return false;
170 }
171
172 return true;
173 }
174
175 public function getNotInstalledMessage() {
176 return $this->notInstalledMessage;
177 }
178
179 private function initTpl()
180 {
181 $loaderChain = new Twig_Loader_Chain();
182
183 # add the current theme as first to the loader chain so Twig will look there first for overridden template files
184 try {
185 $loaderChain->addLoader(new Twig_Loader_Filesystem(THEME . '/' . $this->getTheme()));
186 } catch (Twig_Error_Loader $e) {
187 # @todo isInstalled() should catch this, inject Twig later
188 die('The currently selected theme (' . $this->getTheme() . ') does not seem to be properly installed (' . THEME . '/' . $this->getTheme() .' is missing)');
189 }
190
191 # add all required themes to the loader chain
192 foreach ($this->installedThemes[$this->getTheme()]['requires'] as $requiredTheme) {
193 try {
194 $loaderChain->addLoader(new Twig_Loader_Filesystem(THEME . '/' . DEFAULT_THEME));
195 } catch (Twig_Error_Loader $e) {
196 # @todo isInstalled() should catch this, inject Twig later
197 die('The required "' . $requiredTheme . '" theme is missing for the current theme (' . $this->getTheme() . ')');
198 }
199 }
200
201 if (DEBUG_POCHE) {
202 $twig_params = array();
203 } else {
204 $twig_params = array('cache' => CACHE);
205 }
206
207 $this->tpl = new Twig_Environment($loaderChain, $twig_params);
208 $this->tpl->addExtension(new Twig_Extensions_Extension_I18n());
209
210 # filter to display domain name of an url
211 $filter = new Twig_SimpleFilter('getDomain', 'Tools::getDomain');
212 $this->tpl->addFilter($filter);
213
214 # filter for reading time
215 $filter = new Twig_SimpleFilter('getReadingTime', 'Tools::getReadingTime');
216 $this->tpl->addFilter($filter);
217
218 # filter for simple filenames in config view
219 $filter = new Twig_SimpleFilter('getPrettyFilename', function($string) { return str_replace(ROOT, '', $string); });
220 $this->tpl->addFilter($filter);
221 }
222
223 private function install()
224 {
225 Tools::logm('poche still not installed');
226 echo $this->tpl->render('install.twig', array(
227 'token' => Session::getToken(),
228 'theme' => $this->getTheme(),
229 'poche_url' => Tools::getPocheUrl()
230 ));
231 if (isset($_GET['install'])) {
232 if (($_POST['password'] == $_POST['password_repeat'])
233 && $_POST['password'] != "" && $_POST['login'] != "") {
234 # let's rock, install poche baby !
235 if ($this->store->install($_POST['login'], Tools::encodeString($_POST['password'] . $_POST['login'])))
236 {
237 Session::logout();
238 Tools::logm('poche is now installed');
239 Tools::redirect();
240 }
241 }
242 else {
243 Tools::logm('error during installation');
244 Tools::redirect();
245 }
246 }
247 exit();
248 }
249
250 public function getTheme() {
251 return $this->currentTheme;
252 }
253
254 public function getInstalledThemes() {
255 $handle = opendir(THEME);
256 $themes = array();
257
258 while (($theme = readdir($handle)) !== false) {
259 # Themes are stored in a directory, so all directory names are themes
260 # @todo move theme installation data to database
261 if (! is_dir(THEME . '/' . $theme) || in_array($theme, array('..', '.'))) {
262 continue;
263 }
264
265 $current = false;
266
267 if ($theme === $this->getTheme()) {
268 $current = true;
269 }
270
271 $themes[] = array('name' => $theme, 'current' => $current);
272 }
273
274 sort($themes);
275 return $themes;
276 }
277
278 public function getDefaultConfig()
279 {
280 return array(
281 'pager' => PAGINATION,
282 'language' => LANG,
283 'theme' => DEFAULT_THEME
284 );
285 }
286
287 /**
288 * Call action (mark as fav, archive, delete, etc.)
289 */
290 public function action($action, Url $url, $id = 0, $import = FALSE)
291 {
292 switch ($action)
293 {
294 case 'add':
295 $content = $url->extract();
296
297 if ($this->store->add($url->getUrl(), $content['title'], $content['body'], $this->user->getId())) {
298 Tools::logm('add link ' . $url->getUrl());
299 $sequence = '';
300 if (STORAGE == 'postgres') {
301 $sequence = 'entries_id_seq';
302 }
303 $last_id = $this->store->getLastId($sequence);
304 if (DOWNLOAD_PICTURES) {
305 $content = filtre_picture($content['body'], $url->getUrl(), $last_id);
306 Tools::logm('updating content article');
307 $this->store->updateContent($last_id, $content, $this->user->getId());
308 }
309 if (!$import) {
310 $this->messages->add('s', _('the link has been added successfully'));
311 }
312 }
313 else {
314 if (!$import) {
315 $this->messages->add('e', _('error during insertion : the link wasn\'t added'));
316 Tools::logm('error during insertion : the link wasn\'t added ' . $url->getUrl());
317 }
318 }
319
320 if (!$import) {
321 Tools::redirect('?view=home');
322 }
323 break;
324 case 'delete':
325 $msg = 'delete link #' . $id;
326 if ($this->store->deleteById($id, $this->user->getId())) {
327 if (DOWNLOAD_PICTURES) {
328 remove_directory(ABS_PATH . $id);
329 }
330 $this->messages->add('s', _('the link has been deleted successfully'));
331 }
332 else {
333 $this->messages->add('e', _('the link wasn\'t deleted'));
334 $msg = 'error : can\'t delete link #' . $id;
335 }
336 Tools::logm($msg);
337 Tools::redirect();
338 break;
339 case 'toggle_fav' :
340 $this->store->favoriteById($id, $this->user->getId());
341 Tools::logm('mark as favorite link #' . $id);
342 if (!$import) {
343 Tools::redirect();
344 }
345 break;
346 case 'toggle_archive' :
347 $this->store->archiveById($id, $this->user->getId());
348 Tools::logm('archive link #' . $id);
349 if (!$import) {
350 Tools::redirect();
351 }
352 break;
353 default:
354 break;
355 }
356 }
357
358 function displayView($view, $id = 0)
359 {
360 $tpl_vars = array();
361
362 switch ($view)
363 {
364 case 'config':
365 $dev = $this->getPocheVersion('dev');
366 $prod = $this->getPocheVersion('prod');
367 $compare_dev = version_compare(POCHE_VERSION, $dev);
368 $compare_prod = version_compare(POCHE_VERSION, $prod);
369 $themes = $this->getInstalledThemes();
370 $tpl_vars = array(
371 'themes' => $themes,
372 'dev' => $dev,
373 'prod' => $prod,
374 'compare_dev' => $compare_dev,
375 'compare_prod' => $compare_prod,
376 );
377 Tools::logm('config view');
378 break;
379 case 'view':
380 $entry = $this->store->retrieveOneById($id, $this->user->getId());
381 if ($entry != NULL) {
382 Tools::logm('view link #' . $id);
383 $content = $entry['content'];
384 if (function_exists('tidy_parse_string')) {
385 $tidy = tidy_parse_string($content, array('indent'=>true, 'show-body-only' => true), 'UTF8');
386 $tidy->cleanRepair();
387 $content = $tidy->value;
388 }
389
390 # flattr checking
391 $flattr = new FlattrItem();
392 $flattr->checkItem($entry['url'],$entry['id']);
393
394 $tpl_vars = array(
395 'entry' => $entry,
396 'content' => $content,
397 'flattr' => $flattr
398 );
399 }
400 else {
401 Tools::logm('error in view call : entry is null');
402 }
403 break;
404 default: # home, favorites and archive views
405 $entries = $this->store->getEntriesByView($view, $this->user->getId());
406 $tpl_vars = array(
407 'entries' => '',
408 'page_links' => '',
409 'nb_results' => '',
410 );
411
412 if (count($entries) > 0) {
413 $this->pagination->set_total(count($entries));
414 $page_links = $this->pagination->page_links('?view=' . $view . '&sort=' . $_SESSION['sort'] . '&');
415 $datas = $this->store->getEntriesByView($view, $this->user->getId(), $this->pagination->get_limit());
416 $tpl_vars['entries'] = $datas;
417 $tpl_vars['page_links'] = $page_links;
418 $tpl_vars['nb_results'] = count($entries);
419 }
420 Tools::logm('display ' . $view . ' view');
421 break;
422 }
423
424 return $tpl_vars;
425 }
426
427 /**
428 * update the password of the current user.
429 * if MODE_DEMO is TRUE, the password can't be updated.
430 * @todo add the return value
431 * @todo set the new password in function header like this updatePassword($newPassword)
432 * @return boolean
433 */
434 public function updatePassword()
435 {
436 if (MODE_DEMO) {
437 $this->messages->add('i', _('in demo mode, you can\'t update your password'));
438 Tools::logm('in demo mode, you can\'t do this');
439 Tools::redirect('?view=config');
440 }
441 else {
442 if (isset($_POST['password']) && isset($_POST['password_repeat'])) {
443 if ($_POST['password'] == $_POST['password_repeat'] && $_POST['password'] != "") {
444 $this->messages->add('s', _('your password has been updated'));
445 $this->store->updatePassword($this->user->getId(), Tools::encodeString($_POST['password'] . $this->user->getUsername()));
446 Session::logout();
447 Tools::logm('password updated');
448 Tools::redirect();
449 }
450 else {
451 $this->messages->add('e', _('the two fields have to be filled & the password must be the same in the two fields'));
452 Tools::redirect('?view=config');
453 }
454 }
455 }
456 }
457
458 public function updateTheme()
459 {
460 # no data
461 if (empty($_POST['theme'])) {
462 }
463
464 # we are not going to change it to the current theme...
465 if ($_POST['theme'] == $this->getTheme()) {
466 $this->messages->add('w', _('still using the "' . $this->getTheme() . '" theme!'));
467 Tools::redirect('?view=config');
468 }
469
470 $themes = $this->getInstalledThemes();
471 $actualTheme = false;
472
473 foreach ($themes as $theme) {
474 if ($theme['name'] == $_POST['theme']) {
475 $actualTheme = true;
476 break;
477 }
478 }
479
480 if (! $actualTheme) {
481 $this->messages->add('e', _('that theme does not seem to be installed'));
482 Tools::redirect('?view=config');
483 }
484
485 $this->store->updateUserConfig($this->user->getId(), 'theme', $_POST['theme']);
486 $this->messages->add('s', _('you have changed your theme preferences'));
487
488 $currentConfig = $_SESSION['poche_user']->config;
489 $currentConfig['theme'] = $_POST['theme'];
490
491 $_SESSION['poche_user']->setConfig($currentConfig);
492
493 Tools::redirect('?view=config');
494 }
495
496 /**
497 * checks if login & password are correct and save the user in session.
498 * it redirects the user to the $referer link
499 * @param string $referer the url to redirect after login
500 * @todo add the return value
501 * @return boolean
502 */
503 public function login($referer)
504 {
505 if (!empty($_POST['login']) && !empty($_POST['password'])) {
506 $user = $this->store->login($_POST['login'], Tools::encodeString($_POST['password'] . $_POST['login']));
507 if ($user != array()) {
508 # Save login into Session
509 Session::login($user['username'], $user['password'], $_POST['login'], Tools::encodeString($_POST['password'] . $_POST['login']), array('poche_user' => new User($user)));
510 $this->messages->add('s', _('welcome to your poche'));
511 Tools::logm('login successful');
512 Tools::redirect($referer);
513 }
514 $this->messages->add('e', _('login failed: bad login or password'));
515 Tools::logm('login failed');
516 Tools::redirect();
517 } else {
518 $this->messages->add('e', _('login failed: you have to fill all fields'));
519 Tools::logm('login failed');
520 Tools::redirect();
521 }
522 }
523
524 /**
525 * log out the poche user. It cleans the session.
526 * @todo add the return value
527 * @return boolean
528 */
529 public function logout()
530 {
531 $this->user = array();
532 Session::logout();
533 $this->messages->add('s', _('see you soon!'));
534 Tools::logm('logout');
535 Tools::redirect();
536 }
537
538 /**
539 * import from Instapaper. poche needs a ./instapaper-export.html file
540 * @todo add the return value
541 * @param string $targetFile the file used for importing
542 * @return boolean
543 */
544 private function importFromInstapaper($targetFile)
545 {
546 # TODO gestion des articles favs
547 $html = new simple_html_dom();
548 $html->load_file($targetFile);
549 Tools::logm('starting import from instapaper');
550
551 $read = 0;
552 $errors = array();
553 foreach($html->find('ol') as $ul)
554 {
555 foreach($ul->find('li') as $li)
556 {
557 $a = $li->find('a');
558 $url = new Url(base64_encode($a[0]->href));
559 $this->action('add', $url, 0, TRUE);
560 if ($read == '1') {
561 $sequence = '';
562 if (STORAGE == 'postgres') {
563 $sequence = 'entries_id_seq';
564 }
565 $last_id = $this->store->getLastId($sequence);
566 $this->action('toggle_archive', $url, $last_id, TRUE);
567 }
568 }
569
570 # the second <ol> is for read links
571 $read = 1;
572 }
573 $this->messages->add('s', _('import from instapaper completed'));
574 Tools::logm('import from instapaper completed');
575 Tools::redirect();
576 }
577
578 /**
579 * import from Pocket. poche needs a ./ril_export.html file
580 * @todo add the return value
581 * @param string $targetFile the file used for importing
582 * @return boolean
583 */
584 private function importFromPocket($targetFile)
585 {
586 # TODO gestion des articles favs
587 $html = new simple_html_dom();
588 $html->load_file($targetFile);
589 Tools::logm('starting import from pocket');
590
591 $read = 0;
592 $errors = array();
593 foreach($html->find('ul') as $ul)
594 {
595 foreach($ul->find('li') as $li)
596 {
597 $a = $li->find('a');
598 $url = new Url(base64_encode($a[0]->href));
599 $this->action('add', $url, 0, TRUE);
600 if ($read == '1') {
601 $sequence = '';
602 if (STORAGE == 'postgres') {
603 $sequence = 'entries_id_seq';
604 }
605 $last_id = $this->store->getLastId($sequence);
606 $this->action('toggle_archive', $url, $last_id, TRUE);
607 }
608 }
609
610 # the second <ul> is for read links
611 $read = 1;
612 }
613 $this->messages->add('s', _('import from pocket completed'));
614 Tools::logm('import from pocket completed');
615 Tools::redirect();
616 }
617
618 /**
619 * import from Readability. poche needs a ./readability file
620 * @todo add the return value
621 * @param string $targetFile the file used for importing
622 * @return boolean
623 */
624 private function importFromReadability($targetFile)
625 {
626 # TODO gestion des articles lus / favs
627 $str_data = file_get_contents($targetFile);
628 $data = json_decode($str_data,true);
629 Tools::logm('starting import from Readability');
630 $count = 0;
631 foreach ($data as $key => $value) {
632 $url = NULL;
633 $favorite = FALSE;
634 $archive = FALSE;
635 foreach ($value as $attr => $attr_value) {
636 if ($attr == 'article__url') {
637 $url = new Url(base64_encode($attr_value));
638 }
639 $sequence = '';
640 if (STORAGE == 'postgres') {
641 $sequence = 'entries_id_seq';
642 }
643 if ($attr_value == 'true') {
644 if ($attr == 'favorite') {
645 $favorite = TRUE;
646 }
647 if ($attr == 'archive') {
648 $archive = TRUE;
649 }
650 }
651 }
652 # we can add the url
653 if (!is_null($url) && $url->isCorrect()) {
654 $this->action('add', $url, 0, TRUE);
655 $count++;
656 if ($favorite) {
657 $last_id = $this->store->getLastId($sequence);
658 $this->action('toggle_fav', $url, $last_id, TRUE);
659 }
660 if ($archive) {
661 $last_id = $this->store->getLastId($sequence);
662 $this->action('toggle_archive', $url, $last_id, TRUE);
663 }
664 }
665 }
666 $this->messages->add('s', _('import from Readability completed. ' . $count . ' new links.'));
667 Tools::logm('import from Readability completed');
668 Tools::redirect();
669 }
670
671 /**
672 * import datas into your poche
673 * @param string $from name of the service to import : pocket, instapaper or readability
674 * @todo add the return value
675 * @return boolean
676 */
677 public function import($from)
678 {
679 $providers = array(
680 'pocket' => 'importFromPocket',
681 'readability' => 'importFromReadability',
682 'instapaper' => 'importFromInstapaper'
683 );
684
685 if (! isset($providers[$from])) {
686 $this->messages->add('e', _('Unknown import provider.'));
687 Tools::redirect();
688 }
689
690 $targetDefinition = 'IMPORT_' . strtoupper($from) . '_FILE';
691 $targetFile = constant($targetDefinition);
692
693 if (! defined($targetDefinition)) {
694 $this->messages->add('e', _('Incomplete inc/poche/define.inc.php file, please define "' . $targetDefinition . '".'));
695 Tools::redirect();
696 }
697
698 if (! file_exists($targetFile)) {
699 $this->messages->add('e', _('Could not find required "' . $targetFile . '" import file.'));
700 Tools::redirect();
701 }
702
703 $this->$providers[$from]($targetFile);
704 }
705
706 /**
707 * export poche entries in json
708 * @return json all poche entries
709 */
710 public function export()
711 {
712 $entries = $this->store->retrieveAll($this->user->getId());
713 echo $this->tpl->render('export.twig', array(
714 'export' => Tools::renderJson($entries),
715 ));
716 Tools::logm('export view');
717 }
718
719 /**
720 * Checks online the latest version of poche and cache it
721 * @param string $which 'prod' or 'dev'
722 * @return string latest $which version
723 */
724 private function getPocheVersion($which = 'prod')
725 {
726 $cache_file = CACHE . '/' . $which;
727
728 # checks if the cached version file exists
729 if (file_exists($cache_file) && (filemtime($cache_file) > (time() - 86400 ))) {
730 $version = file_get_contents($cache_file);
731 } else {
732 $version = file_get_contents('http://static.inthepoche.com/versions/' . $which);
733 file_put_contents($cache_file, $version, LOCK_EX);
734 }
735 return $version;
736 }
737 }