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