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