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