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