]> git.immae.eu Git - github/wallabag/wallabag.git/blame - inc/poche/Poche.class.php
Fixed errors and changed source of flattrs
[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();
96 Session::init();
97
98 if (isset($_SESSION['poche_user']) && $_SESSION['poche_user'] != array()) {
99 $this->user = $_SESSION['poche_user'];
100 }
101 else {
102 # fake user, just for install & login screens
103 $this->user = new User();
104 $this->user->setConfig($this->getDefaultConfig());
105 }
106
107 # l10n
108 $language = $this->user->getConfigValue('language');
109 putenv('LC_ALL=' . $language);
110 setlocale(LC_ALL, $language);
111 bindtextdomain($language, LOCALE);
112 textdomain($language);
d9178758 113
7ce7ec4c 114 # Pagination
8d3275be 115 $this->pagination = new Paginator($this->user->getConfigValue('pager'), 'p');
eb1af592
NL
116 }
117
118 private function install()
119 {
120 Tools::logm('poche still not installed');
121 echo $this->tpl->render('install.twig', array(
6a361945 122 'token' => Session::getToken()
eb1af592
NL
123 ));
124 if (isset($_GET['install'])) {
125 if (($_POST['password'] == $_POST['password_repeat'])
126 && $_POST['password'] != "" && $_POST['login'] != "") {
127 # let's rock, install poche baby !
bb5a7d9e
NL
128 if ($this->store->install($_POST['login'], Tools::encodeString($_POST['password'] . $_POST['login'])))
129 {
130 Session::logout();
131 Tools::logm('poche is now installed');
132 Tools::redirect();
133 }
6a361945
NL
134 }
135 else {
136 Tools::logm('error during installation');
eb1af592
NL
137 Tools::redirect();
138 }
139 }
140 exit();
141 }
142
8d3275be
NL
143 public function getDefaultConfig()
144 {
145 return array(
146 'pager' => PAGINATION,
147 'language' => LANG,
148 );
149 }
150
eb1af592
NL
151 /**
152 * Call action (mark as fav, archive, delete, etc.)
153 */
b916bcfc 154 public function action($action, Url $url, $id = 0, $import = FALSE)
eb1af592
NL
155 {
156 switch ($action)
157 {
158 case 'add':
ec397236
NL
159 $content = $url->extract();
160
161 if ($this->store->add($url->getUrl(), $content['title'], $content['body'], $this->user->getId())) {
162 Tools::logm('add link ' . $url->getUrl());
163 $sequence = '';
164 if (STORAGE == 'postgres') {
165 $sequence = 'entries_id_seq';
eb1af592 166 }
ec397236
NL
167 $last_id = $this->store->getLastId($sequence);
168 if (DOWNLOAD_PICTURES) {
6fb46003 169 $content = filtre_picture($content['body'], $url->getUrl(), $last_id);
ec397236
NL
170 Tools::logm('updating content article');
171 $this->store->updateContent($last_id, $content, $this->user->getId());
172 }
173 if (!$import) {
174 $this->messages->add('s', _('the link has been added successfully'));
eb1af592
NL
175 }
176 }
177 else {
b916bcfc 178 if (!$import) {
ec397236
NL
179 $this->messages->add('e', _('error during insertion : the link wasn\'t added'));
180 Tools::logm('error during insertion : the link wasn\'t added ' . $url->getUrl());
b916bcfc
NL
181 }
182 }
ec397236 183
b916bcfc
NL
184 if (!$import) {
185 Tools::redirect();
eb1af592
NL
186 }
187 break;
188 case 'delete':
bc1ee852 189 $msg = 'delete link #' . $id;
8d3275be 190 if ($this->store->deleteById($id, $this->user->getId())) {
eb1af592
NL
191 if (DOWNLOAD_PICTURES) {
192 remove_directory(ABS_PATH . $id);
193 }
6a361945 194 $this->messages->add('s', _('the link has been deleted successfully'));
eb1af592
NL
195 }
196 else {
6a361945 197 $this->messages->add('e', _('the link wasn\'t deleted'));
bc1ee852 198 $msg = 'error : can\'t delete link #' . $id;
eb1af592 199 }
bc1ee852
NL
200 Tools::logm($msg);
201 Tools::redirect('?');
eb1af592
NL
202 break;
203 case 'toggle_fav' :
8d3275be 204 $this->store->favoriteById($id, $this->user->getId());
eb1af592 205 Tools::logm('mark as favorite link #' . $id);
b916bcfc
NL
206 if (!$import) {
207 Tools::redirect();
208 }
eb1af592
NL
209 break;
210 case 'toggle_archive' :
8d3275be 211 $this->store->archiveById($id, $this->user->getId());
eb1af592 212 Tools::logm('archive link #' . $id);
b916bcfc
NL
213 if (!$import) {
214 Tools::redirect();
215 }
eb1af592
NL
216 break;
217 default:
218 break;
219 }
220 }
221
222 function displayView($view, $id = 0)
223 {
224 $tpl_vars = array();
225
226 switch ($view)
227 {
eb1af592 228 case 'config':
32520785
NL
229 $dev = $this->getPocheVersion('dev');
230 $prod = $this->getPocheVersion('prod');
231 $compare_dev = version_compare(POCHE_VERSION, $dev);
232 $compare_prod = version_compare(POCHE_VERSION, $prod);
233 $tpl_vars = array(
234 'dev' => $dev,
235 'prod' => $prod,
236 'compare_dev' => $compare_dev,
237 'compare_prod' => $compare_prod,
238 );
eb1af592
NL
239 Tools::logm('config view');
240 break;
241 case 'view':
8d3275be 242 $entry = $this->store->retrieveOneById($id, $this->user->getId());
eb1af592
NL
243 if ($entry != NULL) {
244 Tools::logm('view link #' . $id);
245 $content = $entry['content'];
246 if (function_exists('tidy_parse_string')) {
247 $tidy = tidy_parse_string($content, array('indent'=>true, 'show-body-only' => true), 'UTF8');
248 $tidy->cleanRepair();
249 $content = $tidy->value;
a3223127
TC
250
251 // flattr checking
af1d2792
TC
252 $flattr = new FlattrItem();
253 $flattr->checkitem($entry['url']);
a3223127 254
af1d2792 255 $tpl_vars = array(
eb1af592
NL
256 'entry' => $entry,
257 'content' => $content,
af1d2792
TC
258 'flattr' => $flattr
259 );
260 }
eb1af592
NL
261 }
262 else {
d8d1542e 263 Tools::logm('error in view call : entry is null');
eb1af592
NL
264 }
265 break;
af1d2792 266 default : // home, favorites and archive views
8d3275be 267 $entries = $this->store->getEntriesByView($view, $this->user->getId());
eb1af592 268 $tpl_vars = array(
3eb04903
N
269 'entries' => '',
270 'page_links' => '',
eb1af592 271 );
3eb04903
N
272 if (count($entries) > 0) {
273 $this->pagination->set_total(count($entries));
274 $page_links = $this->pagination->page_links('?view=' . $view . '&sort=' . $_SESSION['sort'] . '&');
275 $datas = $this->store->getEntriesByView($view, $this->user->getId(), $this->pagination->get_limit());
276 $tpl_vars['entries'] = $datas;
277 $tpl_vars['page_links'] = $page_links;
278 }
6a361945 279 Tools::logm('display ' . $view . ' view');
eb1af592
NL
280 break;
281 }
282
283 return $tpl_vars;
284 }
c765c367 285
07ee09f4
NL
286 /**
287 * update the password of the current user.
288 * if MODE_DEMO is TRUE, the password can't be updated.
289 * @todo add the return value
290 * @todo set the new password in function header like this updatePassword($newPassword)
291 * @return boolean
292 */
c765c367
NL
293 public function updatePassword()
294 {
55821e04 295 if (MODE_DEMO) {
8d3275be 296 $this->messages->add('i', _('in demo mode, you can\'t update your password'));
55821e04 297 Tools::logm('in demo mode, you can\'t do this');
6a361945 298 Tools::redirect('?view=config');
55821e04
NL
299 }
300 else {
301 if (isset($_POST['password']) && isset($_POST['password_repeat'])) {
302 if ($_POST['password'] == $_POST['password_repeat'] && $_POST['password'] != "") {
8d3275be
NL
303 $this->messages->add('s', _('your password has been updated'));
304 $this->store->updatePassword($this->user->getId(), Tools::encodeString($_POST['password'] . $this->user->getUsername()));
c765c367 305 Session::logout();
8d3275be 306 Tools::logm('password updated');
c765c367
NL
307 Tools::redirect();
308 }
309 else {
8d3275be 310 $this->messages->add('e', _('the two fields have to be filled & the password must be the same in the two fields'));
6a361945 311 Tools::redirect('?view=config');
c765c367
NL
312 }
313 }
314 }
315 }
316
07ee09f4
NL
317 /**
318 * checks if login & password are correct and save the user in session.
319 * it redirects the user to the $referer link
320 * @param string $referer the url to redirect after login
321 * @todo add the return value
322 * @return boolean
323 */
c765c367
NL
324 public function login($referer)
325 {
326 if (!empty($_POST['login']) && !empty($_POST['password'])) {
7ce7ec4c
NL
327 $user = $this->store->login($_POST['login'], Tools::encodeString($_POST['password'] . $_POST['login']));
328 if ($user != array()) {
329 # Save login into Session
330 Session::login($user['username'], $user['password'], $_POST['login'], Tools::encodeString($_POST['password'] . $_POST['login']), array('poche_user' => new User($user)));
331
8d3275be 332 $this->messages->add('s', _('welcome to your poche'));
c765c367
NL
333 if (!empty($_POST['longlastingsession'])) {
334 $_SESSION['longlastingsession'] = 31536000;
335 $_SESSION['expires_on'] = time() + $_SESSION['longlastingsession'];
336 session_set_cookie_params($_SESSION['longlastingsession']);
337 } else {
338 session_set_cookie_params(0);
339 }
340 session_regenerate_id(true);
8d3275be 341 Tools::logm('login successful');
c765c367
NL
342 Tools::redirect($referer);
343 }
8d3275be 344 $this->messages->add('e', _('login failed: bad login or password'));
c765c367
NL
345 Tools::logm('login failed');
346 Tools::redirect();
347 } else {
8d3275be 348 $this->messages->add('e', _('login failed: you have to fill all fields'));
c765c367
NL
349 Tools::logm('login failed');
350 Tools::redirect();
351 }
352 }
353
07ee09f4
NL
354 /**
355 * log out the poche user. It cleans the session.
356 * @todo add the return value
357 * @return boolean
358 */
c765c367
NL
359 public function logout()
360 {
7ce7ec4c 361 $this->user = array();
c765c367 362 Session::logout();
b916bcfc
NL
363 $this->messages->add('s', _('see you soon!'));
364 Tools::logm('logout');
c765c367
NL
365 Tools::redirect();
366 }
367
07ee09f4
NL
368 /**
369 * import from Instapaper. poche needs a ./instapaper-export.html file
370 * @todo add the return value
66b6a3b5 371 * @param string $targetFile the file used for importing
07ee09f4
NL
372 * @return boolean
373 */
66b6a3b5 374 private function importFromInstapaper($targetFile)
c765c367 375 {
7f959169 376 # TODO gestion des articles favs
a62788c6 377 $html = new simple_html_dom();
66b6a3b5 378 $html->load_file($targetFile);
b916bcfc 379 Tools::logm('starting import from instapaper');
a62788c6
NL
380
381 $read = 0;
382 $errors = array();
383 foreach($html->find('ol') as $ul)
384 {
385 foreach($ul->find('li') as $li)
386 {
387 $a = $li->find('a');
388 $url = new Url(base64_encode($a[0]->href));
b916bcfc 389 $this->action('add', $url, 0, TRUE);
a62788c6 390 if ($read == '1') {
b916bcfc
NL
391 $sequence = '';
392 if (STORAGE == 'postgres') {
393 $sequence = 'entries_id_seq';
394 }
395 $last_id = $this->store->getLastId($sequence);
396 $this->action('toggle_archive', $url, $last_id, TRUE);
a62788c6
NL
397 }
398 }
7f959169
NL
399
400 # the second <ol> is for read links
a62788c6
NL
401 $read = 1;
402 }
8d3275be 403 $this->messages->add('s', _('import from instapaper completed'));
63c35580
NL
404 Tools::logm('import from instapaper completed');
405 Tools::redirect();
406 }
c765c367 407
07ee09f4
NL
408 /**
409 * import from Pocket. poche needs a ./ril_export.html file
410 * @todo add the return value
66b6a3b5 411 * @param string $targetFile the file used for importing
07ee09f4
NL
412 * @return boolean
413 */
66b6a3b5 414 private function importFromPocket($targetFile)
63c35580 415 {
7f959169 416 # TODO gestion des articles favs
63c35580 417 $html = new simple_html_dom();
66b6a3b5 418 $html->load_file($targetFile);
b916bcfc 419 Tools::logm('starting import from pocket');
63c35580
NL
420
421 $read = 0;
422 $errors = array();
423 foreach($html->find('ul') as $ul)
424 {
425 foreach($ul->find('li') as $li)
c765c367 426 {
63c35580
NL
427 $a = $li->find('a');
428 $url = new Url(base64_encode($a[0]->href));
b916bcfc 429 $this->action('add', $url, 0, TRUE);
63c35580 430 if ($read == '1') {
b916bcfc
NL
431 $sequence = '';
432 if (STORAGE == 'postgres') {
433 $sequence = 'entries_id_seq';
434 }
435 $last_id = $this->store->getLastId($sequence);
436 $this->action('toggle_archive', $url, $last_id, TRUE);
c765c367 437 }
c765c367 438 }
7f959169
NL
439
440 # the second <ul> is for read links
63c35580 441 $read = 1;
c765c367 442 }
8d3275be 443 $this->messages->add('s', _('import from pocket completed'));
63c35580
NL
444 Tools::logm('import from pocket completed');
445 Tools::redirect();
446 }
c765c367 447
07ee09f4
NL
448 /**
449 * import from Readability. poche needs a ./readability file
450 * @todo add the return value
66b6a3b5 451 * @param string $targetFile the file used for importing
07ee09f4
NL
452 * @return boolean
453 */
66b6a3b5 454 private function importFromReadability($targetFile)
63c35580 455 {
7f959169 456 # TODO gestion des articles lus / favs
66b6a3b5 457 $str_data = file_get_contents($targetFile);
63c35580 458 $data = json_decode($str_data,true);
b916bcfc 459 Tools::logm('starting import from Readability');
c0d321c1 460 $count = 0;
63c35580 461 foreach ($data as $key => $value) {
c0d321c1
NL
462 $url = NULL;
463 $favorite = FALSE;
464 $archive = FALSE;
7f959169
NL
465 foreach ($value as $attr => $attr_value) {
466 if ($attr == 'article__url') {
467 $url = new Url(base64_encode($attr_value));
c765c367 468 }
b916bcfc
NL
469 $sequence = '';
470 if (STORAGE == 'postgres') {
471 $sequence = 'entries_id_seq';
472 }
c0d321c1
NL
473 if ($attr_value == 'true') {
474 if ($attr == 'favorite') {
475 $favorite = TRUE;
476 }
477 if ($attr == 'archive') {
478 $archive = TRUE;
479 }
480 }
481 }
482 # we can add the url
483 if (!is_null($url) && $url->isCorrect()) {
484 $this->action('add', $url, 0, TRUE);
485 $count++;
486 if ($favorite) {
487 $last_id = $this->store->getLastId($sequence);
488 $this->action('toggle_fav', $url, $last_id, TRUE);
489 }
490 if ($archive) {
b916bcfc
NL
491 $last_id = $this->store->getLastId($sequence);
492 $this->action('toggle_archive', $url, $last_id, TRUE);
493 }
c765c367 494 }
c765c367 495 }
c0d321c1 496 $this->messages->add('s', _('import from Readability completed. ' . $count . ' new links.'));
63c35580
NL
497 Tools::logm('import from Readability completed');
498 Tools::redirect();
c765c367
NL
499 }
500
07ee09f4
NL
501 /**
502 * import datas into your poche
503 * @param string $from name of the service to import : pocket, instapaper or readability
504 * @todo add the return value
505 * @return boolean
506 */
63c35580 507 public function import($from)
c765c367 508 {
66b6a3b5
E
509 $providers = array(
510 'pocket' => 'importFromPocket',
511 'readability' => 'importFromReadability',
512 'instapaper' => 'importFromInstapaper'
513 );
514
515 if (! isset($providers[$from])) {
516 $this->messages->add('e', _('Unknown import provider.'));
517 Tools::redirect();
63c35580 518 }
66b6a3b5
E
519
520 $targetDefinition = 'IMPORT_' . strtoupper($from) . '_FILE';
521 $targetFile = constant($targetDefinition);
522
523 if (! defined($targetDefinition)) {
524 $this->messages->add('e', _('Incomplete inc/poche/define.inc.php file, please define "' . $targetDefinition . '".'));
525 Tools::redirect();
63c35580 526 }
66b6a3b5
E
527
528 if (! file_exists($targetFile)) {
529 $this->messages->add('e', _('Could not find required "' . $targetFile . '" import file.'));
530 Tools::redirect();
63c35580 531 }
66b6a3b5
E
532
533 $this->$providers[$from]($targetFile);
63c35580 534 }
c765c367 535
07ee09f4
NL
536 /**
537 * export poche entries in json
538 * @return json all poche entries
539 */
63c35580
NL
540 public function export()
541 {
8d3275be 542 $entries = $this->store->retrieveAll($this->user->getId());
63c35580
NL
543 echo $this->tpl->render('export.twig', array(
544 'export' => Tools::renderJson($entries),
545 ));
546 Tools::logm('export view');
c765c367 547 }
32520785 548
07ee09f4 549 /**
a3436d4c 550 * Checks online the latest version of poche and cache it
07ee09f4
NL
551 * @param string $which 'prod' or 'dev'
552 * @return string latest $which version
553 */
32520785
NL
554 private function getPocheVersion($which = 'prod')
555 {
556 $cache_file = CACHE . '/' . $which;
a3436d4c
NL
557
558 # checks if the cached version file exists
32520785
NL
559 if (file_exists($cache_file) && (filemtime($cache_file) > (time() - 86400 ))) {
560 $version = file_get_contents($cache_file);
561 } else {
bc1ee852 562 $version = file_get_contents('http://static.inthepoche.com/versions/' . $which);
32520785
NL
563 file_put_contents($cache_file, $version, LOCK_EX);
564 }
565 return $version;
566 }
a3223127
TC
567}
568
569/* class for Flattr querying. Should be put in a separate file
570* Or maybe just create an array instead of a complete class... My mistake. :-°
571*/
572class FlattrItem{
573 public $status;
574 public $urltoflattr;
575 public $flattrItemURL;
576 public $numflattrs;
577
578 public function checkitem($urltoflattr){
579 $this->cacheflattrfile($urltoflattr);
580 $flattrResponse = file_get_contents("cache/flattr/".base64_encode($urltoflattr).".cache");
a3223127
TC
581 if($flattrResponse != FALSE){
582 $result = json_decode($flattrResponse);
583 if (isset($result->message)){
584 if ($result->message == "flattrable"){
585 $this->status = "flattrable";
586 }
587 }
588 elseif ($result->link) {
589 $this->status = "flattred";
590 $this->flattrItemURL = $result->link;
af1d2792 591 $this->numflattrs = $result->flattrs;
a3223127
TC
592 }
593 else{
594 $this->status = "not flattrable";
595 }
596 }
597 else
598 {
599 $this->status = "FLATTR_ERR_CONNECTION";
600 }
601 }
602
603 private function cacheflattrfile($urltoflattr){
604 if (!is_dir('cache/flattr')){
605 mkdir('./cache/flattr', 0700);
606 }
607 // if a cache flattr file for this url already exists and it's been less than one day than it have been updated, see in /cache
608 if ((!file_exists("cache/flattr/".base64_encode($urltoflattr).".cache")) || (time() - filemtime("cache/flattr/".base64_encode($urltoflattr).".cache") > 86400))
609 {
610 $askForFlattr = Tools::getFile("https://api.flattr.com/rest/v2/things/lookup/?url=".$urltoflattr);
611 $flattrCacheFile = fopen("cache/flattr/".base64_encode($urltoflattr).".cache", 'w+');
612 fwrite($flattrCacheFile, $askForFlattr);
613 fclose($flattrCacheFile);
614 }
615 }
616}