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