]> git.immae.eu Git - github/wallabag/wallabag.git/blob - inc/poche/Poche.class.php
fefbb02dd24d3a5c25c90ff8910d84f278cb2065
[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 $json = file_get_contents(Tools::getPocheUrl() . '/inc/3rdparty/makefulltextfeed.php?url='.urlencode($url->getUrl()).'&max=5&links=preserve&exc=&format=json&submit=Create+Feed');
336 $content = json_decode($json, true);
337 $title = $content['rss']['channel']['item']['title'];
338 $body = $content['rss']['channel']['item']['description'];
339
340 if ($this->store->add($url->getUrl(), $title, $body, $this->user->getId())) {
341 Tools::logm('add link ' . $url->getUrl());
342 $sequence = '';
343 if (STORAGE == 'postgres') {
344 $sequence = 'entries_id_seq';
345 }
346 $last_id = $this->store->getLastId($sequence);
347 if (DOWNLOAD_PICTURES) {
348 $content = filtre_picture($body, $url->getUrl(), $last_id);
349 Tools::logm('updating content article');
350 $this->store->updateContent($last_id, $content, $this->user->getId());
351 }
352 if (!$import) {
353 $this->messages->add('s', _('the link has been added successfully'));
354 }
355 }
356 else {
357 if (!$import) {
358 $this->messages->add('e', _('error during insertion : the link wasn\'t added'));
359 Tools::logm('error during insertion : the link wasn\'t added ' . $url->getUrl());
360 }
361 }
362
363 if (!$import) {
364 if ($autoclose == TRUE) {
365 Tools::redirect('?view=home');
366 } else {
367 Tools::redirect('?view=home&closewin=true');
368 }
369 }
370 break;
371 case 'delete':
372 $msg = 'delete link #' . $id;
373 if ($this->store->deleteById($id, $this->user->getId())) {
374 if (DOWNLOAD_PICTURES) {
375 remove_directory(ABS_PATH . $id);
376 }
377 $this->messages->add('s', _('the link has been deleted successfully'));
378 }
379 else {
380 $this->messages->add('e', _('the link wasn\'t deleted'));
381 $msg = 'error : can\'t delete link #' . $id;
382 }
383 Tools::logm($msg);
384 Tools::redirect('?');
385 break;
386 case 'toggle_fav' :
387 $this->store->favoriteById($id, $this->user->getId());
388 Tools::logm('mark as favorite link #' . $id);
389 if (!$import) {
390 Tools::redirect();
391 }
392 break;
393 case 'toggle_archive' :
394 $this->store->archiveById($id, $this->user->getId());
395 Tools::logm('archive link #' . $id);
396 if (!$import) {
397 Tools::redirect();
398 }
399 break;
400 default:
401 break;
402 }
403 }
404
405 function displayView($view, $id = 0)
406 {
407 $tpl_vars = array();
408
409 switch ($view)
410 {
411 case 'config':
412 $dev = $this->getPocheVersion('dev');
413 $prod = $this->getPocheVersion('prod');
414 $compare_dev = version_compare(POCHE, $dev);
415 $compare_prod = version_compare(POCHE, $prod);
416 $themes = $this->getInstalledThemes();
417 $languages = $this->getInstalledLanguages();
418 $token = $this->user->getConfigValue('token');
419 $http_auth = (isset($_SERVER['PHP_AUTH_USER']))?true:false;
420 $tpl_vars = array(
421 'themes' => $themes,
422 'languages' => $languages,
423 'dev' => $dev,
424 'prod' => $prod,
425 'compare_dev' => $compare_dev,
426 'compare_prod' => $compare_prod,
427 'token' => $token,
428 'user_id' => $this->user->getId(),
429 'http_auth' => $http_auth,
430 );
431 Tools::logm('config view');
432 break;
433 case 'edit-tags':
434 # tags
435 $tags = $this->store->retrieveTagsByEntry($id);
436 $tpl_vars = array(
437 'tags' => $tags,
438 );
439 break;
440 case 'tag':
441 $entries = $this->store->retrieveEntriesByTag($id);
442 $tag = $this->store->retrieveTag($id);
443 $tpl_vars = array(
444 'tag' => $tag,
445 'entries' => $entries,
446 );
447 break;
448 case 'tags':
449 $tags = $this->store->retrieveAllTags();
450 $tpl_vars = array(
451 'tags' => $tags,
452 );
453 break;
454 case 'view':
455 $entry = $this->store->retrieveOneById($id, $this->user->getId());
456 if ($entry != NULL) {
457 Tools::logm('view link #' . $id);
458 $content = $entry['content'];
459 if (function_exists('tidy_parse_string')) {
460 $tidy = tidy_parse_string($content, array('indent'=>true, 'show-body-only' => true), 'UTF8');
461 $tidy->cleanRepair();
462 $content = $tidy->value;
463 }
464
465 # flattr checking
466 $flattr = new FlattrItem();
467 $flattr->checkItem($entry['url'], $entry['id']);
468
469 # tags
470 $tags = $this->store->retrieveTagsByEntry($entry['id']);
471
472 $tpl_vars = array(
473 'entry' => $entry,
474 'content' => $content,
475 'flattr' => $flattr,
476 'tags' => $tags
477 );
478 }
479 else {
480 Tools::logm('error in view call : entry is null');
481 }
482 break;
483 default: # home, favorites and archive views
484 $entries = $this->store->getEntriesByView($view, $this->user->getId());
485 $tpl_vars = array(
486 'entries' => '',
487 'page_links' => '',
488 'nb_results' => '',
489 );
490
491 if (count($entries) > 0) {
492 $this->pagination->set_total(count($entries));
493 $page_links = $this->pagination->page_links('?view=' . $view . '&sort=' . $_SESSION['sort'] . '&');
494 $datas = $this->store->getEntriesByView($view, $this->user->getId(), $this->pagination->get_limit());
495 $tpl_vars['entries'] = $datas;
496 $tpl_vars['page_links'] = $page_links;
497 $tpl_vars['nb_results'] = count($entries);
498 }
499 Tools::logm('display ' . $view . ' view');
500 break;
501 }
502
503 return $tpl_vars;
504 }
505
506 /**
507 * update the password of the current user.
508 * if MODE_DEMO is TRUE, the password can't be updated.
509 * @todo add the return value
510 * @todo set the new password in function header like this updatePassword($newPassword)
511 * @return boolean
512 */
513 public function updatePassword()
514 {
515 if (MODE_DEMO) {
516 $this->messages->add('i', _('in demo mode, you can\'t update your password'));
517 Tools::logm('in demo mode, you can\'t do this');
518 Tools::redirect('?view=config');
519 }
520 else {
521 if (isset($_POST['password']) && isset($_POST['password_repeat'])) {
522 if ($_POST['password'] == $_POST['password_repeat'] && $_POST['password'] != "") {
523 $this->messages->add('s', _('your password has been updated'));
524 $this->store->updatePassword($this->user->getId(), Tools::encodeString($_POST['password'] . $this->user->getUsername()));
525 Session::logout();
526 Tools::logm('password updated');
527 Tools::redirect();
528 }
529 else {
530 $this->messages->add('e', _('the two fields have to be filled & the password must be the same in the two fields'));
531 Tools::redirect('?view=config');
532 }
533 }
534 }
535 }
536
537 public function updateTheme()
538 {
539 # no data
540 if (empty($_POST['theme'])) {
541 }
542
543 # we are not going to change it to the current theme...
544 if ($_POST['theme'] == $this->getTheme()) {
545 $this->messages->add('w', _('still using the "' . $this->getTheme() . '" theme!'));
546 Tools::redirect('?view=config');
547 }
548
549 $themes = $this->getInstalledThemes();
550 $actualTheme = false;
551
552 foreach ($themes as $theme) {
553 if ($theme['name'] == $_POST['theme']) {
554 $actualTheme = true;
555 break;
556 }
557 }
558
559 if (! $actualTheme) {
560 $this->messages->add('e', _('that theme does not seem to be installed'));
561 Tools::redirect('?view=config');
562 }
563
564 $this->store->updateUserConfig($this->user->getId(), 'theme', $_POST['theme']);
565 $this->messages->add('s', _('you have changed your theme preferences'));
566
567 $currentConfig = $_SESSION['poche_user']->config;
568 $currentConfig['theme'] = $_POST['theme'];
569
570 $_SESSION['poche_user']->setConfig($currentConfig);
571
572 Tools::redirect('?view=config');
573 }
574
575 public function updateLanguage()
576 {
577 # no data
578 if (empty($_POST['language'])) {
579 }
580
581 # we are not going to change it to the current language...
582 if ($_POST['language'] == $this->getLanguage()) {
583 $this->messages->add('w', _('still using the "' . $this->getLanguage() . '" language!'));
584 Tools::redirect('?view=config');
585 }
586
587 $languages = $this->getInstalledLanguages();
588 $actualLanguage = false;
589
590 foreach ($languages as $language) {
591 if ($language['name'] == $_POST['language']) {
592 $actualLanguage = true;
593 break;
594 }
595 }
596
597 if (! $actualLanguage) {
598 $this->messages->add('e', _('that language does not seem to be installed'));
599 Tools::redirect('?view=config');
600 }
601
602 $this->store->updateUserConfig($this->user->getId(), 'language', $_POST['language']);
603 $this->messages->add('s', _('you have changed your language preferences'));
604
605 $currentConfig = $_SESSION['poche_user']->config;
606 $currentConfig['language'] = $_POST['language'];
607
608 $_SESSION['poche_user']->setConfig($currentConfig);
609
610 Tools::redirect('?view=config');
611 }
612
613 /**
614 * get credentials from differents sources
615 * it redirects the user to the $referer link
616 * @return array
617 */
618 private function credentials() {
619 if(isset($_SERVER['PHP_AUTH_USER'])) {
620 return array($_SERVER['PHP_AUTH_USER'],'php_auth');
621 }
622 if(!empty($_POST['login']) && !empty($_POST['password'])) {
623 return array($_POST['login'],$_POST['password']);
624 }
625 return array(false,false);
626 }
627
628 /**
629 * checks if login & password are correct and save the user in session.
630 * it redirects the user to the $referer link
631 * @param string $referer the url to redirect after login
632 * @todo add the return value
633 * @return boolean
634 */
635 public function login($referer)
636 {
637 list($login,$password)=$this->credentials();
638 if($login === false || $password === false) {
639 $this->messages->add('e', _('login failed: you have to fill all fields'));
640 Tools::logm('login failed');
641 Tools::redirect();
642 }
643 if (!empty($login) && !empty($password)) {
644 $user = $this->store->login($login, Tools::encodeString($password . $login));
645 if ($user != array()) {
646 # Save login into Session
647 Session::login($user['username'], $user['password'], $login, Tools::encodeString($password . $login), array('poche_user' => new User($user)));
648 $this->messages->add('s', _('welcome to your poche'));
649 Tools::logm('login successful');
650 Tools::redirect($referer);
651 }
652 $this->messages->add('e', _('login failed: bad login or password'));
653 Tools::logm('login failed');
654 Tools::redirect();
655 }
656 }
657
658 /**
659 * log out the poche user. It cleans the session.
660 * @todo add the return value
661 * @return boolean
662 */
663 public function logout()
664 {
665 $this->user = array();
666 Session::logout();
667 $this->messages->add('s', _('see you soon!'));
668 Tools::logm('logout');
669 Tools::redirect();
670 }
671
672 /**
673 * import from Instapaper. poche needs a ./instapaper-export.html file
674 * @todo add the return value
675 * @param string $targetFile the file used for importing
676 * @return boolean
677 */
678 private function importFromInstapaper($targetFile)
679 {
680 # TODO gestion des articles favs
681 $html = new simple_html_dom();
682 $html->load_file($targetFile);
683 Tools::logm('starting import from instapaper');
684
685 $read = 0;
686 $errors = array();
687 foreach($html->find('ol') as $ul)
688 {
689 foreach($ul->find('li') as $li)
690 {
691 $a = $li->find('a');
692 $url = new Url(base64_encode($a[0]->href));
693 $this->action('add', $url, 0, TRUE);
694 if ($read == '1') {
695 $sequence = '';
696 if (STORAGE == 'postgres') {
697 $sequence = 'entries_id_seq';
698 }
699 $last_id = $this->store->getLastId($sequence);
700 $this->action('toggle_archive', $url, $last_id, TRUE);
701 }
702 }
703
704 # the second <ol> is for read links
705 $read = 1;
706 }
707 $this->messages->add('s', _('import from instapaper completed'));
708 Tools::logm('import from instapaper completed');
709 Tools::redirect();
710 }
711
712 /**
713 * import from Pocket. poche needs a ./ril_export.html file
714 * @todo add the return value
715 * @param string $targetFile the file used for importing
716 * @return boolean
717 */
718 private function importFromPocket($targetFile)
719 {
720 # TODO gestion des articles favs
721 $html = new simple_html_dom();
722 $html->load_file($targetFile);
723 Tools::logm('starting import from pocket');
724
725 $read = 0;
726 $errors = array();
727 foreach($html->find('ul') as $ul)
728 {
729 foreach($ul->find('li') as $li)
730 {
731 $a = $li->find('a');
732 $url = new Url(base64_encode($a[0]->href));
733 $this->action('add', $url, 0, TRUE);
734 if ($read == '1') {
735 $sequence = '';
736 if (STORAGE == 'postgres') {
737 $sequence = 'entries_id_seq';
738 }
739 $last_id = $this->store->getLastId($sequence);
740 $this->action('toggle_archive', $url, $last_id, TRUE);
741 }
742 }
743
744 # the second <ul> is for read links
745 $read = 1;
746 }
747 $this->messages->add('s', _('import from pocket completed'));
748 Tools::logm('import from pocket completed');
749 Tools::redirect();
750 }
751
752 /**
753 * import from Readability. poche needs a ./readability file
754 * @todo add the return value
755 * @param string $targetFile the file used for importing
756 * @return boolean
757 */
758 private function importFromReadability($targetFile)
759 {
760 # TODO gestion des articles lus / favs
761 $str_data = file_get_contents($targetFile);
762 $data = json_decode($str_data,true);
763 Tools::logm('starting import from Readability');
764 $count = 0;
765 foreach ($data as $key => $value) {
766 $url = NULL;
767 $favorite = FALSE;
768 $archive = FALSE;
769 foreach ($value as $attr => $attr_value) {
770 if ($attr == 'article__url') {
771 $url = new Url(base64_encode($attr_value));
772 }
773 $sequence = '';
774 if (STORAGE == 'postgres') {
775 $sequence = 'entries_id_seq';
776 }
777 if ($attr_value == 'true') {
778 if ($attr == 'favorite') {
779 $favorite = TRUE;
780 }
781 if ($attr == 'archive') {
782 $archive = TRUE;
783 }
784 }
785 }
786 # we can add the url
787 if (!is_null($url) && $url->isCorrect()) {
788 $this->action('add', $url, 0, TRUE);
789 $count++;
790 if ($favorite) {
791 $last_id = $this->store->getLastId($sequence);
792 $this->action('toggle_fav', $url, $last_id, TRUE);
793 }
794 if ($archive) {
795 $last_id = $this->store->getLastId($sequence);
796 $this->action('toggle_archive', $url, $last_id, TRUE);
797 }
798 }
799 }
800 $this->messages->add('s', _('import from Readability completed. ' . $count . ' new links.'));
801 Tools::logm('import from Readability completed');
802 Tools::redirect();
803 }
804
805 /**
806 * import datas into your poche
807 * @param string $from name of the service to import : pocket, instapaper or readability
808 * @todo add the return value
809 * @return boolean
810 */
811 public function import($from)
812 {
813 $providers = array(
814 'pocket' => 'importFromPocket',
815 'readability' => 'importFromReadability',
816 'instapaper' => 'importFromInstapaper'
817 );
818
819 if (! isset($providers[$from])) {
820 $this->messages->add('e', _('Unknown import provider.'));
821 Tools::redirect();
822 }
823
824 $targetDefinition = 'IMPORT_' . strtoupper($from) . '_FILE';
825 $targetFile = constant($targetDefinition);
826
827 if (! defined($targetDefinition)) {
828 $this->messages->add('e', _('Incomplete inc/poche/define.inc.php file, please define "' . $targetDefinition . '".'));
829 Tools::redirect();
830 }
831
832 if (! file_exists($targetFile)) {
833 $this->messages->add('e', _('Could not find required "' . $targetFile . '" import file.'));
834 Tools::redirect();
835 }
836
837 $this->$providers[$from]($targetFile);
838 }
839
840 /**
841 * export poche entries in json
842 * @return json all poche entries
843 */
844 public function export()
845 {
846 $entries = $this->store->retrieveAll($this->user->getId());
847 echo $this->tpl->render('export.twig', array(
848 'export' => Tools::renderJson($entries),
849 ));
850 Tools::logm('export view');
851 }
852
853 /**
854 * Checks online the latest version of poche and cache it
855 * @param string $which 'prod' or 'dev'
856 * @return string latest $which version
857 */
858 private function getPocheVersion($which = 'prod')
859 {
860 $cache_file = CACHE . '/' . $which;
861
862 # checks if the cached version file exists
863 if (file_exists($cache_file) && (filemtime($cache_file) > (time() - 86400 ))) {
864 $version = file_get_contents($cache_file);
865 } else {
866 $version = file_get_contents('http://static.inthepoche.com/versions/' . $which);
867 file_put_contents($cache_file, $version, LOCK_EX);
868 }
869 return $version;
870 }
871
872 public function generateToken()
873 {
874 if (ini_get('open_basedir') === '') {
875 $token = substr(base64_encode(file_get_contents('/dev/urandom', false, null, 0, 20)), 0, 15);
876 }
877 else {
878 $token = substr(base64_encode(uniqid(mt_rand(), true)), 0, 20);
879 }
880
881 $this->store->updateUserConfig($this->user->getId(), 'token', $token);
882 $currentConfig = $_SESSION['poche_user']->config;
883 $currentConfig['token'] = $token;
884 $_SESSION['poche_user']->setConfig($currentConfig);
885 }
886
887 public function generateFeeds($token, $user_id, $type = 'home')
888 {
889 $allowed_types = array('home', 'fav', 'archive');
890 $config = $this->store->getConfigUser($user_id);
891
892 if (!in_array($type, $allowed_types) ||
893 $token != $config['token']) {
894 die(_('Uh, there is a problem while generating feeds.'));
895 }
896 // Check the token
897
898 $feed = new FeedWriter(RSS2);
899 $feed->setTitle('poche - ' . $type . ' feed');
900 $feed->setLink(Tools::getPocheUrl());
901 $feed->setChannelElement('updated', date(DATE_RSS , time()));
902 $feed->setChannelElement('author', 'poche');
903
904 $entries = $this->store->getEntriesByView($type, $user_id);
905 if (count($entries) > 0) {
906 foreach ($entries as $entry) {
907 $newItem = $feed->createNewItem();
908 $newItem->setTitle(htmlentities($entry['title']));
909 $newItem->setLink(Tools::getPocheUrl() . '?view=view&amp;id=' . $entry['id']);
910 $newItem->setDate(time());
911 $newItem->setDescription($entry['content']);
912 $feed->addItem($newItem);
913 }
914 }
915
916 $feed->genarateFeed();
917 exit;
918 }
919 }