diff options
Diffstat (limited to 'app/Controllers')
| -rwxr-xr-x | app/Controllers/configureController.php | 356 | ||||
| -rwxr-xr-x | app/Controllers/entryController.php | 158 | ||||
| -rw-r--r-- | app/Controllers/errorController.php | 26 | ||||
| -rwxr-xr-x | app/Controllers/feedController.php | 425 | ||||
| -rwxr-xr-x | app/Controllers/indexController.php | 357 | ||||
| -rwxr-xr-x | app/Controllers/javascriptController.php | 46 | ||||
| -rw-r--r-- | app/Controllers/usersController.php | 178 |
7 files changed, 1546 insertions, 0 deletions
diff --git a/app/Controllers/configureController.php b/app/Controllers/configureController.php new file mode 100755 index 000000000..645f9eabf --- /dev/null +++ b/app/Controllers/configureController.php @@ -0,0 +1,356 @@ +<?php + +class FreshRSS_configure_Controller extends Minz_ActionController { + public function firstAction () { + if (!$this->view->loginOk) { + Minz_Error::error ( + 403, + array ('error' => array (Minz_Translate::t ('access_denied'))) + ); + } + + $catDAO = new FreshRSS_CategoryDAO (); + $catDAO->checkDefault (); + } + + public function categorizeAction () { + $feedDAO = new FreshRSS_FeedDAO (); + $catDAO = new FreshRSS_CategoryDAO (); + $defaultCategory = $catDAO->getDefault (); + $defaultId = $defaultCategory->id (); + + if (Minz_Request::isPost ()) { + $cats = Minz_Request::param ('categories', array ()); + $ids = Minz_Request::param ('ids', array ()); + $newCat = trim (Minz_Request::param ('new_category', '')); + + foreach ($cats as $key => $name) { + if (strlen ($name) > 0) { + $cat = new FreshRSS_Category ($name); + $values = array ( + 'name' => $cat->name (), + 'color' => $cat->color () + ); + $catDAO->updateCategory ($ids[$key], $values); + } elseif ($ids[$key] != $defaultId) { + $feedDAO->changeCategory ($ids[$key], $defaultId); + $catDAO->deleteCategory ($ids[$key]); + } + } + + if ($newCat != '') { + $cat = new FreshRSS_Category ($newCat); + $values = array ( + 'id' => $cat->id (), + 'name' => $cat->name (), + 'color' => $cat->color () + ); + + if ($catDAO->searchByName ($newCat) == false) { + $catDAO->addCategory ($values); + } + } + invalidateHttpCache(); + + $notif = array ( + 'type' => 'good', + 'content' => Minz_Translate::t ('categories_updated') + ); + Minz_Session::_param ('notification', $notif); + + Minz_Request::forward (array ('c' => 'configure', 'a' => 'categorize'), true); + } + + $this->view->categories = $catDAO->listCategories (false); + $this->view->defaultCategory = $catDAO->getDefault (); + $this->view->feeds = $feedDAO->listFeeds (); + $this->view->flux = false; + + Minz_View::prependTitle (Minz_Translate::t ('categories_management') . ' · '); + } + + public function feedAction () { + $catDAO = new FreshRSS_CategoryDAO (); + $this->view->categories = $catDAO->listCategories (false); + + $feedDAO = new FreshRSS_FeedDAO (); + $this->view->feeds = $feedDAO->listFeeds (); + + $id = Minz_Request::param ('id'); + if ($id == false && !empty ($this->view->feeds)) { + $id = current ($this->view->feeds)->id (); + } + + $this->view->flux = false; + if ($id != false) { + $this->view->flux = $this->view->feeds[$id]; + + if (!$this->view->flux) { + Minz_Error::error ( + 404, + array ('error' => array (Minz_Translate::t ('page_not_found'))) + ); + } else { + if (Minz_Request::isPost () && $this->view->flux) { + $user = Minz_Request::param ('http_user', ''); + $pass = Minz_Request::param ('http_pass', ''); + + $httpAuth = ''; + if ($user != '' || $pass != '') { + $httpAuth = $user . ':' . $pass; + } + + $cat = intval(Minz_Request::param('category', 0)); + + $values = array ( + 'name' => Minz_Request::param ('name', ''), + 'description' => sanitizeHTML(Minz_Request::param('description', '', true)), + 'website' => Minz_Request::param('website', ''), + 'url' => Minz_Request::param('url', ''), + 'category' => $cat, + 'pathEntries' => Minz_Request::param ('path_entries', ''), + 'priority' => intval(Minz_Request::param ('priority', 0)), + 'httpAuth' => $httpAuth, + 'keep_history' => intval(Minz_Request::param ('keep_history', -2)), + ); + + if ($feedDAO->updateFeed ($id, $values)) { + $this->view->flux->_category ($cat); + + $notif = array ( + 'type' => 'good', + 'content' => Minz_Translate::t ('feed_updated') + ); + } else { + $notif = array ( + 'type' => 'bad', + 'content' => Minz_Translate::t ('error_occurred_update') + ); + } + invalidateHttpCache(); + + Minz_Session::_param ('notification', $notif); + Minz_Request::forward (array ('c' => 'configure', 'a' => 'feed', 'params' => array ('id' => $id)), true); + } + + Minz_View::prependTitle (Minz_Translate::t ('rss_feed_management') . ' — ' . $this->view->flux->name () . ' · '); + } + } else { + Minz_View::prependTitle (Minz_Translate::t ('rss_feed_management') . ' · '); + } + } + + public function displayAction () { + if (Minz_Request::isPost()) { + $this->view->conf->_language(Minz_Request::param('language', 'en')); + $this->view->conf->_posts_per_page(Minz_Request::param('posts_per_page', 10)); + $this->view->conf->_view_mode(Minz_Request::param('view_mode', 'normal')); + $this->view->conf->_default_view (Minz_Request::param('default_view', 'a')); + $this->view->conf->_auto_load_more(Minz_Request::param('auto_load_more', false)); + $this->view->conf->_display_posts(Minz_Request::param('display_posts', false)); + $this->view->conf->_onread_jump_next(Minz_Request::param('onread_jump_next', false)); + $this->view->conf->_lazyload (Minz_Request::param('lazyload', false)); + $this->view->conf->_sort_order(Minz_Request::param('sort_order', 'DESC')); + $this->view->conf->_mark_when (array( + 'article' => Minz_Request::param('mark_open_article', false), + 'site' => Minz_Request::param('mark_open_site', false), + 'scroll' => Minz_Request::param('mark_scroll', false), + 'reception' => Minz_Request::param('mark_upon_reception', false), + )); + $themeId = Minz_Request::param('theme', ''); + if ($themeId == '') { + $themeId = FreshRSS_Themes::defaultTheme; + } + $this->view->conf->_theme($themeId); + $this->view->conf->_topline_read(Minz_Request::param('topline_read', false)); + $this->view->conf->_topline_favorite(Minz_Request::param('topline_favorite', false)); + $this->view->conf->_topline_date(Minz_Request::param('topline_date', false)); + $this->view->conf->_topline_link(Minz_Request::param('topline_link', false)); + $this->view->conf->_bottomline_read(Minz_Request::param('bottomline_read', false)); + $this->view->conf->_bottomline_favorite(Minz_Request::param('bottomline_favorite', false)); + $this->view->conf->_bottomline_sharing(Minz_Request::param('bottomline_sharing', false)); + $this->view->conf->_bottomline_tags(Minz_Request::param('bottomline_tags', false)); + $this->view->conf->_bottomline_date(Minz_Request::param('bottomline_date', false)); + $this->view->conf->_bottomline_link(Minz_Request::param('bottomline_link', false)); + $this->view->conf->save(); + + Minz_Session::_param ('language', $this->view->conf->language); + Minz_Translate::reset (); + invalidateHttpCache(); + + $notif = array ( + 'type' => 'good', + 'content' => Minz_Translate::t ('configuration_updated') + ); + Minz_Session::_param ('notification', $notif); + + Minz_Request::forward (array ('c' => 'configure', 'a' => 'display'), true); + } + + $this->view->themes = FreshRSS_Themes::get(); + + Minz_View::prependTitle (Minz_Translate::t ('reading_configuration') . ' · '); + } + + public function sharingAction () { + if (Minz_Request::isPost ()) { + $this->view->conf->_sharing (array( + 'shaarli' => Minz_Request::param ('shaarli', false), + 'wallabag' => Minz_Request::param ('wallabag', false), + 'diaspora' => Minz_Request::param ('diaspora', false), + 'twitter' => Minz_Request::param ('twitter', false), + 'g+' => Minz_Request::param ('g+', false), + 'facebook' => Minz_Request::param ('facebook', false), + 'email' => Minz_Request::param ('email', false), + 'print' => Minz_Request::param ('print', false), + )); + $this->view->conf->save(); + invalidateHttpCache(); + + $notif = array ( + 'type' => 'good', + 'content' => Minz_Translate::t ('configuration_updated') + ); + Minz_Session::_param ('notification', $notif); + + Minz_Request::forward (array ('c' => 'configure', 'a' => 'sharing'), true); + } + + Minz_View::prependTitle (Minz_Translate::t ('sharing') . ' · '); + } + + public function importExportAction () { + require_once(LIB_PATH . '/lib_opml.php'); + $catDAO = new FreshRSS_CategoryDAO (); + $this->view->categories = $catDAO->listCategories (); + + $this->view->req = Minz_Request::param ('q'); + + if ($this->view->req == 'export') { + Minz_View::_title ('freshrss_feeds.opml'); + + $this->view->_useLayout (false); + header('Content-Type: application/xml; charset=utf-8'); + header('Content-disposition: attachment; filename=freshrss_feeds.opml'); + + $feedDAO = new FreshRSS_FeedDAO (); + $catDAO = new FreshRSS_CategoryDAO (); + + $list = array (); + foreach ($catDAO->listCategories () as $key => $cat) { + $list[$key]['name'] = $cat->name (); + $list[$key]['feeds'] = $feedDAO->listByCategory ($cat->id ()); + } + + $this->view->categories = $list; + } elseif ($this->view->req == 'import' && Minz_Request::isPost ()) { + if ($_FILES['file']['error'] == 0) { + invalidateHttpCache(); + // on parse le fichier OPML pour récupérer les catégories et les flux associés + try { + list ($categories, $feeds) = opml_import ( + file_get_contents ($_FILES['file']['tmp_name']) + ); + + // On redirige vers le controller feed qui va se charger d'insérer les flux en BDD + // les flux sont mis au préalable dans des variables de Request + Minz_Request::_param ('q', 'null'); + Minz_Request::_param ('categories', $categories); + Minz_Request::_param ('feeds', $feeds); + Minz_Request::forward (array ('c' => 'feed', 'a' => 'massiveImport')); + } catch (FreshRSS_Opml_Exception $e) { + Minz_Log::record ($e->getMessage (), Minz_Log::WARNING); + + $notif = array ( + 'type' => 'bad', + 'content' => Minz_Translate::t ('bad_opml_file') + ); + Minz_Session::_param ('notification', $notif); + + Minz_Request::forward (array ( + 'c' => 'configure', + 'a' => 'importExport' + ), true); + } + } + } + + $feedDAO = new FreshRSS_FeedDAO (); + $this->view->feeds = $feedDAO->listFeeds (); + + // au niveau de la vue, permet de ne pas voir un flux sélectionné dans la liste + $this->view->flux = false; + + Minz_View::prependTitle (Minz_Translate::t ('import_export_opml') . ' · '); + } + + public function shortcutAction () { + $list_keys = array ('a', 'b', 'backspace', 'c', 'd', 'delete', 'down', 'e', 'end', 'enter', + 'escape', 'f', 'g', 'h', 'i', 'insert', 'j', 'k', 'l', 'left', + 'm', 'n', 'o', 'p', 'page_down', 'page_up', 'q', 'r', 'return', 'right', + 's', 'space', 't', 'tab', 'u', 'up', 'v', 'w', 'x', 'y', + 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', + '9', 'f1', 'f2', 'f3', 'f4', 'f5', 'f6', 'f7', 'f8', 'f9', + 'f10', 'f11', 'f12'); + $this->view->list_keys = $list_keys; + + if (Minz_Request::isPost ()) { + $shortcuts = Minz_Request::param ('shortcuts'); + $shortcuts_ok = array (); + + foreach ($shortcuts as $key => $value) { + if (in_array($value, $list_keys)) { + $shortcuts_ok[$key] = $value; + } + } + + $this->view->conf->_shortcuts ($shortcuts_ok); + $this->view->conf->save(); + invalidateHttpCache(); + + $notif = array ( + 'type' => 'good', + 'content' => Minz_Translate::t ('shortcuts_updated') + ); + Minz_Session::_param ('notification', $notif); + + Minz_Request::forward (array ('c' => 'configure', 'a' => 'shortcut'), true); + } + + Minz_View::prependTitle (Minz_Translate::t ('shortcuts') . ' · '); + } + + public function usersAction() { + Minz_View::prependTitle(Minz_Translate::t ('users') . ' · '); + } + + public function archivingAction () { + if (Minz_Request::isPost()) { + $old = Minz_Request::param('old_entries', 3); + $keepHistoryDefault = Minz_Request::param('keep_history_default', 0); + + $this->view->conf->_old_entries($old); + $this->view->conf->_keep_history_default($keepHistoryDefault); + $this->view->conf->save(); + invalidateHttpCache(); + + $notif = array( + 'type' => 'good', + 'content' => Minz_Translate::t('configuration_updated') + ); + Minz_Session::_param('notification', $notif); + + Minz_Request::forward(array('c' => 'configure', 'a' => 'archiving'), true); + } + + Minz_View::prependTitle(Minz_Translate::t('archiving_configuration') . ' · '); + + $entryDAO = new FreshRSS_EntryDAO(); + $this->view->nb_total = $entryDAO->count(); + $this->view->size_user = $entryDAO->size(); + + if (Minz_Configuration::isAdmin(Minz_Session::param('currentUser', '_'))) { + $this->view->size_total = $entryDAO->size(true); + } + } +} diff --git a/app/Controllers/entryController.php b/app/Controllers/entryController.php new file mode 100755 index 000000000..1756c91e5 --- /dev/null +++ b/app/Controllers/entryController.php @@ -0,0 +1,158 @@ +<?php + +class FreshRSS_entry_Controller extends Minz_ActionController { + public function firstAction () { + if (!$this->view->loginOk) { + Minz_Error::error ( + 403, + array ('error' => array (Minz_Translate::t ('access_denied'))) + ); + } + + $this->params = array (); + $output = Minz_Request::param('output', ''); + if (($output != '') && ($this->view->conf->view_mode !== $output)) { + $this->params['output'] = $output; + } + + $this->redirect = false; + $ajax = Minz_Request::param ('ajax'); + if ($ajax) { + $this->view->_useLayout (false); + } + } + + public function lastAction () { + $ajax = Minz_Request::param ('ajax'); + if (!$ajax && $this->redirect) { + Minz_Request::forward (array ( + 'c' => 'index', + 'a' => 'index', + 'params' => $this->params + ), true); + } else { + Minz_Request::_param ('ajax'); + } + } + + public function readAction () { + $this->redirect = true; + + $id = Minz_Request::param ('id'); + $get = Minz_Request::param ('get'); + $nextGet = Minz_Request::param ('nextGet', $get); + $idMax = Minz_Request::param ('idMax', 0); + + $entryDAO = new FreshRSS_EntryDAO (); + if ($id == false) { + if (!$get) { + $entryDAO->markReadEntries ($idMax); + } else { + $typeGet = $get[0]; + $get = substr ($get, 2); + switch ($typeGet) { + case 'c': + $entryDAO->markReadCat ($get, $idMax); + break; + case 'f': + $entryDAO->markReadFeed ($get, $idMax); + break; + case 's': + $entryDAO->markReadEntries ($idMax, true); + break; + case 'a': + $entryDAO->markReadEntries ($idMax); + break; + } + if ($nextGet !== 'a') { + $this->params['get'] = $nextGet; + } + } + + $notif = array ( + 'type' => 'good', + 'content' => Minz_Translate::t ('feeds_marked_read') + ); + Minz_Session::_param ('notification', $notif); + } else { + $is_read = (bool)(Minz_Request::param ('is_read', true)); + $entryDAO->markRead ($id, $is_read); + } + } + + public function bookmarkAction () { + $this->redirect = true; + + $id = Minz_Request::param ('id'); + if ($id) { + $entryDAO = new FreshRSS_EntryDAO (); + $entryDAO->markFavorite ($id, (bool)(Minz_Request::param ('is_favorite', true))); + } + } + + public function optimizeAction() { + if (Minz_Request::isPost()) { + @set_time_limit(300); + + // La table des entrées a tendance à grossir énormément + // Cette action permet d'optimiser cette table permettant de grapiller un peu de place + // Cette fonctionnalité n'est à appeler qu'occasionnellement + $entryDAO = new FreshRSS_EntryDAO(); + $entryDAO->optimizeTable(); + + invalidateHttpCache(); + + $notif = array ( + 'type' => 'good', + 'content' => Minz_Translate::t ('optimization_complete') + ); + Minz_Session::_param ('notification', $notif); + } + + Minz_Request::forward(array( + 'c' => 'configure', + 'a' => 'archiving' + ), true); + } + + public function purgeAction() { + @set_time_limit(300); + + $nb_month_old = max($this->view->conf->old_entries, 1); + $date_min = time() - (3600 * 24 * 30 * $nb_month_old); + + $feedDAO = new FreshRSS_FeedDAO(); + $feeds = $feedDAO->listFeedsOrderUpdate(); + $nbTotal = 0; + + invalidateHttpCache(); + + foreach ($feeds as $feed) { + $feedHistory = $feed->keepHistory(); + if ($feedHistory == -2) { //default + $feedHistory = $this->view->conf->keep_history_default; + } + if ($feedHistory >= 0) { + $nb = $feedDAO->cleanOldEntries($feed->id(), $date_min, $feedHistory); + if ($nb > 0) { + $nbTotal += $nb; + Minz_Log::record($nb . ' old entries cleaned in feed [' . $feed->url() . ']', Minz_Log::DEBUG); + $feedDAO->updateLastUpdate($feed->id()); + } + } + } + + invalidateHttpCache(); + + $notif = array( + 'type' => 'good', + 'content' => Minz_Translate::t('purge_completed', $nbTotal) + ); + Minz_Session::_param('notification', $notif); + + Minz_Request::forward(array( + 'c' => 'configure', + 'a' => 'archiving' + ), true); + } +} diff --git a/app/Controllers/errorController.php b/app/Controllers/errorController.php new file mode 100644 index 000000000..dc9a2ee25 --- /dev/null +++ b/app/Controllers/errorController.php @@ -0,0 +1,26 @@ +<?php + +class FreshRSS_error_Controller extends Minz_ActionController { + public function indexAction () { + switch (Minz_Request::param ('code')) { + case 403: + $this->view->code = 'Error 403 - Forbidden'; + break; + case 404: + $this->view->code = 'Error 404 - Not found'; + break; + case 500: + $this->view->code = 'Error 500 - Internal Server Error'; + break; + case 503: + $this->view->code = 'Error 503 - Service Unavailable'; + break; + default: + $this->view->code = 'Error 404 - Not found'; + } + + $this->view->logs = Minz_Request::param ('logs'); + + Minz_View::prependTitle ($this->view->code . ' · '); + } +} diff --git a/app/Controllers/feedController.php b/app/Controllers/feedController.php new file mode 100755 index 000000000..c40b3c400 --- /dev/null +++ b/app/Controllers/feedController.php @@ -0,0 +1,425 @@ +<?php + +class FreshRSS_feed_Controller extends Minz_ActionController { + public function firstAction () { + if (!$this->view->loginOk) { + $token = $this->view->conf->token; //TODO: check the token logic again, and if it is still needed + $token_param = Minz_Request::param ('token', ''); + $token_is_ok = ($token != '' && $token == $token_param); + $action = Minz_Request::actionName (); + if (!($token_is_ok && $action === 'actualize')) { + Minz_Error::error ( + 403, + array ('error' => array (Minz_Translate::t ('access_denied'))) + ); + } + } + + $this->catDAO = new FreshRSS_CategoryDAO (); + $this->catDAO->checkDefault (); + } + + public function addAction () { + @set_time_limit(300); + + if (Minz_Request::isPost ()) { + $url = Minz_Request::param ('url_rss'); + $cat = Minz_Request::param ('category', false); + if ($cat === false) { + $def_cat = $this->catDAO->getDefault (); + $cat = $def_cat->id (); + } + + $user = Minz_Request::param ('http_user'); + $pass = Minz_Request::param ('http_pass'); + $params = array (); + + $transactionStarted = false; + try { + $feed = new FreshRSS_Feed ($url); + $feed->_category ($cat); + + $httpAuth = ''; + if ($user != '' || $pass != '') { + $httpAuth = $user . ':' . $pass; + } + $feed->_httpAuth ($httpAuth); + + $feed->load(true); + + $feedDAO = new FreshRSS_FeedDAO (); + $values = array ( + 'url' => $feed->url (), + 'category' => $feed->category (), + 'name' => $feed->name (), + 'website' => $feed->website (), + 'description' => $feed->description (), + 'lastUpdate' => time (), + 'httpAuth' => $feed->httpAuth (), + ); + + if ($feedDAO->searchByUrl ($values['url'])) { + // on est déjà abonné à ce flux + $notif = array ( + 'type' => 'bad', + 'content' => Minz_Translate::t ('already_subscribed', $feed->name ()) + ); + Minz_Session::_param ('notification', $notif); + } else { + $id = $feedDAO->addFeed ($values); + if (!$id) { + // problème au niveau de la base de données + $notif = array ( + 'type' => 'bad', + 'content' => Minz_Translate::t ('feed_not_added', $feed->name ()) + ); + Minz_Session::_param ('notification', $notif); + } else { + $feed->_id ($id); + $feed->faviconPrepare(); + + $is_read = $this->view->conf->mark_when['reception'] ? 1 : 0; + + $entryDAO = new FreshRSS_EntryDAO (); + $entries = array_reverse($feed->entries()); //We want chronological order and SimplePie uses reverse order + + // on calcule la date des articles les plus anciens qu'on accepte + $nb_month_old = $this->view->conf->old_entries; + $date_min = time () - (3600 * 24 * 30 * $nb_month_old); + + $transactionStarted = true; + $feedDAO->beginTransaction (); + // on ajoute les articles en masse sans vérification + foreach ($entries as $entry) { + $values = $entry->toArray (); + $values['id_feed'] = $feed->id (); + $values['id'] = min(time(), $entry->date (true)) . uSecString(); + $values['is_read'] = $is_read; + $entryDAO->addEntry ($values); + } + $feedDAO->updateLastUpdate ($feed->id ()); + $feedDAO->commit (); + $transactionStarted = false; + + // ok, ajout terminé + $notif = array ( + 'type' => 'good', + 'content' => Minz_Translate::t ('feed_added', $feed->name ()) + ); + Minz_Session::_param ('notification', $notif); + + // permet de rediriger vers la page de conf du flux + $params['id'] = $feed->id (); + } + } + } catch (FreshRSS_BadUrl_Exception $e) { + Minz_Log::record ($e->getMessage (), Minz_Log::WARNING); + $notif = array ( + 'type' => 'bad', + 'content' => Minz_Translate::t ('invalid_url', $url) + ); + Minz_Session::_param ('notification', $notif); + } catch (FreshRSS_Feed_Exception $e) { + Minz_Log::record ($e->getMessage (), Minz_Log::WARNING); + $notif = array ( + 'type' => 'bad', + 'content' => Minz_Translate::t ('internal_problem_feed') + ); + Minz_Session::_param ('notification', $notif); + } catch (Minz_FileNotExistException $e) { + // Répertoire de cache n'existe pas + Minz_Log::record ($e->getMessage (), Minz_Log::ERROR); + $notif = array ( + 'type' => 'bad', + 'content' => Minz_Translate::t ('internal_problem_feed') + ); + Minz_Session::_param ('notification', $notif); + } + if ($transactionStarted) { + $feedDAO->rollBack (); + } + + Minz_Request::forward (array ('c' => 'configure', 'a' => 'feed', 'params' => $params), true); + } + } + + public function truncateAction () { + if (Minz_Request::isPost ()) { + $id = Minz_Request::param ('id'); + $feedDAO = new FreshRSS_FeedDAO (); + $n = $feedDAO->truncate($id); + $notif = array( + 'type' => $n === false ? 'bad' : 'good', + 'content' => Minz_Translate::t ('n_entries_deleted', $n) + ); + Minz_Session::_param ('notification', $notif); + invalidateHttpCache(); + Minz_Request::forward (array ('c' => 'configure', 'a' => 'feed', 'params' => array('id' => $id)), true); + } + } + + public function actualizeAction () { + @set_time_limit(300); + + $feedDAO = new FreshRSS_FeedDAO (); + $entryDAO = new FreshRSS_EntryDAO (); + + Minz_Session::_param('actualize_feeds', false); + $id = Minz_Request::param ('id'); + $force = Minz_Request::param ('force', false); + + // on créé la liste des flux à mettre à actualiser + // si on veut mettre un flux à jour spécifiquement, on le met + // dans la liste, mais seul (permet d'automatiser le traitement) + $feeds = array (); + if ($id) { + $feed = $feedDAO->searchById ($id); + if ($feed) { + $feeds = array ($feed); + } + } else { + $feeds = $feedDAO->listFeedsOrderUpdate (); + } + + // on calcule la date des articles les plus anciens qu'on accepte + $nb_month_old = max($this->view->conf->old_entries, 1); + $date_min = time () - (3600 * 24 * 30 * $nb_month_old); + + $i = 0; + $flux_update = 0; + $is_read = $this->view->conf->mark_when['reception'] ? 1 : 0; + foreach ($feeds as $feed) { + try { + $url = $feed->url(); + $feed->load(false); + $entries = array_reverse($feed->entries()); //We want chronological order and SimplePie uses reverse order + + //For this feed, check last n entry GUIDs already in database + $existingGuids = array_fill_keys ($entryDAO->listLastGuidsByFeed ($feed->id (), count($entries) + 10), 1); + $useDeclaredDate = empty($existingGuids); + + $feedHistory = $feed->keepHistory(); + if ($feedHistory == -2) { //default + $feedHistory = $this->view->conf->keep_history_default; + } + + // On ne vérifie pas strictement que l'article n'est pas déjà en BDD + // La BDD refusera l'ajout car (id_feed, guid) doit être unique + $feedDAO->beginTransaction (); + foreach ($entries as $entry) { + $eDate = $entry->date (true); + if ((!isset ($existingGuids[$entry->guid ()])) && + (($feedHistory != 0) || ($eDate >= $date_min))) { + $values = $entry->toArray (); + //Use declared date at first import, otherwise use discovery date + $values['id'] = ($useDeclaredDate || $eDate < $date_min) ? + min(time(), $eDate) . uSecString() : + uTimeString(); + $values['is_read'] = $is_read; + $entryDAO->addEntry ($values); + } + } + + if (($feedHistory >= 0) && (rand(0, 30) === 1)) { + $nb = $feedDAO->cleanOldEntries ($feed->id (), $date_min, max($feedHistory, count($entries) + 10)); + if ($nb > 0) { + Minz_Log::record ($nb . ' old entries cleaned in feed [' . $feed->url() . ']', Minz_Log::DEBUG); + } + } + + // on indique que le flux vient d'être mis à jour en BDD + $feedDAO->updateLastUpdate ($feed->id ()); + $feedDAO->commit (); + $flux_update++; + if ($feed->url() !== $url) { //URL has changed (auto-discovery) + $feedDAO->updateFeed($feed->id(), array('url' => $feed->url())); + } + $feed->faviconPrepare(); + } catch (FreshRSS_Feed_Exception $e) { + Minz_Log::record ($e->getMessage (), Minz_Log::NOTICE); + $feedDAO->updateLastUpdate ($feed->id (), 1); + } + + // On arrête à 10 flux pour ne pas surcharger le serveur + // sauf si le paramètre $force est à vrai + $i++; + if ($i >= 10 && !$force) { + break; + } + } + + $url = array (); + if ($flux_update === 1) { + // on a mis un seul flux à jour + $notif = array ( + 'type' => 'good', + 'content' => Minz_Translate::t ('feed_actualized', $feed->name ()) + ); + } elseif ($flux_update > 1) { + // plusieurs flux on été mis à jour + $notif = array ( + 'type' => 'good', + 'content' => Minz_Translate::t ('n_feeds_actualized', $flux_update) + ); + } else { + // aucun flux n'a été mis à jour, oups + $notif = array ( + 'type' => 'bad', + 'content' => Minz_Translate::t ('no_feed_actualized') + ); + } + + if ($i === 1) { + // Si on a voulu mettre à jour qu'un flux + // on filtre l'affichage par ce flux + $feed = reset ($feeds); + $url['params'] = array ('get' => 'f_' . $feed->id ()); + } + + if (Minz_Request::param ('ajax', 0) === 0) { + Minz_Session::_param ('notification', $notif); + Minz_Request::forward ($url, true); + } else { + // Une requête Ajax met un seul flux à jour. + // Comme en principe plusieurs requêtes ont lieu, + // on indique que "plusieurs flux ont été mis à jour". + // Cela permet d'avoir une notification plus proche du + // ressenti utilisateur + $notif = array ( + 'type' => 'good', + 'content' => Minz_Translate::t ('feeds_actualized') + ); + Minz_Session::_param ('notification', $notif); + // et on désactive le layout car ne sert à rien + $this->view->_useLayout (false); + } + } + + public function massiveImportAction () { + @set_time_limit(300); + + $entryDAO = new FreshRSS_EntryDAO (); + $feedDAO = new FreshRSS_FeedDAO (); + + $categories = Minz_Request::param ('categories', array (), true); + $feeds = Minz_Request::param ('feeds', array (), true); + + // on ajoute les catégories en masse dans une fonction à part + $this->addCategories ($categories); + + // on calcule la date des articles les plus anciens qu'on accepte + $nb_month_old = $this->view->conf->old_entries; + $date_min = time () - (3600 * 24 * 30 * $nb_month_old); + + // la variable $error permet de savoir si une erreur est survenue + // Le but est de ne pas arrêter l'import même en cas d'erreur + // L'utilisateur sera mis au courant s'il y a eu des erreurs, mais + // ne connaîtra pas les détails. Ceux-ci seront toutefois logguées + $error = false; + $i = 0; + foreach ($feeds as $feed) { + try { + $values = array ( + 'id' => $feed->id (), + 'url' => $feed->url (), + 'category' => $feed->category (), + 'name' => $feed->name (), + 'website' => $feed->website (), + 'description' => $feed->description (), + 'lastUpdate' => 0, + 'httpAuth' => $feed->httpAuth () + ); + + // ajout du flux que s'il n'est pas déjà en BDD + if (!$feedDAO->searchByUrl ($values['url'])) { + $id = $feedDAO->addFeed ($values); + if ($id) { + $feed->_id ($id); + $feed->faviconPrepare(); + } else { + $error = true; + } + } + } catch (FreshRSS_Feed_Exception $e) { + $error = true; + Minz_Log::record ($e->getMessage (), Minz_Log::WARNING); + } + } + + if ($error) { + $res = Minz_Translate::t ('feeds_imported_with_errors'); + } else { + $res = Minz_Translate::t ('feeds_imported'); + } + + $notif = array ( + 'type' => 'good', + 'content' => $res + ); + Minz_Session::_param ('notification', $notif); + Minz_Session::_param ('actualize_feeds', true); + + // et on redirige vers la page d'accueil + Minz_Request::forward (array ( + 'c' => 'index', + 'a' => 'index' + ), true); + } + + public function deleteAction () { + if (Minz_Request::isPost ()) { + $type = Minz_Request::param ('type', 'feed'); + $id = Minz_Request::param ('id'); + + $feedDAO = new FreshRSS_FeedDAO (); + if ($type == 'category') { + if ($feedDAO->deleteFeedByCategory ($id)) { + $notif = array ( + 'type' => 'good', + 'content' => Minz_Translate::t ('category_emptied') + ); + //TODO: Delete old favicons + } else { + $notif = array ( + 'type' => 'bad', + 'content' => Minz_Translate::t ('error_occured') + ); + } + } else { + if ($feedDAO->deleteFeed ($id)) { + $notif = array ( + 'type' => 'good', + 'content' => Minz_Translate::t ('feed_deleted') + ); + //TODO: Delete old favicon + } else { + $notif = array ( + 'type' => 'bad', + 'content' => Minz_Translate::t ('error_occured') + ); + } + } + + Minz_Session::_param ('notification', $notif); + + if ($type == 'category') { + Minz_Request::forward (array ('c' => 'configure', 'a' => 'categorize'), true); + } else { + Minz_Request::forward (array ('c' => 'configure', 'a' => 'feed'), true); + } + } + } + + private function addCategories ($categories) { + foreach ($categories as $cat) { + if (!$this->catDAO->searchByName ($cat->name ())) { + $values = array ( + 'id' => $cat->id (), + 'name' => $cat->name (), + 'color' => $cat->color () + ); + $catDAO->addCategory ($values); + } + } + } +} diff --git a/app/Controllers/indexController.php b/app/Controllers/indexController.php new file mode 100755 index 000000000..986a322a1 --- /dev/null +++ b/app/Controllers/indexController.php @@ -0,0 +1,357 @@ +<?php + +class FreshRSS_index_Controller extends Minz_ActionController { + private $nb_not_read_cat = 0; + + public function indexAction () { + $output = Minz_Request::param ('output'); + $token = ''; + + // check if user is logged in + if (!$this->view->loginOk && !Minz_Configuration::allowAnonymous()) + { + $token = $this->view->conf->token; + $token_param = Minz_Request::param ('token', ''); + $token_is_ok = ($token != '' && $token === $token_param); + if (!($output === 'rss' && $token_is_ok)) { + return; + } + $params['token'] = $token; + } + + // construction of RSS url of this feed + $params = Minz_Request::params (); + $params['output'] = 'rss'; + if (isset ($params['search'])) { + $params['search'] = urlencode ($params['search']); + } + $this->view->rss_url = array ( + 'c' => 'index', + 'a' => 'index', + 'params' => $params + ); + + if ($output === 'rss') { + // no layout for RSS output + $this->view->_useLayout (false); + header('Content-Type: application/rss+xml; charset=utf-8'); + } elseif ($output === 'global') { + Minz_View::appendScript (Minz_Url::display ('/scripts/global_view.js?' . @filemtime(PUBLIC_PATH . '/scripts/global_view.js'))); + } + + $catDAO = new FreshRSS_CategoryDAO(); + $entryDAO = new FreshRSS_EntryDAO(); + + $this->view->cat_aside = $catDAO->listCategories (); + $this->view->nb_favorites = $entryDAO->countUnreadReadFavorites (); + $this->view->nb_not_read = FreshRSS_CategoryDAO::CountUnreads($this->view->cat_aside, 1); + $this->view->currentName = ''; + + $this->view->get_c = ''; + $this->view->get_f = ''; + + $get = Minz_Request::param ('get', 'a'); + $getType = $get[0]; + $getId = substr ($get, 2); + if (!$this->checkAndProcessType ($getType, $getId)) { + Minz_Log::record ('Not found [' . $getType . '][' . $getId . ']', Minz_Log::DEBUG); + Minz_Error::error ( + 404, + array ('error' => array (Minz_Translate::t ('page_not_found'))) + ); + return; + } + + // mise à jour des titres + $this->view->rss_title = $this->view->currentName . ' | ' . Minz_View::title(); + if ($this->view->nb_not_read > 0) { + Minz_View::appendTitle (' (' . formatNumber($this->view->nb_not_read) . ')'); + } + Minz_View::prependTitle ( + $this->view->currentName . + ($this->nb_not_read_cat > 0 ? ' (' . formatNumber($this->nb_not_read_cat) . ')' : '') . + ' · ' + ); + + // On récupère les différents éléments de filtrage + $this->view->state = $state = Minz_Request::param ('state', $this->view->conf->default_view); + $filter = Minz_Request::param ('search', ''); + if (!empty($filter)) { + $state = 'all'; //Search always in read and unread articles + } + $this->view->order = $order = Minz_Request::param ('order', $this->view->conf->sort_order); + $nb = Minz_Request::param ('nb', $this->view->conf->posts_per_page); + $first = Minz_Request::param ('next', ''); + + if ($state === 'not_read') { //Any unread article in this category at all? + switch ($getType) { + case 'a': + $hasUnread = $this->view->nb_not_read > 0; + break; + case 's': + $hasUnread = $this->view->nb_favorites['unread'] > 0; + break; + case 'c': + $hasUnread = (!isset($this->view->cat_aside[$getId])) || ($this->view->cat_aside[$getId]->nbNotRead() > 0); + break; + case 'f': + $myFeed = FreshRSS_CategoryDAO::findFeed($this->view->cat_aside, $getId); + $hasUnread = ($myFeed === null) || ($myFeed->nbNotRead() > 0); + break; + default: + $hasUnread = true; + break; + } + if (!$hasUnread) { + $this->view->state = $state = 'all'; + } + } + + $today = @strtotime('today'); + $this->view->today = $today; + + // on calcule la date des articles les plus anciens qu'on affiche + $nb_month_old = $this->view->conf->old_entries; + $date_min = $today - (3600 * 24 * 30 * $nb_month_old); //Do not use a fast changing value such as time() to allow SQL caching + $keepHistoryDefault = $this->view->conf->keep_history_default; + + try { + $entries = $entryDAO->listWhere($getType, $getId, $state, $order, $nb + 1, $first, $filter, $date_min, $keepHistoryDefault); + + // Si on a récupéré aucun article "non lus" + // on essaye de récupérer tous les articles + if ($state === 'not_read' && empty($entries)) { + Minz_Log::record ('Conflicting information about nbNotRead!', Minz_Log::DEBUG); + $this->view->state = 'all'; + $entries = $entryDAO->listWhere($getType, $getId, 'all', $order, $nb, $first, $filter, $date_min, $keepHistoryDefault); + } + + if (count($entries) <= $nb) { + $this->view->nextId = ''; + } else { //We have more elements for pagination + $lastEntry = array_pop($entries); + $this->view->nextId = $lastEntry->id(); + } + + $this->view->entries = $entries; + } catch (FreshRSS_EntriesGetter_Exception $e) { + Minz_Log::record ($e->getMessage (), Minz_Log::NOTICE); + Minz_Error::error ( + 404, + array ('error' => array (Minz_Translate::t ('page_not_found'))) + ); + } + } + + /* + * Vérifie que la catégorie / flux sélectionné existe + * + Initialise correctement les variables de vue get_c et get_f + * + Met à jour la variable $this->nb_not_read_cat + */ + private function checkAndProcessType ($getType, $getId) { + switch ($getType) { + case 'a': + $this->view->currentName = Minz_Translate::t ('your_rss_feeds'); + $this->nb_not_read_cat = $this->view->nb_not_read; + $this->view->get_c = $getType; + return true; + case 's': + $this->view->currentName = Minz_Translate::t ('your_favorites'); + $this->nb_not_read_cat = $this->view->nb_favorites['unread']; + $this->view->get_c = $getType; + return true; + case 'c': + $cat = isset($this->view->cat_aside[$getId]) ? $this->view->cat_aside[$getId] : null; + if ($cat === null) { + $catDAO = new FreshRSS_CategoryDAO(); + $cat = $catDAO->searchById($getId); + } + if ($cat) { + $this->view->currentName = $cat->name (); + $this->nb_not_read_cat = $cat->nbNotRead (); + $this->view->get_c = $getId; + return true; + } else { + return false; + } + case 'f': + $feed = FreshRSS_CategoryDAO::findFeed($this->view->cat_aside, $getId); + if (empty($feed)) { + $feedDAO = new FreshRSS_FeedDAO(); + $feed = $feedDAO->searchById($getId); + } + if ($feed) { + $this->view->currentName = $feed->name (); + $this->nb_not_read_cat = $feed->nbNotRead (); + $this->view->get_f = $getId; + $this->view->get_c = $feed->category (); + return true; + } else { + return false; + } + default: + return false; + } + } + + public function statsAction () { + if (!$this->view->loginOk) { + Minz_Error::error ( + 403, + array ('error' => array (Minz_Translate::t ('access_denied'))) + ); + } + + Minz_View::prependTitle (Minz_Translate::t ('stats') . ' · '); + + $statsDAO = new FreshRSS_StatsDAO (); + Minz_View::appendScript (Minz_Url::display ('/scripts/flotr2.min.js?' . @filemtime(PUBLIC_PATH . '/scripts/flotr2.min.js'))); + $this->view->repartition = $statsDAO->calculateEntryRepartition(); + $this->view->count = ($statsDAO->calculateEntryCount()); + $this->view->feedByCategory = $statsDAO->calculateFeedByCategory(); + $this->view->entryByCategory = $statsDAO->calculateEntryByCategory(); + $this->view->topFeed = $statsDAO->calculateTopFeed(); + } + + public function aboutAction () { + Minz_View::prependTitle (Minz_Translate::t ('about') . ' · '); + } + + public function logsAction () { + if (!$this->view->loginOk) { + Minz_Error::error ( + 403, + array ('error' => array (Minz_Translate::t ('access_denied'))) + ); + } + + Minz_View::prependTitle (Minz_Translate::t ('logs') . ' · '); + + if (Minz_Request::isPost ()) { + FreshRSS_LogDAO::truncate(); + } + + $logs = FreshRSS_LogDAO::lines(); //TODO: ask only the necessary lines + + //gestion pagination + $page = Minz_Request::param ('page', 1); + $this->view->logsPaginator = new Minz_Paginator ($logs); + $this->view->logsPaginator->_nbItemsPerPage (50); + $this->view->logsPaginator->_currentPage ($page); + } + + public function loginAction () { + $this->view->_useLayout (false); + + $url = 'https://verifier.login.persona.org/verify'; + $assert = Minz_Request::param ('assertion'); + $params = 'assertion=' . $assert . '&audience=' . + urlencode (Minz_Url::display (null, 'php', true)); + $ch = curl_init (); + $options = array ( + CURLOPT_URL => $url, + CURLOPT_RETURNTRANSFER => TRUE, + CURLOPT_POST => 2, + CURLOPT_POSTFIELDS => $params + ); + curl_setopt_array ($ch, $options); + $result = curl_exec ($ch); + curl_close ($ch); + + $res = json_decode ($result, true); + + $loginOk = false; + $reason = ''; + if ($res['status'] === 'okay') { + $email = filter_var($res['email'], FILTER_VALIDATE_EMAIL); + if ($email != '') { + $personaFile = DATA_PATH . '/persona/' . $email . '.txt'; + if (($currentUser = @file_get_contents($personaFile)) !== false) { + $currentUser = trim($currentUser); + if (ctype_alnum($currentUser)) { + try { + $this->conf = new FreshRSS_Configuration($currentUser); + $loginOk = strcasecmp($email, $this->conf->mail_login) === 0; + } catch (Minz_Exception $e) { + $reason = 'Invalid configuration for user [' . $currentUser . ']! ' . $e->getMessage(); //Permission denied or conf file does not exist + } + } else { + $reason = 'Invalid username format [' . $currentUser . ']!'; + } + } + } else { + $reason = 'Invalid email format [' . $res['email'] . ']!'; + } + } + if ($loginOk) { + Minz_Session::_param('currentUser', $currentUser); + Minz_Session::_param ('mail', $email); + $this->view->loginOk = true; + invalidateHttpCache(); + } else { + $res = array (); + $res['status'] = 'failure'; + $res['reason'] = $reason == '' ? Minz_Translate::t ('invalid_login') : $reason; + Minz_Log::record ('Persona: ' . $res['reason'], Minz_Log::WARNING); + } + + header('Content-Type: application/json; charset=UTF-8'); + $this->view->res = json_encode ($res); + } + + public function logoutAction () { + $this->view->_useLayout(false); + invalidateHttpCache(); + Minz_Session::_param('currentUser'); + Minz_Session::_param('mail'); + Minz_Session::_param('passwordHash'); + } + + public function formLoginAction () { + if (Minz_Request::isPost()) { + $ok = false; + $nonce = Minz_Session::param('nonce'); + $username = Minz_Request::param('username', ''); + $c = Minz_Request::param('challenge', ''); + if (ctype_alnum($username) && ctype_graph($c) && ctype_alnum($nonce)) { + if (!function_exists('password_verify')) { + include_once(LIB_PATH . '/password_compat.php'); + } + try { + $conf = new FreshRSS_Configuration($username); + $s = $conf->passwordHash; + $ok = password_verify($nonce . $s, $c); + if ($ok) { + Minz_Session::_param('currentUser', $username); + Minz_Session::_param('passwordHash', $s); + } else { + Minz_Log::record('Password mismatch for user ' . $username . ', nonce=' . $nonce . ', c=' . $c, Minz_Log::WARNING); + } + } catch (Minz_Exception $me) { + Minz_Log::record('Login failure: ' . $me->getMessage(), Minz_Log::WARNING); + } + } else { + Minz_Log::record('Invalid credential parameters: user=' . $username . ' challenge=' . $c . ' nonce=' . $nonce, Minz_Log::DEBUG); + } + if (!$ok) { + $notif = array( + 'type' => 'bad', + 'content' => Minz_Translate::t('invalid_login') + ); + Minz_Session::_param('notification', $notif); + } + $this->view->_useLayout(false); + Minz_Request::forward(array('c' => 'index', 'a' => 'index'), true); + } + invalidateHttpCache(); + } + + public function formLogoutAction () { + $this->view->_useLayout(false); + invalidateHttpCache(); + Minz_Session::_param('currentUser'); + Minz_Session::_param('mail'); + Minz_Session::_param('passwordHash'); + Minz_Request::forward(array('c' => 'index', 'a' => 'index'), true); + } +} diff --git a/app/Controllers/javascriptController.php b/app/Controllers/javascriptController.php new file mode 100755 index 000000000..b879dcd6d --- /dev/null +++ b/app/Controllers/javascriptController.php @@ -0,0 +1,46 @@ +<?php + +class FreshRSS_javascript_Controller extends Minz_ActionController { + public function firstAction () { + $this->view->_useLayout (false); + } + + public function actualizeAction () { + header('Content-Type: text/javascript; charset=UTF-8'); + $feedDAO = new FreshRSS_FeedDAO (); + $this->view->feeds = $feedDAO->listFeeds (); + } + + public function nbUnreadsPerFeedAction() { + header('Content-Type: application/json; charset=UTF-8'); + $catDAO = new FreshRSS_CategoryDAO(); + $this->view->categories = $catDAO->listCategories(true, false); + } + + //For Web-form login + public function nonceAction() { + header('Content-Type: application/json; charset=UTF-8'); + header('Last-Modified: ' . gmdate('D, d M Y H:i:s \G\M\T')); + header('Expires: 0'); + header('Cache-Control: private, no-cache, no-store, must-revalidate'); + header('Pragma: no-cache'); + + $user = isset($_GET['user']) ? $_GET['user'] : ''; + if (ctype_alnum($user)) { + try { + $conf = new FreshRSS_Configuration($user); + $s = $conf->passwordHash; + if (strlen($s) >= 60) { + $this->view->salt1 = substr($s, 0, 29); //CRYPT_BLOWFISH Salt: "$2a$", a two digit cost parameter, "$", and 22 characters from the alphabet "./0-9A-Za-z". + $this->view->nonce = sha1(Minz_Configuration::salt() . uniqid(mt_rand(), true)); + Minz_Session::_param('nonce', $this->view->nonce); + return; //Success + } + } catch (Minz_Exception $me) { + Minz_Log::record('Nonce failure: ' . $me->getMessage(), Minz_Log::WARNING); + } + } + $this->view->nonce = ''; //Failure + $this->view->salt1 = ''; + } +} diff --git a/app/Controllers/usersController.php b/app/Controllers/usersController.php new file mode 100644 index 000000000..8314b75fc --- /dev/null +++ b/app/Controllers/usersController.php @@ -0,0 +1,178 @@ +<?php + +class FreshRSS_users_Controller extends Minz_ActionController { + + const BCRYPT_COST = 9; //Will also have to be computed client side on mobile devices, so do not use a too high cost + + public function firstAction() { + if (!$this->view->loginOk) { + Minz_Error::error( + 403, + array('error' => array(Minz_Translate::t('access_denied'))) + ); + } + } + + public function authAction() { + if (Minz_Request::isPost()) { + $ok = true; + + $passwordPlain = Minz_Request::param('passwordPlain', false); + if ($passwordPlain != '') { + Minz_Request::_param('passwordPlain'); //Discard plain-text password ASAP + $_POST['passwordPlain'] = ''; + if (!function_exists('password_hash')) { + include_once(LIB_PATH . '/password_compat.php'); + } + $passwordHash = password_hash($passwordPlain, PASSWORD_BCRYPT, array('cost' => self::BCRYPT_COST)); + $passwordPlain = ''; + $passwordHash = preg_replace('/^\$2[xy]\$/', '\$2a\$', $passwordHash); //Compatibility with bcrypt.js + $ok &= ($passwordHash != ''); + $this->view->conf->_passwordHash($passwordHash); + } + Minz_Session::_param('passwordHash', $this->view->conf->passwordHash); + + if (Minz_Configuration::isAdmin(Minz_Session::param('currentUser', '_'))) { + $this->view->conf->_mail_login(Minz_Request::param('mail_login', false)); + } + $email = $this->view->conf->mail_login; + Minz_Session::_param('mail', $email); + + $ok &= $this->view->conf->save(); + + if ($email != '') { + $personaFile = DATA_PATH . '/persona/' . $email . '.txt'; + @unlink($personaFile); + $ok &= (file_put_contents($personaFile, Minz_Session::param('currentUser', '_')) !== false); + } + + if (Minz_Configuration::isAdmin(Minz_Session::param('currentUser', '_'))) { + $current_token = $this->view->conf->token; + $token = Minz_Request::param('token', $current_token); + $this->view->conf->_token($token); + $ok &= $this->view->conf->save(); + + $anon = Minz_Request::param('anon_access', false); + $anon = ((bool)$anon) && ($anon !== 'no'); + $auth_type = Minz_Request::param('auth_type', 'none'); + if ($anon != Minz_Configuration::allowAnonymous() || + $auth_type != Minz_Configuration::authType()) { + Minz_Configuration::_authType($auth_type); + Minz_Configuration::_allowAnonymous($anon); + $ok &= Minz_Configuration::writeFile(); + } + } + + invalidateHttpCache(); + + $notif = array( + 'type' => $ok ? 'good' : 'bad', + 'content' => Minz_Translate::t($ok ? 'configuration_updated' : 'error_occurred') + ); + Minz_Session::_param('notification', $notif); + } + Minz_Request::forward(array('c' => 'configure', 'a' => 'users'), true); + } + + public function createAction() { + if (Minz_Request::isPost() && Minz_Configuration::isAdmin(Minz_Session::param('currentUser', '_'))) { + require_once(APP_PATH . '/sql.php'); + + $new_user_language = Minz_Request::param('new_user_language', $this->view->conf->language); + if (!in_array($new_user_language, $this->view->conf->availableLanguages())) { + $new_user_language = $this->view->conf->language; + } + + $new_user_name = Minz_Request::param('new_user_name'); + $ok = ($new_user_name != '') && ctype_alnum($new_user_name); + + if ($ok) { + $ok &= (strcasecmp($new_user_name, Minz_Configuration::defaultUser()) !== 0); //It is forbidden to alter the default user + + $ok &= !in_array(strtoupper($new_user_name), array_map('strtoupper', listUsers())); //Not an existing user, case-insensitive + + $configPath = DATA_PATH . '/' . $new_user_name . '_user.php'; + $ok &= !file_exists($configPath); + } + if ($ok) { + + $passwordPlain = Minz_Request::param('new_user_passwordPlain', false); + $passwordHash = ''; + if ($passwordPlain != '') { + Minz_Request::_param('new_user_passwordPlain'); //Discard plain-text password ASAP + $_POST['new_user_passwordPlain'] = ''; + if (!function_exists('password_hash')) { + include_once(LIB_PATH . '/password_compat.php'); + } + $passwordHash = password_hash($passwordPlain, PASSWORD_BCRYPT, array('cost' => self::BCRYPT_COST)); + $passwordPlain = ''; + $passwordHash = preg_replace('/^\$2[xy]\$/', '\$2a\$', $passwordHash); //Compatibility with bcrypt.js + $ok &= ($passwordHash != ''); + } + if (empty($passwordHash)) { + $passwordHash = ''; + } + + $new_user_email = filter_var($_POST['new_user_email'], FILTER_VALIDATE_EMAIL); + if (empty($new_user_email)) { + $new_user_email = ''; + } else { + $personaFile = DATA_PATH . '/persona/' . $new_user_email . '.txt'; + @unlink($personaFile); + $ok &= (file_put_contents($personaFile, $new_user_name) !== false); + } + } + if ($ok) { + $config_array = array( + 'language' => $new_user_language, + 'passwordHash' => $passwordHash, + 'mail_login' => $new_user_email, + ); + $ok &= (file_put_contents($configPath, "<?php\n return " . var_export($config_array, true) . ';') !== false); + } + if ($ok) { + $userDAO = new FreshRSS_UserDAO(); + $ok &= $userDAO->createUser($new_user_name); + } + invalidateHttpCache(); + + $notif = array( + 'type' => $ok ? 'good' : 'bad', + 'content' => Minz_Translate::t($ok ? 'user_created' : 'error_occurred', $new_user_name) + ); + Minz_Session::_param('notification', $notif); + } + Minz_Request::forward(array('c' => 'configure', 'a' => 'users'), true); + } + + public function deleteAction() { + if (Minz_Request::isPost() && Minz_Configuration::isAdmin(Minz_Session::param('currentUser', '_'))) { + require_once(APP_PATH . '/sql.php'); + + $username = Minz_Request::param('username'); + $ok = ctype_alnum($username); + + if ($ok) { + $ok &= (strcasecmp($username, Minz_Configuration::defaultUser()) !== 0); //It is forbidden to delete the default user + } + if ($ok) { + $configPath = DATA_PATH . '/' . $username . '_user.php'; + $ok &= file_exists($configPath); + } + if ($ok) { + $userDAO = new FreshRSS_UserDAO(); + $ok &= $userDAO->deleteUser($username); + $ok &= unlink($configPath); + //TODO: delete Persona file + } + invalidateHttpCache(); + + $notif = array( + 'type' => $ok ? 'good' : 'bad', + 'content' => Minz_Translate::t($ok ? 'user_deleted' : 'error_occurred', $username) + ); + Minz_Session::_param('notification', $notif); + } + Minz_Request::forward(array('c' => 'configure', 'a' => 'users'), true); + } +} |
