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