]> git.immae.eu Git - github/wallabag/wallabag.git/blame - inc/poche/Poche.class.php
what this f* F?
[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 = '';
9d3b88b3 23 private $notInstalledMessage = array();
00dbaf90
NL
24
25 # @todo make this dynamic (actually install themes and save them in the database including author information et cetera)
26 private $installedThemes = array(
27 'default' => array('requires' => array()),
28 'dark' => array('requires' => array('default')),
29 'dmagenta' => array('requires' => array('default')),
30 'solarized' => array('requires' => array('default')),
31 'solarized-dark' => array('requires' => array('default'))
32 );
eb1af592 33
00dbaf90 34 public function __construct()
eb1af592 35 {
9d3b88b3
NL
36 if ($this->configFileIsAvailable()) {
37 $this->init();
00dbaf90
NL
38 }
39
9d3b88b3
NL
40 if ($this->themeIsInstalled()) {
41 $this->initTpl();
00dbaf90
NL
42 }
43
9d3b88b3
NL
44 if ($this->systemIsInstalled()) {
45 $this->store = new Database();
46 $this->messages = new Messages();
47 # installation
48 if (! $this->store->isInstalled()) {
49 $this->install();
50 }
eb1af592 51 }
eb1af592 52 }
00dbaf90
NL
53
54 private function init()
55 {
56 Tools::initPhp();
57 Session::$sessionName = 'poche';
58 Session::init();
eb1af592 59
00dbaf90
NL
60 if (isset($_SESSION['poche_user']) && $_SESSION['poche_user'] != array()) {
61 $this->user = $_SESSION['poche_user'];
62 } else {
63 # fake user, just for install & login screens
64 $this->user = new User();
65 $this->user->setConfig($this->getDefaultConfig());
66 }
67
68 # l10n
69 $language = $this->user->getConfigValue('language');
70 putenv('LC_ALL=' . $language);
71 setlocale(LC_ALL, $language);
72 bindtextdomain($language, LOCALE);
73 textdomain($language);
74
75 # Pagination
76 $this->pagination = new Paginator($this->user->getConfigValue('pager'), 'p');
77
78 # Set up theme
79 $themeDirectory = $this->user->getConfigValue('theme');
80
81 if ($themeDirectory === false) {
82 $themeDirectory = DEFAULT_THEME;
83 }
84
85 $this->currentTheme = $themeDirectory;
86 }
87
88 public function configFileIsAvailable() {
89 if (! self::$configFileAvailable) {
9d3b88b3 90 $this->notInstalledMessage[] = 'You have to rename inc/poche/config.inc.php.new to inc/poche/config.inc.php.';
00dbaf90
NL
91
92 return false;
93 }
94
95 return true;
96 }
97
98 public function themeIsInstalled() {
9d3b88b3 99 $passTheme = TRUE;
00dbaf90
NL
100 # Twig is an absolute requirement for Poche to function. Abort immediately if the Composer installer hasn't been run yet
101 if (! self::$canRenderTemplates) {
9d3b88b3
NL
102 $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>';
103 $passTheme = FALSE;
00dbaf90 104 }
7f17a38d
NL
105
106 if (! is_writable(CACHE)) {
9d3b88b3 107 $this->notInstalledMessage[] = 'You don\'t have write access on cache directory.';
7f17a38d
NL
108
109 self::$canRenderTemplates = false;
110
9d3b88b3 111 $passTheme = FALSE;
7f17a38d 112 }
00dbaf90
NL
113
114 # Check if the selected theme and its requirements are present
9d3b88b3
NL
115 if ($this->getTheme() != '' && ! is_dir(THEME . '/' . $this->getTheme())) {
116 $this->notInstalledMessage[] = 'The currently selected theme (' . $this->getTheme() . ') does not seem to be properly installed (Missing directory: ' . THEME . '/' . $this->getTheme() . ')';
00dbaf90
NL
117
118 self::$canRenderTemplates = false;
119
9d3b88b3 120 $passTheme = FALSE;
00dbaf90
NL
121 }
122
123 foreach ($this->installedThemes[$this->getTheme()]['requires'] as $requiredTheme) {
124 if (! is_dir(THEME . '/' . $requiredTheme)) {
9d3b88b3 125 $this->notInstalledMessage[] = 'The required "' . $requiredTheme . '" theme is missing for the current theme (' . $this->getTheme() . ')';
00dbaf90
NL
126
127 self::$canRenderTemplates = false;
128
9d3b88b3 129 $passTheme = FALSE;
00dbaf90
NL
130 }
131 }
9d3b88b3
NL
132
133 if (!$passTheme) {
134 return FALSE;
135 }
136
00dbaf90
NL
137
138 return true;
139 }
140
4a291288
NL
141 /**
142 * all checks before installation.
00dbaf90 143 * @todo move HTML to template
4a291288
NL
144 * @return boolean
145 */
00dbaf90 146 public function systemIsInstalled()
eb1af592 147 {
9d3b88b3 148 $msg = TRUE;
00dbaf90
NL
149
150 $configSalt = defined('SALT') ? constant('SALT') : '';
151
152 if (empty($configSalt)) {
9d3b88b3
NL
153 $this->notInstalledMessage[] = 'You have not yet filled in the SALT value in the config.inc.php file.';
154 $msg = FALSE;
155 }
156 if (STORAGE == 'sqlite' && ! file_exists(STORAGE_SQLITE)) {
00dbaf90 157 Tools::logm('sqlite file doesn\'t exist');
9d3b88b3
NL
158 $this->notInstalledMessage[] = 'sqlite file doesn\'t exist, you can find it in install folder. Copy it in /db folder.';
159 $msg = FALSE;
160 }
161 if (is_dir(ROOT . '/install') && ! DEBUG_POCHE) {
162 $this->notInstalledMessage[] = 'you have to delete the /install folder before using poche.';
163 $msg = FALSE;
164 }
165 if (STORAGE == 'sqlite' && ! is_writable(STORAGE_SQLITE)) {
bb5a7d9e 166 Tools::logm('you don\'t have write access on sqlite file');
9d3b88b3
NL
167 $this->notInstalledMessage[] = 'You don\'t have write access on sqlite file.';
168 $msg = FALSE;
bb5a7d9e 169 }
00dbaf90 170
9d3b88b3 171 if (! $msg) {
00dbaf90 172 return false;
8d3275be 173 }
7ce7ec4c 174
00dbaf90
NL
175 return true;
176 }
177
178 public function getNotInstalledMessage() {
179 return $this->notInstalledMessage;
4a291288 180 }
eb1af592 181
4a291288
NL
182 private function initTpl()
183 {
00dbaf90
NL
184 $loaderChain = new Twig_Loader_Chain();
185
186 # add the current theme as first to the loader chain so Twig will look there first for overridden template files
187 try {
188 $loaderChain->addLoader(new Twig_Loader_Filesystem(THEME . '/' . $this->getTheme()));
189 } catch (Twig_Error_Loader $e) {
190 # @todo isInstalled() should catch this, inject Twig later
191 die('The currently selected theme (' . $this->getTheme() . ') does not seem to be properly installed (' . THEME . '/' . $this->getTheme() .' is missing)');
192 }
193
194 # add all required themes to the loader chain
195 foreach ($this->installedThemes[$this->getTheme()]['requires'] as $requiredTheme) {
196 try {
197 $loaderChain->addLoader(new Twig_Loader_Filesystem(THEME . '/' . DEFAULT_THEME));
198 } catch (Twig_Error_Loader $e) {
199 # @todo isInstalled() should catch this, inject Twig later
200 die('The required "' . $requiredTheme . '" theme is missing for the current theme (' . $this->getTheme() . ')');
201 }
202 }
203
bc1ee852
NL
204 if (DEBUG_POCHE) {
205 $twig_params = array();
00dbaf90 206 } else {
bc1ee852
NL
207 $twig_params = array('cache' => CACHE);
208 }
00dbaf90
NL
209
210 $this->tpl = new Twig_Environment($loaderChain, $twig_params);
eb1af592 211 $this->tpl->addExtension(new Twig_Extensions_Extension_I18n());
00dbaf90 212
55821e04
NL
213 # filter to display domain name of an url
214 $filter = new Twig_SimpleFilter('getDomain', 'Tools::getDomain');
215 $this->tpl->addFilter($filter);
eb1af592 216
d9178758
NL
217 # filter for reading time
218 $filter = new Twig_SimpleFilter('getReadingTime', 'Tools::getReadingTime');
219 $this->tpl->addFilter($filter);
00dbaf90
NL
220
221 # filter for simple filenames in config view
222 $filter = new Twig_SimpleFilter('getPrettyFilename', function($string) { return str_replace(ROOT, '', $string); });
223 $this->tpl->addFilter($filter);
eb1af592
NL
224 }
225
226 private function install()
227 {
228 Tools::logm('poche still not installed');
229 echo $this->tpl->render('install.twig', array(
00dbaf90
NL
230 'token' => Session::getToken(),
231 'theme' => $this->getTheme(),
232 'poche_url' => Tools::getPocheUrl()
eb1af592
NL
233 ));
234 if (isset($_GET['install'])) {
235 if (($_POST['password'] == $_POST['password_repeat'])
236 && $_POST['password'] != "" && $_POST['login'] != "") {
237 # let's rock, install poche baby !
bb5a7d9e
NL
238 if ($this->store->install($_POST['login'], Tools::encodeString($_POST['password'] . $_POST['login'])))
239 {
240 Session::logout();
241 Tools::logm('poche is now installed');
242 Tools::redirect();
243 }
6a361945
NL
244 }
245 else {
246 Tools::logm('error during installation');
eb1af592
NL
247 Tools::redirect();
248 }
249 }
250 exit();
251 }
00dbaf90
NL
252
253 public function getTheme() {
254 return $this->currentTheme;
255 }
256
257 public function getInstalledThemes() {
258 $handle = opendir(THEME);
259 $themes = array();
260
261 while (($theme = readdir($handle)) !== false) {
262 # Themes are stored in a directory, so all directory names are themes
263 # @todo move theme installation data to database
3cc22aab 264 if (! is_dir(THEME . '/' . $theme) || in_array($theme, array('..', '.', '.git'))) {
00dbaf90
NL
265 continue;
266 }
267
268 $current = false;
269
270 if ($theme === $this->getTheme()) {
271 $current = true;
272 }
273
274 $themes[] = array('name' => $theme, 'current' => $current);
275 }
276
277 return $themes;
278 }
eb1af592 279
8d3275be 280 public function getDefaultConfig()
00dbaf90 281 {
8d3275be
NL
282 return array(
283 'pager' => PAGINATION,
284 'language' => LANG,
00dbaf90
NL
285 'theme' => DEFAULT_THEME
286 );
8d3275be
NL
287 }
288
eb1af592
NL
289 /**
290 * Call action (mark as fav, archive, delete, etc.)
291 */
b916bcfc 292 public function action($action, Url $url, $id = 0, $import = FALSE)
eb1af592
NL
293 {
294 switch ($action)
295 {
296 case 'add':
ec397236
NL
297 $content = $url->extract();
298
299 if ($this->store->add($url->getUrl(), $content['title'], $content['body'], $this->user->getId())) {
300 Tools::logm('add link ' . $url->getUrl());
301 $sequence = '';
302 if (STORAGE == 'postgres') {
303 $sequence = 'entries_id_seq';
eb1af592 304 }
ec397236
NL
305 $last_id = $this->store->getLastId($sequence);
306 if (DOWNLOAD_PICTURES) {
6fb46003 307 $content = filtre_picture($content['body'], $url->getUrl(), $last_id);
ec397236
NL
308 Tools::logm('updating content article');
309 $this->store->updateContent($last_id, $content, $this->user->getId());
310 }
311 if (!$import) {
312 $this->messages->add('s', _('the link has been added successfully'));
eb1af592
NL
313 }
314 }
315 else {
b916bcfc 316 if (!$import) {
ec397236
NL
317 $this->messages->add('e', _('error during insertion : the link wasn\'t added'));
318 Tools::logm('error during insertion : the link wasn\'t added ' . $url->getUrl());
b916bcfc
NL
319 }
320 }
ec397236 321
b916bcfc 322 if (!$import) {
ce4a1dcc 323 Tools::redirect('?view=home');
eb1af592
NL
324 }
325 break;
326 case 'delete':
bc1ee852 327 $msg = 'delete link #' . $id;
8d3275be 328 if ($this->store->deleteById($id, $this->user->getId())) {
eb1af592
NL
329 if (DOWNLOAD_PICTURES) {
330 remove_directory(ABS_PATH . $id);
331 }
6a361945 332 $this->messages->add('s', _('the link has been deleted successfully'));
eb1af592
NL
333 }
334 else {
6a361945 335 $this->messages->add('e', _('the link wasn\'t deleted'));
bc1ee852 336 $msg = 'error : can\'t delete link #' . $id;
eb1af592 337 }
bc1ee852 338 Tools::logm($msg);
6cd8af85 339 Tools::redirect();
eb1af592
NL
340 break;
341 case 'toggle_fav' :
8d3275be 342 $this->store->favoriteById($id, $this->user->getId());
eb1af592 343 Tools::logm('mark as favorite link #' . $id);
b916bcfc
NL
344 if (!$import) {
345 Tools::redirect();
346 }
eb1af592
NL
347 break;
348 case 'toggle_archive' :
8d3275be 349 $this->store->archiveById($id, $this->user->getId());
eb1af592 350 Tools::logm('archive link #' . $id);
b916bcfc
NL
351 if (!$import) {
352 Tools::redirect();
353 }
eb1af592
NL
354 break;
355 default:
356 break;
357 }
358 }
359
360 function displayView($view, $id = 0)
361 {
362 $tpl_vars = array();
363
364 switch ($view)
365 {
eb1af592 366 case 'config':
32520785
NL
367 $dev = $this->getPocheVersion('dev');
368 $prod = $this->getPocheVersion('prod');
031df528
NL
369 $compare_dev = version_compare(POCHE, $dev);
370 $compare_prod = version_compare(POCHE, $prod);
00dbaf90 371 $themes = $this->getInstalledThemes();
32520785 372 $tpl_vars = array(
00dbaf90 373 'themes' => $themes,
32520785
NL
374 'dev' => $dev,
375 'prod' => $prod,
376 'compare_dev' => $compare_dev,
377 'compare_prod' => $compare_prod,
378 );
eb1af592
NL
379 Tools::logm('config view');
380 break;
381 case 'view':
8d3275be 382 $entry = $this->store->retrieveOneById($id, $this->user->getId());
eb1af592
NL
383 if ($entry != NULL) {
384 Tools::logm('view link #' . $id);
385 $content = $entry['content'];
386 if (function_exists('tidy_parse_string')) {
387 $tidy = tidy_parse_string($content, array('indent'=>true, 'show-body-only' => true), 'UTF8');
388 $tidy->cleanRepair();
389 $content = $tidy->value;
3408ed48 390 }
a3223127 391
3408ed48
NL
392 # flattr checking
393 $flattr = new FlattrItem();
4e5b0411 394 $flattr->checkItem($entry['url'],$entry['id']);
a3223127 395
3408ed48
NL
396 $tpl_vars = array(
397 'entry' => $entry,
398 'content' => $content,
399 'flattr' => $flattr
400 );
eb1af592
NL
401 }
402 else {
d8d1542e 403 Tools::logm('error in view call : entry is null');
eb1af592
NL
404 }
405 break;
12d9cfbc 406 default: # home, favorites and archive views
8d3275be 407 $entries = $this->store->getEntriesByView($view, $this->user->getId());
eb1af592 408 $tpl_vars = array(
3eb04903
N
409 'entries' => '',
410 'page_links' => '',
7f9f5281 411 'nb_results' => '',
eb1af592 412 );
34d67c83 413
3eb04903
N
414 if (count($entries) > 0) {
415 $this->pagination->set_total(count($entries));
416 $page_links = $this->pagination->page_links('?view=' . $view . '&sort=' . $_SESSION['sort'] . '&');
417 $datas = $this->store->getEntriesByView($view, $this->user->getId(), $this->pagination->get_limit());
418 $tpl_vars['entries'] = $datas;
419 $tpl_vars['page_links'] = $page_links;
7f9f5281 420 $tpl_vars['nb_results'] = count($entries);
3eb04903 421 }
6a361945 422 Tools::logm('display ' . $view . ' view');
eb1af592
NL
423 break;
424 }
425
426 return $tpl_vars;
427 }
c765c367 428
07ee09f4
NL
429 /**
430 * update the password of the current user.
431 * if MODE_DEMO is TRUE, the password can't be updated.
432 * @todo add the return value
433 * @todo set the new password in function header like this updatePassword($newPassword)
434 * @return boolean
435 */
c765c367
NL
436 public function updatePassword()
437 {
55821e04 438 if (MODE_DEMO) {
8d3275be 439 $this->messages->add('i', _('in demo mode, you can\'t update your password'));
55821e04 440 Tools::logm('in demo mode, you can\'t do this');
6a361945 441 Tools::redirect('?view=config');
55821e04
NL
442 }
443 else {
444 if (isset($_POST['password']) && isset($_POST['password_repeat'])) {
445 if ($_POST['password'] == $_POST['password_repeat'] && $_POST['password'] != "") {
8d3275be
NL
446 $this->messages->add('s', _('your password has been updated'));
447 $this->store->updatePassword($this->user->getId(), Tools::encodeString($_POST['password'] . $this->user->getUsername()));
c765c367 448 Session::logout();
8d3275be 449 Tools::logm('password updated');
c765c367
NL
450 Tools::redirect();
451 }
452 else {
8d3275be 453 $this->messages->add('e', _('the two fields have to be filled & the password must be the same in the two fields'));
6a361945 454 Tools::redirect('?view=config');
c765c367
NL
455 }
456 }
457 }
458 }
00dbaf90
NL
459
460 public function updateTheme()
461 {
462 # no data
463 if (empty($_POST['theme'])) {
464 }
465
466 # we are not going to change it to the current theme...
467 if ($_POST['theme'] == $this->getTheme()) {
468 $this->messages->add('w', _('still using the "' . $this->getTheme() . '" theme!'));
469 Tools::redirect('?view=config');
470 }
471
472 $themes = $this->getInstalledThemes();
473 $actualTheme = false;
474
475 foreach ($themes as $theme) {
476 if ($theme['name'] == $_POST['theme']) {
477 $actualTheme = true;
478 break;
479 }
480 }
481
482 if (! $actualTheme) {
483 $this->messages->add('e', _('that theme does not seem to be installed'));
484 Tools::redirect('?view=config');
485 }
486
487 $this->store->updateUserConfig($this->user->getId(), 'theme', $_POST['theme']);
488 $this->messages->add('s', _('you have changed your theme preferences'));
489
490 $currentConfig = $_SESSION['poche_user']->config;
491 $currentConfig['theme'] = $_POST['theme'];
492
493 $_SESSION['poche_user']->setConfig($currentConfig);
494
495 Tools::redirect('?view=config');
496 }
c765c367 497
07ee09f4
NL
498 /**
499 * checks if login & password are correct and save the user in session.
500 * it redirects the user to the $referer link
501 * @param string $referer the url to redirect after login
502 * @todo add the return value
503 * @return boolean
504 */
c765c367
NL
505 public function login($referer)
506 {
507 if (!empty($_POST['login']) && !empty($_POST['password'])) {
7ce7ec4c
NL
508 $user = $this->store->login($_POST['login'], Tools::encodeString($_POST['password'] . $_POST['login']));
509 if ($user != array()) {
510 # Save login into Session
511 Session::login($user['username'], $user['password'], $_POST['login'], Tools::encodeString($_POST['password'] . $_POST['login']), array('poche_user' => new User($user)));
8d3275be 512 $this->messages->add('s', _('welcome to your poche'));
8d3275be 513 Tools::logm('login successful');
c765c367
NL
514 Tools::redirect($referer);
515 }
8d3275be 516 $this->messages->add('e', _('login failed: bad login or password'));
c765c367
NL
517 Tools::logm('login failed');
518 Tools::redirect();
519 } else {
8d3275be 520 $this->messages->add('e', _('login failed: you have to fill all fields'));
c765c367
NL
521 Tools::logm('login failed');
522 Tools::redirect();
523 }
524 }
525
07ee09f4
NL
526 /**
527 * log out the poche user. It cleans the session.
528 * @todo add the return value
529 * @return boolean
530 */
c765c367
NL
531 public function logout()
532 {
7ce7ec4c 533 $this->user = array();
c765c367 534 Session::logout();
b916bcfc
NL
535 $this->messages->add('s', _('see you soon!'));
536 Tools::logm('logout');
c765c367
NL
537 Tools::redirect();
538 }
539
07ee09f4
NL
540 /**
541 * import from Instapaper. poche needs a ./instapaper-export.html file
542 * @todo add the return value
66b6a3b5 543 * @param string $targetFile the file used for importing
07ee09f4
NL
544 * @return boolean
545 */
66b6a3b5 546 private function importFromInstapaper($targetFile)
c765c367 547 {
7f959169 548 # TODO gestion des articles favs
a62788c6 549 $html = new simple_html_dom();
66b6a3b5 550 $html->load_file($targetFile);
b916bcfc 551 Tools::logm('starting import from instapaper');
a62788c6
NL
552
553 $read = 0;
554 $errors = array();
555 foreach($html->find('ol') as $ul)
556 {
557 foreach($ul->find('li') as $li)
558 {
559 $a = $li->find('a');
560 $url = new Url(base64_encode($a[0]->href));
b916bcfc 561 $this->action('add', $url, 0, TRUE);
a62788c6 562 if ($read == '1') {
b916bcfc
NL
563 $sequence = '';
564 if (STORAGE == 'postgres') {
565 $sequence = 'entries_id_seq';
566 }
567 $last_id = $this->store->getLastId($sequence);
568 $this->action('toggle_archive', $url, $last_id, TRUE);
a62788c6
NL
569 }
570 }
7f959169
NL
571
572 # the second <ol> is for read links
a62788c6
NL
573 $read = 1;
574 }
8d3275be 575 $this->messages->add('s', _('import from instapaper completed'));
63c35580
NL
576 Tools::logm('import from instapaper completed');
577 Tools::redirect();
578 }
c765c367 579
07ee09f4
NL
580 /**
581 * import from Pocket. poche needs a ./ril_export.html file
582 * @todo add the return value
66b6a3b5 583 * @param string $targetFile the file used for importing
07ee09f4
NL
584 * @return boolean
585 */
66b6a3b5 586 private function importFromPocket($targetFile)
63c35580 587 {
7f959169 588 # TODO gestion des articles favs
63c35580 589 $html = new simple_html_dom();
66b6a3b5 590 $html->load_file($targetFile);
b916bcfc 591 Tools::logm('starting import from pocket');
63c35580
NL
592
593 $read = 0;
594 $errors = array();
595 foreach($html->find('ul') as $ul)
596 {
597 foreach($ul->find('li') as $li)
c765c367 598 {
63c35580
NL
599 $a = $li->find('a');
600 $url = new Url(base64_encode($a[0]->href));
b916bcfc 601 $this->action('add', $url, 0, TRUE);
63c35580 602 if ($read == '1') {
b916bcfc
NL
603 $sequence = '';
604 if (STORAGE == 'postgres') {
605 $sequence = 'entries_id_seq';
606 }
607 $last_id = $this->store->getLastId($sequence);
608 $this->action('toggle_archive', $url, $last_id, TRUE);
c765c367 609 }
c765c367 610 }
7f959169
NL
611
612 # the second <ul> is for read links
63c35580 613 $read = 1;
c765c367 614 }
8d3275be 615 $this->messages->add('s', _('import from pocket completed'));
63c35580
NL
616 Tools::logm('import from pocket completed');
617 Tools::redirect();
618 }
c765c367 619
07ee09f4
NL
620 /**
621 * import from Readability. poche needs a ./readability file
622 * @todo add the return value
66b6a3b5 623 * @param string $targetFile the file used for importing
07ee09f4
NL
624 * @return boolean
625 */
66b6a3b5 626 private function importFromReadability($targetFile)
63c35580 627 {
7f959169 628 # TODO gestion des articles lus / favs
66b6a3b5 629 $str_data = file_get_contents($targetFile);
63c35580 630 $data = json_decode($str_data,true);
b916bcfc 631 Tools::logm('starting import from Readability');
c0d321c1 632 $count = 0;
63c35580 633 foreach ($data as $key => $value) {
c0d321c1
NL
634 $url = NULL;
635 $favorite = FALSE;
636 $archive = FALSE;
7f959169
NL
637 foreach ($value as $attr => $attr_value) {
638 if ($attr == 'article__url') {
639 $url = new Url(base64_encode($attr_value));
c765c367 640 }
b916bcfc
NL
641 $sequence = '';
642 if (STORAGE == 'postgres') {
643 $sequence = 'entries_id_seq';
644 }
c0d321c1
NL
645 if ($attr_value == 'true') {
646 if ($attr == 'favorite') {
647 $favorite = TRUE;
648 }
649 if ($attr == 'archive') {
650 $archive = TRUE;
651 }
652 }
653 }
654 # we can add the url
655 if (!is_null($url) && $url->isCorrect()) {
656 $this->action('add', $url, 0, TRUE);
657 $count++;
658 if ($favorite) {
659 $last_id = $this->store->getLastId($sequence);
660 $this->action('toggle_fav', $url, $last_id, TRUE);
661 }
662 if ($archive) {
b916bcfc
NL
663 $last_id = $this->store->getLastId($sequence);
664 $this->action('toggle_archive', $url, $last_id, TRUE);
665 }
c765c367 666 }
c765c367 667 }
c0d321c1 668 $this->messages->add('s', _('import from Readability completed. ' . $count . ' new links.'));
63c35580
NL
669 Tools::logm('import from Readability completed');
670 Tools::redirect();
c765c367
NL
671 }
672
07ee09f4
NL
673 /**
674 * import datas into your poche
675 * @param string $from name of the service to import : pocket, instapaper or readability
676 * @todo add the return value
677 * @return boolean
678 */
63c35580 679 public function import($from)
c765c367 680 {
66b6a3b5
E
681 $providers = array(
682 'pocket' => 'importFromPocket',
683 'readability' => 'importFromReadability',
684 'instapaper' => 'importFromInstapaper'
685 );
686
687 if (! isset($providers[$from])) {
688 $this->messages->add('e', _('Unknown import provider.'));
689 Tools::redirect();
63c35580 690 }
66b6a3b5
E
691
692 $targetDefinition = 'IMPORT_' . strtoupper($from) . '_FILE';
693 $targetFile = constant($targetDefinition);
694
695 if (! defined($targetDefinition)) {
696 $this->messages->add('e', _('Incomplete inc/poche/define.inc.php file, please define "' . $targetDefinition . '".'));
697 Tools::redirect();
63c35580 698 }
66b6a3b5
E
699
700 if (! file_exists($targetFile)) {
701 $this->messages->add('e', _('Could not find required "' . $targetFile . '" import file.'));
702 Tools::redirect();
63c35580 703 }
66b6a3b5
E
704
705 $this->$providers[$from]($targetFile);
63c35580 706 }
c765c367 707
07ee09f4
NL
708 /**
709 * export poche entries in json
710 * @return json all poche entries
711 */
63c35580
NL
712 public function export()
713 {
8d3275be 714 $entries = $this->store->retrieveAll($this->user->getId());
63c35580
NL
715 echo $this->tpl->render('export.twig', array(
716 'export' => Tools::renderJson($entries),
717 ));
718 Tools::logm('export view');
c765c367 719 }
32520785 720
07ee09f4 721 /**
a3436d4c 722 * Checks online the latest version of poche and cache it
07ee09f4
NL
723 * @param string $which 'prod' or 'dev'
724 * @return string latest $which version
725 */
32520785
NL
726 private function getPocheVersion($which = 'prod')
727 {
728 $cache_file = CACHE . '/' . $which;
a3436d4c
NL
729
730 # checks if the cached version file exists
32520785
NL
731 if (file_exists($cache_file) && (filemtime($cache_file) > (time() - 86400 ))) {
732 $version = file_get_contents($cache_file);
733 } else {
bc1ee852 734 $version = file_get_contents('http://static.inthepoche.com/versions/' . $which);
32520785
NL
735 file_put_contents($cache_file, $version, LOCK_EX);
736 }
737 return $version;
738 }
eb1af592 739}