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