]> git.immae.eu Git - github/wallabag/wallabag.git/blame - inc/poche/Poche.class.php
fixes with new session class
[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{
7ce7ec4c 13 public $user;
eb1af592
NL
14 public $store;
15 public $tpl;
55821e04 16 public $messages;
6a361945 17 public $pagination;
eb1af592 18
bc1ee852 19 function __construct()
eb1af592 20 {
4a291288
NL
21 $this->initTpl();
22 if (!$this->checkBeforeInstall()) {
23 exit;
6c158544 24 }
bc1ee852 25 $this->store = new Database();
eb1af592 26 $this->init();
6a361945 27 $this->messages = new Messages();
eb1af592
NL
28
29 # installation
30 if(!$this->store->isInstalled())
31 {
32 $this->install();
33 }
eb1af592
NL
34 }
35
4a291288
NL
36 /**
37 * all checks before installation.
38 * @return boolean
39 */
40 private function checkBeforeInstall()
eb1af592 41 {
4a291288
NL
42 $msg = '';
43 $allIsGood = TRUE;
bb5a7d9e 44
abed0f21
NL
45 if (!is_writable(CACHE)) {
46 Tools::logm('you don\'t have write access on cache directory');
47 die('You don\'t have write access on cache directory.');
48 }
49 else if (file_exists('./install/update.php') && !DEBUG_POCHE) {
6d7defc8 50 $msg = '<h1>setup</h1><p><strong>It\'s your first time here?</strong> Please copy /install/poche.sqlite in db folder. Then, delete install folder.<br /><strong>If you have already installed poche</strong>, an update is needed <a href="install/update.php">by clicking here</a>.</p>';
bb5a7d9e
NL
51 $allIsGood = FALSE;
52 }
53 else if (file_exists('./install') && !DEBUG_POCHE) {
6d7defc8 54 $msg = '<h1>setup</h1><p><strong>If you want to update your poche</strong>, you just have to delete /install folder. <br /><strong>To install your poche with sqlite</strong>, copy /install/poche.sqlite in /db and delete the folder /install. you have to delete the /install folder before using poche.</p>';
4a291288
NL
55 $allIsGood = FALSE;
56 }
bb5a7d9e
NL
57 else if (STORAGE == 'sqlite' && !is_writable(STORAGE_SQLITE)) {
58 Tools::logm('you don\'t have write access on sqlite file');
6d7defc8 59 $msg = '<h1>error</h1><p>You don\'t have write access on sqlite file.</p>';
bb5a7d9e
NL
60 $allIsGood = FALSE;
61 }
abed0f21 62
4a291288
NL
63 if (!$allIsGood) {
64 echo $this->tpl->render('error.twig', array(
65 'msg' => $msg
66 ));
8d3275be 67 }
7ce7ec4c 68
4a291288
NL
69 return $allIsGood;
70 }
eb1af592 71
4a291288
NL
72 private function initTpl()
73 {
eb1af592
NL
74 # template engine
75 $loader = new Twig_Loader_Filesystem(TPL);
bc1ee852
NL
76 if (DEBUG_POCHE) {
77 $twig_params = array();
78 }
79 else {
80 $twig_params = array('cache' => CACHE);
81 }
82 $this->tpl = new Twig_Environment($loader, $twig_params);
eb1af592 83 $this->tpl->addExtension(new Twig_Extensions_Extension_I18n());
55821e04
NL
84 # filter to display domain name of an url
85 $filter = new Twig_SimpleFilter('getDomain', 'Tools::getDomain');
86 $this->tpl->addFilter($filter);
eb1af592 87
d9178758
NL
88 # filter for reading time
89 $filter = new Twig_SimpleFilter('getReadingTime', 'Tools::getReadingTime');
90 $this->tpl->addFilter($filter);
4a291288
NL
91 }
92
93 private function init()
94 {
95 Tools::initPhp();
f6597c7c 96 Session::$sessionName = 'poche';
4a291288
NL
97 Session::init();
98
99 if (isset($_SESSION['poche_user']) && $_SESSION['poche_user'] != array()) {
100 $this->user = $_SESSION['poche_user'];
101 }
102 else {
103 # fake user, just for install & login screens
104 $this->user = new User();
105 $this->user->setConfig($this->getDefaultConfig());
106 }
107
108 # l10n
109 $language = $this->user->getConfigValue('language');
110 putenv('LC_ALL=' . $language);
111 setlocale(LC_ALL, $language);
112 bindtextdomain($language, LOCALE);
113 textdomain($language);
d9178758 114
7ce7ec4c 115 # Pagination
8d3275be 116 $this->pagination = new Paginator($this->user->getConfigValue('pager'), 'p');
eb1af592
NL
117 }
118
119 private function install()
120 {
121 Tools::logm('poche still not installed');
122 echo $this->tpl->render('install.twig', array(
6a361945 123 'token' => Session::getToken()
eb1af592
NL
124 ));
125 if (isset($_GET['install'])) {
126 if (($_POST['password'] == $_POST['password_repeat'])
127 && $_POST['password'] != "" && $_POST['login'] != "") {
128 # let's rock, install poche baby !
bb5a7d9e
NL
129 if ($this->store->install($_POST['login'], Tools::encodeString($_POST['password'] . $_POST['login'])))
130 {
131 Session::logout();
132 Tools::logm('poche is now installed');
133 Tools::redirect();
134 }
6a361945
NL
135 }
136 else {
137 Tools::logm('error during installation');
eb1af592
NL
138 Tools::redirect();
139 }
140 }
141 exit();
142 }
143
8d3275be
NL
144 public function getDefaultConfig()
145 {
146 return array(
147 'pager' => PAGINATION,
148 'language' => LANG,
149 );
150 }
151
eb1af592
NL
152 /**
153 * Call action (mark as fav, archive, delete, etc.)
154 */
b916bcfc 155 public function action($action, Url $url, $id = 0, $import = FALSE)
eb1af592
NL
156 {
157 switch ($action)
158 {
159 case 'add':
ec397236
NL
160 $content = $url->extract();
161
162 if ($this->store->add($url->getUrl(), $content['title'], $content['body'], $this->user->getId())) {
163 Tools::logm('add link ' . $url->getUrl());
164 $sequence = '';
165 if (STORAGE == 'postgres') {
166 $sequence = 'entries_id_seq';
eb1af592 167 }
ec397236
NL
168 $last_id = $this->store->getLastId($sequence);
169 if (DOWNLOAD_PICTURES) {
6fb46003 170 $content = filtre_picture($content['body'], $url->getUrl(), $last_id);
ec397236
NL
171 Tools::logm('updating content article');
172 $this->store->updateContent($last_id, $content, $this->user->getId());
173 }
174 if (!$import) {
175 $this->messages->add('s', _('the link has been added successfully'));
eb1af592
NL
176 }
177 }
178 else {
b916bcfc 179 if (!$import) {
ec397236
NL
180 $this->messages->add('e', _('error during insertion : the link wasn\'t added'));
181 Tools::logm('error during insertion : the link wasn\'t added ' . $url->getUrl());
b916bcfc
NL
182 }
183 }
ec397236 184
b916bcfc 185 if (!$import) {
ce4a1dcc 186 Tools::redirect('?view=home');
eb1af592
NL
187 }
188 break;
189 case 'delete':
bc1ee852 190 $msg = 'delete link #' . $id;
8d3275be 191 if ($this->store->deleteById($id, $this->user->getId())) {
eb1af592
NL
192 if (DOWNLOAD_PICTURES) {
193 remove_directory(ABS_PATH . $id);
194 }
6a361945 195 $this->messages->add('s', _('the link has been deleted successfully'));
eb1af592
NL
196 }
197 else {
6a361945 198 $this->messages->add('e', _('the link wasn\'t deleted'));
bc1ee852 199 $msg = 'error : can\'t delete link #' . $id;
eb1af592 200 }
bc1ee852
NL
201 Tools::logm($msg);
202 Tools::redirect('?');
eb1af592
NL
203 break;
204 case 'toggle_fav' :
8d3275be 205 $this->store->favoriteById($id, $this->user->getId());
eb1af592 206 Tools::logm('mark as favorite link #' . $id);
b916bcfc
NL
207 if (!$import) {
208 Tools::redirect();
209 }
eb1af592
NL
210 break;
211 case 'toggle_archive' :
8d3275be 212 $this->store->archiveById($id, $this->user->getId());
eb1af592 213 Tools::logm('archive link #' . $id);
b916bcfc
NL
214 if (!$import) {
215 Tools::redirect();
216 }
eb1af592
NL
217 break;
218 default:
219 break;
220 }
221 }
222
223 function displayView($view, $id = 0)
224 {
225 $tpl_vars = array();
226
227 switch ($view)
228 {
eb1af592 229 case 'config':
32520785
NL
230 $dev = $this->getPocheVersion('dev');
231 $prod = $this->getPocheVersion('prod');
232 $compare_dev = version_compare(POCHE_VERSION, $dev);
233 $compare_prod = version_compare(POCHE_VERSION, $prod);
234 $tpl_vars = array(
235 'dev' => $dev,
236 'prod' => $prod,
237 'compare_dev' => $compare_dev,
238 'compare_prod' => $compare_prod,
239 );
eb1af592
NL
240 Tools::logm('config view');
241 break;
242 case 'view':
8d3275be 243 $entry = $this->store->retrieveOneById($id, $this->user->getId());
eb1af592
NL
244 if ($entry != NULL) {
245 Tools::logm('view link #' . $id);
246 $content = $entry['content'];
247 if (function_exists('tidy_parse_string')) {
248 $tidy = tidy_parse_string($content, array('indent'=>true, 'show-body-only' => true), 'UTF8');
249 $tidy->cleanRepair();
250 $content = $tidy->value;
a3223127 251
12d9cfbc 252 # flattr checking
af1d2792 253 $flattr = new FlattrItem();
12d9cfbc 254 $flattr->checkItem($entry['url']);
a3223127 255
af1d2792 256 $tpl_vars = array(
eb1af592
NL
257 'entry' => $entry,
258 'content' => $content,
af1d2792
TC
259 'flattr' => $flattr
260 );
261 }
eb1af592
NL
262 }
263 else {
d8d1542e 264 Tools::logm('error in view call : entry is null');
eb1af592
NL
265 }
266 break;
12d9cfbc 267 default: # home, favorites and archive views
8d3275be 268 $entries = $this->store->getEntriesByView($view, $this->user->getId());
eb1af592 269 $tpl_vars = array(
3eb04903
N
270 'entries' => '',
271 'page_links' => '',
7f9f5281 272 'nb_results' => '',
eb1af592 273 );
3eb04903
N
274 if (count($entries) > 0) {
275 $this->pagination->set_total(count($entries));
276 $page_links = $this->pagination->page_links('?view=' . $view . '&sort=' . $_SESSION['sort'] . '&');
277 $datas = $this->store->getEntriesByView($view, $this->user->getId(), $this->pagination->get_limit());
278 $tpl_vars['entries'] = $datas;
279 $tpl_vars['page_links'] = $page_links;
7f9f5281 280 $tpl_vars['nb_results'] = count($entries);
3eb04903 281 }
6a361945 282 Tools::logm('display ' . $view . ' view');
eb1af592
NL
283 break;
284 }
285
286 return $tpl_vars;
287 }
c765c367 288
07ee09f4
NL
289 /**
290 * update the password of the current user.
291 * if MODE_DEMO is TRUE, the password can't be updated.
292 * @todo add the return value
293 * @todo set the new password in function header like this updatePassword($newPassword)
294 * @return boolean
295 */
c765c367
NL
296 public function updatePassword()
297 {
55821e04 298 if (MODE_DEMO) {
8d3275be 299 $this->messages->add('i', _('in demo mode, you can\'t update your password'));
55821e04 300 Tools::logm('in demo mode, you can\'t do this');
6a361945 301 Tools::redirect('?view=config');
55821e04
NL
302 }
303 else {
304 if (isset($_POST['password']) && isset($_POST['password_repeat'])) {
305 if ($_POST['password'] == $_POST['password_repeat'] && $_POST['password'] != "") {
8d3275be
NL
306 $this->messages->add('s', _('your password has been updated'));
307 $this->store->updatePassword($this->user->getId(), Tools::encodeString($_POST['password'] . $this->user->getUsername()));
c765c367 308 Session::logout();
8d3275be 309 Tools::logm('password updated');
c765c367
NL
310 Tools::redirect();
311 }
312 else {
8d3275be 313 $this->messages->add('e', _('the two fields have to be filled & the password must be the same in the two fields'));
6a361945 314 Tools::redirect('?view=config');
c765c367
NL
315 }
316 }
317 }
318 }
319
07ee09f4
NL
320 /**
321 * checks if login & password are correct and save the user in session.
322 * it redirects the user to the $referer link
323 * @param string $referer the url to redirect after login
324 * @todo add the return value
325 * @return boolean
326 */
c765c367
NL
327 public function login($referer)
328 {
329 if (!empty($_POST['login']) && !empty($_POST['password'])) {
7ce7ec4c
NL
330 $user = $this->store->login($_POST['login'], Tools::encodeString($_POST['password'] . $_POST['login']));
331 if ($user != array()) {
332 # Save login into Session
333 Session::login($user['username'], $user['password'], $_POST['login'], Tools::encodeString($_POST['password'] . $_POST['login']), array('poche_user' => new User($user)));
8d3275be 334 $this->messages->add('s', _('welcome to your poche'));
8d3275be 335 Tools::logm('login successful');
c765c367
NL
336 Tools::redirect($referer);
337 }
8d3275be 338 $this->messages->add('e', _('login failed: bad login or password'));
c765c367
NL
339 Tools::logm('login failed');
340 Tools::redirect();
341 } else {
8d3275be 342 $this->messages->add('e', _('login failed: you have to fill all fields'));
c765c367
NL
343 Tools::logm('login failed');
344 Tools::redirect();
345 }
346 }
347
07ee09f4
NL
348 /**
349 * log out the poche user. It cleans the session.
350 * @todo add the return value
351 * @return boolean
352 */
c765c367
NL
353 public function logout()
354 {
7ce7ec4c 355 $this->user = array();
c765c367 356 Session::logout();
b916bcfc
NL
357 $this->messages->add('s', _('see you soon!'));
358 Tools::logm('logout');
c765c367
NL
359 Tools::redirect();
360 }
361
07ee09f4
NL
362 /**
363 * import from Instapaper. poche needs a ./instapaper-export.html file
364 * @todo add the return value
66b6a3b5 365 * @param string $targetFile the file used for importing
07ee09f4
NL
366 * @return boolean
367 */
66b6a3b5 368 private function importFromInstapaper($targetFile)
c765c367 369 {
7f959169 370 # TODO gestion des articles favs
a62788c6 371 $html = new simple_html_dom();
66b6a3b5 372 $html->load_file($targetFile);
b916bcfc 373 Tools::logm('starting import from instapaper');
a62788c6
NL
374
375 $read = 0;
376 $errors = array();
377 foreach($html->find('ol') as $ul)
378 {
379 foreach($ul->find('li') as $li)
380 {
381 $a = $li->find('a');
382 $url = new Url(base64_encode($a[0]->href));
b916bcfc 383 $this->action('add', $url, 0, TRUE);
a62788c6 384 if ($read == '1') {
b916bcfc
NL
385 $sequence = '';
386 if (STORAGE == 'postgres') {
387 $sequence = 'entries_id_seq';
388 }
389 $last_id = $this->store->getLastId($sequence);
390 $this->action('toggle_archive', $url, $last_id, TRUE);
a62788c6
NL
391 }
392 }
7f959169
NL
393
394 # the second <ol> is for read links
a62788c6
NL
395 $read = 1;
396 }
8d3275be 397 $this->messages->add('s', _('import from instapaper completed'));
63c35580
NL
398 Tools::logm('import from instapaper completed');
399 Tools::redirect();
400 }
c765c367 401
07ee09f4
NL
402 /**
403 * import from Pocket. poche needs a ./ril_export.html file
404 * @todo add the return value
66b6a3b5 405 * @param string $targetFile the file used for importing
07ee09f4
NL
406 * @return boolean
407 */
66b6a3b5 408 private function importFromPocket($targetFile)
63c35580 409 {
7f959169 410 # TODO gestion des articles favs
63c35580 411 $html = new simple_html_dom();
66b6a3b5 412 $html->load_file($targetFile);
b916bcfc 413 Tools::logm('starting import from pocket');
63c35580
NL
414
415 $read = 0;
416 $errors = array();
417 foreach($html->find('ul') as $ul)
418 {
419 foreach($ul->find('li') as $li)
c765c367 420 {
63c35580
NL
421 $a = $li->find('a');
422 $url = new Url(base64_encode($a[0]->href));
b916bcfc 423 $this->action('add', $url, 0, TRUE);
63c35580 424 if ($read == '1') {
b916bcfc
NL
425 $sequence = '';
426 if (STORAGE == 'postgres') {
427 $sequence = 'entries_id_seq';
428 }
429 $last_id = $this->store->getLastId($sequence);
430 $this->action('toggle_archive', $url, $last_id, TRUE);
c765c367 431 }
c765c367 432 }
7f959169
NL
433
434 # the second <ul> is for read links
63c35580 435 $read = 1;
c765c367 436 }
8d3275be 437 $this->messages->add('s', _('import from pocket completed'));
63c35580
NL
438 Tools::logm('import from pocket completed');
439 Tools::redirect();
440 }
c765c367 441
07ee09f4
NL
442 /**
443 * import from Readability. poche needs a ./readability file
444 * @todo add the return value
66b6a3b5 445 * @param string $targetFile the file used for importing
07ee09f4
NL
446 * @return boolean
447 */
66b6a3b5 448 private function importFromReadability($targetFile)
63c35580 449 {
7f959169 450 # TODO gestion des articles lus / favs
66b6a3b5 451 $str_data = file_get_contents($targetFile);
63c35580 452 $data = json_decode($str_data,true);
b916bcfc 453 Tools::logm('starting import from Readability');
c0d321c1 454 $count = 0;
63c35580 455 foreach ($data as $key => $value) {
c0d321c1
NL
456 $url = NULL;
457 $favorite = FALSE;
458 $archive = FALSE;
7f959169
NL
459 foreach ($value as $attr => $attr_value) {
460 if ($attr == 'article__url') {
461 $url = new Url(base64_encode($attr_value));
c765c367 462 }
b916bcfc
NL
463 $sequence = '';
464 if (STORAGE == 'postgres') {
465 $sequence = 'entries_id_seq';
466 }
c0d321c1
NL
467 if ($attr_value == 'true') {
468 if ($attr == 'favorite') {
469 $favorite = TRUE;
470 }
471 if ($attr == 'archive') {
472 $archive = TRUE;
473 }
474 }
475 }
476 # we can add the url
477 if (!is_null($url) && $url->isCorrect()) {
478 $this->action('add', $url, 0, TRUE);
479 $count++;
480 if ($favorite) {
481 $last_id = $this->store->getLastId($sequence);
482 $this->action('toggle_fav', $url, $last_id, TRUE);
483 }
484 if ($archive) {
b916bcfc
NL
485 $last_id = $this->store->getLastId($sequence);
486 $this->action('toggle_archive', $url, $last_id, TRUE);
487 }
c765c367 488 }
c765c367 489 }
c0d321c1 490 $this->messages->add('s', _('import from Readability completed. ' . $count . ' new links.'));
63c35580
NL
491 Tools::logm('import from Readability completed');
492 Tools::redirect();
c765c367
NL
493 }
494
07ee09f4
NL
495 /**
496 * import datas into your poche
497 * @param string $from name of the service to import : pocket, instapaper or readability
498 * @todo add the return value
499 * @return boolean
500 */
63c35580 501 public function import($from)
c765c367 502 {
66b6a3b5
E
503 $providers = array(
504 'pocket' => 'importFromPocket',
505 'readability' => 'importFromReadability',
506 'instapaper' => 'importFromInstapaper'
507 );
508
509 if (! isset($providers[$from])) {
510 $this->messages->add('e', _('Unknown import provider.'));
511 Tools::redirect();
63c35580 512 }
66b6a3b5
E
513
514 $targetDefinition = 'IMPORT_' . strtoupper($from) . '_FILE';
515 $targetFile = constant($targetDefinition);
516
517 if (! defined($targetDefinition)) {
518 $this->messages->add('e', _('Incomplete inc/poche/define.inc.php file, please define "' . $targetDefinition . '".'));
519 Tools::redirect();
63c35580 520 }
66b6a3b5
E
521
522 if (! file_exists($targetFile)) {
523 $this->messages->add('e', _('Could not find required "' . $targetFile . '" import file.'));
524 Tools::redirect();
63c35580 525 }
66b6a3b5
E
526
527 $this->$providers[$from]($targetFile);
63c35580 528 }
c765c367 529
07ee09f4
NL
530 /**
531 * export poche entries in json
532 * @return json all poche entries
533 */
63c35580
NL
534 public function export()
535 {
8d3275be 536 $entries = $this->store->retrieveAll($this->user->getId());
63c35580
NL
537 echo $this->tpl->render('export.twig', array(
538 'export' => Tools::renderJson($entries),
539 ));
540 Tools::logm('export view');
c765c367 541 }
32520785 542
07ee09f4 543 /**
a3436d4c 544 * Checks online the latest version of poche and cache it
07ee09f4
NL
545 * @param string $which 'prod' or 'dev'
546 * @return string latest $which version
547 */
32520785
NL
548 private function getPocheVersion($which = 'prod')
549 {
550 $cache_file = CACHE . '/' . $which;
a3436d4c
NL
551
552 # checks if the cached version file exists
32520785
NL
553 if (file_exists($cache_file) && (filemtime($cache_file) > (time() - 86400 ))) {
554 $version = file_get_contents($cache_file);
555 } else {
bc1ee852 556 $version = file_get_contents('http://static.inthepoche.com/versions/' . $which);
32520785
NL
557 file_put_contents($cache_file, $version, LOCK_EX);
558 }
559 return $version;
560 }
eb1af592 561}