]> git.immae.eu Git - github/wallabag/wallabag.git/blob - inc/poche/Poche.class.php
cb338766fd0d9b6efbe79e58f7f97a5b78f11b15
[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 if($parametres_url = $url->fetchContent()) {
160 if ($this->store->add($url->getUrl(), $parametres_url['title'], $parametres_url['content'], $this->user->getId())) {
161 Tools::logm('add link ' . $url->getUrl());
162 $sequence = '';
163 if (STORAGE == 'postgres') {
164 $sequence = 'entries_id_seq';
165 }
166 $last_id = $this->store->getLastId($sequence);
167 if (DOWNLOAD_PICTURES) {
168 $content = filtre_picture($parametres_url['content'], $url->getUrl(), $last_id);
169 Tools::logm('updating content article');
170 $this->store->updateContent($last_id, $content, $this->user->getId());
171 }
172 if (!$import) {
173 $this->messages->add('s', _('the link has been added successfully'));
174 }
175 }
176 else {
177 if (!$import) {
178 $this->messages->add('e', _('error during insertion : the link wasn\'t added'));
179 Tools::logm('error during insertion : the link wasn\'t added ' . $url->getUrl());
180 }
181 }
182 }
183 else {
184 if (!$import) {
185 $this->messages->add('e', _('error during fetching content : the link wasn\'t added'));
186 Tools::logm('error during content fetch ' . $url->getUrl());
187 }
188 }
189 if (!$import) {
190 Tools::redirect();
191 }
192 break;
193 case 'delete':
194 $msg = 'delete link #' . $id;
195 if ($this->store->deleteById($id, $this->user->getId())) {
196 if (DOWNLOAD_PICTURES) {
197 remove_directory(ABS_PATH . $id);
198 }
199 $this->messages->add('s', _('the link has been deleted successfully'));
200 }
201 else {
202 $this->messages->add('e', _('the link wasn\'t deleted'));
203 $msg = 'error : can\'t delete link #' . $id;
204 }
205 Tools::logm($msg);
206 Tools::redirect('?');
207 break;
208 case 'toggle_fav' :
209 $this->store->favoriteById($id, $this->user->getId());
210 Tools::logm('mark as favorite link #' . $id);
211 if (!$import) {
212 Tools::redirect();
213 }
214 break;
215 case 'toggle_archive' :
216 $this->store->archiveById($id, $this->user->getId());
217 Tools::logm('archive link #' . $id);
218 if (!$import) {
219 Tools::redirect();
220 }
221 break;
222 default:
223 Tools::logm('action ' . $action . 'doesn\'t exist');
224 break;
225 }
226 }
227
228 function displayView($view, $id = 0)
229 {
230 $tpl_vars = array();
231
232 switch ($view)
233 {
234 case 'config':
235 $dev = $this->getPocheVersion('dev');
236 $prod = $this->getPocheVersion('prod');
237 $compare_dev = version_compare(POCHE_VERSION, $dev);
238 $compare_prod = version_compare(POCHE_VERSION, $prod);
239 $tpl_vars = array(
240 'dev' => $dev,
241 'prod' => $prod,
242 'compare_dev' => $compare_dev,
243 'compare_prod' => $compare_prod,
244 );
245 Tools::logm('config view');
246 break;
247 case 'view':
248 $entry = $this->store->retrieveOneById($id, $this->user->getId());
249 if ($entry != NULL) {
250 Tools::logm('view link #' . $id);
251 $content = $entry['content'];
252 if (function_exists('tidy_parse_string')) {
253 $tidy = tidy_parse_string($content, array('indent'=>true, 'show-body-only' => true), 'UTF8');
254 $tidy->cleanRepair();
255 $content = $tidy->value;
256 }
257 $tpl_vars = array(
258 'entry' => $entry,
259 'content' => $content,
260 );
261 }
262 else {
263 Tools::logm('error in view call : entry is null');
264 }
265 break;
266 default: # home view
267 $entries = $this->store->getEntriesByView($view, $this->user->getId());
268 $this->pagination->set_total(count($entries));
269 $page_links = $this->pagination->page_links('?view=' . $view . '&sort=' . $_SESSION['sort'] . '&');
270 $datas = $this->store->getEntriesByView($view, $this->user->getId(), $this->pagination->get_limit());
271 $tpl_vars = array(
272 'entries' => $datas,
273 'page_links' => $page_links,
274 );
275 Tools::logm('display ' . $view . ' view');
276 break;
277 }
278
279 return $tpl_vars;
280 }
281
282 /**
283 * update the password of the current user.
284 * if MODE_DEMO is TRUE, the password can't be updated.
285 * @todo add the return value
286 * @todo set the new password in function header like this updatePassword($newPassword)
287 * @return boolean
288 */
289 public function updatePassword()
290 {
291 if (MODE_DEMO) {
292 $this->messages->add('i', _('in demo mode, you can\'t update your password'));
293 Tools::logm('in demo mode, you can\'t do this');
294 Tools::redirect('?view=config');
295 }
296 else {
297 if (isset($_POST['password']) && isset($_POST['password_repeat'])) {
298 if ($_POST['password'] == $_POST['password_repeat'] && $_POST['password'] != "") {
299 $this->messages->add('s', _('your password has been updated'));
300 $this->store->updatePassword($this->user->getId(), Tools::encodeString($_POST['password'] . $this->user->getUsername()));
301 Session::logout();
302 Tools::logm('password updated');
303 Tools::redirect();
304 }
305 else {
306 $this->messages->add('e', _('the two fields have to be filled & the password must be the same in the two fields'));
307 Tools::redirect('?view=config');
308 }
309 }
310 }
311 }
312
313 /**
314 * checks if login & password are correct and save the user in session.
315 * it redirects the user to the $referer link
316 * @param string $referer the url to redirect after login
317 * @todo add the return value
318 * @return boolean
319 */
320 public function login($referer)
321 {
322 if (!empty($_POST['login']) && !empty($_POST['password'])) {
323 $user = $this->store->login($_POST['login'], Tools::encodeString($_POST['password'] . $_POST['login']));
324 if ($user != array()) {
325 # Save login into Session
326 Session::login($user['username'], $user['password'], $_POST['login'], Tools::encodeString($_POST['password'] . $_POST['login']), array('poche_user' => new User($user)));
327
328 $this->messages->add('s', _('welcome to your poche'));
329 if (!empty($_POST['longlastingsession'])) {
330 $_SESSION['longlastingsession'] = 31536000;
331 $_SESSION['expires_on'] = time() + $_SESSION['longlastingsession'];
332 session_set_cookie_params($_SESSION['longlastingsession']);
333 } else {
334 session_set_cookie_params(0);
335 }
336 session_regenerate_id(true);
337 Tools::logm('login successful');
338 Tools::redirect($referer);
339 }
340 $this->messages->add('e', _('login failed: bad login or password'));
341 Tools::logm('login failed');
342 Tools::redirect();
343 } else {
344 $this->messages->add('e', _('login failed: you have to fill all fields'));
345 Tools::logm('login failed');
346 Tools::redirect();
347 }
348 }
349
350 /**
351 * log out the poche user. It cleans the session.
352 * @todo add the return value
353 * @return boolean
354 */
355 public function logout()
356 {
357 $this->user = array();
358 Session::logout();
359 $this->messages->add('s', _('see you soon!'));
360 Tools::logm('logout');
361 Tools::redirect();
362 }
363
364 /**
365 * import from Instapaper. poche needs a ./instapaper-export.html file
366 * @todo add the return value
367 * @param string $targetFile the file used for importing
368 * @return boolean
369 */
370 private function importFromInstapaper($targetFile)
371 {
372 # TODO gestion des articles favs
373 $html = new simple_html_dom();
374 $html->load_file($targetFile);
375 Tools::logm('starting import from instapaper');
376
377 $read = 0;
378 $errors = array();
379 foreach($html->find('ol') as $ul)
380 {
381 foreach($ul->find('li') as $li)
382 {
383 $a = $li->find('a');
384 $url = new Url(base64_encode($a[0]->href));
385 $this->action('add', $url, 0, TRUE);
386 if ($read == '1') {
387 $sequence = '';
388 if (STORAGE == 'postgres') {
389 $sequence = 'entries_id_seq';
390 }
391 $last_id = $this->store->getLastId($sequence);
392 $this->action('toggle_archive', $url, $last_id, TRUE);
393 }
394 }
395
396 # the second <ol> is for read links
397 $read = 1;
398 }
399 $this->messages->add('s', _('import from instapaper completed'));
400 Tools::logm('import from instapaper completed');
401 Tools::redirect();
402 }
403
404 /**
405 * import from Pocket. poche needs a ./ril_export.html file
406 * @todo add the return value
407 * @param string $targetFile the file used for importing
408 * @return boolean
409 */
410 private function importFromPocket($targetFile)
411 {
412 # TODO gestion des articles favs
413 $html = new simple_html_dom();
414 $html->load_file($targetFile);
415 Tools::logm('starting import from pocket');
416
417 $read = 0;
418 $errors = array();
419 foreach($html->find('ul') as $ul)
420 {
421 foreach($ul->find('li') as $li)
422 {
423 $a = $li->find('a');
424 $url = new Url(base64_encode($a[0]->href));
425 $this->action('add', $url, 0, TRUE);
426 if ($read == '1') {
427 $sequence = '';
428 if (STORAGE == 'postgres') {
429 $sequence = 'entries_id_seq';
430 }
431 $last_id = $this->store->getLastId($sequence);
432 $this->action('toggle_archive', $url, $last_id, TRUE);
433 }
434 }
435
436 # the second <ul> is for read links
437 $read = 1;
438 }
439 $this->messages->add('s', _('import from pocket completed'));
440 Tools::logm('import from pocket completed');
441 Tools::redirect();
442 }
443
444 /**
445 * import from Readability. poche needs a ./readability file
446 * @todo add the return value
447 * @param string $targetFile the file used for importing
448 * @return boolean
449 */
450 private function importFromReadability($targetFile)
451 {
452 # TODO gestion des articles lus / favs
453 $str_data = file_get_contents($targetFile);
454 $data = json_decode($str_data,true);
455 Tools::logm('starting import from Readability');
456 $count = 0;
457 foreach ($data as $key => $value) {
458 $url = NULL;
459 $favorite = FALSE;
460 $archive = FALSE;
461 foreach ($value as $attr => $attr_value) {
462 if ($attr == 'article__url') {
463 $url = new Url(base64_encode($attr_value));
464 }
465 $sequence = '';
466 if (STORAGE == 'postgres') {
467 $sequence = 'entries_id_seq';
468 }
469 if ($attr_value == 'true') {
470 if ($attr == 'favorite') {
471 $favorite = TRUE;
472 }
473 if ($attr == 'archive') {
474 $archive = TRUE;
475 }
476 }
477 }
478 # we can add the url
479 if (!is_null($url) && $url->isCorrect()) {
480 $this->action('add', $url, 0, TRUE);
481 $count++;
482 if ($favorite) {
483 $last_id = $this->store->getLastId($sequence);
484 $this->action('toggle_fav', $url, $last_id, TRUE);
485 }
486 if ($archive) {
487 $last_id = $this->store->getLastId($sequence);
488 $this->action('toggle_archive', $url, $last_id, TRUE);
489 }
490 }
491 }
492 $this->messages->add('s', _('import from Readability completed. ' . $count . ' new links.'));
493 Tools::logm('import from Readability completed');
494 Tools::redirect();
495 }
496
497 /**
498 * import datas into your poche
499 * @param string $from name of the service to import : pocket, instapaper or readability
500 * @todo add the return value
501 * @return boolean
502 */
503 public function import($from)
504 {
505 $providers = array(
506 'pocket' => 'importFromPocket',
507 'readability' => 'importFromReadability',
508 'instapaper' => 'importFromInstapaper'
509 );
510
511 if (! isset($providers[$from])) {
512 $this->messages->add('e', _('Unknown import provider.'));
513 Tools::redirect();
514 }
515
516 $targetDefinition = 'IMPORT_' . strtoupper($from) . '_FILE';
517 $targetFile = constant($targetDefinition);
518
519 if (! defined($targetDefinition)) {
520 $this->messages->add('e', _('Incomplete inc/poche/define.inc.php file, please define "' . $targetDefinition . '".'));
521 Tools::redirect();
522 }
523
524 if (! file_exists($targetFile)) {
525 $this->messages->add('e', _('Could not find required "' . $targetFile . '" import file.'));
526 Tools::redirect();
527 }
528
529 $this->$providers[$from]($targetFile);
530 }
531
532 /**
533 * export poche entries in json
534 * @return json all poche entries
535 */
536 public function export()
537 {
538 $entries = $this->store->retrieveAll($this->user->getId());
539 echo $this->tpl->render('export.twig', array(
540 'export' => Tools::renderJson($entries),
541 ));
542 Tools::logm('export view');
543 }
544
545 /**
546 * Checks online the latest version of poche and cache it
547 * @param string $which 'prod' or 'dev'
548 * @return string latest $which version
549 */
550 private function getPocheVersion($which = 'prod')
551 {
552 $cache_file = CACHE . '/' . $which;
553
554 # checks if the cached version file exists
555 if (file_exists($cache_file) && (filemtime($cache_file) > (time() - 86400 ))) {
556 $version = file_get_contents($cache_file);
557 } else {
558 $version = file_get_contents('http://static.inthepoche.com/versions/' . $which);
559 file_put_contents($cache_file, $version, LOCK_EX);
560 }
561 return $version;
562 }
563 }