]> git.immae.eu Git - github/wallabag/wallabag.git/blob - inc/poche/Poche.class.php
updating script
[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 (file_exists('./install/update.php') && !DEBUG_POCHE) {
46 $msg = 'A poche update is needed. Please execute this update <a href="install/update.php">by clicking here</a>. If you have already do the update, please delete /install folder.';
47 $allIsGood = FALSE;
48 }
49 else if (file_exists('./install') && !DEBUG_POCHE) {
50 $msg = 'If you want to update your poche, you just have to delete /install folder. <br />To install your poche with sqlite, copy /install/poche.sqlite in /db and delete the folder /install. you have to delete the /install folder before using poche.';
51 $allIsGood = FALSE;
52 }
53 else if (STORAGE == 'sqlite' && !is_writable(STORAGE_SQLITE)) {
54 Tools::logm('you don\'t have write access on sqlite file');
55 $msg = 'You don\'t have write access on sqlite file.';
56 $allIsGood = FALSE;
57 }
58 else if (!is_writable(CACHE)) {
59 Tools::logm('you don\'t have write access on cache directory');
60 $msg = 'You don\'t have write access on cache directory.';
61 $allIsGood = FALSE;
62 }
63
64 if (!$allIsGood) {
65 echo $this->tpl->render('error.twig', array(
66 'msg' => $msg
67 ));
68 }
69
70 return $allIsGood;
71 }
72
73 private function initTpl()
74 {
75 # template engine
76 $loader = new Twig_Loader_Filesystem(TPL);
77 if (DEBUG_POCHE) {
78 $twig_params = array();
79 }
80 else {
81 $twig_params = array('cache' => CACHE);
82 }
83 $this->tpl = new Twig_Environment($loader, $twig_params);
84 $this->tpl->addExtension(new Twig_Extensions_Extension_I18n());
85 # filter to display domain name of an url
86 $filter = new Twig_SimpleFilter('getDomain', 'Tools::getDomain');
87 $this->tpl->addFilter($filter);
88
89 # filter for reading time
90 $filter = new Twig_SimpleFilter('getReadingTime', 'Tools::getReadingTime');
91 $this->tpl->addFilter($filter);
92 }
93
94 private function init()
95 {
96 Tools::initPhp();
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);
114
115 # Pagination
116 $this->pagination = new Paginator($this->user->getConfigValue('pager'), 'p');
117 }
118
119 private function install()
120 {
121 Tools::logm('poche still not installed');
122 echo $this->tpl->render('install.twig', array(
123 'token' => Session::getToken()
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 !
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 }
135 }
136 else {
137 Tools::logm('error during installation');
138 Tools::redirect();
139 }
140 }
141 exit();
142 }
143
144 public function getDefaultConfig()
145 {
146 return array(
147 'pager' => PAGINATION,
148 'language' => LANG,
149 );
150 }
151
152 /**
153 * Call action (mark as fav, archive, delete, etc.)
154 */
155 public function action($action, Url $url, $id = 0, $import = FALSE)
156 {
157 switch ($action)
158 {
159 case 'add':
160 if($parametres_url = $url->fetchContent()) {
161 if ($this->store->add($url->getUrl(), $parametres_url['title'], $parametres_url['content'], $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($parametres_url['content'], $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 else {
185 if (!$import) {
186 $this->messages->add('e', _('error during fetching content : the link wasn\'t added'));
187 Tools::logm('error during content fetch ' . $url->getUrl());
188 }
189 }
190 if (!$import) {
191 Tools::redirect();
192 }
193 break;
194 case 'delete':
195 $msg = 'delete link #' . $id;
196 if ($this->store->deleteById($id, $this->user->getId())) {
197 if (DOWNLOAD_PICTURES) {
198 remove_directory(ABS_PATH . $id);
199 }
200 $this->messages->add('s', _('the link has been deleted successfully'));
201 }
202 else {
203 $this->messages->add('e', _('the link wasn\'t deleted'));
204 $msg = 'error : can\'t delete link #' . $id;
205 }
206 Tools::logm($msg);
207 Tools::redirect('?');
208 break;
209 case 'toggle_fav' :
210 $this->store->favoriteById($id, $this->user->getId());
211 Tools::logm('mark as favorite link #' . $id);
212 if (!$import) {
213 Tools::redirect();
214 }
215 break;
216 case 'toggle_archive' :
217 $this->store->archiveById($id, $this->user->getId());
218 Tools::logm('archive link #' . $id);
219 if (!$import) {
220 Tools::redirect();
221 }
222 break;
223 default:
224 Tools::logm('action ' . $action . 'doesn\'t exist');
225 break;
226 }
227 }
228
229 function displayView($view, $id = 0)
230 {
231 $tpl_vars = array();
232
233 switch ($view)
234 {
235 case 'config':
236 $dev = $this->getPocheVersion('dev');
237 $prod = $this->getPocheVersion('prod');
238 $compare_dev = version_compare(POCHE_VERSION, $dev);
239 $compare_prod = version_compare(POCHE_VERSION, $prod);
240 $tpl_vars = array(
241 'dev' => $dev,
242 'prod' => $prod,
243 'compare_dev' => $compare_dev,
244 'compare_prod' => $compare_prod,
245 );
246 Tools::logm('config view');
247 break;
248 case 'view':
249 $entry = $this->store->retrieveOneById($id, $this->user->getId());
250 if ($entry != NULL) {
251 Tools::logm('view link #' . $id);
252 $content = $entry['content'];
253 if (function_exists('tidy_parse_string')) {
254 $tidy = tidy_parse_string($content, array('indent'=>true, 'show-body-only' => true), 'UTF8');
255 $tidy->cleanRepair();
256 $content = $tidy->value;
257 }
258 $tpl_vars = array(
259 'entry' => $entry,
260 'content' => $content,
261 );
262 }
263 else {
264 Tools::logm('error in view call : entry is null');
265 }
266 break;
267 default: # home view
268 $entries = $this->store->getEntriesByView($view, $this->user->getId());
269 $this->pagination->set_total(count($entries));
270 $page_links = $this->pagination->page_links('?view=' . $view . '&sort=' . $_SESSION['sort'] . '&');
271 $datas = $this->store->getEntriesByView($view, $this->user->getId(), $this->pagination->get_limit());
272 $tpl_vars = array(
273 'entries' => $datas,
274 'page_links' => $page_links,
275 );
276 Tools::logm('display ' . $view . ' view');
277 break;
278 }
279
280 return $tpl_vars;
281 }
282
283 /**
284 * update the password of the current user.
285 * if MODE_DEMO is TRUE, the password can't be updated.
286 * @todo add the return value
287 * @todo set the new password in function header like this updatePassword($newPassword)
288 * @return boolean
289 */
290 public function updatePassword()
291 {
292 if (MODE_DEMO) {
293 $this->messages->add('i', _('in demo mode, you can\'t update your password'));
294 Tools::logm('in demo mode, you can\'t do this');
295 Tools::redirect('?view=config');
296 }
297 else {
298 if (isset($_POST['password']) && isset($_POST['password_repeat'])) {
299 if ($_POST['password'] == $_POST['password_repeat'] && $_POST['password'] != "") {
300 $this->messages->add('s', _('your password has been updated'));
301 $this->store->updatePassword($this->user->getId(), Tools::encodeString($_POST['password'] . $this->user->getUsername()));
302 Session::logout();
303 Tools::logm('password updated');
304 Tools::redirect();
305 }
306 else {
307 $this->messages->add('e', _('the two fields have to be filled & the password must be the same in the two fields'));
308 Tools::redirect('?view=config');
309 }
310 }
311 }
312 }
313
314 /**
315 * checks if login & password are correct and save the user in session.
316 * it redirects the user to the $referer link
317 * @param string $referer the url to redirect after login
318 * @todo add the return value
319 * @return boolean
320 */
321 public function login($referer)
322 {
323 if (!empty($_POST['login']) && !empty($_POST['password'])) {
324 $user = $this->store->login($_POST['login'], Tools::encodeString($_POST['password'] . $_POST['login']));
325 if ($user != array()) {
326 # Save login into Session
327 Session::login($user['username'], $user['password'], $_POST['login'], Tools::encodeString($_POST['password'] . $_POST['login']), array('poche_user' => new User($user)));
328
329 $this->messages->add('s', _('welcome to your poche'));
330 if (!empty($_POST['longlastingsession'])) {
331 $_SESSION['longlastingsession'] = 31536000;
332 $_SESSION['expires_on'] = time() + $_SESSION['longlastingsession'];
333 session_set_cookie_params($_SESSION['longlastingsession']);
334 } else {
335 session_set_cookie_params(0);
336 }
337 session_regenerate_id(true);
338 Tools::logm('login successful');
339 Tools::redirect($referer);
340 }
341 $this->messages->add('e', _('login failed: bad login or password'));
342 Tools::logm('login failed');
343 Tools::redirect();
344 } else {
345 $this->messages->add('e', _('login failed: you have to fill all fields'));
346 Tools::logm('login failed');
347 Tools::redirect();
348 }
349 }
350
351 /**
352 * log out the poche user. It cleans the session.
353 * @todo add the return value
354 * @return boolean
355 */
356 public function logout()
357 {
358 $this->user = array();
359 Session::logout();
360 $this->messages->add('s', _('see you soon!'));
361 Tools::logm('logout');
362 Tools::redirect();
363 }
364
365 /**
366 * import from Instapaper. poche needs a ./instapaper-export.html file
367 * @todo add the return value
368 * @return boolean
369 */
370 private function importFromInstapaper()
371 {
372 # TODO gestion des articles favs
373 $html = new simple_html_dom();
374 $html->load_file('./instapaper-export.html');
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 * @return boolean
408 */
409 private function importFromPocket()
410 {
411 # TODO gestion des articles favs
412 $html = new simple_html_dom();
413 $html->load_file('./ril_export.html');
414 Tools::logm('starting import from pocket');
415
416 $read = 0;
417 $errors = array();
418 foreach($html->find('ul') as $ul)
419 {
420 foreach($ul->find('li') as $li)
421 {
422 $a = $li->find('a');
423 $url = new Url(base64_encode($a[0]->href));
424 $this->action('add', $url, 0, TRUE);
425 if ($read == '1') {
426 $sequence = '';
427 if (STORAGE == 'postgres') {
428 $sequence = 'entries_id_seq';
429 }
430 $last_id = $this->store->getLastId($sequence);
431 $this->action('toggle_archive', $url, $last_id, TRUE);
432 }
433 }
434
435 # the second <ul> is for read links
436 $read = 1;
437 }
438 $this->messages->add('s', _('import from pocket completed'));
439 Tools::logm('import from pocket completed');
440 Tools::redirect();
441 }
442
443 /**
444 * import from Readability. poche needs a ./readability file
445 * @todo add the return value
446 * @return boolean
447 */
448 private function importFromReadability()
449 {
450 # TODO gestion des articles lus / favs
451 $str_data = file_get_contents("./readability");
452 $data = json_decode($str_data,true);
453 Tools::logm('starting import from Readability');
454 $count = 0;
455 foreach ($data as $key => $value) {
456 $url = NULL;
457 $favorite = FALSE;
458 $archive = FALSE;
459 foreach ($value as $attr => $attr_value) {
460 if ($attr == 'article__url') {
461 $url = new Url(base64_encode($attr_value));
462 }
463 $sequence = '';
464 if (STORAGE == 'postgres') {
465 $sequence = 'entries_id_seq';
466 }
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) {
485 $last_id = $this->store->getLastId($sequence);
486 $this->action('toggle_archive', $url, $last_id, TRUE);
487 }
488 }
489 }
490 $this->messages->add('s', _('import from Readability completed. ' . $count . ' new links.'));
491 Tools::logm('import from Readability completed');
492 Tools::redirect();
493 }
494
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 */
501 public function import($from)
502 {
503 if ($from == 'pocket') {
504 return $this->importFromPocket();
505 }
506 else if ($from == 'readability') {
507 return $this->importFromReadability();
508 }
509 else if ($from == 'instapaper') {
510 return $this->importFromInstapaper();
511 }
512 }
513
514 /**
515 * export poche entries in json
516 * @return json all poche entries
517 */
518 public function export()
519 {
520 $entries = $this->store->retrieveAll($this->user->getId());
521 echo $this->tpl->render('export.twig', array(
522 'export' => Tools::renderJson($entries),
523 ));
524 Tools::logm('export view');
525 }
526
527 /**
528 * Checks online the latest version of poche and cache it
529 * @param string $which 'prod' or 'dev'
530 * @return string latest $which version
531 */
532 private function getPocheVersion($which = 'prod')
533 {
534 $cache_file = CACHE . '/' . $which;
535
536 # checks if the cached version file exists
537 if (file_exists($cache_file) && (filemtime($cache_file) > (time() - 86400 ))) {
538 $version = file_get_contents($cache_file);
539 } else {
540 $version = file_get_contents('http://static.inthepoche.com/versions/' . $which);
541 file_put_contents($cache_file, $version, LOCK_EX);
542 }
543 return $version;
544 }
545 }