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