]> git.immae.eu Git - github/wallabag/wallabag.git/blame - inc/poche/Poche.class.php
bug fix #215: change language from config screen
[github/wallabag/wallabag.git] / inc / poche / Poche.class.php
CommitLineData
eb1af592
NL
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
11class Poche
12{
00dbaf90
NL
13 public static $canRenderTemplates = true;
14 public static $configFileAvailable = true;
15
7ce7ec4c 16 public $user;
eb1af592
NL
17 public $store;
18 public $tpl;
55821e04 19 public $messages;
6a361945 20 public $pagination;
00dbaf90
NL
21
22 private $currentTheme = '';
5011388f 23 private $currentLanguage = '';
9d3b88b3 24 private $notInstalledMessage = array();
00dbaf90
NL
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 );
eb1af592 34
00dbaf90 35 public function __construct()
eb1af592 36 {
9d3b88b3
NL
37 if ($this->configFileIsAvailable()) {
38 $this->init();
00dbaf90
NL
39 }
40
9d3b88b3
NL
41 if ($this->themeIsInstalled()) {
42 $this->initTpl();
00dbaf90
NL
43 }
44
9d3b88b3
NL
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 }
eb1af592 52 }
eb1af592 53 }
00dbaf90
NL
54
55 private function init()
56 {
57 Tools::initPhp();
58 Session::$sessionName = 'poche';
59 Session::init();
eb1af592 60
00dbaf90
NL
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;
5011388f
NL
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;
00dbaf90
NL
96 }
97
98 public function configFileIsAvailable() {
99 if (! self::$configFileAvailable) {
9d3b88b3 100 $this->notInstalledMessage[] = 'You have to rename inc/poche/config.inc.php.new to inc/poche/config.inc.php.';
00dbaf90
NL
101
102 return false;
103 }
104
105 return true;
106 }
107
108 public function themeIsInstalled() {
9d3b88b3 109 $passTheme = TRUE;
00dbaf90
NL
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) {
9d3b88b3
NL
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;
00dbaf90 114 }
7f17a38d
NL
115
116 if (! is_writable(CACHE)) {
9d3b88b3 117 $this->notInstalledMessage[] = 'You don\'t have write access on cache directory.';
7f17a38d
NL
118
119 self::$canRenderTemplates = false;
120
9d3b88b3 121 $passTheme = FALSE;
7f17a38d 122 }
00dbaf90
NL
123
124 # Check if the selected theme and its requirements are present
9d3b88b3
NL
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() . ')';
00dbaf90
NL
127
128 self::$canRenderTemplates = false;
129
9d3b88b3 130 $passTheme = FALSE;
00dbaf90
NL
131 }
132
133 foreach ($this->installedThemes[$this->getTheme()]['requires'] as $requiredTheme) {
134 if (! is_dir(THEME . '/' . $requiredTheme)) {
9d3b88b3 135 $this->notInstalledMessage[] = 'The required "' . $requiredTheme . '" theme is missing for the current theme (' . $this->getTheme() . ')';
00dbaf90
NL
136
137 self::$canRenderTemplates = false;
138
9d3b88b3 139 $passTheme = FALSE;
00dbaf90
NL
140 }
141 }
9d3b88b3
NL
142
143 if (!$passTheme) {
144 return FALSE;
145 }
146
00dbaf90
NL
147
148 return true;
149 }
150
4a291288
NL
151 /**
152 * all checks before installation.
00dbaf90 153 * @todo move HTML to template
4a291288
NL
154 * @return boolean
155 */
00dbaf90 156 public function systemIsInstalled()
eb1af592 157 {
9d3b88b3 158 $msg = TRUE;
00dbaf90
NL
159
160 $configSalt = defined('SALT') ? constant('SALT') : '';
161
162 if (empty($configSalt)) {
9d3b88b3
NL
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)) {
00dbaf90 167 Tools::logm('sqlite file doesn\'t exist');
9d3b88b3
NL
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)) {
bb5a7d9e 176 Tools::logm('you don\'t have write access on sqlite file');
9d3b88b3
NL
177 $this->notInstalledMessage[] = 'You don\'t have write access on sqlite file.';
178 $msg = FALSE;
bb5a7d9e 179 }
00dbaf90 180
9d3b88b3 181 if (! $msg) {
00dbaf90 182 return false;
8d3275be 183 }
7ce7ec4c 184
00dbaf90
NL
185 return true;
186 }
187
188 public function getNotInstalledMessage() {
189 return $this->notInstalledMessage;
4a291288 190 }
eb1af592 191
4a291288
NL
192 private function initTpl()
193 {
00dbaf90
NL
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
bc1ee852
NL
214 if (DEBUG_POCHE) {
215 $twig_params = array();
00dbaf90 216 } else {
bc1ee852
NL
217 $twig_params = array('cache' => CACHE);
218 }
00dbaf90
NL
219
220 $this->tpl = new Twig_Environment($loaderChain, $twig_params);
eb1af592 221 $this->tpl->addExtension(new Twig_Extensions_Extension_I18n());
00dbaf90 222
55821e04
NL
223 # filter to display domain name of an url
224 $filter = new Twig_SimpleFilter('getDomain', 'Tools::getDomain');
225 $this->tpl->addFilter($filter);
eb1af592 226
d9178758
NL
227 # filter for reading time
228 $filter = new Twig_SimpleFilter('getReadingTime', 'Tools::getReadingTime');
229 $this->tpl->addFilter($filter);
00dbaf90
NL
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);
eb1af592
NL
234 }
235
236 private function install()
237 {
238 Tools::logm('poche still not installed');
239 echo $this->tpl->render('install.twig', array(
00dbaf90
NL
240 'token' => Session::getToken(),
241 'theme' => $this->getTheme(),
242 'poche_url' => Tools::getPocheUrl()
eb1af592
NL
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 !
bb5a7d9e
NL
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 }
6a361945
NL
254 }
255 else {
256 Tools::logm('error during installation');
eb1af592
NL
257 Tools::redirect();
258 }
259 }
260 exit();
261 }
00dbaf90
NL
262
263 public function getTheme() {
264 return $this->currentTheme;
265 }
5011388f
NL
266
267 public function getLanguage() {
268 return $this->currentLanguage;
269 }
00dbaf90
NL
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
3cc22aab 278 if (! is_dir(THEME . '/' . $theme) || in_array($theme, array('..', '.', '.git'))) {
00dbaf90
NL
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 return $themes;
292 }
eb1af592 293
5011388f
NL
294 public function getInstalledLanguages() {
295 $handle = opendir(LOCALE);
296 $languages = array();
297
298 while (($language = readdir($handle)) !== false) {
299 # Languages are stored in a directory, so all directory names are languages
300 # @todo move language installation data to database
301 if (! is_dir(LOCALE . '/' . $language) || in_array($language, array('..', '.'))) {
302 continue;
303 }
304
305 $current = false;
306
307 if ($language === $this->getLanguage()) {
308 $current = true;
309 }
310
311 $languages[] = array('name' => $language, 'current' => $current);
312 }
313
314 return $languages;
315 }
316
8d3275be 317 public function getDefaultConfig()
00dbaf90 318 {
8d3275be
NL
319 return array(
320 'pager' => PAGINATION,
321 'language' => LANG,
00dbaf90
NL
322 'theme' => DEFAULT_THEME
323 );
8d3275be
NL
324 }
325
eb1af592
NL
326 /**
327 * Call action (mark as fav, archive, delete, etc.)
328 */
b916bcfc 329 public function action($action, Url $url, $id = 0, $import = FALSE)
eb1af592
NL
330 {
331 switch ($action)
332 {
333 case 'add':
ec397236
NL
334 $content = $url->extract();
335
336 if ($this->store->add($url->getUrl(), $content['title'], $content['body'], $this->user->getId())) {
337 Tools::logm('add link ' . $url->getUrl());
338 $sequence = '';
339 if (STORAGE == 'postgres') {
340 $sequence = 'entries_id_seq';
eb1af592 341 }
ec397236
NL
342 $last_id = $this->store->getLastId($sequence);
343 if (DOWNLOAD_PICTURES) {
6fb46003 344 $content = filtre_picture($content['body'], $url->getUrl(), $last_id);
ec397236
NL
345 Tools::logm('updating content article');
346 $this->store->updateContent($last_id, $content, $this->user->getId());
347 }
348 if (!$import) {
349 $this->messages->add('s', _('the link has been added successfully'));
eb1af592
NL
350 }
351 }
352 else {
b916bcfc 353 if (!$import) {
ec397236
NL
354 $this->messages->add('e', _('error during insertion : the link wasn\'t added'));
355 Tools::logm('error during insertion : the link wasn\'t added ' . $url->getUrl());
b916bcfc
NL
356 }
357 }
ec397236 358
b916bcfc 359 if (!$import) {
ce4a1dcc 360 Tools::redirect('?view=home');
eb1af592
NL
361 }
362 break;
363 case 'delete':
bc1ee852 364 $msg = 'delete link #' . $id;
8d3275be 365 if ($this->store->deleteById($id, $this->user->getId())) {
eb1af592
NL
366 if (DOWNLOAD_PICTURES) {
367 remove_directory(ABS_PATH . $id);
368 }
6a361945 369 $this->messages->add('s', _('the link has been deleted successfully'));
eb1af592
NL
370 }
371 else {
6a361945 372 $this->messages->add('e', _('the link wasn\'t deleted'));
bc1ee852 373 $msg = 'error : can\'t delete link #' . $id;
eb1af592 374 }
bc1ee852 375 Tools::logm($msg);
6cd8af85 376 Tools::redirect();
eb1af592
NL
377 break;
378 case 'toggle_fav' :
8d3275be 379 $this->store->favoriteById($id, $this->user->getId());
eb1af592 380 Tools::logm('mark as favorite link #' . $id);
b916bcfc
NL
381 if (!$import) {
382 Tools::redirect();
383 }
eb1af592
NL
384 break;
385 case 'toggle_archive' :
8d3275be 386 $this->store->archiveById($id, $this->user->getId());
eb1af592 387 Tools::logm('archive link #' . $id);
b916bcfc
NL
388 if (!$import) {
389 Tools::redirect();
390 }
eb1af592
NL
391 break;
392 default:
393 break;
394 }
395 }
396
397 function displayView($view, $id = 0)
398 {
399 $tpl_vars = array();
400
401 switch ($view)
402 {
eb1af592 403 case 'config':
32520785
NL
404 $dev = $this->getPocheVersion('dev');
405 $prod = $this->getPocheVersion('prod');
031df528
NL
406 $compare_dev = version_compare(POCHE, $dev);
407 $compare_prod = version_compare(POCHE, $prod);
00dbaf90 408 $themes = $this->getInstalledThemes();
5011388f 409 $languages = $this->getInstalledLanguages();
32520785 410 $tpl_vars = array(
00dbaf90 411 'themes' => $themes,
5011388f 412 'languages' => $languages,
32520785
NL
413 'dev' => $dev,
414 'prod' => $prod,
415 'compare_dev' => $compare_dev,
416 'compare_prod' => $compare_prod,
417 );
eb1af592
NL
418 Tools::logm('config view');
419 break;
420 case 'view':
8d3275be 421 $entry = $this->store->retrieveOneById($id, $this->user->getId());
eb1af592
NL
422 if ($entry != NULL) {
423 Tools::logm('view link #' . $id);
424 $content = $entry['content'];
425 if (function_exists('tidy_parse_string')) {
426 $tidy = tidy_parse_string($content, array('indent'=>true, 'show-body-only' => true), 'UTF8');
427 $tidy->cleanRepair();
428 $content = $tidy->value;
3408ed48 429 }
a3223127 430
3408ed48
NL
431 # flattr checking
432 $flattr = new FlattrItem();
4e5b0411 433 $flattr->checkItem($entry['url'],$entry['id']);
a3223127 434
3408ed48
NL
435 $tpl_vars = array(
436 'entry' => $entry,
437 'content' => $content,
438 'flattr' => $flattr
439 );
eb1af592
NL
440 }
441 else {
d8d1542e 442 Tools::logm('error in view call : entry is null');
eb1af592
NL
443 }
444 break;
12d9cfbc 445 default: # home, favorites and archive views
8d3275be 446 $entries = $this->store->getEntriesByView($view, $this->user->getId());
eb1af592 447 $tpl_vars = array(
3eb04903
N
448 'entries' => '',
449 'page_links' => '',
7f9f5281 450 'nb_results' => '',
eb1af592 451 );
34d67c83 452
3eb04903
N
453 if (count($entries) > 0) {
454 $this->pagination->set_total(count($entries));
455 $page_links = $this->pagination->page_links('?view=' . $view . '&sort=' . $_SESSION['sort'] . '&');
456 $datas = $this->store->getEntriesByView($view, $this->user->getId(), $this->pagination->get_limit());
457 $tpl_vars['entries'] = $datas;
458 $tpl_vars['page_links'] = $page_links;
7f9f5281 459 $tpl_vars['nb_results'] = count($entries);
3eb04903 460 }
6a361945 461 Tools::logm('display ' . $view . ' view');
eb1af592
NL
462 break;
463 }
464
465 return $tpl_vars;
466 }
c765c367 467
07ee09f4
NL
468 /**
469 * update the password of the current user.
470 * if MODE_DEMO is TRUE, the password can't be updated.
471 * @todo add the return value
472 * @todo set the new password in function header like this updatePassword($newPassword)
473 * @return boolean
474 */
c765c367
NL
475 public function updatePassword()
476 {
55821e04 477 if (MODE_DEMO) {
8d3275be 478 $this->messages->add('i', _('in demo mode, you can\'t update your password'));
55821e04 479 Tools::logm('in demo mode, you can\'t do this');
6a361945 480 Tools::redirect('?view=config');
55821e04
NL
481 }
482 else {
483 if (isset($_POST['password']) && isset($_POST['password_repeat'])) {
484 if ($_POST['password'] == $_POST['password_repeat'] && $_POST['password'] != "") {
8d3275be
NL
485 $this->messages->add('s', _('your password has been updated'));
486 $this->store->updatePassword($this->user->getId(), Tools::encodeString($_POST['password'] . $this->user->getUsername()));
c765c367 487 Session::logout();
8d3275be 488 Tools::logm('password updated');
c765c367
NL
489 Tools::redirect();
490 }
491 else {
8d3275be 492 $this->messages->add('e', _('the two fields have to be filled & the password must be the same in the two fields'));
6a361945 493 Tools::redirect('?view=config');
c765c367
NL
494 }
495 }
496 }
497 }
00dbaf90
NL
498
499 public function updateTheme()
500 {
501 # no data
502 if (empty($_POST['theme'])) {
503 }
504
505 # we are not going to change it to the current theme...
506 if ($_POST['theme'] == $this->getTheme()) {
507 $this->messages->add('w', _('still using the "' . $this->getTheme() . '" theme!'));
508 Tools::redirect('?view=config');
509 }
510
511 $themes = $this->getInstalledThemes();
512 $actualTheme = false;
513
514 foreach ($themes as $theme) {
515 if ($theme['name'] == $_POST['theme']) {
516 $actualTheme = true;
517 break;
518 }
519 }
520
521 if (! $actualTheme) {
522 $this->messages->add('e', _('that theme does not seem to be installed'));
523 Tools::redirect('?view=config');
524 }
525
526 $this->store->updateUserConfig($this->user->getId(), 'theme', $_POST['theme']);
527 $this->messages->add('s', _('you have changed your theme preferences'));
528
529 $currentConfig = $_SESSION['poche_user']->config;
530 $currentConfig['theme'] = $_POST['theme'];
531
532 $_SESSION['poche_user']->setConfig($currentConfig);
533
534 Tools::redirect('?view=config');
535 }
c765c367 536
5011388f
NL
537 public function updateLanguage()
538 {
539 # no data
540 if (empty($_POST['language'])) {
541 }
542
543 # we are not going to change it to the current language...
544 if ($_POST['language'] == $this->getLanguage()) {
545 $this->messages->add('w', _('still using the "' . $this->getLanguage() . '" language!'));
546 Tools::redirect('?view=config');
547 }
548
549 $languages = $this->getInstalledLanguages();
550 $actualLanguage = false;
551
552 foreach ($languages as $language) {
553 if ($language['name'] == $_POST['language']) {
554 $actualLanguage = true;
555 break;
556 }
557 }
558
559 if (! $actualLanguage) {
560 $this->messages->add('e', _('that language does not seem to be installed'));
561 Tools::redirect('?view=config');
562 }
563
564 $this->store->updateUserConfig($this->user->getId(), 'language', $_POST['language']);
565 $this->messages->add('s', _('you have changed your language preferences'));
566
567 $currentConfig = $_SESSION['poche_user']->config;
568 $currentConfig['language'] = $_POST['language'];
569
570 $_SESSION['poche_user']->setConfig($currentConfig);
571
572 Tools::redirect('?view=config');
573 }
574
07ee09f4
NL
575 /**
576 * checks if login & password are correct and save the user in session.
577 * it redirects the user to the $referer link
578 * @param string $referer the url to redirect after login
579 * @todo add the return value
580 * @return boolean
581 */
c765c367
NL
582 public function login($referer)
583 {
584 if (!empty($_POST['login']) && !empty($_POST['password'])) {
7ce7ec4c
NL
585 $user = $this->store->login($_POST['login'], Tools::encodeString($_POST['password'] . $_POST['login']));
586 if ($user != array()) {
587 # Save login into Session
588 Session::login($user['username'], $user['password'], $_POST['login'], Tools::encodeString($_POST['password'] . $_POST['login']), array('poche_user' => new User($user)));
8d3275be 589 $this->messages->add('s', _('welcome to your poche'));
8d3275be 590 Tools::logm('login successful');
c765c367
NL
591 Tools::redirect($referer);
592 }
8d3275be 593 $this->messages->add('e', _('login failed: bad login or password'));
c765c367
NL
594 Tools::logm('login failed');
595 Tools::redirect();
596 } else {
8d3275be 597 $this->messages->add('e', _('login failed: you have to fill all fields'));
c765c367
NL
598 Tools::logm('login failed');
599 Tools::redirect();
600 }
601 }
602
07ee09f4
NL
603 /**
604 * log out the poche user. It cleans the session.
605 * @todo add the return value
606 * @return boolean
607 */
c765c367
NL
608 public function logout()
609 {
7ce7ec4c 610 $this->user = array();
c765c367 611 Session::logout();
b916bcfc
NL
612 $this->messages->add('s', _('see you soon!'));
613 Tools::logm('logout');
c765c367
NL
614 Tools::redirect();
615 }
616
07ee09f4
NL
617 /**
618 * import from Instapaper. poche needs a ./instapaper-export.html file
619 * @todo add the return value
66b6a3b5 620 * @param string $targetFile the file used for importing
07ee09f4
NL
621 * @return boolean
622 */
66b6a3b5 623 private function importFromInstapaper($targetFile)
c765c367 624 {
7f959169 625 # TODO gestion des articles favs
a62788c6 626 $html = new simple_html_dom();
66b6a3b5 627 $html->load_file($targetFile);
b916bcfc 628 Tools::logm('starting import from instapaper');
a62788c6
NL
629
630 $read = 0;
631 $errors = array();
632 foreach($html->find('ol') as $ul)
633 {
634 foreach($ul->find('li') as $li)
635 {
636 $a = $li->find('a');
637 $url = new Url(base64_encode($a[0]->href));
b916bcfc 638 $this->action('add', $url, 0, TRUE);
a62788c6 639 if ($read == '1') {
b916bcfc
NL
640 $sequence = '';
641 if (STORAGE == 'postgres') {
642 $sequence = 'entries_id_seq';
643 }
644 $last_id = $this->store->getLastId($sequence);
645 $this->action('toggle_archive', $url, $last_id, TRUE);
a62788c6
NL
646 }
647 }
7f959169
NL
648
649 # the second <ol> is for read links
a62788c6
NL
650 $read = 1;
651 }
8d3275be 652 $this->messages->add('s', _('import from instapaper completed'));
63c35580
NL
653 Tools::logm('import from instapaper completed');
654 Tools::redirect();
655 }
c765c367 656
07ee09f4
NL
657 /**
658 * import from Pocket. poche needs a ./ril_export.html file
659 * @todo add the return value
66b6a3b5 660 * @param string $targetFile the file used for importing
07ee09f4
NL
661 * @return boolean
662 */
66b6a3b5 663 private function importFromPocket($targetFile)
63c35580 664 {
7f959169 665 # TODO gestion des articles favs
63c35580 666 $html = new simple_html_dom();
66b6a3b5 667 $html->load_file($targetFile);
b916bcfc 668 Tools::logm('starting import from pocket');
63c35580
NL
669
670 $read = 0;
671 $errors = array();
672 foreach($html->find('ul') as $ul)
673 {
674 foreach($ul->find('li') as $li)
c765c367 675 {
63c35580
NL
676 $a = $li->find('a');
677 $url = new Url(base64_encode($a[0]->href));
b916bcfc 678 $this->action('add', $url, 0, TRUE);
63c35580 679 if ($read == '1') {
b916bcfc
NL
680 $sequence = '';
681 if (STORAGE == 'postgres') {
682 $sequence = 'entries_id_seq';
683 }
684 $last_id = $this->store->getLastId($sequence);
685 $this->action('toggle_archive', $url, $last_id, TRUE);
c765c367 686 }
c765c367 687 }
7f959169
NL
688
689 # the second <ul> is for read links
63c35580 690 $read = 1;
c765c367 691 }
8d3275be 692 $this->messages->add('s', _('import from pocket completed'));
63c35580
NL
693 Tools::logm('import from pocket completed');
694 Tools::redirect();
695 }
c765c367 696
07ee09f4
NL
697 /**
698 * import from Readability. poche needs a ./readability file
699 * @todo add the return value
66b6a3b5 700 * @param string $targetFile the file used for importing
07ee09f4
NL
701 * @return boolean
702 */
66b6a3b5 703 private function importFromReadability($targetFile)
63c35580 704 {
7f959169 705 # TODO gestion des articles lus / favs
66b6a3b5 706 $str_data = file_get_contents($targetFile);
63c35580 707 $data = json_decode($str_data,true);
b916bcfc 708 Tools::logm('starting import from Readability');
c0d321c1 709 $count = 0;
63c35580 710 foreach ($data as $key => $value) {
c0d321c1
NL
711 $url = NULL;
712 $favorite = FALSE;
713 $archive = FALSE;
7f959169
NL
714 foreach ($value as $attr => $attr_value) {
715 if ($attr == 'article__url') {
716 $url = new Url(base64_encode($attr_value));
c765c367 717 }
b916bcfc
NL
718 $sequence = '';
719 if (STORAGE == 'postgres') {
720 $sequence = 'entries_id_seq';
721 }
c0d321c1
NL
722 if ($attr_value == 'true') {
723 if ($attr == 'favorite') {
724 $favorite = TRUE;
725 }
726 if ($attr == 'archive') {
727 $archive = TRUE;
728 }
729 }
730 }
731 # we can add the url
732 if (!is_null($url) && $url->isCorrect()) {
733 $this->action('add', $url, 0, TRUE);
734 $count++;
735 if ($favorite) {
736 $last_id = $this->store->getLastId($sequence);
737 $this->action('toggle_fav', $url, $last_id, TRUE);
738 }
739 if ($archive) {
b916bcfc
NL
740 $last_id = $this->store->getLastId($sequence);
741 $this->action('toggle_archive', $url, $last_id, TRUE);
742 }
c765c367 743 }
c765c367 744 }
c0d321c1 745 $this->messages->add('s', _('import from Readability completed. ' . $count . ' new links.'));
63c35580
NL
746 Tools::logm('import from Readability completed');
747 Tools::redirect();
c765c367
NL
748 }
749
07ee09f4
NL
750 /**
751 * import datas into your poche
752 * @param string $from name of the service to import : pocket, instapaper or readability
753 * @todo add the return value
754 * @return boolean
755 */
63c35580 756 public function import($from)
c765c367 757 {
66b6a3b5
E
758 $providers = array(
759 'pocket' => 'importFromPocket',
760 'readability' => 'importFromReadability',
761 'instapaper' => 'importFromInstapaper'
762 );
763
764 if (! isset($providers[$from])) {
765 $this->messages->add('e', _('Unknown import provider.'));
766 Tools::redirect();
63c35580 767 }
66b6a3b5
E
768
769 $targetDefinition = 'IMPORT_' . strtoupper($from) . '_FILE';
770 $targetFile = constant($targetDefinition);
771
772 if (! defined($targetDefinition)) {
773 $this->messages->add('e', _('Incomplete inc/poche/define.inc.php file, please define "' . $targetDefinition . '".'));
774 Tools::redirect();
63c35580 775 }
66b6a3b5
E
776
777 if (! file_exists($targetFile)) {
778 $this->messages->add('e', _('Could not find required "' . $targetFile . '" import file.'));
779 Tools::redirect();
63c35580 780 }
66b6a3b5
E
781
782 $this->$providers[$from]($targetFile);
63c35580 783 }
c765c367 784
07ee09f4
NL
785 /**
786 * export poche entries in json
787 * @return json all poche entries
788 */
63c35580
NL
789 public function export()
790 {
8d3275be 791 $entries = $this->store->retrieveAll($this->user->getId());
63c35580
NL
792 echo $this->tpl->render('export.twig', array(
793 'export' => Tools::renderJson($entries),
794 ));
795 Tools::logm('export view');
c765c367 796 }
32520785 797
07ee09f4 798 /**
a3436d4c 799 * Checks online the latest version of poche and cache it
07ee09f4
NL
800 * @param string $which 'prod' or 'dev'
801 * @return string latest $which version
802 */
32520785
NL
803 private function getPocheVersion($which = 'prod')
804 {
805 $cache_file = CACHE . '/' . $which;
a3436d4c
NL
806
807 # checks if the cached version file exists
32520785
NL
808 if (file_exists($cache_file) && (filemtime($cache_file) > (time() - 86400 ))) {
809 $version = file_get_contents($cache_file);
810 } else {
bc1ee852 811 $version = file_get_contents('http://static.inthepoche.com/versions/' . $which);
32520785
NL
812 file_put_contents($cache_file, $version, LOCK_EX);
813 }
814 return $version;
815 }
eb1af592 816}