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