]> git.immae.eu Git - github/wallabag/wallabag.git/blob - inc/poche/Poche.class.php
Implemented Flattr changes
[github/wallabag/wallabag.git] / inc / poche / Poche.class.php
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
11 class Poche
12 {
13 public $user;
14 public $store;
15 public $tpl;
16 public $messages;
17 public $pagination;
18
19 function __construct()
20 {
21 $this->initTpl();
22 if (!$this->checkBeforeInstall()) {
23 exit;
24 }
25 $this->store = new Database();
26 $this->init();
27 $this->messages = new Messages();
28
29 # installation
30 if(!$this->store->isInstalled())
31 {
32 $this->install();
33 }
34 }
35
36 /**
37 * all checks before installation.
38 * @return boolean
39 */
40 private function checkBeforeInstall()
41 {
42 $msg = '';
43 $allIsGood = TRUE;
44
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) {
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>';
51 $allIsGood = FALSE;
52 }
53 else if (file_exists('./install') && !DEBUG_POCHE) {
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>';
55 $allIsGood = FALSE;
56 }
57 else if (STORAGE == 'sqlite' && !is_writable(STORAGE_SQLITE)) {
58 Tools::logm('you don\'t have write access on sqlite file');
59 $msg = '<h1>error</h1><p>You don\'t have write access on sqlite file.</p>';
60 $allIsGood = FALSE;
61 }
62
63 if (!$allIsGood) {
64 echo $this->tpl->render('error.twig', array(
65 'msg' => $msg
66 ));
67 }
68
69 return $allIsGood;
70 }
71
72 private function initTpl()
73 {
74 # template engine
75 $loader = new Twig_Loader_Filesystem(TPL);
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);
83 $this->tpl->addExtension(new Twig_Extensions_Extension_I18n());
84 # filter to display domain name of an url
85 $filter = new Twig_SimpleFilter('getDomain', 'Tools::getDomain');
86 $this->tpl->addFilter($filter);
87
88 # filter for reading time
89 $filter = new Twig_SimpleFilter('getReadingTime', 'Tools::getReadingTime');
90 $this->tpl->addFilter($filter);
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);
113
114 # Pagination
115 $this->pagination = new Paginator($this->user->getConfigValue('pager'), 'p');
116 }
117
118 private function install()
119 {
120 Tools::logm('poche still not installed');
121 echo $this->tpl->render('install.twig', array(
122 'token' => Session::getToken()
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 !
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 }
134 }
135 else {
136 Tools::logm('error during installation');
137 Tools::redirect();
138 }
139 }
140 exit();
141 }
142
143 public function getDefaultConfig()
144 {
145 return array(
146 'pager' => PAGINATION,
147 'language' => LANG,
148 );
149 }
150
151 /**
152 * Call action (mark as fav, archive, delete, etc.)
153 */
154 public function action($action, Url $url, $id = 0, $import = FALSE)
155 {
156 switch ($action)
157 {
158 case 'add':
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';
166 }
167 $last_id = $this->store->getLastId($sequence);
168 if (DOWNLOAD_PICTURES) {
169 $content = filtre_picture($content['body'], $url->getUrl(), $last_id);
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'));
175 }
176 }
177 else {
178 if (!$import) {
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());
181 }
182 }
183
184 if (!$import) {
185 Tools::redirect();
186 }
187 break;
188 case 'delete':
189 $msg = 'delete link #' . $id;
190 if ($this->store->deleteById($id, $this->user->getId())) {
191 if (DOWNLOAD_PICTURES) {
192 remove_directory(ABS_PATH . $id);
193 }
194 $this->messages->add('s', _('the link has been deleted successfully'));
195 }
196 else {
197 $this->messages->add('e', _('the link wasn\'t deleted'));
198 $msg = 'error : can\'t delete link #' . $id;
199 }
200 Tools::logm($msg);
201 Tools::redirect('?');
202 break;
203 case 'toggle_fav' :
204 $this->store->favoriteById($id, $this->user->getId());
205 Tools::logm('mark as favorite link #' . $id);
206 if (!$import) {
207 Tools::redirect();
208 }
209 break;
210 case 'toggle_archive' :
211 $this->store->archiveById($id, $this->user->getId());
212 Tools::logm('archive link #' . $id);
213 if (!$import) {
214 Tools::redirect();
215 }
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 {
228 case 'config':
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 );
239 Tools::logm('config view');
240 break;
241 case 'view':
242 $entry = $this->store->retrieveOneById($id, $this->user->getId());
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;
250
251 // flattr checking
252 $flattr = new FlattrItem();
253 $flattr->checkitem($entry['url']);
254
255 $tpl_vars = array(
256 'entry' => $entry,
257 'content' => $content,
258 'flattr' => $flattr,
259 );
260 }
261 else {
262 Tools::logm('error in view call : entry is null');
263 }
264 break;
265 default: # home, favorites and archive views
266 $entries = $this->store->getEntriesByView($view, $this->user->getId());
267 $tpl_vars = array(
268 'entries' => '',
269 'page_links' => '',
270 );
271 if (count($entries) > 0) {
272 $this->pagination->set_total(count($entries));
273 $page_links = $this->pagination->page_links('?view=' . $view . '&sort=' . $_SESSION['sort'] . '&');
274 $datas = $this->store->getEntriesByView($view, $this->user->getId(), $this->pagination->get_limit());
275 $tpl_vars['entries'] = $datas;
276 $tpl_vars['page_links'] = $page_links;
277 }
278 Tools::logm('display ' . $view . ' view');
279 break;
280 }
281
282 return $tpl_vars;
283 }
284
285 /**
286 * update the password of the current user.
287 * if MODE_DEMO is TRUE, the password can't be updated.
288 * @todo add the return value
289 * @todo set the new password in function header like this updatePassword($newPassword)
290 * @return boolean
291 */
292 public function updatePassword()
293 {
294 if (MODE_DEMO) {
295 $this->messages->add('i', _('in demo mode, you can\'t update your password'));
296 Tools::logm('in demo mode, you can\'t do this');
297 Tools::redirect('?view=config');
298 }
299 else {
300 if (isset($_POST['password']) && isset($_POST['password_repeat'])) {
301 if ($_POST['password'] == $_POST['password_repeat'] && $_POST['password'] != "") {
302 $this->messages->add('s', _('your password has been updated'));
303 $this->store->updatePassword($this->user->getId(), Tools::encodeString($_POST['password'] . $this->user->getUsername()));
304 Session::logout();
305 Tools::logm('password updated');
306 Tools::redirect();
307 }
308 else {
309 $this->messages->add('e', _('the two fields have to be filled & the password must be the same in the two fields'));
310 Tools::redirect('?view=config');
311 }
312 }
313 }
314 }
315
316 /**
317 * checks if login & password are correct and save the user in session.
318 * it redirects the user to the $referer link
319 * @param string $referer the url to redirect after login
320 * @todo add the return value
321 * @return boolean
322 */
323 public function login($referer)
324 {
325 if (!empty($_POST['login']) && !empty($_POST['password'])) {
326 $user = $this->store->login($_POST['login'], Tools::encodeString($_POST['password'] . $_POST['login']));
327 if ($user != array()) {
328 # Save login into Session
329 Session::login($user['username'], $user['password'], $_POST['login'], Tools::encodeString($_POST['password'] . $_POST['login']), array('poche_user' => new User($user)));
330
331 $this->messages->add('s', _('welcome to your poche'));
332 if (!empty($_POST['longlastingsession'])) {
333 $_SESSION['longlastingsession'] = 31536000;
334 $_SESSION['expires_on'] = time() + $_SESSION['longlastingsession'];
335 session_set_cookie_params($_SESSION['longlastingsession']);
336 } else {
337 session_set_cookie_params(0);
338 }
339 session_regenerate_id(true);
340 Tools::logm('login successful');
341 Tools::redirect($referer);
342 }
343 $this->messages->add('e', _('login failed: bad login or password'));
344 Tools::logm('login failed');
345 Tools::redirect();
346 } else {
347 $this->messages->add('e', _('login failed: you have to fill all fields'));
348 Tools::logm('login failed');
349 Tools::redirect();
350 }
351 }
352
353 /**
354 * log out the poche user. It cleans the session.
355 * @todo add the return value
356 * @return boolean
357 */
358 public function logout()
359 {
360 $this->user = array();
361 Session::logout();
362 $this->messages->add('s', _('see you soon!'));
363 Tools::logm('logout');
364 Tools::redirect();
365 }
366
367 /**
368 * import from Instapaper. poche needs a ./instapaper-export.html file
369 * @todo add the return value
370 * @param string $targetFile the file used for importing
371 * @return boolean
372 */
373 private function importFromInstapaper($targetFile)
374 {
375 # TODO gestion des articles favs
376 $html = new simple_html_dom();
377 $html->load_file($targetFile);
378 Tools::logm('starting import from instapaper');
379
380 $read = 0;
381 $errors = array();
382 foreach($html->find('ol') as $ul)
383 {
384 foreach($ul->find('li') as $li)
385 {
386 $a = $li->find('a');
387 $url = new Url(base64_encode($a[0]->href));
388 $this->action('add', $url, 0, TRUE);
389 if ($read == '1') {
390 $sequence = '';
391 if (STORAGE == 'postgres') {
392 $sequence = 'entries_id_seq';
393 }
394 $last_id = $this->store->getLastId($sequence);
395 $this->action('toggle_archive', $url, $last_id, TRUE);
396 }
397 }
398
399 # the second <ol> is for read links
400 $read = 1;
401 }
402 $this->messages->add('s', _('import from instapaper completed'));
403 Tools::logm('import from instapaper completed');
404 Tools::redirect();
405 }
406
407 /**
408 * import from Pocket. poche needs a ./ril_export.html file
409 * @todo add the return value
410 * @param string $targetFile the file used for importing
411 * @return boolean
412 */
413 private function importFromPocket($targetFile)
414 {
415 # TODO gestion des articles favs
416 $html = new simple_html_dom();
417 $html->load_file($targetFile);
418 Tools::logm('starting import from pocket');
419
420 $read = 0;
421 $errors = array();
422 foreach($html->find('ul') as $ul)
423 {
424 foreach($ul->find('li') as $li)
425 {
426 $a = $li->find('a');
427 $url = new Url(base64_encode($a[0]->href));
428 $this->action('add', $url, 0, TRUE);
429 if ($read == '1') {
430 $sequence = '';
431 if (STORAGE == 'postgres') {
432 $sequence = 'entries_id_seq';
433 }
434 $last_id = $this->store->getLastId($sequence);
435 $this->action('toggle_archive', $url, $last_id, TRUE);
436 }
437 }
438
439 # the second <ul> is for read links
440 $read = 1;
441 }
442 $this->messages->add('s', _('import from pocket completed'));
443 Tools::logm('import from pocket completed');
444 Tools::redirect();
445 }
446
447 /**
448 * import from Readability. poche needs a ./readability file
449 * @todo add the return value
450 * @param string $targetFile the file used for importing
451 * @return boolean
452 */
453 private function importFromReadability($targetFile)
454 {
455 # TODO gestion des articles lus / favs
456 $str_data = file_get_contents($targetFile);
457 $data = json_decode($str_data,true);
458 Tools::logm('starting import from Readability');
459 $count = 0;
460 foreach ($data as $key => $value) {
461 $url = NULL;
462 $favorite = FALSE;
463 $archive = FALSE;
464 foreach ($value as $attr => $attr_value) {
465 if ($attr == 'article__url') {
466 $url = new Url(base64_encode($attr_value));
467 }
468 $sequence = '';
469 if (STORAGE == 'postgres') {
470 $sequence = 'entries_id_seq';
471 }
472 if ($attr_value == 'true') {
473 if ($attr == 'favorite') {
474 $favorite = TRUE;
475 }
476 if ($attr == 'archive') {
477 $archive = TRUE;
478 }
479 }
480 }
481 # we can add the url
482 if (!is_null($url) && $url->isCorrect()) {
483 $this->action('add', $url, 0, TRUE);
484 $count++;
485 if ($favorite) {
486 $last_id = $this->store->getLastId($sequence);
487 $this->action('toggle_fav', $url, $last_id, TRUE);
488 }
489 if ($archive) {
490 $last_id = $this->store->getLastId($sequence);
491 $this->action('toggle_archive', $url, $last_id, TRUE);
492 }
493 }
494 }
495 $this->messages->add('s', _('import from Readability completed. ' . $count . ' new links.'));
496 Tools::logm('import from Readability completed');
497 Tools::redirect();
498 }
499
500 /**
501 * import datas into your poche
502 * @param string $from name of the service to import : pocket, instapaper or readability
503 * @todo add the return value
504 * @return boolean
505 */
506 public function import($from)
507 {
508 $providers = array(
509 'pocket' => 'importFromPocket',
510 'readability' => 'importFromReadability',
511 'instapaper' => 'importFromInstapaper'
512 );
513
514 if (! isset($providers[$from])) {
515 $this->messages->add('e', _('Unknown import provider.'));
516 Tools::redirect();
517 }
518
519 $targetDefinition = 'IMPORT_' . strtoupper($from) . '_FILE';
520 $targetFile = constant($targetDefinition);
521
522 if (! defined($targetDefinition)) {
523 $this->messages->add('e', _('Incomplete inc/poche/define.inc.php file, please define "' . $targetDefinition . '".'));
524 Tools::redirect();
525 }
526
527 if (! file_exists($targetFile)) {
528 $this->messages->add('e', _('Could not find required "' . $targetFile . '" import file.'));
529 Tools::redirect();
530 }
531
532 $this->$providers[$from]($targetFile);
533 }
534
535 /**
536 * export poche entries in json
537 * @return json all poche entries
538 */
539 public function export()
540 {
541 $entries = $this->store->retrieveAll($this->user->getId());
542 echo $this->tpl->render('export.twig', array(
543 'export' => Tools::renderJson($entries),
544 ));
545 Tools::logm('export view');
546 }
547
548 /**
549 * Checks online the latest version of poche and cache it
550 * @param string $which 'prod' or 'dev'
551 * @return string latest $which version
552 */
553 private function getPocheVersion($which = 'prod')
554 {
555 $cache_file = CACHE . '/' . $which;
556
557 # checks if the cached version file exists
558 if (file_exists($cache_file) && (filemtime($cache_file) > (time() - 86400 ))) {
559 $version = file_get_contents($cache_file);
560 } else {
561 $version = file_get_contents('http://static.inthepoche.com/versions/' . $which);
562 file_put_contents($cache_file, $version, LOCK_EX);
563 }
564 return $version;
565 }
566 }
567
568 /* class for Flattr querying. Should be put in a separate file
569 * Or maybe just create an array instead of a complete class... My mistake. :-°
570 */
571 class FlattrItem{
572 public $status;
573 public $urltoflattr;
574 public $flattrItemURL;
575 public $numflattrs;
576
577 public function checkitem($urltoflattr){
578 $this->cacheflattrfile($urltoflattr);
579 $flattrResponse = file_get_contents("cache/flattr/".base64_encode($urltoflattr).".cache");
580 var_dump($flattrResponse);
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;
591 $this->numflattrs = $result->flattrs_user_count;
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 }