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