]> git.immae.eu Git - github/wallabag/wallabag.git/blob - inc/poche/Poche.class.php
change instructions messages
[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://inthepoche.com/?pages/Documentation">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('..', '.', '.git'))) {
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 return $themes;
275 }
276
277 public function getDefaultConfig()
278 {
279 return array(
280 'pager' => PAGINATION,
281 'language' => LANG,
282 'theme' => DEFAULT_THEME
283 );
284 }
285
286 /**
287 * Call action (mark as fav, archive, delete, etc.)
288 */
289 public function action($action, Url $url, $id = 0, $import = FALSE)
290 {
291 switch ($action)
292 {
293 case 'add':
294 $content = $url->extract();
295
296 if ($this->store->add($url->getUrl(), $content['title'], $content['body'], $this->user->getId())) {
297 Tools::logm('add link ' . $url->getUrl());
298 $sequence = '';
299 if (STORAGE == 'postgres') {
300 $sequence = 'entries_id_seq';
301 }
302 $last_id = $this->store->getLastId($sequence);
303 if (DOWNLOAD_PICTURES) {
304 $content = filtre_picture($content['body'], $url->getUrl(), $last_id);
305 Tools::logm('updating content article');
306 $this->store->updateContent($last_id, $content, $this->user->getId());
307 }
308 if (!$import) {
309 $this->messages->add('s', _('the link has been added successfully'));
310 }
311 }
312 else {
313 if (!$import) {
314 $this->messages->add('e', _('error during insertion : the link wasn\'t added'));
315 Tools::logm('error during insertion : the link wasn\'t added ' . $url->getUrl());
316 }
317 }
318
319 if (!$import) {
320 Tools::redirect('?view=home');
321 }
322 break;
323 case 'delete':
324 $msg = 'delete link #' . $id;
325 if ($this->store->deleteById($id, $this->user->getId())) {
326 if (DOWNLOAD_PICTURES) {
327 remove_directory(ABS_PATH . $id);
328 }
329 $this->messages->add('s', _('the link has been deleted successfully'));
330 }
331 else {
332 $this->messages->add('e', _('the link wasn\'t deleted'));
333 $msg = 'error : can\'t delete link #' . $id;
334 }
335 Tools::logm($msg);
336 Tools::redirect('?');
337 break;
338 case 'toggle_fav' :
339 $this->store->favoriteById($id, $this->user->getId());
340 Tools::logm('mark as favorite link #' . $id);
341 if (!$import) {
342 Tools::redirect();
343 }
344 break;
345 case 'toggle_archive' :
346 $this->store->archiveById($id, $this->user->getId());
347 Tools::logm('archive link #' . $id);
348 if (!$import) {
349 Tools::redirect();
350 }
351 break;
352 default:
353 break;
354 }
355 }
356
357 function displayView($view, $id = 0)
358 {
359 $tpl_vars = array();
360
361 switch ($view)
362 {
363 case 'config':
364 $dev = $this->getPocheVersion('dev');
365 $prod = $this->getPocheVersion('prod');
366 $compare_dev = version_compare(POCHE_VERSION, $dev);
367 $compare_prod = version_compare(POCHE_VERSION, $prod);
368 $themes = $this->getInstalledThemes();
369 $tpl_vars = array(
370 'themes' => $themes,
371 'dev' => $dev,
372 'prod' => $prod,
373 'compare_dev' => $compare_dev,
374 'compare_prod' => $compare_prod,
375 );
376 Tools::logm('config view');
377 break;
378 case 'view':
379 $entry = $this->store->retrieveOneById($id, $this->user->getId());
380 if ($entry != NULL) {
381 Tools::logm('view link #' . $id);
382 $content = $entry['content'];
383 if (function_exists('tidy_parse_string')) {
384 $tidy = tidy_parse_string($content, array('indent'=>true, 'show-body-only' => true), 'UTF8');
385 $tidy->cleanRepair();
386 $content = $tidy->value;
387 }
388
389 # flattr checking
390 $flattr = new FlattrItem();
391 $flattr->checkItem($entry['url']);
392
393 $tpl_vars = array(
394 'entry' => $entry,
395 'content' => $content,
396 'flattr' => $flattr
397 );
398 }
399 else {
400 Tools::logm('error in view call : entry is null');
401 }
402 break;
403 default: # home, favorites and archive views
404 $entries = $this->store->getEntriesByView($view, $this->user->getId());
405 $tpl_vars = array(
406 'entries' => '',
407 'page_links' => '',
408 'nb_results' => '',
409 );
410 if (count($entries) > 0) {
411 $this->pagination->set_total(count($entries));
412 $page_links = $this->pagination->page_links('?view=' . $view . '&sort=' . $_SESSION['sort'] . '&');
413 $datas = $this->store->getEntriesByView($view, $this->user->getId(), $this->pagination->get_limit());
414 $tpl_vars['entries'] = $datas;
415 $tpl_vars['page_links'] = $page_links;
416 $tpl_vars['nb_results'] = count($entries);
417 }
418 Tools::logm('display ' . $view . ' view');
419 break;
420 }
421
422 return $tpl_vars;
423 }
424
425 /**
426 * update the password of the current user.
427 * if MODE_DEMO is TRUE, the password can't be updated.
428 * @todo add the return value
429 * @todo set the new password in function header like this updatePassword($newPassword)
430 * @return boolean
431 */
432 public function updatePassword()
433 {
434 if (MODE_DEMO) {
435 $this->messages->add('i', _('in demo mode, you can\'t update your password'));
436 Tools::logm('in demo mode, you can\'t do this');
437 Tools::redirect('?view=config');
438 }
439 else {
440 if (isset($_POST['password']) && isset($_POST['password_repeat'])) {
441 if ($_POST['password'] == $_POST['password_repeat'] && $_POST['password'] != "") {
442 $this->messages->add('s', _('your password has been updated'));
443 $this->store->updatePassword($this->user->getId(), Tools::encodeString($_POST['password'] . $this->user->getUsername()));
444 Session::logout();
445 Tools::logm('password updated');
446 Tools::redirect();
447 }
448 else {
449 $this->messages->add('e', _('the two fields have to be filled & the password must be the same in the two fields'));
450 Tools::redirect('?view=config');
451 }
452 }
453 }
454 }
455
456 public function updateTheme()
457 {
458 # no data
459 if (empty($_POST['theme'])) {
460 }
461
462 # we are not going to change it to the current theme...
463 if ($_POST['theme'] == $this->getTheme()) {
464 $this->messages->add('w', _('still using the "' . $this->getTheme() . '" theme!'));
465 Tools::redirect('?view=config');
466 }
467
468 $themes = $this->getInstalledThemes();
469 $actualTheme = false;
470
471 foreach ($themes as $theme) {
472 if ($theme['name'] == $_POST['theme']) {
473 $actualTheme = true;
474 break;
475 }
476 }
477
478 if (! $actualTheme) {
479 $this->messages->add('e', _('that theme does not seem to be installed'));
480 Tools::redirect('?view=config');
481 }
482
483 $this->store->updateUserConfig($this->user->getId(), 'theme', $_POST['theme']);
484 $this->messages->add('s', _('you have changed your theme preferences'));
485
486 $currentConfig = $_SESSION['poche_user']->config;
487 $currentConfig['theme'] = $_POST['theme'];
488
489 $_SESSION['poche_user']->setConfig($currentConfig);
490
491 Tools::redirect('?view=config');
492 }
493
494 /**
495 * checks if login & password are correct and save the user in session.
496 * it redirects the user to the $referer link
497 * @param string $referer the url to redirect after login
498 * @todo add the return value
499 * @return boolean
500 */
501 public function login($referer)
502 {
503 if (!empty($_POST['login']) && !empty($_POST['password'])) {
504 $user = $this->store->login($_POST['login'], Tools::encodeString($_POST['password'] . $_POST['login']));
505 if ($user != array()) {
506 # Save login into Session
507 Session::login($user['username'], $user['password'], $_POST['login'], Tools::encodeString($_POST['password'] . $_POST['login']), array('poche_user' => new User($user)));
508 $this->messages->add('s', _('welcome to your poche'));
509 Tools::logm('login successful');
510 Tools::redirect($referer);
511 }
512 $this->messages->add('e', _('login failed: bad login or password'));
513 Tools::logm('login failed');
514 Tools::redirect();
515 } else {
516 $this->messages->add('e', _('login failed: you have to fill all fields'));
517 Tools::logm('login failed');
518 Tools::redirect();
519 }
520 }
521
522 /**
523 * log out the poche user. It cleans the session.
524 * @todo add the return value
525 * @return boolean
526 */
527 public function logout()
528 {
529 $this->user = array();
530 Session::logout();
531 $this->messages->add('s', _('see you soon!'));
532 Tools::logm('logout');
533 Tools::redirect();
534 }
535
536 /**
537 * import from Instapaper. poche needs a ./instapaper-export.html file
538 * @todo add the return value
539 * @param string $targetFile the file used for importing
540 * @return boolean
541 */
542 private function importFromInstapaper($targetFile)
543 {
544 # TODO gestion des articles favs
545 $html = new simple_html_dom();
546 $html->load_file($targetFile);
547 Tools::logm('starting import from instapaper');
548
549 $read = 0;
550 $errors = array();
551 foreach($html->find('ol') as $ul)
552 {
553 foreach($ul->find('li') as $li)
554 {
555 $a = $li->find('a');
556 $url = new Url(base64_encode($a[0]->href));
557 $this->action('add', $url, 0, TRUE);
558 if ($read == '1') {
559 $sequence = '';
560 if (STORAGE == 'postgres') {
561 $sequence = 'entries_id_seq';
562 }
563 $last_id = $this->store->getLastId($sequence);
564 $this->action('toggle_archive', $url, $last_id, TRUE);
565 }
566 }
567
568 # the second <ol> is for read links
569 $read = 1;
570 }
571 $this->messages->add('s', _('import from instapaper completed'));
572 Tools::logm('import from instapaper completed');
573 Tools::redirect();
574 }
575
576 /**
577 * import from Pocket. poche needs a ./ril_export.html file
578 * @todo add the return value
579 * @param string $targetFile the file used for importing
580 * @return boolean
581 */
582 private function importFromPocket($targetFile)
583 {
584 # TODO gestion des articles favs
585 $html = new simple_html_dom();
586 $html->load_file($targetFile);
587 Tools::logm('starting import from pocket');
588
589 $read = 0;
590 $errors = array();
591 foreach($html->find('ul') as $ul)
592 {
593 foreach($ul->find('li') as $li)
594 {
595 $a = $li->find('a');
596 $url = new Url(base64_encode($a[0]->href));
597 $this->action('add', $url, 0, TRUE);
598 if ($read == '1') {
599 $sequence = '';
600 if (STORAGE == 'postgres') {
601 $sequence = 'entries_id_seq';
602 }
603 $last_id = $this->store->getLastId($sequence);
604 $this->action('toggle_archive', $url, $last_id, TRUE);
605 }
606 }
607
608 # the second <ul> is for read links
609 $read = 1;
610 }
611 $this->messages->add('s', _('import from pocket completed'));
612 Tools::logm('import from pocket completed');
613 Tools::redirect();
614 }
615
616 /**
617 * import from Readability. poche needs a ./readability file
618 * @todo add the return value
619 * @param string $targetFile the file used for importing
620 * @return boolean
621 */
622 private function importFromReadability($targetFile)
623 {
624 # TODO gestion des articles lus / favs
625 $str_data = file_get_contents($targetFile);
626 $data = json_decode($str_data,true);
627 Tools::logm('starting import from Readability');
628 $count = 0;
629 foreach ($data as $key => $value) {
630 $url = NULL;
631 $favorite = FALSE;
632 $archive = FALSE;
633 foreach ($value as $attr => $attr_value) {
634 if ($attr == 'article__url') {
635 $url = new Url(base64_encode($attr_value));
636 }
637 $sequence = '';
638 if (STORAGE == 'postgres') {
639 $sequence = 'entries_id_seq';
640 }
641 if ($attr_value == 'true') {
642 if ($attr == 'favorite') {
643 $favorite = TRUE;
644 }
645 if ($attr == 'archive') {
646 $archive = TRUE;
647 }
648 }
649 }
650 # we can add the url
651 if (!is_null($url) && $url->isCorrect()) {
652 $this->action('add', $url, 0, TRUE);
653 $count++;
654 if ($favorite) {
655 $last_id = $this->store->getLastId($sequence);
656 $this->action('toggle_fav', $url, $last_id, TRUE);
657 }
658 if ($archive) {
659 $last_id = $this->store->getLastId($sequence);
660 $this->action('toggle_archive', $url, $last_id, TRUE);
661 }
662 }
663 }
664 $this->messages->add('s', _('import from Readability completed. ' . $count . ' new links.'));
665 Tools::logm('import from Readability completed');
666 Tools::redirect();
667 }
668
669 /**
670 * import datas into your poche
671 * @param string $from name of the service to import : pocket, instapaper or readability
672 * @todo add the return value
673 * @return boolean
674 */
675 public function import($from)
676 {
677 $providers = array(
678 'pocket' => 'importFromPocket',
679 'readability' => 'importFromReadability',
680 'instapaper' => 'importFromInstapaper'
681 );
682
683 if (! isset($providers[$from])) {
684 $this->messages->add('e', _('Unknown import provider.'));
685 Tools::redirect();
686 }
687
688 $targetDefinition = 'IMPORT_' . strtoupper($from) . '_FILE';
689 $targetFile = constant($targetDefinition);
690
691 if (! defined($targetDefinition)) {
692 $this->messages->add('e', _('Incomplete inc/poche/define.inc.php file, please define "' . $targetDefinition . '".'));
693 Tools::redirect();
694 }
695
696 if (! file_exists($targetFile)) {
697 $this->messages->add('e', _('Could not find required "' . $targetFile . '" import file.'));
698 Tools::redirect();
699 }
700
701 $this->$providers[$from]($targetFile);
702 }
703
704 /**
705 * export poche entries in json
706 * @return json all poche entries
707 */
708 public function export()
709 {
710 $entries = $this->store->retrieveAll($this->user->getId());
711 echo $this->tpl->render('export.twig', array(
712 'export' => Tools::renderJson($entries),
713 ));
714 Tools::logm('export view');
715 }
716
717 /**
718 * Checks online the latest version of poche and cache it
719 * @param string $which 'prod' or 'dev'
720 * @return string latest $which version
721 */
722 private function getPocheVersion($which = 'prod')
723 {
724 $cache_file = CACHE . '/' . $which;
725
726 # checks if the cached version file exists
727 if (file_exists($cache_file) && (filemtime($cache_file) > (time() - 86400 ))) {
728 $version = file_get_contents($cache_file);
729 } else {
730 $version = file_get_contents('http://static.inthepoche.com/versions/' . $which);
731 file_put_contents($cache_file, $version, LOCK_EX);
732 }
733 return $version;
734 }
735 }