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