3 * wallabag, self hostable application allowing you to not miss any content anymore
6 * @author Nicolas Lœuillet <nicolas@loeuillet.org>
8 * @license http://www.wtfpl.net/ see COPYING file
13 public static $canRenderTemplates = true;
14 public static $configFileAvailable = true;
22 private $currentTheme = '';
23 private $currentLanguage = '';
24 private $notInstalledMessage = array();
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 'pt_BR.utf8' => 'Português (Brasil)',
36 'ru_RU.utf8' => 'Pусский',
37 'sl_SI.utf8' => 'Slovenščina',
38 'uk_UA.utf8' => 'Українська',
40 public function __construct()
42 if ($this->configFileIsAvailable()) {
46 if ($this->themeIsInstalled()) {
50 if ($this->systemIsInstalled()) {
51 $this->store
= new Database();
52 $this->messages
= new Messages();
54 if (! $this->store
->isInstalled()) {
57 $this->store
->checkTags();
61 private function init()
65 if (isset($_SESSION['poche_user']) && $_SESSION['poche_user'] != array()) {
66 $this->user
= $_SESSION['poche_user'];
68 # fake user, just for install & login screens
69 $this->user
= new User();
70 $this->user
->setConfig($this->getDefaultConfig());
74 $language = $this->user
->getConfigValue('language');
75 @putenv('LC_ALL=' . $language);
76 setlocale(LC_ALL
, $language);
77 bindtextdomain($language, LOCALE
);
78 textdomain($language);
81 $this->pagination
= new Paginator($this->user
->getConfigValue('pager'), 'p');
84 $themeDirectory = $this->user
->getConfigValue('theme');
86 if ($themeDirectory === false) {
87 $themeDirectory = DEFAULT_THEME
;
90 $this->currentTheme
= $themeDirectory;
93 $languageDirectory = $this->user
->getConfigValue('language');
95 if ($languageDirectory === false) {
96 $languageDirectory = DEFAULT_THEME
;
99 $this->currentLanguage
= $languageDirectory;
102 public function configFileIsAvailable() {
103 if (! self
::$configFileAvailable) {
104 $this->notInstalledMessage
[] = 'You have to copy (don\'t just rename!) inc/poche/config.inc.default.php to inc/poche/config.inc.php.';
112 public function themeIsInstalled() {
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) {
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.';
120 if (! is_writable(CACHE
)) {
121 $this->notInstalledMessage
[] = 'You don\'t have write access on cache directory.';
123 self
::$canRenderTemplates = false;
128 # Check if the selected theme and its requirements are present
129 $theme = $this->getTheme();
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 . ')';
134 self
::$canRenderTemplates = false;
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 . ')';
145 self
::$canRenderTemplates = false;
161 * all checks before installation.
162 * @todo move HTML to template
165 public function systemIsInstalled()
169 $configSalt = defined('SALT') ? constant('SALT') : '';
171 if (empty($configSalt)) {
172 $this->notInstalledMessage
[] = 'You have not yet filled in the SALT value in the config.inc.php file.';
175 if (STORAGE
== 'sqlite' && ! file_exists(STORAGE_SQLITE
)) {
176 Tools
::logm('sqlite file doesn\'t exist');
177 $this->notInstalledMessage
[] = 'sqlite file doesn\'t exist, you can find it in install folder. Copy it in /db folder.';
180 if (is_dir(ROOT
. '/install') && ! DEBUG_POCHE
) {
181 $this->notInstalledMessage
[] = 'you have to delete the /install folder before using poche.';
184 if (STORAGE
== 'sqlite' && ! is_writable(STORAGE_SQLITE
)) {
185 Tools
::logm('you don\'t have write access on sqlite file');
186 $this->notInstalledMessage
[] = 'You don\'t have write access on sqlite file.';
197 public function getNotInstalledMessage() {
198 return $this->notInstalledMessage
;
201 private function initTpl()
203 $loaderChain = new Twig_Loader_Chain();
204 $theme = $this->getTheme();
206 # add the current theme as first to the loader chain so Twig will look there first for overridden template files
208 $loaderChain->addLoader(new Twig_Loader_Filesystem(THEME
. '/' . $theme));
209 } catch (Twig_Error_Loader
$e) {
210 # @todo isInstalled() should catch this, inject Twig later
211 die('The currently selected theme (' . $theme . ') does not seem to be properly installed (' . THEME
. '/' . $theme .' is missing)');
214 # add all required themes to the loader chain
215 $themeInfo = $this->getThemeInfo($theme);
216 if (isset($themeInfo['requirements']) && is_array($themeInfo['requirements'])) {
217 foreach ($themeInfo['requirements'] as $requiredTheme) {
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 . ')');
228 $twigParams = array();
230 $twigParams = array('cache' => CACHE
);
233 $this->tpl
= new Twig_Environment($loaderChain, $twigParams);
234 $this->tpl
->addExtension(new Twig_Extensions_Extension_I18n());
236 # filter to display domain name of an url
237 $filter = new Twig_SimpleFilter('getDomain', 'Tools::getDomain');
238 $this->tpl
->addFilter($filter);
240 # filter for reading time
241 $filter = new Twig_SimpleFilter('getReadingTime', 'Tools::getReadingTime');
242 $this->tpl
->addFilter($filter);
245 public function createNewUser() {
246 if (isset($_GET['newuser'])){
247 if ($_POST['newusername'] != "" && $_POST['password4newuser'] != ""){
248 $newusername = filter_var($_POST['newusername'], FILTER_SANITIZE_STRING
);
249 if (!$this->store
->userExists($newusername)){
250 if ($this->store
->install($newusername, Tools
::encodeString($_POST['password4newuser'] . $newusername))) {
251 Tools
::logm('The new user '.$newusername.' has been installed');
252 $this->messages
->add('s', sprintf(_('The new user %s has been installed. Do you want to <a href="?logout">logout ?</a>'),$newusername));
256 Tools
::logm('error during adding new user');
261 $this->messages
->add('e', sprintf(_('Error : An user with the name %s already exists !'),$newusername));
262 Tools
::logm('An user with the name '.$newusername.' already exists !');
269 public function deleteUser(){
270 if (isset($_GET['deluser'])){
271 if ($this->store
->listUsers() > 1) {
272 if (Tools
::encodeString($_POST['password4deletinguser'].$this->user
->getUsername()) == $this->store
->getUserPassword($this->user
->getId())) {
273 $username = $this->user
->getUsername();
274 $this->store
->deleteUserConfig($this->user
->getId());
275 Tools
::logm('The configuration for user '. $username .' has been deleted !');
276 $this->store
->deleteTagsEntriesAndEntries($this->user
->getId());
277 Tools
::logm('The entries for user '. $username .' has been deleted !');
278 $this->store
->deleteUser($this->user
->getId());
279 Tools
::logm('User '. $username .' has been completely deleted !');
281 Tools
::logm('logout');
283 $this->messages
->add('s', sprintf(_('User %s has been successfully deleted !'),$newusername));
286 Tools
::logm('Bad password !');
287 $this->messages
->add('e', _('Error : The password is wrong !'));
291 Tools
::logm('Only user !');
292 $this->messages
->add('e', _('Error : You are the only user, you cannot delete your account !'));
297 private function install()
299 Tools
::logm('poche still not installed');
300 echo $this->tpl
->render('install.twig', array(
301 'token' => Session
::getToken(),
302 'theme' => $this->getTheme(),
303 'poche_url' => Tools
::getPocheUrl()
305 if (isset($_GET['install'])) {
306 if (($_POST['password'] == $_POST['password_repeat'])
307 && $_POST['password'] != "" && $_POST['login'] != "") {
308 # let's rock, install poche baby !
309 if ($this->store
->install($_POST['login'], Tools
::encodeString($_POST['password'] . $_POST['login'])))
312 Tools
::logm('poche is now installed');
317 Tools
::logm('error during installation');
324 public function getTheme() {
325 return $this->currentTheme
;
329 * Provides theme information by parsing theme.ini file if present in the theme's root directory.
330 * In all cases, the following data will be returned:
331 * - name: theme's name, or key if the theme is unnamed,
332 * - current: boolean informing if the theme is the current user theme.
334 * @param string $theme Theme key (directory name)
335 * @return array|boolean Theme information, or false if the theme doesn't exist.
337 public function getThemeInfo($theme) {
338 if (!is_dir(THEME
. '/' . $theme)) {
342 $themeIniFile = THEME
. '/' . $theme . '/theme.ini';
343 $themeInfo = array();
345 if (is_file($themeIniFile) && is_readable($themeIniFile)) {
346 $themeInfo = parse_ini_file($themeIniFile);
349 if ($themeInfo === false) {
350 $themeInfo = array();
352 if (!isset($themeInfo['name'])) {
353 $themeInfo['name'] = $theme;
355 $themeInfo['current'] = ($theme === $this->getTheme());
360 public function getInstalledThemes() {
361 $handle = opendir(THEME
);
364 while (($theme = readdir($handle)) !== false) {
365 # Themes are stored in a directory, so all directory names are themes
366 # @todo move theme installation data to database
367 if (!is_dir(THEME
. '/' . $theme) || in_array($theme, array('.', '..'))) {
371 $themes[$theme] = $this->getThemeInfo($theme);
379 public function getLanguage() {
380 return $this->currentLanguage
;
383 public function getInstalledLanguages() {
384 $handle = opendir(LOCALE
);
385 $languages = array();
387 while (($language = readdir($handle)) !== false) {
388 # Languages are stored in a directory, so all directory names are languages
389 # @todo move language installation data to database
390 if (! is_dir(LOCALE
. '/' . $language) || in_array($language, array('..', '.', 'tools'))) {
396 if ($language === $this->getLanguage()) {
400 $languages[] = array('name' => (isset($this->language_names
[$language]) ? $this->language_names
[$language] : $language), 'value' => $language, 'current' => $current);
406 public function getDefaultConfig()
409 'pager' => PAGINATION
,
411 'theme' => DEFAULT_THEME
416 * Call action (mark as fav, archive, delete, etc.)
418 public function action($action, Url
$url, $id = 0, $import = FALSE, $autoclose = FALSE, $tags = null)
423 $content = Tools
::getPageContent($url);
424 $title = ($content['rss']['channel']['item']['title'] != '') ? $content['rss']['channel']['item']['title'] : _('Untitled');
425 $body = $content['rss']['channel']['item']['description'];
427 // clean content from prevent xss attack
428 $purifier = $this->getPurifier();
429 $title = $purifier->purify($title);
430 $body = $purifier->purify($body);
432 //search for possible duplicate
434 $duplicate = $this->store
->retrieveOneByURL($url->getUrl(), $this->user
->getId());
436 $last_id = $this->store
->add($url->getUrl(), $title, $body, $this->user
->getId());
438 Tools
::logm('add link ' . $url->getUrl());
439 if (DOWNLOAD_PICTURES
) {
440 $content = filtre_picture($body, $url->getUrl(), $last_id);
441 Tools
::logm('updating content article');
442 $this->store
->updateContent($last_id, $content, $this->user
->getId());
445 if ($duplicate != NULL) {
446 // 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
447 Tools
::logm('link ' . $url->getUrl() . ' is a duplicate');
448 // 1) - preserve tags and favorite, then drop old entry
449 $this->store
->reassignTags($duplicate['id'], $last_id);
450 if ($duplicate['is_fav']) {
451 $this->store
->favoriteById($last_id, $this->user
->getId());
453 if ($this->store
->deleteById($duplicate['id'], $this->user
->getId())) {
454 Tools
::logm('previous link ' . $url->getUrl() .' entry deleted');
458 $this->messages
->add('s', _('the link has been added successfully'));
461 $this->messages
->add('e', _('error during insertion : the link wasn\'t added'));
462 Tools
::logm('error during insertion : the link wasn\'t added ' . $url->getUrl());
465 if ($autoclose == TRUE) {
466 Tools
::redirect('?view=home');
468 Tools
::redirect('?view=home&closewin=true');
472 $msg = 'delete link #' . $id;
473 if ($this->store
->deleteById($id, $this->user
->getId())) {
474 if (DOWNLOAD_PICTURES
) {
475 remove_directory(ABS_PATH
. $id);
477 $this->messages
->add('s', _('the link has been deleted successfully'));
480 $this->messages
->add('e', _('the link wasn\'t deleted'));
481 $msg = 'error : can\'t delete link #' . $id;
484 Tools
::redirect('?');
487 $this->store
->favoriteById($id, $this->user
->getId());
488 Tools
::logm('mark as favorite link #' . $id);
489 if ( Tools
::isAjaxRequest() ) {
497 case 'toggle_archive' :
498 $this->store
->archiveById($id, $this->user
->getId());
499 Tools
::logm('archive link #' . $id);
500 if ( Tools
::isAjaxRequest() ) {
509 $this->store
->archiveAll($this->user
->getId());
510 Tools
::logm('archive all links');
514 if (isset($_GET['search'])) {
515 //when we want to apply a tag to a search
516 $tags = array($_GET['search']);
517 $allentry_ids = $this->store
->search($tags[0], $this->user
->getId());
518 $entry_ids = array();
519 foreach ($allentry_ids as $eachentry) {
520 $entry_ids[] = $eachentry[0];
522 } else { //add a tag to a single article
523 $tags = explode(',', $_POST['value']);
524 $entry_ids = array($_POST['entry_id']);
526 foreach($entry_ids as $entry_id) {
527 $entry = $this->store
->retrieveOneById($entry_id, $this->user
->getId());
529 $this->messages
->add('e', _('Article not found!'));
530 Tools
::logm('error : article not found');
533 //get all already set tags to preven duplicates
534 $already_set_tags = array();
535 $entry_tags = $this->store
->retrieveTagsByEntry($entry_id);
536 foreach ($entry_tags as $tag) {
537 $already_set_tags[] = $tag['value'];
539 foreach($tags as $key => $tag_value) {
540 $value = trim($tag_value);
541 if ($value && !in_array($value, $already_set_tags)) {
542 $tag = $this->store
->retrieveTagByValue($value);
545 $tag = $this->store
->createTag($value);
547 if (STORAGE
== 'postgres') {
548 $sequence = 'tags_id_seq';
550 $tag_id = $this->store
->getLastId($sequence);
553 $tag_id = $tag['id'];
556 # we assign the tag to the article
557 $this->store
->setTagToEntry($tag_id, $entry_id);
561 $this->messages
->add('s', _('The tag has been applied successfully'));
565 $tag_id = $_GET['tag_id'];
566 $entry = $this->store
->retrieveOneById($id, $this->user
->getId());
568 $this->messages
->add('e', _('Article not found!'));
569 Tools
::logm('error : article not found');
572 $this->store
->removeTagForEntry($id, $tag_id);
573 Tools
::logm('tag entry deleted');
574 $this->store
->cleanUnusedTags();
575 Tools
::logm('old tags cleaned');
576 $this->messages
->add('s', _('The tag has been successfully deleted'));
584 function displayView($view, $id = 0)
591 $dev_infos = $this->getPocheVersion('dev');
592 $dev = trim($dev_infos[0]);
593 $check_time_dev = date('d-M-Y H:i', $dev_infos[1]);
594 $prod_infos = $this->getPocheVersion('prod');
595 $prod = trim($prod_infos[0]);
596 $check_time_prod = date('d-M-Y H:i', $prod_infos[1]);
597 $compare_dev = version_compare(POCHE
, $dev);
598 $compare_prod = version_compare(POCHE
, $prod);
599 $themes = $this->getInstalledThemes();
600 $languages = $this->getInstalledLanguages();
601 $token = $this->user
->getConfigValue('token');
602 $http_auth = (isset($_SERVER['PHP_AUTH_USER']) || isset($_SERVER['REMOTE_USER'])) ? true : false;
603 $only_user = ($this->store
->listUsers() > 1) ? false : true;
606 'languages' => $languages,
609 'check_time_dev' => $check_time_dev,
610 'check_time_prod' => $check_time_prod,
611 'compare_dev' => $compare_dev,
612 'compare_prod' => $compare_prod,
614 'user_id' => $this->user
->getId(),
615 'http_auth' => $http_auth,
616 'only_user' => $only_user
618 Tools
::logm('config view');
622 $entry = $this->store
->retrieveOneById($id, $this->user
->getId());
624 $this->messages
->add('e', _('Article not found!'));
625 Tools
::logm('error : article not found');
628 $tags = $this->store
->retrieveTagsByEntry($id);
636 $token = $this->user
->getConfigValue('token');
637 //if term is set - search tags for this term
638 $term = Tools
::checkVar('term');
639 $tags = $this->store
->retrieveAllTags($this->user
->getId(), $term);
640 if (Tools
::isAjaxRequest()) {
642 foreach ($tags as $tag) {
643 $result[] = $tag['value'];
645 echo json_encode($result);
650 'user_id' => $this->user
->getId(),
655 if (isset($_GET['search'])) {
656 $search = filter_var($_GET['search'], FILTER_SANITIZE_STRING
);
657 $tpl_vars['entries'] = $this->store
->search($search, $this->user
->getId());
658 $count = count($tpl_vars['entries']);
659 $this->pagination
->set_total($count);
660 $page_links = str_replace(array('previous', 'next'), array(_('previous'), _('next')),
661 $this->pagination
->page_links('?view=' . $view . '?search=' . $search . '&sort=' . $_SESSION['sort'] . '&' ));
662 $tpl_vars['page_links'] = $page_links;
663 $tpl_vars['nb_results'] = $count;
664 $tpl_vars['search_term'] = $search;
668 $entry = $this->store
->retrieveOneById($id, $this->user
->getId());
669 if ($entry != NULL) {
670 Tools
::logm('view link #' . $id);
671 $content = $entry['content'];
672 if (function_exists('tidy_parse_string')) {
673 $tidy = tidy_parse_string($content, array('indent'=>true, 'show-body-only' => true), 'UTF8');
674 $tidy->cleanRepair();
675 $content = $tidy->value
;
679 $flattr = new FlattrItem();
680 $flattr->checkItem($entry['url'], $entry['id']);
683 $tags = $this->store
->retrieveTagsByEntry($entry['id']);
687 'content' => $content,
693 Tools
::logm('error in view call : entry is null');
696 default: # home, favorites, archive and tag views
701 'listmode' => (isset($_COOKIE['listmode']) ? true : false),
704 //if id is given - we retrive entries by tag: id is tag id
706 $tpl_vars['tag'] = $this->store
->retrieveTag($id, $this->user
->getId());
707 $tpl_vars['id'] = intval($id);
710 $count = $this->store
->getEntriesByViewCount($view, $this->user
->getId(), $id);
713 $this->pagination
->set_total($count);
714 $page_links = str_replace(array('previous', 'next'), array(_('previous'), _('next')),
715 $this->pagination
->page_links('?view=' . $view . '&sort=' . $_SESSION['sort'] . (($id)?'&id='.$id:'') . '&' ));
716 $tpl_vars['entries'] = $this->store
->getEntriesByView($view, $this->user
->getId(), $this->pagination
->get_limit(), $id);
717 $tpl_vars['page_links'] = $page_links;
718 $tpl_vars['nb_results'] = $count;
720 Tools
::logm('display ' . $view . ' view');
728 * update the password of the current user.
729 * if MODE_DEMO is TRUE, the password can't be updated.
730 * @todo add the return value
731 * @todo set the new password in function header like this updatePassword($newPassword)
734 public function updatePassword()
737 $this->messages
->add('i', _('in demo mode, you can\'t update your password'));
738 Tools
::logm('in demo mode, you can\'t do this');
739 Tools
::redirect('?view=config');
742 if (isset($_POST['password']) && isset($_POST['password_repeat'])) {
743 if ($_POST['password'] == $_POST['password_repeat'] && $_POST['password'] != "") {
744 $this->messages
->add('s', _('your password has been updated'));
745 $this->store
->updatePassword($this->user
->getId(), Tools
::encodeString($_POST['password'] . $this->user
->getUsername()));
747 Tools
::logm('password updated');
751 $this->messages
->add('e', _('the two fields have to be filled & the password must be the same in the two fields'));
752 Tools
::redirect('?view=config');
758 public function updateTheme()
761 if (empty($_POST['theme'])) {
764 # we are not going to change it to the current theme...
765 if ($_POST['theme'] == $this->getTheme()) {
766 $this->messages
->add('w', _('still using the "' . $this->getTheme() . '" theme!'));
767 Tools
::redirect('?view=config');
770 $themes = $this->getInstalledThemes();
771 $actualTheme = false;
773 foreach (array_keys($themes) as $theme) {
774 if ($theme == $_POST['theme']) {
780 if (! $actualTheme) {
781 $this->messages
->add('e', _('that theme does not seem to be installed'));
782 Tools
::redirect('?view=config');
785 $this->store
->updateUserConfig($this->user
->getId(), 'theme', $_POST['theme']);
786 $this->messages
->add('s', _('you have changed your theme preferences'));
788 $currentConfig = $_SESSION['poche_user']->config
;
789 $currentConfig['theme'] = $_POST['theme'];
791 $_SESSION['poche_user']->setConfig($currentConfig);
795 Tools
::redirect('?view=config');
798 public function updateLanguage()
801 if (empty($_POST['language'])) {
804 # we are not going to change it to the current language...
805 if ($_POST['language'] == $this->getLanguage()) {
806 $this->messages
->add('w', _('still using the "' . $this->getLanguage() . '" language!'));
807 Tools
::redirect('?view=config');
810 $languages = $this->getInstalledLanguages();
811 $actualLanguage = false;
813 foreach ($languages as $language) {
814 if ($language['value'] == $_POST['language']) {
815 $actualLanguage = true;
820 if (! $actualLanguage) {
821 $this->messages
->add('e', _('that language does not seem to be installed'));
822 Tools
::redirect('?view=config');
825 $this->store
->updateUserConfig($this->user
->getId(), 'language', $_POST['language']);
826 $this->messages
->add('s', _('you have changed your language preferences'));
828 $currentConfig = $_SESSION['poche_user']->config
;
829 $currentConfig['language'] = $_POST['language'];
831 $_SESSION['poche_user']->setConfig($currentConfig);
835 Tools
::redirect('?view=config');
838 * get credentials from differents sources
839 * it redirects the user to the $referer link
842 private function credentials() {
843 if(isset($_SERVER['PHP_AUTH_USER'])) {
844 return array($_SERVER['PHP_AUTH_USER'],'php_auth',true);
846 if(!empty($_POST['login']) && !empty($_POST['password'])) {
847 return array($_POST['login'],$_POST['password'],false);
849 if(isset($_SERVER['REMOTE_USER'])) {
850 return array($_SERVER['REMOTE_USER'],'http_auth',true);
853 return array(false,false,false);
857 * checks if login & password are correct and save the user in session.
858 * it redirects the user to the $referer link
859 * @param string $referer the url to redirect after login
860 * @todo add the return value
863 public function login($referer)
865 list($login,$password,$isauthenticated)=$this->credentials();
866 if($login === false || $password === false) {
867 $this->messages
->add('e', _('login failed: you have to fill all fields'));
868 Tools
::logm('login failed');
871 if (!empty($login) && !empty($password)) {
872 $user = $this->store
->login($login, Tools
::encodeString($password . $login), $isauthenticated);
873 if ($user != array()) {
874 # Save login into Session
875 $longlastingsession = isset($_POST['longlastingsession']);
876 $passwordTest = ($isauthenticated) ? $user['password'] : Tools
::encodeString($password . $login);
877 Session
::login($user['username'], $user['password'], $login, $passwordTest, $longlastingsession, array('poche_user' => new User($user)));
878 $this->messages
->add('s', _('welcome to your wallabag'));
879 Tools
::logm('login successful');
880 Tools
::redirect($referer);
882 $this->messages
->add('e', _('login failed: bad login or password'));
883 Tools
::logm('login failed');
889 * log out the poche user. It cleans the session.
890 * @todo add the return value
893 public function logout()
895 $this->user
= array();
897 Tools
::logm('logout');
902 * import datas into your poche
905 public function import() {
907 if ( isset($_FILES['file']) ) {
908 Tools
::logm('Import stated: parsing file');
910 // assume, that file is in json format
911 $str_data = file_get_contents($_FILES['file']['tmp_name']);
912 $data = json_decode($str_data, true);
914 if ( $data === null ) {
915 //not json - assume html
916 $html = new simple_html_dom();
917 $html->load_file($_FILES['file']['tmp_name']);
920 foreach (array('ol','ul') as $list) {
921 foreach ($html->find($list) as $ul) {
922 foreach ($ul->find('li') as $li) {
925 $tmpEntry['url'] = $a[0]->href
;
926 $tmpEntry['tags'] = $a[0]->tags
;
927 $tmpEntry['is_read'] = $read;
928 if ($tmpEntry['url']) {
932 # the second <ol/ul> is for read links
933 $read = ((sizeof($data) && $read)?0:1);
938 //for readability structure
939 foreach ($data as $record) {
940 if (is_array($record)) {
942 foreach ($record as $record2) {
943 if (is_array($record2)) {
950 $urlsInserted = array(); //urls of articles inserted
951 foreach ($data as $record) {
952 $url = trim( isset($record['article__url']) ? $record['article__url'] : (isset($record['url']) ? $record['url'] : '') );
953 if ( $url and !in_array($url, $urlsInserted) ) {
954 $title = (isset($record['title']) ? $record['title'] : _('Untitled - Import - ').'</a> <a href="./?import">'._('click to finish import').'</a><a>');
955 $body = (isset($record['content']) ? $record['content'] : '');
956 $isRead = (isset($record['is_read']) ? intval($record['is_read']) : (isset($record['archive'])?intval($record['archive']):0));
957 $isFavorite = (isset($record['is_fav']) ? intval($record['is_fav']) : (isset($record['favorite'])?intval($record['favorite']):0) );
959 $id = $this->store
->add($url, $title, $body, $this->user
->getId(), $isFavorite, $isRead);
961 $urlsInserted[] = $url; //add
963 if ( isset($record['tags']) && trim($record['tags']) ) {
971 $i = sizeof($urlsInserted);
973 $this->messages
->add('s', _('Articles inserted: ').$i._('. Please note, that some may be marked as "read".'));
975 Tools
::logm('Import of articles finished: '.$i.' articles added (w/o content if not provided).');
977 //file parsing finished here
979 //now download article contents if any
981 //check if we need to download any content
982 $recordsDownloadRequired = $this->store
->retrieveUnfetchedEntriesCount($this->user
->getId());
983 if ( $recordsDownloadRequired == 0 ) {
984 //nothing to download
985 $this->messages
->add('s', _('Import finished.'));
986 Tools
::logm('Import finished completely');
990 //if just inserted - don't download anything, download will start in next reload
991 if ( !isset($_FILES['file']) ) {
992 //download next batch
993 Tools
::logm('Fetching next batch of articles...');
994 $items = $this->store
->retrieveUnfetchedEntries($this->user
->getId(), IMPORT_LIMIT
);
996 $purifier = $this->getPurifier();
998 foreach ($items as $item) {
999 $url = new Url(base64_encode($item['url']));
1000 Tools
::logm('Fetching article '.$item['id']);
1001 $content = Tools
::getPageContent($url);
1003 $title = (($content['rss']['channel']['item']['title'] != '') ? $content['rss']['channel']['item']['title'] : _('Untitled'));
1004 $body = (($content['rss']['channel']['item']['description'] != '') ? $content['rss']['channel']['item']['description'] : _('Undefined'));
1006 //clean content to prevent xss attack
1007 $title = $purifier->purify($title);
1008 $body = $purifier->purify($body);
1010 $this->store
->updateContentAndTitle($item['id'], $title, $body, $this->user
->getId());
1011 Tools
::logm('Article '.$item['id'].' updated.');
1017 return array('includeImport'=>true, 'import'=>array('recordsDownloadRequired'=>$recordsDownloadRequired, 'recordsUnderDownload'=> IMPORT_LIMIT
, 'delay'=> IMPORT_DELAY
* 1000) );
1021 * export poche entries in json
1022 * @return json all poche entries
1024 public function export() {
1025 $filename = "wallabag-export-".$this->user
->getId()."-".date("Y-m-d").".json";
1026 header('Content-Disposition: attachment; filename='.$filename);
1028 $entries = $this->store
->retrieveAll($this->user
->getId());
1029 echo $this->tpl
->render('export.twig', array(
1030 'export' => Tools
::renderJson($entries),
1032 Tools
::logm('export view');
1036 * Checks online the latest version of poche and cache it
1037 * @param string $which 'prod' or 'dev'
1038 * @return string latest $which version
1040 private function getPocheVersion($which = 'prod') {
1041 $cache_file = CACHE
. '/' . $which;
1042 $check_time = time();
1044 # checks if the cached version file exists
1045 if (file_exists($cache_file) && (filemtime($cache_file) > (time() - 86400 ))) {
1046 $version = file_get_contents($cache_file);
1047 $check_time = filemtime($cache_file);
1049 $version = file_get_contents('http://static.wallabag.org/versions/' . $which);
1050 file_put_contents($cache_file, $version, LOCK_EX
);
1052 return array($version, $check_time);
1055 public function generateToken()
1057 if (ini_get('open_basedir') === '') {
1058 if (strtoupper(substr(PHP_OS
, 0, 3)) === 'WIN') {
1059 echo 'This is a server using Windows!';
1060 // alternative to /dev/urandom for Windows
1061 $token = substr(base64_encode(uniqid(mt_rand(), true)), 0, 20);
1063 $token = substr(base64_encode(file_get_contents('/dev/urandom', false, null, 0, 20)), 0, 15);
1067 $token = substr(base64_encode(uniqid(mt_rand(), true)), 0, 20);
1070 $token = str_replace('+', '', $token);
1071 $this->store
->updateUserConfig($this->user
->getId(), 'token', $token);
1072 $currentConfig = $_SESSION['poche_user']->config
;
1073 $currentConfig['token'] = $token;
1074 $_SESSION['poche_user']->setConfig($currentConfig);
1078 public function generateFeeds($token, $user_id, $tag_id, $type = 'home')
1080 $allowed_types = array('home', 'fav', 'archive', 'tag');
1081 $config = $this->store
->getConfigUser($user_id);
1083 if ($config == null) {
1084 die(_('User with this id (' . $user_id . ') does not exist.'));
1087 if (!in_array($type, $allowed_types) ||
1088 $token != $config['token']) {
1089 die(_('Uh, there is a problem while generating feeds.'));
1093 $feed = new FeedWriter(RSS2
);
1094 $feed->setTitle('wallabag — ' . $type . ' feed');
1095 $feed->setLink(Tools
::getPocheUrl());
1096 $feed->setChannelElement('pubDate', date(DATE_RSS
, time()));
1097 $feed->setChannelElement('generator', 'wallabag');
1098 $feed->setDescription('wallabag ' . $type . ' elements');
1100 if ($type == 'tag') {
1101 $entries = $this->store
->retrieveEntriesByTag($tag_id, $user_id);
1104 $entries = $this->store
->getEntriesByView($type, $user_id);
1107 if (count($entries) > 0) {
1108 foreach ($entries as $entry) {
1109 $newItem = $feed->createNewItem();
1110 $newItem->setTitle($entry['title']);
1111 $newItem->setSource(Tools
::getPocheUrl() . '?view=view&id=' . $entry['id']);
1112 $newItem->setLink($entry['url']);
1113 $newItem->setDate(time());
1114 $newItem->setDescription($entry['content']);
1115 $feed->addItem($newItem);
1119 $feed->genarateFeed();
1123 public function emptyCache() {
1124 $files = new RecursiveIteratorIterator(
1125 new RecursiveDirectoryIterator(CACHE
, RecursiveDirectoryIterator
::SKIP_DOTS
),
1126 RecursiveIteratorIterator
::CHILD_FIRST
1129 foreach ($files as $fileinfo) {
1130 $todo = ($fileinfo->isDir() ? 'rmdir' : 'unlink');
1131 $todo($fileinfo->getRealPath());
1134 Tools
::logm('empty cache');
1135 $this->messages
->add('s', _('Cache deleted.'));
1139 public function cleanTags() {
1140 $this->store
->cleanUnusedTags();
1141 $this->messages
->add('s', _('The unused tags have been cleaned.'));
1142 Tools
::logm('clean tags');
1147 * return new purifier object with actual config
1149 protected function getPurifier() {
1150 $config = HTMLPurifier_Config
::createDefault();
1151 $config->set('Cache.SerializerPath', CACHE
);
1152 $config->set('HTML.SafeIframe', true);
1153 $config->set('URI.SafeIframeRegexp', '%^(https?:)?//(www\.youtube(?:-nocookie)?\.com/embed/|player\.vimeo\.com/video/)%'); //allow YouTube and Vimeo$purifier = new HTMLPurifier($config);
1155 return new HTMLPurifier($config);