]> git.immae.eu Git - github/wallabag/wallabag.git/blame - src/Wallabag/Wallabag/Wallabag.php
restructure folders
[github/wallabag/wallabag.git] / src / Wallabag / Wallabag / Wallabag.php
CommitLineData
eb1af592
NL
1<?php
2/**
c95b78a8 3 * wallabag, self hostable application allowing you to not miss any content anymore
eb1af592 4 *
c95b78a8
NL
5 * @category wallabag
6 * @author Nicolas Lœuillet <nicolas@loeuillet.org>
eb1af592 7 * @copyright 2013
3602405e 8 * @license http://opensource.org/licenses/MIT see COPYING file
eb1af592
NL
9 */
10
6ad93dff
NL
11namespace Wallabag\Wallabag;
12
79e051a1
NL
13use \Paginator;
14use \Session;
15use \Messages;
16use \FeedWriter;
17
6ad93dff 18class Wallabag
eb1af592 19{
3602405e
NL
20 /**
21 * @var User
22 */
7ce7ec4c 23 public $user;
3602405e
NL
24 /**
25 * @var Database
26 */
eb1af592 27 public $store;
3602405e
NL
28 /**
29 * @var Template
30 */
eb1af592 31 public $tpl;
3602405e
NL
32 /**
33 * @var Language
34 */
35 public $language;
36 /**
37 * @var Routing
38 */
39 public $routing;
40 /**
41 * @var Messages
42 */
55821e04 43 public $messages;
3602405e
NL
44 /**
45 * @var Paginator
46 */
6a361945 47 public $pagination;
182faf26 48
00dbaf90 49 public function __construct()
eb1af592 50 {
3602405e 51 $this->init();
eb1af592 52 }
182faf26
MR
53
54 private function init()
00dbaf90
NL
55 {
56 Tools::initPhp();
eb1af592 57
79e051a1 58 $pocheUser = \Session::getParam('poche_user');
3602405e
NL
59
60 if ($pocheUser && $pocheUser != array()) {
61 $this->user = $pocheUser;
00dbaf90 62 } else {
3602405e 63 // fake user, just for install & login screens
00dbaf90
NL
64 $this->user = new User();
65 $this->user->setConfig($this->getDefaultConfig());
66 }
67
3602405e
NL
68 $this->pagination = new Paginator($this->user->getConfigValue('pager'), 'p');
69 $this->language = new Language($this);
70 $this->tpl = new Template($this);
71 $this->store = new Database();
72 $this->messages = new Messages();
73 $this->routing = new Routing($this);
00dbaf90 74 }
182faf26 75
3602405e
NL
76 public function run()
77 {
78 $this->routing->run();
00dbaf90 79 }
182faf26 80
4a291288 81 /**
3602405e 82 * Creates a new user
4a291288 83 */
046b9316 84 public function createNewUser($username, $password, $email = "")
eb1af592 85 {
2f26729c
NL
86 if (!empty($username) && !empty($password)){
87 $newUsername = filter_var($username, FILTER_SANITIZE_STRING);
046b9316 88 $email = filter_var($email, FILTER_SANITIZE_STRING);
2f26729c 89 if (!$this->store->userExists($newUsername)){
046b9316 90 if ($this->store->install($newUsername, Tools::encodeString($password . $newUsername), $email)) {
2f26729c
NL
91 Tools::logm('The new user ' . $newUsername . ' has been installed');
92 $this->messages->add('s', sprintf(_('The new user %s has been installed. Do you want to <a href="?logout">logout ?</a>'), $newUsername));
93 Tools::redirect();
4d99bae8 94 }
95 else {
2f26729c 96 Tools::logm('error during adding new user');
4d99bae8 97 Tools::redirect();
98 }
99 }
2f26729c
NL
100 else {
101 $this->messages->add('e', sprintf(_('Error : An user with the name %s already exists !'), $newUsername));
102 Tools::logm('An user with the name ' . $newUsername . ' already exists !');
103 Tools::redirect();
104 }
4d99bae8 105 }
106 }
b6413975 107
3602405e
NL
108 /**
109 * Delete an existing user
110 */
2f26729c 111 public function deleteUser($password)
3602405e 112 {
2f26729c
NL
113 if ($this->store->listUsers() > 1) {
114 if (Tools::encodeString($password . $this->user->getUsername()) == $this->store->getUserPassword($this->user->getId())) {
115 $username = $this->user->getUsername();
116 $this->store->deleteUserConfig($this->user->getId());
117 Tools::logm('The configuration for user '. $username .' has been deleted !');
118 $this->store->deleteTagsEntriesAndEntries($this->user->getId());
119 Tools::logm('The entries for user '. $username .' has been deleted !');
120 $this->store->deleteUser($this->user->getId());
121 Tools::logm('User '. $username .' has been completely deleted !');
122 Session::logout();
123 Tools::logm('logout');
124 Tools::redirect();
125 $this->messages->add('s', sprintf(_('User %s has been successfully deleted !'), $username));
4d99bae8 126 }
127 else {
2f26729c
NL
128 Tools::logm('Bad password !');
129 $this->messages->add('e', _('Error : The password is wrong !'));
4d99bae8 130 }
131 }
2f26729c
NL
132 else {
133 Tools::logm('Only user !');
134 $this->messages->add('e', _('Error : You are the only user, you cannot delete your account !'));
135 }
4d99bae8 136 }
eb1af592 137
8d3275be 138 public function getDefaultConfig()
182faf26 139 {
8d3275be
NL
140 return array(
141 'pager' => PAGINATION,
142 'language' => LANG,
00dbaf90
NL
143 'theme' => DEFAULT_THEME
144 );
8d3275be
NL
145 }
146
eb1af592
NL
147 /**
148 * Call action (mark as fav, archive, delete, etc.)
149 */
926acd7b 150 public function action($action, Url $url, $id = 0, $import = FALSE, $autoclose = FALSE, $tags = null)
eb1af592
NL
151 {
152 switch ($action)
153 {
154 case 'add':
a297fb1e
MR
155 $content = Tools::getPageContent($url);
156 $title = ($content['rss']['channel']['item']['title'] != '') ? $content['rss']['channel']['item']['title'] : _('Untitled');
157 $body = $content['rss']['channel']['item']['description'];
158
159 // clean content from prevent xss attack
2f26729c 160 $purifier = $this->_getPurifier();
a297fb1e
MR
161 $title = $purifier->purify($title);
162 $body = $purifier->purify($body);
1570a653 163
182faf26 164 //search for possible duplicate
8d7cd2cc 165 $duplicate = NULL;
a297fb1e 166 $duplicate = $this->store->retrieveOneByURL($url->getUrl(), $this->user->getId());
488fc63b 167
182faf26 168 $last_id = $this->store->add($url->getUrl(), $title, $body, $this->user->getId());
a297fb1e 169 if ( $last_id ) {
ec397236 170 Tools::logm('add link ' . $url->getUrl());
ec397236 171 if (DOWNLOAD_PICTURES) {
3602405e 172 $content = Picture::filterPicture($body, $url->getUrl(), $last_id);
ec397236
NL
173 Tools::logm('updating content article');
174 $this->store->updateContent($last_id, $content, $this->user->getId());
175 }
488fc63b
MR
176
177 if ($duplicate != NULL) {
178 // duplicate exists, so, older entry needs to be deleted (as new entry should go to the top of list), BUT favorite mark and tags should be preserved
179 Tools::logm('link ' . $url->getUrl() . ' is a duplicate');
180 // 1) - preserve tags and favorite, then drop old entry
181 $this->store->reassignTags($duplicate['id'], $last_id);
182 if ($duplicate['is_fav']) {
183 $this->store->favoriteById($last_id, $this->user->getId());
184 }
185 if ($this->store->deleteById($duplicate['id'], $this->user->getId())) {
186 Tools::logm('previous link ' . $url->getUrl() .' entry deleted');
187 }
188 }
189
7f782e44 190 // if there are tags, add them to the new article
191 if (isset($_GET['tags'])) {
192 $_POST['value'] = $_GET['tags'];
193 $_POST['entry_id'] = $last_id;
194 $this->action('add_tag', $url);
195 }
196
182faf26 197 $this->messages->add('s', _('the link has been added successfully'));
eb1af592
NL
198 }
199 else {
a297fb1e
MR
200 $this->messages->add('e', _('error during insertion : the link wasn\'t added'));
201 Tools::logm('error during insertion : the link wasn\'t added ' . $url->getUrl());
b916bcfc 202 }
ec397236 203
a297fb1e
MR
204 if ($autoclose == TRUE) {
205 Tools::redirect('?view=home');
206 } else {
207 Tools::redirect('?view=home&closewin=true');
eb1af592
NL
208 }
209 break;
210 case 'delete':
512e5e5b 211 if (isset($_GET['search'])) {
212 //when we want to apply a delete to a search
213 $tags = array($_GET['search']);
214 $allentry_ids = $this->store->search($tags[0], $this->user->getId());
215 $entry_ids = array();
216 foreach ($allentry_ids as $eachentry) {
217 $entry_ids[] = $eachentry[0];
eb1af592 218 }
512e5e5b 219 } else { // delete a single article
220 $entry_ids = array($id);
eb1af592 221 }
512e5e5b 222 foreach($entry_ids as $id) {
223 $msg = 'delete link #' . $id;
224 if ($this->store->deleteById($id, $this->user->getId())) {
225 if (DOWNLOAD_PICTURES) {
226 Picture::removeDirectory(ABS_PATH . $id);
227 }
228 $this->messages->add('s', _('the link has been deleted successfully'));
229 }
230 else {
231 $this->messages->add('e', _('the link wasn\'t deleted'));
232 $msg = 'error : can\'t delete link #' . $id;
233 }
234 Tools::logm($msg);
eb1af592 235 }
985ce3ec 236 Tools::redirect('?');
eb1af592
NL
237 break;
238 case 'toggle_fav' :
8d3275be 239 $this->store->favoriteById($id, $this->user->getId());
eb1af592 240 Tools::logm('mark as favorite link #' . $id);
c2cf7075
MR
241 if ( Tools::isAjaxRequest() ) {
242 echo 1;
243 exit;
244 }
245 else {
246 Tools::redirect();
247 }
eb1af592
NL
248 break;
249 case 'toggle_archive' :
13c7f9a4 250 if (isset($_GET['tag_id'])) {
251 //when we want to archive a whole tag
252 $tag_id = $_GET['tag_id'];
253 $allentry_ids = $this->store->retrieveEntriesByTag($tag_id, $this->user->getId());
254 $entry_ids = array();
255 foreach ($allentry_ids as $eachentry) {
256 $entry_ids[] = $eachentry[0];
257 }
258 } else { //archive a single article
259 $entry_ids = array($id);
260 }
261 foreach($entry_ids as $id) {
262 $this->store->archiveById($id, $this->user->getId());
263 Tools::logm('archive link #' . $id);
264 }
c2cf7075
MR
265 if ( Tools::isAjaxRequest() ) {
266 echo 1;
267 exit;
268 }
269 else {
270 Tools::redirect();
271 }
eb1af592 272 break;
f14807de
NL
273 case 'archive_all' :
274 $this->store->archiveAll($this->user->getId());
275 Tools::logm('archive all links');
a297fb1e 276 Tools::redirect();
f14807de 277 break;
c432fa16 278 case 'add_tag' :
decc23aa 279 if (isset($_GET['search'])) {
280 //when we want to apply a tag to a search
decc23aa 281 $tags = array($_GET['search']);
282 $allentry_ids = $this->store->search($tags[0], $this->user->getId());
283 $entry_ids = array();
284 foreach ($allentry_ids as $eachentry) {
285 $entry_ids[] = $eachentry[0];
286 }
287 } else { //add a tag to a single article
288 $tags = explode(',', $_POST['value']);
289 $entry_ids = array($_POST['entry_id']);
fb26cc93 290 }
decc23aa 291 foreach($entry_ids as $entry_id) {
292 $entry = $this->store->retrieveOneById($entry_id, $this->user->getId());
293 if (!$entry) {
294 $this->messages->add('e', _('Article not found!'));
295 Tools::logm('error : article not found');
296 Tools::redirect();
297 }
298 //get all already set tags to preven duplicates
299 $already_set_tags = array();
300 $entry_tags = $this->store->retrieveTagsByEntry($entry_id);
301 foreach ($entry_tags as $tag) {
302 $already_set_tags[] = $tag['value'];
303 }
304 foreach($tags as $key => $tag_value) {
305 $value = trim($tag_value);
306 if ($value && !in_array($value, $already_set_tags)) {
307 $tag = $this->store->retrieveTagByValue($value);
308 if (is_null($tag)) {
309 # we create the tag
310 $tag = $this->store->createTag($value);
311 $sequence = '';
312 if (STORAGE == 'postgres') {
313 $sequence = 'tags_id_seq';
314 }
315 $tag_id = $this->store->getLastId($sequence);
fb26cc93 316 }
decc23aa 317 else {
318 $tag_id = $tag['id'];
319 }
320
321 # we assign the tag to the article
322 $this->store->setTagToEntry($tag_id, $entry_id);
323 }
c432fa16 324 }
c432fa16 325 }
9c743ab9 326 $this->messages->add('s', _('The tag has been applied successfully'));
24696800 327 Tools::logm('The tag has been applied successfully');
a297fb1e 328 Tools::redirect();
c432fa16
NL
329 break;
330 case 'remove_tag' :
331 $tag_id = $_GET['tag_id'];
b89d5a2b
NL
332 $entry = $this->store->retrieveOneById($id, $this->user->getId());
333 if (!$entry) {
334 $this->messages->add('e', _('Article not found!'));
335 Tools::logm('error : article not found');
336 Tools::redirect();
337 }
c432fa16 338 $this->store->removeTagForEntry($id, $tag_id);
9c743ab9 339 Tools::logm('tag entry deleted');
24696800 340 if ($this->store->cleanUnusedTag($tag_id)) {
341 Tools::logm('tag deleted');
342 }
9c743ab9 343 $this->messages->add('s', _('The tag has been successfully deleted'));
c432fa16
NL
344 Tools::redirect();
345 break;
eb1af592
NL
346 default:
347 break;
348 }
349 }
350
351 function displayView($view, $id = 0)
352 {
353 $tpl_vars = array();
354
355 switch ($view)
356 {
3c133bff
NL
357 case 'about':
358 break;
eb1af592 359 case 'config':
2f26729c 360 $dev_infos = $this->_getPocheVersion('dev');
11c680f9
NL
361 $dev = trim($dev_infos[0]);
362 $check_time_dev = date('d-M-Y H:i', $dev_infos[1]);
2f26729c 363 $prod_infos = $this->_getPocheVersion('prod');
11c680f9
NL
364 $prod = trim($prod_infos[0]);
365 $check_time_prod = date('d-M-Y H:i', $prod_infos[1]);
031df528
NL
366 $compare_dev = version_compare(POCHE, $dev);
367 $compare_prod = version_compare(POCHE, $prod);
3602405e
NL
368 $themes = $this->tpl->getInstalledThemes();
369 $languages = $this->language->getInstalledLanguages();
72c20a52 370 $token = $this->user->getConfigValue('token');
1810c13b 371 $http_auth = (isset($_SERVER['PHP_AUTH_USER']) || isset($_SERVER['REMOTE_USER'])) ? true : false;
4d99bae8 372 $only_user = ($this->store->listUsers() > 1) ? false : true;
32520785 373 $tpl_vars = array(
00dbaf90 374 'themes' => $themes,
5011388f 375 'languages' => $languages,
32520785
NL
376 'dev' => $dev,
377 'prod' => $prod,
11c680f9
NL
378 'check_time_dev' => $check_time_dev,
379 'check_time_prod' => $check_time_prod,
32520785
NL
380 'compare_dev' => $compare_dev,
381 'compare_prod' => $compare_prod,
72c20a52
NL
382 'token' => $token,
383 'user_id' => $this->user->getId(),
df6afaf0 384 'http_auth' => $http_auth,
4d99bae8 385 'only_user' => $only_user
32520785 386 );
eb1af592
NL
387 Tools::logm('config view');
388 break;
6cab59c3
NL
389 case 'edit-tags':
390 # tags
b89d5a2b
NL
391 $entry = $this->store->retrieveOneById($id, $this->user->getId());
392 if (!$entry) {
393 $this->messages->add('e', _('Article not found!'));
394 Tools::logm('error : article not found');
395 Tools::redirect();
396 }
6cab59c3
NL
397 $tags = $this->store->retrieveTagsByEntry($id);
398 $tpl_vars = array(
c432fa16 399 'entry_id' => $id,
6cab59c3 400 'tags' => $tags,
032e0ca1 401 'entry' => $entry,
4886ed6d
NL
402 );
403 break;
2e2ebe5e 404 case 'tags':
f778e472 405 $token = $this->user->getConfigValue('token');
fb26cc93
MR
406 //if term is set - search tags for this term
407 $term = Tools::checkVar('term');
408 $tags = $this->store->retrieveAllTags($this->user->getId(), $term);
409 if (Tools::isAjaxRequest()) {
410 $result = array();
411 foreach ($tags as $tag) {
412 $result[] = $tag['value'];
413 }
414 echo json_encode($result);
415 exit;
416 }
2e2ebe5e 417 $tpl_vars = array(
f778e472
NL
418 'token' => $token,
419 'user_id' => $this->user->getId(),
2e2ebe5e
NL
420 'tags' => $tags,
421 );
422 break;
a4585f7e
MR
423 case 'search':
424 if (isset($_GET['search'])) {
425 $search = filter_var($_GET['search'], FILTER_SANITIZE_STRING);
426 $tpl_vars['entries'] = $this->store->search($search, $this->user->getId());
427 $count = count($tpl_vars['entries']);
428 $this->pagination->set_total($count);
429 $page_links = str_replace(array('previous', 'next'), array(_('previous'), _('next')),
430 $this->pagination->page_links('?view=' . $view . '?search=' . $search . '&sort=' . $_SESSION['sort'] . '&' ));
431 $tpl_vars['page_links'] = $page_links;
432 $tpl_vars['nb_results'] = $count;
1b6e21d7 433 $tpl_vars['searchterm'] = $search;
a4585f7e
MR
434 }
435 break;
eb1af592 436 case 'view':
8d3275be 437 $entry = $this->store->retrieveOneById($id, $this->user->getId());
eb1af592
NL
438 if ($entry != NULL) {
439 Tools::logm('view link #' . $id);
440 $content = $entry['content'];
441 if (function_exists('tidy_parse_string')) {
442 $tidy = tidy_parse_string($content, array('indent'=>true, 'show-body-only' => true), 'UTF8');
443 $tidy->cleanRepair();
444 $content = $tidy->value;
3408ed48 445 }
a3223127 446
3408ed48 447 # flattr checking
37cad522
TC
448 $flattr = NULL;
449 if (FLATTR) {
450 $flattr = new FlattrItem();
451 $flattr->checkItem($entry['url'], $entry['id']);
452 }
453
7b171c73
NL
454 # tags
455 $tags = $this->store->retrieveTagsByEntry($entry['id']);
a3223127 456
3408ed48 457 $tpl_vars = array(
7b171c73
NL
458 'entry' => $entry,
459 'content' => $content,
460 'flattr' => $flattr,
461 'tags' => $tags
3408ed48 462 );
eb1af592
NL
463 }
464 else {
d8d1542e 465 Tools::logm('error in view call : entry is null');
eb1af592
NL
466 }
467 break;
032e0ca1 468 default: # home, favorites, archive and tag views
eb1af592 469 $tpl_vars = array(
3eb04903
N
470 'entries' => '',
471 'page_links' => '',
7f9f5281 472 'nb_results' => '',
6065553c 473 'listmode' => (isset($_COOKIE['listmode']) ? true : false),
eb1af592 474 );
182faf26 475
3602405e 476 //if id is given - we retrieve entries by tag: id is tag id
032e0ca1
MR
477 if ($id) {
478 $tpl_vars['tag'] = $this->store->retrieveTag($id, $this->user->getId());
479 $tpl_vars['id'] = intval($id);
480 }
481
482 $count = $this->store->getEntriesByViewCount($view, $this->user->getId(), $id);
483
484 if ($count > 0) {
485 $this->pagination->set_total($count);
c515ffec 486 $page_links = str_replace(array('previous', 'next'), array(_('previous'), _('next')),
032e0ca1
MR
487 $this->pagination->page_links('?view=' . $view . '&sort=' . $_SESSION['sort'] . (($id)?'&id='.$id:'') . '&' ));
488 $tpl_vars['entries'] = $this->store->getEntriesByView($view, $this->user->getId(), $this->pagination->get_limit(), $id);
3eb04903 489 $tpl_vars['page_links'] = $page_links;
032e0ca1 490 $tpl_vars['nb_results'] = $count;
3eb04903 491 }
6a361945 492 Tools::logm('display ' . $view . ' view');
eb1af592
NL
493 break;
494 }
495
496 return $tpl_vars;
497 }
c765c367 498
07ee09f4 499 /**
182faf26
MR
500 * update the password of the current user.
501 * if MODE_DEMO is TRUE, the password can't be updated.
07ee09f4
NL
502 * @todo add the return value
503 * @todo set the new password in function header like this updatePassword($newPassword)
504 * @return boolean
505 */
2f26729c 506 public function updatePassword($password, $confirmPassword)
c765c367 507 {
55821e04 508 if (MODE_DEMO) {
8d3275be 509 $this->messages->add('i', _('in demo mode, you can\'t update your password'));
55821e04 510 Tools::logm('in demo mode, you can\'t do this');
6a361945 511 Tools::redirect('?view=config');
55821e04
NL
512 }
513 else {
2f26729c
NL
514 if (isset($password) && isset($confirmPassword)) {
515 if ($password == $confirmPassword && !empty($password)) {
8d3275be 516 $this->messages->add('s', _('your password has been updated'));
2f26729c 517 $this->store->updatePassword($this->user->getId(), Tools::encodeString($password . $this->user->getUsername()));
c765c367 518 Session::logout();
8d3275be 519 Tools::logm('password updated');
c765c367
NL
520 Tools::redirect();
521 }
522 else {
8d3275be 523 $this->messages->add('e', _('the two fields have to be filled & the password must be the same in the two fields'));
6a361945 524 Tools::redirect('?view=config');
c765c367
NL
525 }
526 }
527 }
528 }
182faf26 529
df6afaf0 530 /**
2f26729c
NL
531 * Get credentials from differents sources
532 * It redirects the user to the $referer link
533 *
df6afaf0
DS
534 * @return array
535 */
2f26729c
NL
536 private function credentials()
537 {
538 if (isset($_SERVER['PHP_AUTH_USER'])) {
539 return array($_SERVER['PHP_AUTH_USER'], 'php_auth', true);
1810c13b 540 }
2f26729c
NL
541 if (!empty($_POST['login']) && !empty($_POST['password'])) {
542 return array($_POST['login'], $_POST['password'], false);
1810c13b 543 }
2f26729c
NL
544 if (isset($_SERVER['REMOTE_USER'])) {
545 return array($_SERVER['REMOTE_USER'], 'http_auth', true);
1810c13b 546 }
5cfafc61 547
2f26729c 548 return array(false, false, false);
6af66b11 549 }
df6afaf0 550
07ee09f4
NL
551 /**
552 * checks if login & password are correct and save the user in session.
553 * it redirects the user to the $referer link
554 * @param string $referer the url to redirect after login
555 * @todo add the return value
556 * @return boolean
557 */
c765c367
NL
558 public function login($referer)
559 {
6af66b11 560 list($login,$password,$isauthenticated)=$this->credentials();
df6afaf0
DS
561 if($login === false || $password === false) {
562 $this->messages->add('e', _('login failed: you have to fill all fields'));
563 Tools::logm('login failed');
564 Tools::redirect();
565 }
566 if (!empty($login) && !empty($password)) {
6af66b11 567 $user = $this->store->login($login, Tools::encodeString($password . $login), $isauthenticated);
7ce7ec4c
NL
568 if ($user != array()) {
569 # Save login into Session
6af66b11
MR
570 $longlastingsession = isset($_POST['longlastingsession']);
571 $passwordTest = ($isauthenticated) ? $user['password'] : Tools::encodeString($password . $login);
572 Session::login($user['username'], $user['password'], $login, $passwordTest, $longlastingsession, array('poche_user' => new User($user)));
9cf6bac1
NL
573
574 # reload l10n
575 $language = $user['config']['language'];
576 @putenv('LC_ALL=' . $language);
577 setlocale(LC_ALL, $language);
578 bindtextdomain($language, LOCALE);
579 textdomain($language);
580
26929c08 581 $this->messages->add('s', _('welcome to your wallabag'));
8d3275be 582 Tools::logm('login successful');
c765c367
NL
583 Tools::redirect($referer);
584 }
8d3275be 585 $this->messages->add('e', _('login failed: bad login or password'));
c86b40f0
GV
586 // log login failure in web server log to allow fail2ban usage
587 error_log('user '.$login.' authentication failure');
c765c367
NL
588 Tools::logm('login failed');
589 Tools::redirect();
c765c367
NL
590 }
591 }
592
07ee09f4
NL
593 /**
594 * log out the poche user. It cleans the session.
595 * @todo add the return value
182faf26 596 * @return boolean
07ee09f4 597 */
c765c367
NL
598 public function logout()
599 {
7ce7ec4c 600 $this->user = array();
c765c367 601 Session::logout();
b916bcfc 602 Tools::logm('logout');
c765c367
NL
603 Tools::redirect();
604 }
605
07ee09f4 606 /**
2f26729c 607 * import datas into your wallabag
182faf26 608 * @return boolean
07ee09f4 609 */
2f26729c 610
182faf26
MR
611 public function import() {
612
dc764892 613 if ( isset($_FILES['file']) && $_FILES['file']['tmp_name'] ) {
5ce39784
MR
614 Tools::logm('Import stated: parsing file');
615
182faf26
MR
616 // assume, that file is in json format
617 $str_data = file_get_contents($_FILES['file']['tmp_name']);
618 $data = json_decode($str_data, true);
619
620 if ( $data === null ) {
621 //not json - assume html
622 $html = new simple_html_dom();
623 $html->load_file($_FILES['file']['tmp_name']);
624 $data = array();
625 $read = 0;
626 foreach (array('ol','ul') as $list) {
627 foreach ($html->find($list) as $ul) {
86da3988
MR
628 foreach ($ul->find('li') as $li) {
629 $tmpEntry = array();
a8ef1f3f
MR
630 $a = $li->find('a');
631 $tmpEntry['url'] = $a[0]->href;
632 $tmpEntry['tags'] = $a[0]->tags;
633 $tmpEntry['is_read'] = $read;
634 if ($tmpEntry['url']) {
635 $data[] = $tmpEntry;
636 }
86da3988
MR
637 }
638 # the second <ol/ul> is for read links
639 $read = ((sizeof($data) && $read)?0:1);
182faf26
MR
640 }
641 }
1daa8e4a 642 }
182faf26 643
2f26729c
NL
644 // for readability structure
645
646 foreach($data as $record) {
647 if (is_array($record)) {
648 $data[] = $record;
649 foreach($record as $record2) {
650 if (is_array($record2)) {
651 $data[] = $record2;
652 }
653 }
654 }
a297fb1e 655 }
a297fb1e 656
2f26729c
NL
657 $urlsInserted = array(); //urls of articles inserted
658 foreach($data as $record) {
659 $url = trim(isset($record['article__url']) ? $record['article__url'] : (isset($record['url']) ? $record['url'] : ''));
660 if ($url and !in_array($url, $urlsInserted)) {
661 $title = (isset($record['title']) ? $record['title'] : _('Untitled - Import - ') . '</a> <a href="./?import">' . _('click to finish import') . '</a><a>');
662 $body = (isset($record['content']) ? $record['content'] : '');
663 $isRead = (isset($record['is_read']) ? intval($record['is_read']) : (isset($record['archive']) ? intval($record['archive']) : 0));
664 $isFavorite = (isset($record['is_fav']) ? intval($record['is_fav']) : (isset($record['favorite']) ? intval($record['favorite']) : 0));
665
666 // insert new record
667
668 $id = $this->store->add($url, $title, $body, $this->user->getId() , $isFavorite, $isRead);
669 if ($id) {
670 $urlsInserted[] = $url; //add
671 if (isset($record['tags']) && trim($record['tags'])) {
672
673 // @TODO: set tags
674
675 }
676 }
677 }
182faf26 678 }
182faf26 679
2f26729c
NL
680 $i = sizeof($urlsInserted);
681 if ($i > 0) {
682 $this->messages->add('s', _('Articles inserted: ') . $i . _('. Please note, that some may be marked as "read".'));
683 }
684
5ce39784 685 Tools::logm('Import of articles finished: '.$i.' articles added (w/o content if not provided).');
182faf26 686 }
dc764892
MR
687 else {
688 $this->messages->add('s', _('Did you forget to select a file?'));
689 }
2f26729c
NL
690 // file parsing finished here
691 // now download article contents if any
692 // check if we need to download any content
182faf26 693
2f26729c
NL
694 $recordsDownloadRequired = $this->store->retrieveUnfetchedEntriesCount($this->user->getId());
695
696 if ($recordsDownloadRequired == 0) {
182faf26 697
2f26729c 698 // nothing to download
182faf26 699
2f26729c
NL
700 $this->messages->add('s', _('Import finished.'));
701 Tools::logm('Import finished completely');
702 Tools::redirect();
703 }
704 else {
182faf26 705
2f26729c 706 // if just inserted - don't download anything, download will start in next reload
182faf26 707
2f26729c 708 if (!isset($_FILES['file'])) {
182faf26 709
2f26729c 710 // download next batch
182faf26 711
2f26729c
NL
712 Tools::logm('Fetching next batch of articles...');
713 $items = $this->store->retrieveUnfetchedEntries($this->user->getId() , IMPORT_LIMIT);
714 $purifier = $this->_getPurifier();
715 foreach($items as $item) {
716 $url = new Url(base64_encode($item['url']));
717 Tools::logm('Fetching article ' . $item['id']);
718 $content = Tools::getPageContent($url);
719 $title = (($content['rss']['channel']['item']['title'] != '') ? $content['rss']['channel']['item']['title'] : _('Untitled'));
720 $body = (($content['rss']['channel']['item']['description'] != '') ? $content['rss']['channel']['item']['description'] : _('Undefined'));
721
722 // clean content to prevent xss attack
723
724 $title = $purifier->purify($title);
725 $body = $purifier->purify($body);
726 $this->store->updateContentAndTitle($item['id'], $title, $body, $this->user->getId());
727 Tools::logm('Article ' . $item['id'] . ' updated.');
728 }
729 }
63c35580 730 }
182faf26 731
2f26729c
NL
732 return array(
733 'includeImport' => true,
734 'import' => array(
735 'recordsDownloadRequired' => $recordsDownloadRequired,
736 'recordsUnderDownload' => IMPORT_LIMIT,
737 'delay' => IMPORT_DELAY * 1000
738 )
739 );
63c35580 740 }
c765c367 741
07ee09f4
NL
742 /**
743 * export poche entries in json
744 * @return json all poche entries
745 */
2f26729c
NL
746 public function export()
747 {
a8ef1f3f
MR
748 $filename = "wallabag-export-".$this->user->getId()."-".date("Y-m-d").".json";
749 header('Content-Disposition: attachment; filename='.$filename);
750
751 $entries = $this->store->retrieveAll($this->user->getId());
752 echo $this->tpl->render('export.twig', array(
753 'export' => Tools::renderJson($entries),
754 ));
755 Tools::logm('export view');
c765c367 756 }
32520785 757
07ee09f4 758 /**
a3436d4c 759 * Checks online the latest version of poche and cache it
07ee09f4
NL
760 * @param string $which 'prod' or 'dev'
761 * @return string latest $which version
762 */
2f26729c 763 private function _getPocheVersion($which = 'prod') {
a8ef1f3f
MR
764 $cache_file = CACHE . '/' . $which;
765 $check_time = time();
766
767 # checks if the cached version file exists
768 if (file_exists($cache_file) && (filemtime($cache_file) > (time() - 86400 ))) {
769 $version = file_get_contents($cache_file);
770 $check_time = filemtime($cache_file);
771 } else {
772 $version = file_get_contents('http://static.wallabag.org/versions/' . $which);
773 file_put_contents($cache_file, $version, LOCK_EX);
774 }
775 return array($version, $check_time);
32520785 776 }
72c20a52 777
2f26729c
NL
778 /**
779 * Update token for current user
780 */
781 public function updateToken()
72c20a52 782 {
2f26729c
NL
783 $token = Tools::generateToken();
784 $this->store->updateUserConfig($this->user->getId(), 'token', $token);
785 $currentConfig = $_SESSION['poche_user']->config;
786 $currentConfig['token'] = $token;
787 $_SESSION['poche_user']->setConfig($currentConfig);
788 Tools::redirect();
72c20a52
NL
789 }
790
2f26729c
NL
791 /**
792 * Generate RSS feeds for current user
793 *
794 * @param $token
795 * @param $user_id
7fe8a9ad
VM
796 * @param $tag_id if $type is 'tag', the id of the tag to generate feed for
797 * @param string $type the type of feed to generate
798 * @param int $limit the maximum number of items (0 means all)
2f26729c 799 */
7fe8a9ad 800 public function generateFeeds($token, $user_id, $tag_id, $type = 'home', $limit = 0)
72c20a52 801 {
f778e472 802 $allowed_types = array('home', 'fav', 'archive', 'tag');
72c20a52
NL
803 $config = $this->store->getConfigUser($user_id);
804
17b2afef 805 if ($config == null) {
30bd2735 806 die(sprintf(_('User with this id (%d) does not exist.'), $user_id));
17b2afef
NL
807 }
808
7dd8b502
MR
809 if (!in_array($type, $allowed_types) || !isset($config['token']) || $token != $config['token']) {
810 die(_('Uh, there is a problem while generating feed. Wrong token used?'));
72c20a52 811 }
72c20a52 812
9e7c840b 813 $feed = new FeedWriter(RSS2);
2e4440c3 814 $feed->setTitle('wallabag — ' . $type . ' feed');
72c20a52 815 $feed->setLink(Tools::getPocheUrl());
223268c2
NL
816 $feed->setChannelElement('pubDate', date(DATE_RSS , time()));
817 $feed->setChannelElement('generator', 'wallabag');
818 $feed->setDescription('wallabag ' . $type . ' elements');
72c20a52 819
f778e472 820 if ($type == 'tag') {
b89d5a2b 821 $entries = $this->store->retrieveEntriesByTag($tag_id, $user_id);
f778e472
NL
822 }
823 else {
824 $entries = $this->store->getEntriesByView($type, $user_id);
825 }
826
7fe8a9ad
VM
827 // if $limit is set to zero, use all entries
828 if (0 == $limit) {
829 $limit = count($entries);
830 }
72c20a52 831 if (count($entries) > 0) {
7fe8a9ad
VM
832 for ($i = 0; $i < min(count($entries), $limit); $i++) {
833 $entry = $entries[$i];
72c20a52 834 $newItem = $feed->createNewItem();
0b57c682 835 $newItem->setTitle($entry['title']);
f86784c2 836 $newItem->setSource(Tools::getPocheUrl() . '?view=view&amp;id=' . $entry['id']);
ed02e38e 837 $newItem->setLink($entry['url']);
72c20a52
NL
838 $newItem->setDate(time());
839 $newItem->setDescription($entry['content']);
840 $feed->addItem($newItem);
841 }
842 }
843
844 $feed->genarateFeed();
845 exit;
846 }
6285e57c 847
6285e57c 848
0f859c6f
MR
849
850 /**
2f26729c 851 * Returns new purifier object with actual config
0f859c6f 852 */
2f26729c
NL
853 private function _getPurifier()
854 {
855 $config = HTMLPurifier_Config::createDefault();
856 $config->set('Cache.SerializerPath', CACHE);
857 $config->set('HTML.SafeIframe', true);
35d4e275 858
2f26729c
NL
859 //allow YouTube, Vimeo and dailymotion videos
860 $config->set('URI.SafeIframeRegexp', '%^(https?:)?//(www\.youtube(?:-nocookie)?\.com/embed/|player\.vimeo\.com/video/|www\.dailymotion\.com/embed/video/)%');
ec15d0a7 861
2f26729c 862 return new HTMLPurifier($config);
0f859c6f 863 }
cbc75bef 864
cbc75bef 865
37cad522 866}