]> git.immae.eu Git - github/wallabag/wallabag.git/blame - inc/poche/Poche.class.php
import without cron
[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
NL
7 * @copyright 2013
8 * @license http://www.wtfpl.net/ see COPYING file
9 */
10
11class Poche
12{
00dbaf90
NL
13 public static $canRenderTemplates = true;
14 public static $configFileAvailable = true;
15
7ce7ec4c 16 public $user;
eb1af592
NL
17 public $store;
18 public $tpl;
55821e04 19 public $messages;
6a361945 20 public $pagination;
182faf26 21
00dbaf90 22 private $currentTheme = '';
5011388f 23 private $currentLanguage = '';
9d3b88b3 24 private $notInstalledMessage = array();
eb1af592 25
c9bd17a1
NL
26 private $language_names = array(
27 'cs_CZ.utf8' => 'čeština',
28 'de_DE.utf8' => 'German',
29 'en_EN.utf8' => 'English',
30 'es_ES.utf8' => 'Español',
31 'fa_IR.utf8' => 'فارسی',
32 'fr_FR.utf8' => 'Français',
33 'it_IT.utf8' => 'Italiano',
34 'pl_PL.utf8' => 'Polski',
5805ac45 35 'pt_BR.utf8' => 'Português (Brasil)',
c9bd17a1
NL
36 'ru_RU.utf8' => 'Pусский',
37 'sl_SI.utf8' => 'Slovenščina',
cbcae403 38 'uk_UA.utf8' => 'Українська',
c9bd17a1 39 );
00dbaf90 40 public function __construct()
eb1af592 41 {
9d3b88b3
NL
42 if ($this->configFileIsAvailable()) {
43 $this->init();
00dbaf90 44 }
182faf26 45
9d3b88b3
NL
46 if ($this->themeIsInstalled()) {
47 $this->initTpl();
00dbaf90 48 }
182faf26 49
9d3b88b3
NL
50 if ($this->systemIsInstalled()) {
51 $this->store = new Database();
52 $this->messages = new Messages();
53 # installation
54 if (! $this->store->isInstalled()) {
55 $this->install();
56 }
5cfafc61 57 $this->store->checkTags();
eb1af592 58 }
eb1af592 59 }
182faf26
MR
60
61 private function init()
00dbaf90
NL
62 {
63 Tools::initPhp();
eb1af592 64
00dbaf90
NL
65 if (isset($_SESSION['poche_user']) && $_SESSION['poche_user'] != array()) {
66 $this->user = $_SESSION['poche_user'];
67 } else {
68 # fake user, just for install & login screens
69 $this->user = new User();
70 $this->user->setConfig($this->getDefaultConfig());
71 }
72
73 # l10n
74 $language = $this->user->getConfigValue('language');
75 putenv('LC_ALL=' . $language);
76 setlocale(LC_ALL, $language);
182faf26
MR
77 bindtextdomain($language, LOCALE);
78 textdomain($language);
00dbaf90
NL
79
80 # Pagination
81 $this->pagination = new Paginator($this->user->getConfigValue('pager'), 'p');
182faf26 82
00dbaf90
NL
83 # Set up theme
84 $themeDirectory = $this->user->getConfigValue('theme');
182faf26 85
00dbaf90
NL
86 if ($themeDirectory === false) {
87 $themeDirectory = DEFAULT_THEME;
88 }
182faf26 89
00dbaf90 90 $this->currentTheme = $themeDirectory;
5011388f
NL
91
92 # Set up language
93 $languageDirectory = $this->user->getConfigValue('language');
182faf26 94
5011388f
NL
95 if ($languageDirectory === false) {
96 $languageDirectory = DEFAULT_THEME;
97 }
182faf26 98
5011388f 99 $this->currentLanguage = $languageDirectory;
00dbaf90
NL
100 }
101
102 public function configFileIsAvailable() {
103 if (! self::$configFileAvailable) {
9d3b88b3 104 $this->notInstalledMessage[] = 'You have to rename inc/poche/config.inc.php.new to inc/poche/config.inc.php.';
00dbaf90
NL
105
106 return false;
107 }
108
109 return true;
110 }
182faf26 111
00dbaf90 112 public function themeIsInstalled() {
9d3b88b3 113 $passTheme = TRUE;
00dbaf90
NL
114 # Twig is an absolute requirement for Poche to function. Abort immediately if the Composer installer hasn't been run yet
115 if (! self::$canRenderTemplates) {
41265e07 116 $this->notInstalledMessage[] = 'Twig does not seem to be installed. Please initialize the Composer installation to automatically fetch dependencies. You can also download <a href="http://wllbg.org/vendor">vendor.zip</a> and extract it in your wallabag folder.';
9d3b88b3 117 $passTheme = FALSE;
00dbaf90 118 }
7f17a38d
NL
119
120 if (! is_writable(CACHE)) {
9d3b88b3 121 $this->notInstalledMessage[] = 'You don\'t have write access on cache directory.';
7f17a38d
NL
122
123 self::$canRenderTemplates = false;
124
9d3b88b3 125 $passTheme = FALSE;
182faf26
MR
126 }
127
00dbaf90 128 # Check if the selected theme and its requirements are present
f4fbfaa7
NL
129 $theme = $this->getTheme();
130
131 if ($theme != '' && ! is_dir(THEME . '/' . $theme)) {
132 $this->notInstalledMessage[] = 'The currently selected theme (' . $theme . ') does not seem to be properly installed (Missing directory: ' . THEME . '/' . $theme . ')';
182faf26 133
00dbaf90 134 self::$canRenderTemplates = false;
182faf26 135
9d3b88b3 136 $passTheme = FALSE;
00dbaf90 137 }
182faf26 138
f4fbfaa7
NL
139 $themeInfo = $this->getThemeInfo($theme);
140 if (isset($themeInfo['requirements']) && is_array($themeInfo['requirements'])) {
141 foreach ($themeInfo['requirements'] as $requiredTheme) {
142 if (! is_dir(THEME . '/' . $requiredTheme)) {
143 $this->notInstalledMessage[] = 'The required "' . $requiredTheme . '" theme is missing for the current theme (' . $theme . ')';
182faf26 144
f4fbfaa7 145 self::$canRenderTemplates = false;
182faf26 146
f4fbfaa7
NL
147 $passTheme = FALSE;
148 }
00dbaf90
NL
149 }
150 }
9d3b88b3
NL
151
152 if (!$passTheme) {
153 return FALSE;
154 }
155
182faf26 156
00dbaf90
NL
157 return true;
158 }
182faf26 159
4a291288
NL
160 /**
161 * all checks before installation.
00dbaf90 162 * @todo move HTML to template
182faf26 163 * @return boolean
4a291288 164 */
00dbaf90 165 public function systemIsInstalled()
eb1af592 166 {
9d3b88b3 167 $msg = TRUE;
182faf26 168
00dbaf90 169 $configSalt = defined('SALT') ? constant('SALT') : '';
182faf26 170
00dbaf90 171 if (empty($configSalt)) {
9d3b88b3
NL
172 $this->notInstalledMessage[] = 'You have not yet filled in the SALT value in the config.inc.php file.';
173 $msg = FALSE;
174 }
175 if (STORAGE == 'sqlite' && ! file_exists(STORAGE_SQLITE)) {
00dbaf90 176 Tools::logm('sqlite file doesn\'t exist');
9d3b88b3
NL
177 $this->notInstalledMessage[] = 'sqlite file doesn\'t exist, you can find it in install folder. Copy it in /db folder.';
178 $msg = FALSE;
179 }
180 if (is_dir(ROOT . '/install') && ! DEBUG_POCHE) {
181 $this->notInstalledMessage[] = 'you have to delete the /install folder before using poche.';
182 $msg = FALSE;
183 }
184 if (STORAGE == 'sqlite' && ! is_writable(STORAGE_SQLITE)) {
bb5a7d9e 185 Tools::logm('you don\'t have write access on sqlite file');
9d3b88b3
NL
186 $this->notInstalledMessage[] = 'You don\'t have write access on sqlite file.';
187 $msg = FALSE;
bb5a7d9e 188 }
00dbaf90 189
9d3b88b3 190 if (! $msg) {
00dbaf90 191 return false;
8d3275be 192 }
7ce7ec4c 193
00dbaf90
NL
194 return true;
195 }
182faf26 196
00dbaf90
NL
197 public function getNotInstalledMessage() {
198 return $this->notInstalledMessage;
4a291288 199 }
eb1af592 200
4a291288
NL
201 private function initTpl()
202 {
00dbaf90 203 $loaderChain = new Twig_Loader_Chain();
f4fbfaa7 204 $theme = $this->getTheme();
182faf26 205
00dbaf90
NL
206 # add the current theme as first to the loader chain so Twig will look there first for overridden template files
207 try {
f4fbfaa7 208 $loaderChain->addLoader(new Twig_Loader_Filesystem(THEME . '/' . $theme));
00dbaf90
NL
209 } catch (Twig_Error_Loader $e) {
210 # @todo isInstalled() should catch this, inject Twig later
f4fbfaa7 211 die('The currently selected theme (' . $theme . ') does not seem to be properly installed (' . THEME . '/' . $theme .' is missing)');
00dbaf90 212 }
182faf26 213
00dbaf90 214 # add all required themes to the loader chain
f4fbfaa7
NL
215 $themeInfo = $this->getThemeInfo($theme);
216 if (isset($themeInfo['requirements']) && is_array($themeInfo['requirements'])) {
217 foreach ($themeInfo['requirements'] as $requiredTheme) {
218 try {
219 $loaderChain->addLoader(new Twig_Loader_Filesystem(THEME . '/' . $requiredTheme));
220 } catch (Twig_Error_Loader $e) {
221 # @todo isInstalled() should catch this, inject Twig later
222 die('The required "' . $requiredTheme . '" theme is missing for the current theme (' . $theme . ')');
223 }
00dbaf90
NL
224 }
225 }
182faf26 226
bc1ee852 227 if (DEBUG_POCHE) {
f4fbfaa7 228 $twigParams = array();
00dbaf90 229 } else {
f4fbfaa7 230 $twigParams = array('cache' => CACHE);
bc1ee852 231 }
182faf26 232
f4fbfaa7 233 $this->tpl = new Twig_Environment($loaderChain, $twigParams);
eb1af592 234 $this->tpl->addExtension(new Twig_Extensions_Extension_I18n());
182faf26 235
55821e04
NL
236 # filter to display domain name of an url
237 $filter = new Twig_SimpleFilter('getDomain', 'Tools::getDomain');
238 $this->tpl->addFilter($filter);
eb1af592 239
d9178758
NL
240 # filter for reading time
241 $filter = new Twig_SimpleFilter('getReadingTime', 'Tools::getReadingTime');
242 $this->tpl->addFilter($filter);
eb1af592
NL
243 }
244
f4fbfaa7 245 private function install()
eb1af592
NL
246 {
247 Tools::logm('poche still not installed');
248 echo $this->tpl->render('install.twig', array(
00dbaf90
NL
249 'token' => Session::getToken(),
250 'theme' => $this->getTheme(),
251 'poche_url' => Tools::getPocheUrl()
eb1af592
NL
252 ));
253 if (isset($_GET['install'])) {
182faf26 254 if (($_POST['password'] == $_POST['password_repeat'])
eb1af592
NL
255 && $_POST['password'] != "" && $_POST['login'] != "") {
256 # let's rock, install poche baby !
bb5a7d9e
NL
257 if ($this->store->install($_POST['login'], Tools::encodeString($_POST['password'] . $_POST['login'])))
258 {
259 Session::logout();
260 Tools::logm('poche is now installed');
261 Tools::redirect();
262 }
6a361945
NL
263 }
264 else {
265 Tools::logm('error during installation');
eb1af592
NL
266 Tools::redirect();
267 }
268 }
269 exit();
270 }
182faf26 271
00dbaf90
NL
272 public function getTheme() {
273 return $this->currentTheme;
274 }
5011388f 275
f4fbfaa7
NL
276 /**
277 * Provides theme information by parsing theme.ini file if present in the theme's root directory.
278 * In all cases, the following data will be returned:
279 * - name: theme's name, or key if the theme is unnamed,
280 * - current: boolean informing if the theme is the current user theme.
281 *
282 * @param string $theme Theme key (directory name)
283 * @return array|boolean Theme information, or false if the theme doesn't exist.
284 */
285 public function getThemeInfo($theme) {
286 if (!is_dir(THEME . '/' . $theme)) {
287 return false;
288 }
289
290 $themeIniFile = THEME . '/' . $theme . '/theme.ini';
291 $themeInfo = array();
292
293 if (is_file($themeIniFile) && is_readable($themeIniFile)) {
294 $themeInfo = parse_ini_file($themeIniFile);
295 }
182faf26 296
f4fbfaa7
NL
297 if ($themeInfo === false) {
298 $themeInfo = array();
299 }
300 if (!isset($themeInfo['name'])) {
301 $themeInfo['name'] = $theme;
302 }
303 $themeInfo['current'] = ($theme === $this->getTheme());
304
305 return $themeInfo;
5011388f 306 }
182faf26 307
00dbaf90
NL
308 public function getInstalledThemes() {
309 $handle = opendir(THEME);
310 $themes = array();
f4fbfaa7 311
00dbaf90
NL
312 while (($theme = readdir($handle)) !== false) {
313 # Themes are stored in a directory, so all directory names are themes
314 # @todo move theme installation data to database
f4fbfaa7 315 if (!is_dir(THEME . '/' . $theme) || in_array($theme, array('.', '..'))) {
00dbaf90
NL
316 continue;
317 }
f4fbfaa7
NL
318
319 $themes[$theme] = $this->getThemeInfo($theme);
00dbaf90 320 }
f4fbfaa7 321
3ade95a3
NL
322 ksort($themes);
323
00dbaf90
NL
324 return $themes;
325 }
eb1af592 326
f4fbfaa7
NL
327 public function getLanguage() {
328 return $this->currentLanguage;
329 }
330
5011388f
NL
331 public function getInstalledLanguages() {
332 $handle = opendir(LOCALE);
333 $languages = array();
182faf26 334
5011388f
NL
335 while (($language = readdir($handle)) !== false) {
336 # Languages are stored in a directory, so all directory names are languages
337 # @todo move language installation data to database
cbcae403 338 if (! is_dir(LOCALE . '/' . $language) || in_array($language, array('..', '.', 'tools'))) {
5011388f
NL
339 continue;
340 }
182faf26 341
5011388f 342 $current = false;
182faf26 343
5011388f
NL
344 if ($language === $this->getLanguage()) {
345 $current = true;
346 }
182faf26 347
cbcae403 348 $languages[] = array('name' => (isset($this->language_names[$language]) ? $this->language_names[$language] : $language), 'value' => $language, 'current' => $current);
5011388f 349 }
182faf26 350
5011388f
NL
351 return $languages;
352 }
353
8d3275be 354 public function getDefaultConfig()
182faf26 355 {
8d3275be
NL
356 return array(
357 'pager' => PAGINATION,
358 'language' => LANG,
00dbaf90
NL
359 'theme' => DEFAULT_THEME
360 );
8d3275be
NL
361 }
362
eb1af592
NL
363 /**
364 * Call action (mark as fav, archive, delete, etc.)
365 */
926acd7b 366 public function action($action, Url $url, $id = 0, $import = FALSE, $autoclose = FALSE, $tags = null)
eb1af592
NL
367 {
368 switch ($action)
369 {
370 case 'add':
53e3158d
NL
371 if (!$import) {
372 $content = Tools::getPageContent($url);
373 $title = ($content['rss']['channel']['item']['title'] != '') ? $content['rss']['channel']['item']['title'] : _('Untitled');
374 $body = $content['rss']['channel']['item']['description'];
ec397236 375
53e3158d
NL
376 // clean content from prevent xss attack
377 $config = HTMLPurifier_Config::createDefault();
042486c5 378 $config->set('Cache.SerializerPath', CACHE);
53e3158d
NL
379 $purifier = new HTMLPurifier($config);
380 $title = $purifier->purify($title);
381 $body = $purifier->purify($body);
382 }
383 else {
384 $title = '';
385 $body = '';
386 }
1570a653 387
182faf26 388 //search for possible duplicate
8d7cd2cc 389 $duplicate = NULL;
488fc63b 390 if (!$import) {
182faf26 391 $duplicate = $this->store->retrieveOneByURL($url->getUrl(), $this->user->getId());
488fc63b
MR
392 }
393
182faf26
MR
394 $last_id = $this->store->add($url->getUrl(), $title, $body, $this->user->getId());
395 if ( $last_id && !$import ) {
ec397236 396 Tools::logm('add link ' . $url->getUrl());
ec397236 397 if (DOWNLOAD_PICTURES) {
42c80841 398 $content = filtre_picture($body, $url->getUrl(), $last_id);
ec397236
NL
399 Tools::logm('updating content article');
400 $this->store->updateContent($last_id, $content, $this->user->getId());
401 }
488fc63b
MR
402
403 if ($duplicate != NULL) {
404 // 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
405 Tools::logm('link ' . $url->getUrl() . ' is a duplicate');
406 // 1) - preserve tags and favorite, then drop old entry
407 $this->store->reassignTags($duplicate['id'], $last_id);
408 if ($duplicate['is_fav']) {
409 $this->store->favoriteById($last_id, $this->user->getId());
410 }
411 if ($this->store->deleteById($duplicate['id'], $this->user->getId())) {
412 Tools::logm('previous link ' . $url->getUrl() .' entry deleted');
413 }
414 }
415
182faf26 416 $this->messages->add('s', _('the link has been added successfully'));
eb1af592
NL
417 }
418 else {
b916bcfc 419 if (!$import) {
ec397236
NL
420 $this->messages->add('e', _('error during insertion : the link wasn\'t added'));
421 Tools::logm('error during insertion : the link wasn\'t added ' . $url->getUrl());
b916bcfc
NL
422 }
423 }
ec397236 424
b916bcfc 425 if (!$import) {
363bc4eb 426 if ($autoclose == TRUE) {
427 Tools::redirect('?view=home');
428 } else {
f616ab60 429 Tools::redirect('?view=home&closewin=true');
363bc4eb 430 }
eb1af592
NL
431 }
432 break;
433 case 'delete':
bc1ee852 434 $msg = 'delete link #' . $id;
8d3275be 435 if ($this->store->deleteById($id, $this->user->getId())) {
eb1af592
NL
436 if (DOWNLOAD_PICTURES) {
437 remove_directory(ABS_PATH . $id);
438 }
6a361945 439 $this->messages->add('s', _('the link has been deleted successfully'));
eb1af592
NL
440 }
441 else {
6a361945 442 $this->messages->add('e', _('the link wasn\'t deleted'));
bc1ee852 443 $msg = 'error : can\'t delete link #' . $id;
eb1af592 444 }
bc1ee852 445 Tools::logm($msg);
985ce3ec 446 Tools::redirect('?');
eb1af592
NL
447 break;
448 case 'toggle_fav' :
8d3275be 449 $this->store->favoriteById($id, $this->user->getId());
eb1af592 450 Tools::logm('mark as favorite link #' . $id);
b916bcfc
NL
451 if (!$import) {
452 Tools::redirect();
453 }
eb1af592
NL
454 break;
455 case 'toggle_archive' :
8d3275be 456 $this->store->archiveById($id, $this->user->getId());
eb1af592 457 Tools::logm('archive link #' . $id);
b916bcfc
NL
458 if (!$import) {
459 Tools::redirect();
460 }
eb1af592 461 break;
f14807de
NL
462 case 'archive_all' :
463 $this->store->archiveAll($this->user->getId());
464 Tools::logm('archive all links');
465 if (!$import) {
466 Tools::redirect();
467 }
468 break;
c432fa16 469 case 'add_tag' :
926acd7b 470 if($import){
471 $entry_id = $id;
472 $tags = explode(',', $tags);
473 }
474 else{
475 $tags = explode(',', $_POST['value']);
476 $entry_id = $_POST['entry_id'];
477 }
b89d5a2b
NL
478 $entry = $this->store->retrieveOneById($entry_id, $this->user->getId());
479 if (!$entry) {
480 $this->messages->add('e', _('Article not found!'));
481 Tools::logm('error : article not found');
482 Tools::redirect();
483 }
fb26cc93
MR
484 //get all already set tags to preven duplicates
485 $already_set_tags = array();
486 $entry_tags = $this->store->retrieveTagsByEntry($entry_id);
487 foreach ($entry_tags as $tag) {
488 $already_set_tags[] = $tag['value'];
489 }
c432fa16
NL
490 foreach($tags as $key => $tag_value) {
491 $value = trim($tag_value);
fb26cc93
MR
492 if ($value && !in_array($value, $already_set_tags)) {
493 $tag = $this->store->retrieveTagByValue($value);
494
495 if (is_null($tag)) {
496 # we create the tag
497 $tag = $this->store->createTag($value);
498 $sequence = '';
499 if (STORAGE == 'postgres') {
500 $sequence = 'tags_id_seq';
501 }
502 $tag_id = $this->store->getLastId($sequence);
503 }
504 else {
505 $tag_id = $tag['id'];
506 }
507
508 # we assign the tag to the article
509 $this->store->setTagToEntry($tag_id, $entry_id);
c432fa16 510 }
c432fa16 511 }
926acd7b 512 if(!$import) {
513 Tools::redirect();
514 }
c432fa16
NL
515 break;
516 case 'remove_tag' :
517 $tag_id = $_GET['tag_id'];
b89d5a2b
NL
518 $entry = $this->store->retrieveOneById($id, $this->user->getId());
519 if (!$entry) {
520 $this->messages->add('e', _('Article not found!'));
521 Tools::logm('error : article not found');
522 Tools::redirect();
523 }
c432fa16
NL
524 $this->store->removeTagForEntry($id, $tag_id);
525 Tools::redirect();
526 break;
eb1af592
NL
527 default:
528 break;
529 }
530 }
531
532 function displayView($view, $id = 0)
533 {
534 $tpl_vars = array();
535
536 switch ($view)
537 {
eb1af592 538 case 'config':
11c680f9
NL
539 $dev_infos = $this->getPocheVersion('dev');
540 $dev = trim($dev_infos[0]);
541 $check_time_dev = date('d-M-Y H:i', $dev_infos[1]);
542 $prod_infos = $this->getPocheVersion('prod');
543 $prod = trim($prod_infos[0]);
544 $check_time_prod = date('d-M-Y H:i', $prod_infos[1]);
031df528
NL
545 $compare_dev = version_compare(POCHE, $dev);
546 $compare_prod = version_compare(POCHE, $prod);
00dbaf90 547 $themes = $this->getInstalledThemes();
5011388f 548 $languages = $this->getInstalledLanguages();
72c20a52 549 $token = $this->user->getConfigValue('token');
1810c13b 550 $http_auth = (isset($_SERVER['PHP_AUTH_USER']) || isset($_SERVER['REMOTE_USER'])) ? true : false;
32520785 551 $tpl_vars = array(
00dbaf90 552 'themes' => $themes,
5011388f 553 'languages' => $languages,
32520785
NL
554 'dev' => $dev,
555 'prod' => $prod,
11c680f9
NL
556 'check_time_dev' => $check_time_dev,
557 'check_time_prod' => $check_time_prod,
32520785
NL
558 'compare_dev' => $compare_dev,
559 'compare_prod' => $compare_prod,
72c20a52
NL
560 'token' => $token,
561 'user_id' => $this->user->getId(),
df6afaf0 562 'http_auth' => $http_auth,
32520785 563 );
eb1af592
NL
564 Tools::logm('config view');
565 break;
6cab59c3
NL
566 case 'edit-tags':
567 # tags
b89d5a2b
NL
568 $entry = $this->store->retrieveOneById($id, $this->user->getId());
569 if (!$entry) {
570 $this->messages->add('e', _('Article not found!'));
571 Tools::logm('error : article not found');
572 Tools::redirect();
573 }
6cab59c3
NL
574 $tags = $this->store->retrieveTagsByEntry($id);
575 $tpl_vars = array(
c432fa16 576 'entry_id' => $id,
6cab59c3 577 'tags' => $tags,
032e0ca1 578 'entry' => $entry,
4886ed6d
NL
579 );
580 break;
2e2ebe5e 581 case 'tags':
f778e472 582 $token = $this->user->getConfigValue('token');
fb26cc93
MR
583 //if term is set - search tags for this term
584 $term = Tools::checkVar('term');
585 $tags = $this->store->retrieveAllTags($this->user->getId(), $term);
586 if (Tools::isAjaxRequest()) {
587 $result = array();
588 foreach ($tags as $tag) {
589 $result[] = $tag['value'];
590 }
591 echo json_encode($result);
592 exit;
593 }
2e2ebe5e 594 $tpl_vars = array(
f778e472
NL
595 'token' => $token,
596 'user_id' => $this->user->getId(),
2e2ebe5e
NL
597 'tags' => $tags,
598 );
599 break;
182faf26 600
a33a3d2a 601 case 'search':
2c4e7a1c 602 if (isset($_GET['search'])){
603 $search = $_GET['search'];
a33a3d2a 604 $tpl_vars['entries'] = $this->store->search($search);
605 $tpl_vars['nb_results'] = count($tpl_vars['entries']);
606 }
607 break;
eb1af592 608 case 'view':
8d3275be 609 $entry = $this->store->retrieveOneById($id, $this->user->getId());
eb1af592
NL
610 if ($entry != NULL) {
611 Tools::logm('view link #' . $id);
612 $content = $entry['content'];
613 if (function_exists('tidy_parse_string')) {
614 $tidy = tidy_parse_string($content, array('indent'=>true, 'show-body-only' => true), 'UTF8');
615 $tidy->cleanRepair();
616 $content = $tidy->value;
3408ed48 617 }
a3223127 618
3408ed48
NL
619 # flattr checking
620 $flattr = new FlattrItem();
7b171c73
NL
621 $flattr->checkItem($entry['url'], $entry['id']);
622
623 # tags
624 $tags = $this->store->retrieveTagsByEntry($entry['id']);
a3223127 625
3408ed48 626 $tpl_vars = array(
7b171c73
NL
627 'entry' => $entry,
628 'content' => $content,
629 'flattr' => $flattr,
630 'tags' => $tags
3408ed48 631 );
eb1af592
NL
632 }
633 else {
d8d1542e 634 Tools::logm('error in view call : entry is null');
eb1af592
NL
635 }
636 break;
032e0ca1 637 default: # home, favorites, archive and tag views
eb1af592 638 $tpl_vars = array(
3eb04903
N
639 'entries' => '',
640 'page_links' => '',
7f9f5281 641 'nb_results' => '',
6065553c 642 'listmode' => (isset($_COOKIE['listmode']) ? true : false),
eb1af592 643 );
182faf26 644
032e0ca1
MR
645 //if id is given - we retrive entries by tag: id is tag id
646 if ($id) {
647 $tpl_vars['tag'] = $this->store->retrieveTag($id, $this->user->getId());
648 $tpl_vars['id'] = intval($id);
649 }
650
651 $count = $this->store->getEntriesByViewCount($view, $this->user->getId(), $id);
652
653 if ($count > 0) {
654 $this->pagination->set_total($count);
c515ffec 655 $page_links = str_replace(array('previous', 'next'), array(_('previous'), _('next')),
032e0ca1
MR
656 $this->pagination->page_links('?view=' . $view . '&sort=' . $_SESSION['sort'] . (($id)?'&id='.$id:'') . '&' ));
657 $tpl_vars['entries'] = $this->store->getEntriesByView($view, $this->user->getId(), $this->pagination->get_limit(), $id);
3eb04903 658 $tpl_vars['page_links'] = $page_links;
032e0ca1 659 $tpl_vars['nb_results'] = $count;
3eb04903 660 }
6a361945 661 Tools::logm('display ' . $view . ' view');
eb1af592
NL
662 break;
663 }
664
665 return $tpl_vars;
666 }
c765c367 667
07ee09f4 668 /**
182faf26
MR
669 * update the password of the current user.
670 * if MODE_DEMO is TRUE, the password can't be updated.
07ee09f4
NL
671 * @todo add the return value
672 * @todo set the new password in function header like this updatePassword($newPassword)
673 * @return boolean
674 */
c765c367
NL
675 public function updatePassword()
676 {
55821e04 677 if (MODE_DEMO) {
8d3275be 678 $this->messages->add('i', _('in demo mode, you can\'t update your password'));
55821e04 679 Tools::logm('in demo mode, you can\'t do this');
6a361945 680 Tools::redirect('?view=config');
55821e04
NL
681 }
682 else {
683 if (isset($_POST['password']) && isset($_POST['password_repeat'])) {
684 if ($_POST['password'] == $_POST['password_repeat'] && $_POST['password'] != "") {
8d3275be
NL
685 $this->messages->add('s', _('your password has been updated'));
686 $this->store->updatePassword($this->user->getId(), Tools::encodeString($_POST['password'] . $this->user->getUsername()));
c765c367 687 Session::logout();
8d3275be 688 Tools::logm('password updated');
c765c367
NL
689 Tools::redirect();
690 }
691 else {
8d3275be 692 $this->messages->add('e', _('the two fields have to be filled & the password must be the same in the two fields'));
6a361945 693 Tools::redirect('?view=config');
c765c367
NL
694 }
695 }
696 }
697 }
182faf26 698
00dbaf90
NL
699 public function updateTheme()
700 {
701 # no data
702 if (empty($_POST['theme'])) {
703 }
182faf26 704
00dbaf90
NL
705 # we are not going to change it to the current theme...
706 if ($_POST['theme'] == $this->getTheme()) {
707 $this->messages->add('w', _('still using the "' . $this->getTheme() . '" theme!'));
708 Tools::redirect('?view=config');
709 }
182faf26 710
00dbaf90
NL
711 $themes = $this->getInstalledThemes();
712 $actualTheme = false;
182faf26 713
f4fbfaa7
NL
714 foreach (array_keys($themes) as $theme) {
715 if ($theme == $_POST['theme']) {
00dbaf90
NL
716 $actualTheme = true;
717 break;
718 }
719 }
182faf26 720
00dbaf90
NL
721 if (! $actualTheme) {
722 $this->messages->add('e', _('that theme does not seem to be installed'));
723 Tools::redirect('?view=config');
724 }
182faf26 725
00dbaf90
NL
726 $this->store->updateUserConfig($this->user->getId(), 'theme', $_POST['theme']);
727 $this->messages->add('s', _('you have changed your theme preferences'));
182faf26 728
00dbaf90
NL
729 $currentConfig = $_SESSION['poche_user']->config;
730 $currentConfig['theme'] = $_POST['theme'];
182faf26 731
00dbaf90 732 $_SESSION['poche_user']->setConfig($currentConfig);
56532c4e
NL
733
734 $this->emptyCache();
182faf26 735
00dbaf90
NL
736 Tools::redirect('?view=config');
737 }
c765c367 738
5011388f
NL
739 public function updateLanguage()
740 {
741 # no data
742 if (empty($_POST['language'])) {
743 }
182faf26 744
5011388f
NL
745 # we are not going to change it to the current language...
746 if ($_POST['language'] == $this->getLanguage()) {
747 $this->messages->add('w', _('still using the "' . $this->getLanguage() . '" language!'));
748 Tools::redirect('?view=config');
749 }
182faf26 750
5011388f
NL
751 $languages = $this->getInstalledLanguages();
752 $actualLanguage = false;
182faf26 753
5011388f 754 foreach ($languages as $language) {
c9bd17a1 755 if ($language['value'] == $_POST['language']) {
5011388f
NL
756 $actualLanguage = true;
757 break;
758 }
759 }
182faf26 760
5011388f
NL
761 if (! $actualLanguage) {
762 $this->messages->add('e', _('that language does not seem to be installed'));
763 Tools::redirect('?view=config');
764 }
182faf26 765
5011388f
NL
766 $this->store->updateUserConfig($this->user->getId(), 'language', $_POST['language']);
767 $this->messages->add('s', _('you have changed your language preferences'));
182faf26 768
5011388f
NL
769 $currentConfig = $_SESSION['poche_user']->config;
770 $currentConfig['language'] = $_POST['language'];
182faf26 771
5011388f 772 $_SESSION['poche_user']->setConfig($currentConfig);
e145f767
NL
773
774 $this->emptyCache();
182faf26 775
5011388f 776 Tools::redirect('?view=config');
182faf26 777 }
df6afaf0
DS
778 /**
779 * get credentials from differents sources
780 * it redirects the user to the $referer link
781 * @return array
782 */
1810c13b
NL
783 private function credentials() {
784 if(isset($_SERVER['PHP_AUTH_USER'])) {
6af66b11 785 return array($_SERVER['PHP_AUTH_USER'],'php_auth',true);
1810c13b
NL
786 }
787 if(!empty($_POST['login']) && !empty($_POST['password'])) {
6af66b11 788 return array($_POST['login'],$_POST['password'],false);
1810c13b
NL
789 }
790 if(isset($_SERVER['REMOTE_USER'])) {
6af66b11 791 return array($_SERVER['REMOTE_USER'],'http_auth',true);
1810c13b 792 }
5cfafc61 793
6af66b11
MR
794 return array(false,false,false);
795 }
df6afaf0 796
07ee09f4
NL
797 /**
798 * checks if login & password are correct and save the user in session.
799 * it redirects the user to the $referer link
800 * @param string $referer the url to redirect after login
801 * @todo add the return value
802 * @return boolean
803 */
c765c367
NL
804 public function login($referer)
805 {
6af66b11 806 list($login,$password,$isauthenticated)=$this->credentials();
df6afaf0
DS
807 if($login === false || $password === false) {
808 $this->messages->add('e', _('login failed: you have to fill all fields'));
809 Tools::logm('login failed');
810 Tools::redirect();
811 }
812 if (!empty($login) && !empty($password)) {
6af66b11 813 $user = $this->store->login($login, Tools::encodeString($password . $login), $isauthenticated);
7ce7ec4c
NL
814 if ($user != array()) {
815 # Save login into Session
6af66b11
MR
816 $longlastingsession = isset($_POST['longlastingsession']);
817 $passwordTest = ($isauthenticated) ? $user['password'] : Tools::encodeString($password . $login);
818 Session::login($user['username'], $user['password'], $login, $passwordTest, $longlastingsession, array('poche_user' => new User($user)));
26929c08 819 $this->messages->add('s', _('welcome to your wallabag'));
8d3275be 820 Tools::logm('login successful');
c765c367
NL
821 Tools::redirect($referer);
822 }
8d3275be 823 $this->messages->add('e', _('login failed: bad login or password'));
c765c367
NL
824 Tools::logm('login failed');
825 Tools::redirect();
c765c367
NL
826 }
827 }
828
07ee09f4
NL
829 /**
830 * log out the poche user. It cleans the session.
831 * @todo add the return value
182faf26 832 * @return boolean
07ee09f4 833 */
c765c367
NL
834 public function logout()
835 {
7ce7ec4c 836 $this->user = array();
c765c367 837 Session::logout();
b916bcfc 838 Tools::logm('logout');
c765c367
NL
839 Tools::redirect();
840 }
841
07ee09f4
NL
842 /**
843 * import from Instapaper. poche needs a ./instapaper-export.html file
844 * @todo add the return value
66b6a3b5 845 * @param string $targetFile the file used for importing
07ee09f4
NL
846 * @return boolean
847 */
66b6a3b5 848 private function importFromInstapaper($targetFile)
c765c367 849 {
7f959169 850 # TODO gestion des articles favs
a62788c6 851 $html = new simple_html_dom();
66b6a3b5 852 $html->load_file($targetFile);
b916bcfc 853 Tools::logm('starting import from instapaper');
a62788c6
NL
854
855 $read = 0;
856 $errors = array();
857 foreach($html->find('ol') as $ul)
858 {
859 foreach($ul->find('li') as $li)
860 {
861 $a = $li->find('a');
862 $url = new Url(base64_encode($a[0]->href));
b916bcfc 863 $this->action('add', $url, 0, TRUE);
a62788c6 864 if ($read == '1') {
b916bcfc
NL
865 $sequence = '';
866 if (STORAGE == 'postgres') {
867 $sequence = 'entries_id_seq';
868 }
869 $last_id = $this->store->getLastId($sequence);
870 $this->action('toggle_archive', $url, $last_id, TRUE);
a62788c6
NL
871 }
872 }
7f959169
NL
873
874 # the second <ol> is for read links
a62788c6
NL
875 $read = 1;
876 }
8d7cd2cc
NL
877
878 $unlink = unlink($targetFile);
53e3158d 879 $this->messages->add('s', _('import from instapaper completed. You have to execute the cron to fetch content.'));
63c35580
NL
880 Tools::logm('import from instapaper completed');
881 Tools::redirect();
882 }
c765c367 883
07ee09f4
NL
884 /**
885 * import from Pocket. poche needs a ./ril_export.html file
886 * @todo add the return value
66b6a3b5 887 * @param string $targetFile the file used for importing
182faf26 888 * @return boolean
07ee09f4 889 */
66b6a3b5 890 private function importFromPocket($targetFile)
63c35580 891 {
7f959169 892 # TODO gestion des articles favs
63c35580 893 $html = new simple_html_dom();
66b6a3b5 894 $html->load_file($targetFile);
b916bcfc 895 Tools::logm('starting import from pocket');
63c35580
NL
896
897 $read = 0;
898 $errors = array();
899 foreach($html->find('ul') as $ul)
900 {
901 foreach($ul->find('li') as $li)
c765c367 902 {
63c35580
NL
903 $a = $li->find('a');
904 $url = new Url(base64_encode($a[0]->href));
b916bcfc 905 $this->action('add', $url, 0, TRUE);
926acd7b 906 $sequence = '';
907 if (STORAGE == 'postgres') {
908 $sequence = 'entries_id_seq';
909 }
910 $last_id = $this->store->getLastId($sequence);
63c35580 911 if ($read == '1') {
b916bcfc 912 $this->action('toggle_archive', $url, $last_id, TRUE);
c765c367 913 }
926acd7b 914 $tags = $a[0]->tags;
915 if(!empty($tags)) {
916 $this->action('add_tag',$url,$last_id,true,false,$tags);
917 }
c765c367 918 }
182faf26 919
7f959169 920 # the second <ul> is for read links
63c35580 921 $read = 1;
c765c367 922 }
8d7cd2cc
NL
923
924 $unlink = unlink($targetFile);
53e3158d 925 $this->messages->add('s', _('import from pocket completed. You have to execute the cron to fetch content.'));
63c35580
NL
926 Tools::logm('import from pocket completed');
927 Tools::redirect();
928 }
c765c367 929
07ee09f4
NL
930 /**
931 * import from Readability. poche needs a ./readability file
932 * @todo add the return value
66b6a3b5 933 * @param string $targetFile the file used for importing
182faf26 934 * @return boolean
07ee09f4 935 */
66b6a3b5 936 private function importFromReadability($targetFile)
63c35580 937 {
7f959169 938 # TODO gestion des articles lus / favs
66b6a3b5 939 $str_data = file_get_contents($targetFile);
63c35580 940 $data = json_decode($str_data,true);
b916bcfc 941 Tools::logm('starting import from Readability');
c0d321c1 942 $count = 0;
63c35580 943 foreach ($data as $key => $value) {
c0d321c1
NL
944 $url = NULL;
945 $favorite = FALSE;
946 $archive = FALSE;
9bc32632
NL
947 foreach ($value as $item) {
948 foreach ($item as $attr => $value) {
949 if ($attr == 'article__url') {
950 $url = new Url(base64_encode($value));
c0d321c1 951 }
9bc32632
NL
952 $sequence = '';
953 if (STORAGE == 'postgres') {
954 $sequence = 'entries_id_seq';
955 }
956 if ($value == 'true') {
957 if ($attr == 'favorite') {
958 $favorite = TRUE;
959 }
960 if ($attr == 'archive') {
961 $archive = TRUE;
962 }
c0d321c1
NL
963 }
964 }
9bc32632
NL
965
966 # we can add the url
967 if (!is_null($url) && $url->isCorrect()) {
968 $this->action('add', $url, 0, TRUE);
969 $count++;
970 if ($favorite) {
971 $last_id = $this->store->getLastId($sequence);
972 $this->action('toggle_fav', $url, $last_id, TRUE);
973 }
974 if ($archive) {
975 $last_id = $this->store->getLastId($sequence);
976 $this->action('toggle_archive', $url, $last_id, TRUE);
977 }
b916bcfc 978 }
c765c367 979 }
c765c367 980 }
8d7cd2cc
NL
981
982 unlink($targetFile);
53e3158d 983 $this->messages->add('s', _('import from Readability completed. You have to execute the cron to fetch content.'));
63c35580
NL
984 Tools::logm('import from Readability completed');
985 Tools::redirect();
c765c367
NL
986 }
987
89051914
NL
988 /**
989 * import from Poche exported file
990 * @param string $targetFile the file used for importing
182faf26 991 * @return boolean
89051914
NL
992 */
993 private function importFromPoche($targetFile)
994 {
995 $str_data = file_get_contents($targetFile);
996 $data = json_decode($str_data,true);
997 Tools::logm('starting import from Poche');
998
999
1000 $sequence = '';
1001 if (STORAGE == 'postgres') {
1002 $sequence = 'entries_id_seq';
1003 }
1004
1005 $count = 0;
1006 foreach ($data as $value) {
1007
1008 $url = new Url(base64_encode($value['url']));
1009 $favorite = ($value['is_fav'] == -1);
1010 $archive = ($value['is_read'] == -1);
182faf26 1011
89051914
NL
1012 # we can add the url
1013 if (!is_null($url) && $url->isCorrect()) {
182faf26 1014
89051914 1015 $this->action('add', $url, 0, TRUE);
182faf26 1016
89051914
NL
1017 $count++;
1018 if ($favorite) {
1019 $last_id = $this->store->getLastId($sequence);
1020 $this->action('toggle_fav', $url, $last_id, TRUE);
1021 }
1022 if ($archive) {
1023 $last_id = $this->store->getLastId($sequence);
1024 $this->action('toggle_archive', $url, $last_id, TRUE);
1025 }
1026 }
182faf26 1027
89051914 1028 }
8d7cd2cc
NL
1029
1030 unlink($targetFile);
53e3158d 1031 $this->messages->add('s', _('import from Poche completed. You have to execute the cron to fetch content.'));
89051914
NL
1032 Tools::logm('import from Poche completed');
1033 Tools::redirect();
1034 }
1035
07ee09f4
NL
1036 /**
1037 * import datas into your poche
182faf26 1038 * @return boolean
07ee09f4 1039 */
182faf26
MR
1040 public function import() {
1041
1042 if ( isset($_FILES['file']) ) {
1043 // assume, that file is in json format
1044 $str_data = file_get_contents($_FILES['file']['tmp_name']);
1045 $data = json_decode($str_data, true);
1046
1047 if ( $data === null ) {
1048 //not json - assume html
1049 $html = new simple_html_dom();
1050 $html->load_file($_FILES['file']['tmp_name']);
1051 $data = array();
1052 $read = 0;
1053 foreach (array('ol','ul') as $list) {
1054 foreach ($html->find($list) as $ul) {
1055 foreach ($ul->find('li') as $li) {
1056 $tmpEntry = array();
1057 $a = $li->find('a');
1058 $tmpEntry['url'] = $a[0]->href;
1059 $tmpEntry['tags'] = $a[0]->tags;
1060 $tmpEntry['is_read'] = $read;
1061 if ($tmpEntry['url']) {
1062 $data[] = $tmpEntry;
1063 }
1064 }
1065 # the second <ol/ul> is for read links
1066 $read = ((sizeof($data) && $read)?0:1);
1067 }
1068 }
63c35580 1069 }
182faf26
MR
1070
1071 $i = 0; //counter for articles inserted
1072 foreach ($data as $record) {
1073 //echo '<pre>';
1074 //var_dump($record);
1075 // foreach ($record as $key=>$val) {
1076 // echo "\n=================\n$i: $key: $val\n";
1077 // }
1078 // exit;
1079
1080 $url = trim($record['url']);
1081 if ( $url ) {
1082 $title = (isset($record['title']) ? $record['title'] : _('Untitled - Import - ').'</a> <a href="./?import">'._('click to finish import').'</a><a>');
1083 $body = (isset($record['content']) ? $record['content'] : '');
1084 $isRead = (isset($record['is_read']) ? intval($record['is_read']) : 0);
1085 $isFavorite = (isset($record['is_fav']) ? intval($record['is_fav']) : 0);
1086 //insert new record
1087 $id = $this->store->add($url, $title, $body, $this->user->getId(), $isFavorite, $isRead);
1088 if ( $id ) {
1089 //increment no of records inserted
1090 $i++;
1091 if ( isset($record['tags']) && trim($record['tags']) ) {
1092 //@TODO: set tags
1093
1094 }
1095 }
1096 }
1097 }
1098
1099 if ( $i > 0 ) {
1100 $this->messages->add('s', _('Articles inserted: ').$i._('. Please note, that some may be marked as "read".'));
1101 }
1102 }
1103 //file parsing finished here
1104
1105 //now download article contents if any
1106
1107 //check if we need to download any content
1108 $recordsDownloadRequired = $this->store->retrieveUnfetchedEntriesCount($this->user->getId());
1109 if ( $recordsDownloadRequired == 0 ) {
1110 //nothing to download
1111 $this->messages->add('s', _('Import finished.'));
1112 Tools::redirect();
1113 }
1114 else {
1115 //if just inserted - don't download anything, download will start in next reload
1116 if ( !isset($_FILES['file']) ) {
1117 //download next batch
1118 $items = $this->store->retrieveUnfetchedEntries($this->user->getId(), IMPORT_LIMIT);
1119
1120 $config = HTMLPurifier_Config::createDefault();
1121 $config->set('Cache.SerializerPath', CACHE);
1122 $purifier = new HTMLPurifier($config);
1123
1124 foreach ($items as $item) {
1125 $url = new Url(base64_encode($item['url']));
1126 $content = Tools::getPageContent($url);
1127
1128 $title = (($content['rss']['channel']['item']['title'] != '') ? $content['rss']['channel']['item']['title'] : _('Untitled'));
1129 $body = (($content['rss']['channel']['item']['description'] != '') ? $content['rss']['channel']['item']['description'] : _('Undefined'));
1130
1131 //clean content to prevent xss attack
1132 $title = $purifier->purify($title);
1133 $body = $purifier->purify($body);
1134
1135 $this->store->updateContentAndTitle($item['id'], $title, $body, $this->user->getId());
1136 }
1137
63c35580 1138 }
182faf26
MR
1139 }
1140
1141 return array('includeImport'=>true, 'import'=>array('recordsDownloadRequired'=>$recordsDownloadRequired, 'recordsUnderDownload'=> IMPORT_LIMIT, 'delay'=> IMPORT_DELAY * 1000) );
63c35580 1142 }
c765c367 1143
31a10069 1144 public function uploadFile() {
182faf26
MR
1145 if (isset($_FILES['file']))
1146 {
31a10069
NL
1147 $dir = CACHE . '/';
1148 $file = basename($_FILES['file']['name']);
1149 if(move_uploaded_file($_FILES['file']['tmp_name'], $dir . $file)) {
1150 $this->messages->add('s', _('File uploaded. You can now execute import.'));
1151 }
1152 else {
1153 $this->messages->add('e', _('Error while importing file. Do you have access to upload it?'));
1154 }
1155 }
182faf26 1156
31a10069
NL
1157 Tools::redirect('?view=config');
1158 }
1159
07ee09f4
NL
1160 /**
1161 * export poche entries in json
1162 * @return json all poche entries
1163 */
63c35580
NL
1164 public function export()
1165 {
ad697686 1166 $filename = "wallabag-export-".$this->user->getId()."-".date("Y-m-d").".json";
1167 header('Content-Disposition: attachment; filename='.$filename);
182faf26 1168
8d3275be 1169 $entries = $this->store->retrieveAll($this->user->getId());
63c35580
NL
1170 echo $this->tpl->render('export.twig', array(
1171 'export' => Tools::renderJson($entries),
1172 ));
1173 Tools::logm('export view');
c765c367 1174 }
32520785 1175
07ee09f4 1176 /**
a3436d4c 1177 * Checks online the latest version of poche and cache it
07ee09f4
NL
1178 * @param string $which 'prod' or 'dev'
1179 * @return string latest $which version
1180 */
32520785
NL
1181 private function getPocheVersion($which = 'prod')
1182 {
1183 $cache_file = CACHE . '/' . $which;
11c680f9 1184 $check_time = time();
a3436d4c
NL
1185
1186 # checks if the cached version file exists
32520785
NL
1187 if (file_exists($cache_file) && (filemtime($cache_file) > (time() - 86400 ))) {
1188 $version = file_get_contents($cache_file);
11c680f9 1189 $check_time = filemtime($cache_file);
32520785 1190 } else {
3e0e7e12 1191 $version = file_get_contents('http://static.wallabag.org/versions/' . $which);
32520785
NL
1192 file_put_contents($cache_file, $version, LOCK_EX);
1193 }
11c680f9 1194 return array($version, $check_time);
32520785 1195 }
72c20a52
NL
1196
1197 public function generateToken()
1198 {
1199 if (ini_get('open_basedir') === '') {
ad03eb62 1200 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
1201 echo 'This is a server using Windows!';
1202 // alternative to /dev/urandom for Windows
1203 $token = substr(base64_encode(uniqid(mt_rand(), true)), 0, 20);
1204 } else {
1205 $token = substr(base64_encode(file_get_contents('/dev/urandom', false, null, 0, 20)), 0, 15);
1206 }
72c20a52
NL
1207 }
1208 else {
1209 $token = substr(base64_encode(uniqid(mt_rand(), true)), 0, 20);
1210 }
1211
044bf638 1212 $token = str_replace('+', '', $token);
72c20a52
NL
1213 $this->store->updateUserConfig($this->user->getId(), 'token', $token);
1214 $currentConfig = $_SESSION['poche_user']->config;
1215 $currentConfig['token'] = $token;
1216 $_SESSION['poche_user']->setConfig($currentConfig);
92fc97ee 1217 Tools::redirect();
72c20a52
NL
1218 }
1219
f778e472 1220 public function generateFeeds($token, $user_id, $tag_id, $type = 'home')
72c20a52 1221 {
f778e472 1222 $allowed_types = array('home', 'fav', 'archive', 'tag');
72c20a52
NL
1223 $config = $this->store->getConfigUser($user_id);
1224
17b2afef
NL
1225 if ($config == null) {
1226 die(_('User with this id (' . $user_id . ') does not exist.'));
1227 }
1228
72c20a52
NL
1229 if (!in_array($type, $allowed_types) ||
1230 $token != $config['token']) {
1231 die(_('Uh, there is a problem while generating feeds.'));
1232 }
1233 // Check the token
1234
9e7c840b 1235 $feed = new FeedWriter(RSS2);
2e4440c3 1236 $feed->setTitle('wallabag — ' . $type . ' feed');
72c20a52 1237 $feed->setLink(Tools::getPocheUrl());
223268c2
NL
1238 $feed->setChannelElement('pubDate', date(DATE_RSS , time()));
1239 $feed->setChannelElement('generator', 'wallabag');
1240 $feed->setDescription('wallabag ' . $type . ' elements');
72c20a52 1241
f778e472 1242 if ($type == 'tag') {
b89d5a2b 1243 $entries = $this->store->retrieveEntriesByTag($tag_id, $user_id);
f778e472
NL
1244 }
1245 else {
1246 $entries = $this->store->getEntriesByView($type, $user_id);
1247 }
1248
72c20a52
NL
1249 if (count($entries) > 0) {
1250 foreach ($entries as $entry) {
1251 $newItem = $feed->createNewItem();
0b57c682 1252 $newItem->setTitle($entry['title']);
ed02e38e 1253 $newItem->setLink($entry['url']);
72c20a52
NL
1254 $newItem->setDate(time());
1255 $newItem->setDescription($entry['content']);
1256 $feed->addItem($newItem);
1257 }
1258 }
1259
1260 $feed->genarateFeed();
1261 exit;
1262 }
6285e57c
NL
1263
1264 public function emptyCache() {
1265 $files = new RecursiveIteratorIterator(
1266 new RecursiveDirectoryIterator(CACHE, RecursiveDirectoryIterator::SKIP_DOTS),
1267 RecursiveIteratorIterator::CHILD_FIRST
1268 );
1269
1270 foreach ($files as $fileinfo) {
1271 $todo = ($fileinfo->isDir() ? 'rmdir' : 'unlink');
1272 $todo($fileinfo->getRealPath());
1273 }
1274
1275 Tools::logm('empty cache');
1276 $this->messages->add('s', _('Cache deleted.'));
1277 Tools::redirect();
1278 }
df6afaf0 1279}