diff --git a/core/authorize.php b/core/authorize.php index 9ab60dcdcb..18adbd9581 100644 --- a/core/authorize.php +++ b/core/authorize.php @@ -94,20 +94,14 @@ function authorize_access_allowed(Request $request) { require_once __DIR__ . '/includes/form.inc'; require_once __DIR__ . '/includes/batch.inc'; - if (isset($_SESSION['authorize_page_title'])) { - $page_title = $_SESSION['authorize_page_title']; - } - else { - $page_title = t('Authorize file system changes'); - } + $page_title = $request->getSession()->get('authorize_page_title', t('Authorize file system changes')); // See if we've run the operation and need to display a report. - if (isset($_SESSION['authorize_results']) && $results = $_SESSION['authorize_results']) { + if ($results = $request->getSession()->remove('authorize_results')) { // Clear the session out. - unset($_SESSION['authorize_results']); - unset($_SESSION['authorize_operation']); - unset($_SESSION['authorize_filetransfer_info']); + $request->getSession()->remove('authorize_operation'); + $request->getSession()->remove('authorize_filetransfer_info'); if (!empty($results['page_title'])) { $page_title = $results['page_title']; @@ -165,7 +159,7 @@ function authorize_access_allowed(Request $request) { } } else { - if (empty($_SESSION['authorize_operation']) || empty($_SESSION['authorize_filetransfer_info'])) { + if (!$request->getSession()->has('authorize_operation') || !$request->getSession()->has('authorize_filetransfer_info')) { $content = ['#markup' => t('It appears you have reached this page in error.')]; } elseif (!$batch = batch_get()) { diff --git a/core/includes/batch.inc b/core/includes/batch.inc index de43364d68..3d6e44006c 100644 --- a/core/includes/batch.inc +++ b/core/includes/batch.inc @@ -464,6 +464,7 @@ function _batch_finished() { } } + $request = \Drupal::request(); // Clean up the batch table and unset the static $batch variable. if ($batch['progressive']) { \Drupal::service('batch.storage')->delete($batch['id']); @@ -473,10 +474,11 @@ function _batch_finished() { } } // Clean-up the session. Not needed for CLI updates. - if (isset($_SESSION)) { - unset($_SESSION['batches'][$batch['id']]); - if (empty($_SESSION['batches'])) { - unset($_SESSION['batches']); + if ($request->hasSession()) { + $batches = $request->getSession()->remove('batches'); + unset($batches[$batch['id']]); + if (!empty($batches)) { + $request->getSession()->set('batches', $batches); } } } @@ -530,7 +532,7 @@ function _batch_finished() { // form needs to be rebuilt, save the final $form_state for // \Drupal\Core\Form\FormBuilderInterface::buildForm(). if ($_batch['form_state']->isRebuilding()) { - $_SESSION['batch_form_state'] = $_batch['form_state']; + $request->getSession()->set('batch_form_state', $_batch['form_state']); } $callback = $_batch['redirect_callback']; $_batch['source_url']->mergeOptions(['query' => ['op' => 'finish', 'id' => $_batch['id']]]); diff --git a/core/includes/database.inc b/core/includes/database.inc index 6891ea92e1..4ac867cc98 100644 --- a/core/includes/database.inc +++ b/core/includes/database.inc @@ -1039,12 +1039,12 @@ function db_ignore_replica() { $connection_info = Database::getConnectionInfo(); // Only set ignore_replica_server if there are replica servers being used, // which is assumed if there are more than one. - if (count($connection_info) > 1) { + if (count($connection_info) > 1 && \Drupal::request()->hasSession()) { // Five minutes is long enough to allow the replica to break and resume // interrupted replication without causing problems on the Drupal site from // the old data. $duration = Settings::get('maximum_replication_lag', 300); // Set session variable with amount of time to delay before using replica. - $_SESSION['ignore_replica_server'] = REQUEST_TIME + $duration; + \Drupal::request()->getSession()->set('ignore_replica_server', REQUEST_TIME + $duration); } } diff --git a/core/includes/form.inc b/core/includes/form.inc index 052c9ce87a..1e67c7d65e 100644 --- a/core/includes/form.inc +++ b/core/includes/form.inc @@ -587,7 +587,7 @@ function template_preprocess_form_element_label(&$variables) { * // The following keys allow for multi-step operations : * // 'sandbox' (read / write): An array that can be freely used to * // store persistent data between iterations. It is recommended to - * // use this instead of $_SESSION, which is unsafe if the user + * // use this instead of the user's session, which is unsafe if the user * // continues browsing in a separate window while the batch is processing. * // 'finished' (write): A float number between 0 and 1 informing * // the processing engine of the completion level for the operation. @@ -640,11 +640,12 @@ function template_preprocess_form_element_label(&$variables) { * $message = t('Finished with an error.'); * } * \Drupal::messenger()->addMessage($message); - * // Providing data for the redirected page is done through $_SESSION. + * // Providing data for the redirected page is done through the user's + * // session. * foreach ($results as $result) { * $items[] = t('Loaded node %title.', array('%title' => $result)); * } - * $_SESSION['my_batch_results'] = $items; + * \Drupal::request()->getSession()->set('my_batch_results', $items); * } * @endcode */ @@ -689,7 +690,7 @@ function template_preprocess_form_element_label(&$variables) { * - finished: Name of an implementation of callback_batch_finished(). This is * executed after the batch has completed. This should be used to perform * any result massaging that may be needed, and possibly save data in - * $_SESSION for display after final page redirection. + * the user's session for display after final page redirection. * - file: Path to the file containing the definitions of the 'operations' and * 'finished' functions, for instance if they don't reside in the main * .module file. The path should be relative to base_path(), and thus should @@ -854,7 +855,9 @@ function batch_process($redirect = NULL, Url $url = NULL, $redirect_callback = N \Drupal::service('batch.storage')->create($batch); // Set the batch number in the session to guarantee that it will stay alive. - $_SESSION['batches'][$batch['id']] = TRUE; + $batches = $request->getSession()->get('batches', []); + $batches[$batch['id']] = TRUE; + $request->getSession()->set('batches', $batches); // Redirect for processing. $query_options = $error_url->getOption('query'); diff --git a/core/lib/Drupal/Core/EventSubscriber/ReplicaDatabaseIgnoreSubscriber.php b/core/lib/Drupal/Core/EventSubscriber/ReplicaDatabaseIgnoreSubscriber.php index fc123d36d1..c1c3e617f2 100644 --- a/core/lib/Drupal/Core/EventSubscriber/ReplicaDatabaseIgnoreSubscriber.php +++ b/core/lib/Drupal/Core/EventSubscriber/ReplicaDatabaseIgnoreSubscriber.php @@ -30,16 +30,17 @@ public function checkReplicaServer(GetResponseEvent $event) { // server to catch up. // That way, that user will see their changes immediately while for other // users we still get the benefits of having a replica server, just with - // slightly stale data. Code that wants to disable the replica server should - // use the db_set_ignore_replica() function to set - // $_SESSION['ignore_replica_server'] to the timestamp after which the replica - // can be re-enabled. - if (isset($_SESSION['ignore_replica_server'])) { - if ($_SESSION['ignore_replica_server'] >= REQUEST_TIME) { + // slightly stale data. Code that wants to disable the replica server should + // use the db_set_ignore_replica() function to set the + // 'ignore_replica_server' property in the user's session to the timestamp + // after which the replica can be re-enabled. + $request = $event->getRequest(); + if ($request->hasSession() && $request->getSession()->has('ignore_replica_server')) { + if ($request->getSession()->get('ignore_replica_server') >= REQUEST_TIME) { Database::ignoreTarget('default', 'replica'); } else { - unset($_SESSION['ignore_replica_server']); + $request->getSession()->remove('ignore_replica_server'); } } } diff --git a/core/lib/Drupal/Core/FileTransfer/Form/FileTransferAuthorizeForm.php b/core/lib/Drupal/Core/FileTransfer/Form/FileTransferAuthorizeForm.php index 3f8fd6d364..fcedc0a052 100644 --- a/core/lib/Drupal/Core/FileTransfer/Form/FileTransferAuthorizeForm.php +++ b/core/lib/Drupal/Core/FileTransfer/Form/FileTransferAuthorizeForm.php @@ -51,11 +51,11 @@ public function getFormId() { */ public function buildForm(array $form, FormStateInterface $form_state) { // Get all the available ways to transfer files. - if (empty($_SESSION['authorize_filetransfer_info'])) { + $available_backends = $this->getRequest()->getSession()->get('authorize_filetransfer_info', []); + if (empty($available_backends)) { drupal_set_message($this->t('Unable to continue, no available methods of file transfer'), 'error'); return []; } - $available_backends = $_SESSION['authorize_filetransfer_info']; if (!$this->getRequest()->isSecure()) { $form['information']['https_warning'] = [ @@ -239,10 +239,10 @@ public function submitForm(array &$form, FormStateInterface $form_state) { */ protected function getFiletransfer($backend, $settings = []) { $filetransfer = FALSE; - if (!empty($_SESSION['authorize_filetransfer_info'][$backend])) { - $backend_info = $_SESSION['authorize_filetransfer_info'][$backend]; - if (class_exists($backend_info['class'])) { - $filetransfer = $backend_info['class']::factory($this->root, $settings); + $info = $this->getRequest()->getSession()->get('authorize_filetransfer_info', []); + if (!empty($info[$backend])) { + if (class_exists($info[$backend]['class'])) { + $filetransfer = $info[$backend]['class']::factory($this->root, $settings); } } return $filetransfer; @@ -307,7 +307,7 @@ protected function setConnectionSettingsDefaults(&$element, $key, array $default } /** - * Runs the operation specified in $_SESSION['authorize_operation']. + * Runs the operation specified in 'authorize_operation' session property. * * @param $filetransfer * The FileTransfer object to use for running the operation. @@ -318,8 +318,7 @@ protected function setConnectionSettingsDefaults(&$element, $key, array $default * that response for the current page request. */ protected function runOperation($filetransfer) { - $operation = $_SESSION['authorize_operation']; - unset($_SESSION['authorize_operation']); + $operation = $this->getRequest()->getSession()->remove('authorize_operation'); require_once $operation['file']; return call_user_func_array($operation['callback'], array_merge([$filetransfer], $operation['arguments'])); diff --git a/core/lib/Drupal/Core/Form/FormBuilder.php b/core/lib/Drupal/Core/Form/FormBuilder.php index be000dcc25..8eec6fcf84 100644 --- a/core/lib/Drupal/Core/Form/FormBuilder.php +++ b/core/lib/Drupal/Core/Form/FormBuilder.php @@ -239,11 +239,10 @@ public function buildForm($form_id, FormStateInterface &$form_state) { $form_state->setUserInput($input); } - if (isset($_SESSION['batch_form_state'])) { + if ($request->hasSession() && ($batch_form_state = $request->getSession()->remove('batch_form_state'))) { // We've been redirected here after a batch processing. The form has // already been processed, but needs to be rebuilt. See _batch_finished(). - $form_state = $_SESSION['batch_form_state']; - unset($_SESSION['batch_form_state']); + $form_state = $batch_form_state; return $this->rebuildForm($form_id, $form_state); } diff --git a/core/lib/Drupal/Core/PageCache/RequestPolicy/NoSessionOpen.php b/core/lib/Drupal/Core/PageCache/RequestPolicy/NoSessionOpen.php index fd583a84b9..38e51dfc90 100644 --- a/core/lib/Drupal/Core/PageCache/RequestPolicy/NoSessionOpen.php +++ b/core/lib/Drupal/Core/PageCache/RequestPolicy/NoSessionOpen.php @@ -10,9 +10,9 @@ * A policy allowing delivery of cached pages when there is no session open. * * Do not serve cached pages to authenticated users, or to anonymous users when - * $_SESSION is non-empty. $_SESSION may contain status messages from a form - * submission, the contents of a shopping cart, or other userspecific content - * that should not be cached and displayed to other users. + * the user's session is non-empty. The user's session may contain status + * messages from a form submission, the contents of a shopping cart, or other + * user-specific content that should not be cached and displayed to other users. */ class NoSessionOpen implements RequestPolicyInterface { diff --git a/core/modules/big_pipe/tests/modules/big_pipe_test/big_pipe_test.module b/core/modules/big_pipe/tests/modules/big_pipe_test/big_pipe_test.module index 67c805bb6c..739825e17a 100644 --- a/core/modules/big_pipe/tests/modules/big_pipe_test/big_pipe_test.module +++ b/core/modules/big_pipe/tests/modules/big_pipe_test/big_pipe_test.module @@ -12,7 +12,8 @@ function big_pipe_test_page_top(array &$page_top) { // Ensure this hook is invoked on every page load. $page_top['#cache']['max-age'] = 0; - if (\Drupal::request()->query->get('trigger_session')) { - $_SESSION['big_pipe_test'] = TRUE; + $request = \Drupal::request(); + if ($request->query->get('trigger_session')) { + $request->getSession()->set('big_pipe_test', TRUE); } } diff --git a/core/modules/dblog/src/Controller/DbLogController.php b/core/modules/dblog/src/Controller/DbLogController.php index 4cfbece02e..a60c3fd574 100644 --- a/core/modules/dblog/src/Controller/DbLogController.php +++ b/core/modules/dblog/src/Controller/DbLogController.php @@ -14,6 +14,7 @@ use Drupal\Core\Url; use Drupal\user\Entity\User; use Symfony\Component\DependencyInjection\ContainerInterface; +use Symfony\Component\HttpFoundation\Request; /** * Returns responses for dblog routes. @@ -112,15 +113,17 @@ public static function getLogLevelClassMap() { * Messages are truncated at 56 chars. * Full-length messages can be viewed on the message details page. * + * @param \Symfony\Component\HttpFoundation\Request $request + * The request. * @return array * A render array as expected by drupal_render(). * * @see Drupal\dblog\Form\DblogClearLogConfirmForm * @see Drupal\dblog\Controller\DbLogController::eventDetails() */ - public function overview() { + public function overview(Request $request) { - $filter = $this->buildFilterQuery(); + $filter = $this->buildFilterQuery($request); $rows = []; $classes = static::getLogLevelClassMap(); @@ -302,12 +305,15 @@ public function eventDetails($event_id) { /** * Builds a query for database log administration filters based on session. * + * @param \Symfony\Component\HttpFoundation\Request $request + * The request. + * * @return array|null * An associative array with keys 'where' and 'args' or NULL if there were * no filters set. */ - protected function buildFilterQuery() { - if (empty($_SESSION['dblog_overview_filter'])) { + protected function buildFilterQuery(Request $request) { + if (!$request->getSession()->has('dblog_overview_filter')) { return; } @@ -317,7 +323,7 @@ protected function buildFilterQuery() { // Build query. $where = $args = []; - foreach ($_SESSION['dblog_overview_filter'] as $key => $filter) { + foreach ($request->getSession()->get('dblog_overview_filter', []) as $key => $filter) { $filter_where = []; foreach ($filter as $value) { $filter_where[] = $filters[$key]['where']; diff --git a/core/modules/dblog/src/Form/DblogClearLogConfirmForm.php b/core/modules/dblog/src/Form/DblogClearLogConfirmForm.php index 46344eba06..0520e8bf18 100644 --- a/core/modules/dblog/src/Form/DblogClearLogConfirmForm.php +++ b/core/modules/dblog/src/Form/DblogClearLogConfirmForm.php @@ -66,7 +66,7 @@ public function getCancelUrl() { * {@inheritdoc} */ public function submitForm(array &$form, FormStateInterface $form_state) { - $_SESSION['dblog_overview_filter'] = []; + $this->getRequest()->getSession()->remove('dblog_overview_filter'); $this->connection->truncate('watchdog')->execute(); drupal_set_message($this->t('Database log cleared.')); $form_state->setRedirectUrl($this->getCancelUrl()); diff --git a/core/modules/dblog/src/Form/DblogFilterForm.php b/core/modules/dblog/src/Form/DblogFilterForm.php index 21619d6fc2..08b7f24e41 100644 --- a/core/modules/dblog/src/Form/DblogFilterForm.php +++ b/core/modules/dblog/src/Form/DblogFilterForm.php @@ -30,6 +30,7 @@ public function buildForm(array $form, FormStateInterface $form_state) { '#title' => $this->t('Filter log messages'), '#open' => TRUE, ]; + $session_filters = $this->getRequest()->getSession()->get('dblog_overview_filter', []); foreach ($filters as $key => $filter) { $form['filters']['status'][$key] = [ '#title' => $filter['title'], @@ -38,8 +39,9 @@ public function buildForm(array $form, FormStateInterface $form_state) { '#size' => 8, '#options' => $filter['options'], ]; - if (!empty($_SESSION['dblog_overview_filter'][$key])) { - $form['filters']['status'][$key]['#default_value'] = $_SESSION['dblog_overview_filter'][$key]; + + if (!empty($session_filters[$key])) { + $form['filters']['status'][$key]['#default_value'] = $session_filters[$key]; } } @@ -51,7 +53,7 @@ public function buildForm(array $form, FormStateInterface $form_state) { '#type' => 'submit', '#value' => $this->t('Filter'), ]; - if (!empty($_SESSION['dblog_overview_filter'])) { + if (!empty($session_filters)) { $form['filters']['actions']['reset'] = [ '#type' => 'submit', '#value' => $this->t('Reset'), @@ -76,11 +78,13 @@ public function validateForm(array &$form, FormStateInterface $form_state) { */ public function submitForm(array &$form, FormStateInterface $form_state) { $filters = dblog_filters(); + $session_filters = $this->getRequest()->getSession()->get('dblog_overview_filter', []); foreach ($filters as $name => $filter) { if ($form_state->hasValue($name)) { - $_SESSION['dblog_overview_filter'][$name] = $form_state->getValue($name); + $session_filters[$name] = $form_state->getValue($name); } } + $this->getRequest()->getSession()->set('dblog_overview_filter', $session_filters); } /** @@ -92,7 +96,7 @@ public function submitForm(array &$form, FormStateInterface $form_state) { * The current state of the form. */ public function resetForm(array &$form, FormStateInterface $form_state) { - $_SESSION['dblog_overview_filter'] = []; + $this->getRequest()->getSession()->remove('dblog_overview_filter'); } } diff --git a/core/modules/file/file.module b/core/modules/file/file.module index 8fd6823104..df6a2b4110 100644 --- a/core/modules/file/file.module +++ b/core/modules/file/file.module @@ -765,7 +765,7 @@ function file_cron() { */ function _file_save_upload_from_form(array $element, FormStateInterface $form_state, $delta = NULL, $replace = FILE_EXISTS_RENAME) { // Get all errors set before calling this method. This will also clear them - // from $_SESSION. + // from the messenger service. $errors_before = drupal_get_messages('error'); $upload_location = isset($element['#upload_location']) ? $element['#upload_location'] : FALSE; @@ -775,7 +775,7 @@ function _file_save_upload_from_form(array $element, FormStateInterface $form_st $result = file_save_upload($upload_name, $upload_validators, $upload_location, $delta, $replace); // Get new errors that are generated while trying to save the upload. This - // will also clear them from $_SESSION. + // will also clear them from the messenger service. $errors_new = drupal_get_messages('error'); if (!empty($errors_new['error'])) { $errors_new = $errors_new['error']; diff --git a/core/modules/language/src/Plugin/LanguageNegotiation/LanguageNegotiationSession.php b/core/modules/language/src/Plugin/LanguageNegotiation/LanguageNegotiationSession.php index 971e907aae..8c3a69918b 100644 --- a/core/modules/language/src/Plugin/LanguageNegotiation/LanguageNegotiationSession.php +++ b/core/modules/language/src/Plugin/LanguageNegotiation/LanguageNegotiationSession.php @@ -56,8 +56,8 @@ public function getLangcode(Request $request = NULL) { $config = $this->config->get('language.negotiation')->get('session'); $param = $config['parameter']; $langcode = $request && $request->query->get($param) ? $request->query->get($param) : NULL; - if (!$langcode && isset($_SESSION[$param])) { - $langcode = $_SESSION[$param]; + if (!$langcode && $request->hasSession() && $request->getSession()->has($param)) { + $langcode = $request->getSession()->get($param); } return $langcode; } @@ -73,7 +73,7 @@ public function persist(LanguageInterface $language) { $languages = $this->languageManager->getLanguages(); if ($this->currentUser->isAuthenticated() && isset($languages[$langcode])) { $config = $this->config->get('language.negotiation')->get('session'); - $_SESSION[$config['parameter']] = $langcode; + \Drupal::request()->getSession()->set($config['parameter'], $langcode); } } } @@ -127,7 +127,7 @@ public function getLanguageSwitchLinks(Request $request, $type, Url $url) { $links = []; $config = $this->config->get('language.negotiation')->get('session'); $param = $config['parameter']; - $language_query = isset($_SESSION[$param]) ? $_SESSION[$param] : $this->languageManager->getCurrentLanguage($type)->getId(); + $language_query = $request->getSession()->get($param, $this->languageManager->getCurrentLanguage($type)->getId()); $query = []; parse_str($request->getQueryString(), $query); diff --git a/core/modules/locale/src/Form/TranslateFilterForm.php b/core/modules/locale/src/Form/TranslateFilterForm.php index cfa3b696e8..1926b231dd 100644 --- a/core/modules/locale/src/Form/TranslateFilterForm.php +++ b/core/modules/locale/src/Form/TranslateFilterForm.php @@ -67,7 +67,7 @@ public function buildForm(array $form, FormStateInterface $form_state) { '#type' => 'submit', '#value' => $this->t('Filter'), ]; - if (!empty($_SESSION['locale_translate_filter'])) { + if ($this->getRequest()->getSession()->has('locale_translate_filter')) { $form['filters']['actions']['reset'] = [ '#type' => 'submit', '#value' => $this->t('Reset'), @@ -83,11 +83,13 @@ public function buildForm(array $form, FormStateInterface $form_state) { */ public function submitForm(array &$form, FormStateInterface $form_state) { $filters = $this->translateFilters(); + $session_filters = $this->getRequest()->getSession()->get('locale_translate_filter', []); foreach ($filters as $name => $filter) { if ($form_state->hasValue($name)) { - $_SESSION['locale_translate_filter'][$name] = $form_state->getValue($name); + $session_filters[$name] = $form_state->getValue($name); } } + $this->getRequest()->getSession()->set('locale_translate_filter', $session_filters); $form_state->setRedirect('locale.translate_page'); } @@ -95,7 +97,7 @@ public function submitForm(array &$form, FormStateInterface $form_state) { * Provides a submit handler for the reset button. */ public function resetForm(array &$form, FormStateInterface $form_state) { - $_SESSION['locale_translate_filter'] = []; + $this->getRequest()->getSession()->remove('locale_translate_filter'); $form_state->setRedirect('locale.translate_page'); } diff --git a/core/modules/locale/src/Form/TranslateFormBase.php b/core/modules/locale/src/Form/TranslateFormBase.php index 9a7ad8bab8..f083f6d9a6 100644 --- a/core/modules/locale/src/Form/TranslateFormBase.php +++ b/core/modules/locale/src/Form/TranslateFormBase.php @@ -125,22 +125,24 @@ protected function translateFilterValues($reset = FALSE) { $filter_values = []; $filters = $this->translateFilters(); + $request = $this->getRequest(); + $session_filter = $request->getSession()->get('locale_translate_filter', []); foreach ($filters as $key => $filter) { $filter_values[$key] = $filter['default']; // Let the filter defaults be overwritten by parameters in the URL. - if ($this->getRequest()->query->has($key)) { + if ($request->query->has($key)) { // Only allow this value if it was among the options, or // if there were no fixed options to filter for. - $value = $this->getRequest()->query->get($key); + $value = $request->query->get($key); if (!isset($filter['options']) || isset($filter['options'][$value])) { $filter_values[$key] = $value; } } - elseif (isset($_SESSION['locale_translate_filter'][$key])) { + elseif (isset($session_filter[$key])) { // Only allow this value if it was among the options, or // if there were no fixed options to filter for. - if (!isset($filter['options']) || isset($filter['options'][$_SESSION['locale_translate_filter'][$key]])) { - $filter_values[$key] = $_SESSION['locale_translate_filter'][$key]; + if (!isset($filter['options']) || isset($filter['options'][$session_filter[$key]])) { + $filter_values[$key] = $session_filter[$key]; } } } diff --git a/core/modules/migrate_drupal_ui/src/Controller/MigrateController.php b/core/modules/migrate_drupal_ui/src/Controller/MigrateController.php index 2054766a13..461a4ec173 100644 --- a/core/modules/migrate_drupal_ui/src/Controller/MigrateController.php +++ b/core/modules/migrate_drupal_ui/src/Controller/MigrateController.php @@ -3,6 +3,7 @@ namespace Drupal\migrate_drupal_ui\Controller; use Drupal\Core\Controller\ControllerBase; +use Symfony\Component\HttpFoundation\Request; /** * Provides controller methods for the migration. @@ -12,12 +13,14 @@ class MigrateController extends ControllerBase { /** * Sets a log filter and redirects to the log. * + * @param \Symfony\Component\HttpFoundation\Request $request + * The request. + * * @return \Symfony\Component\HttpFoundation\RedirectResponse * A redirect response object that may be returned by the controller. */ - public function showLog() { - $_SESSION['dblog_overview_filter'] = []; - $_SESSION['dblog_overview_filter']['type'] = ['migrate_drupal_ui' => 'migrate_drupal_ui']; + public function showLog(Request $request) { + $request->getSession()->set('dblog_overview_filter', ['type' => ['migrate_drupal_ui' => 'migrate_drupal_ui']]); return $this->redirect('dblog.overview'); } diff --git a/core/modules/simpletest/src/TestBase.php b/core/modules/simpletest/src/TestBase.php index 260d1a34af..ef5e29b9a3 100644 --- a/core/modules/simpletest/src/TestBase.php +++ b/core/modules/simpletest/src/TestBase.php @@ -1186,7 +1186,9 @@ protected function tearDown() { */ private function restoreEnvironment() { // Destroy the session if one was started during the test-run. - $_SESSION = []; + if (\Drupal::hasContainer() && \Drupal::request()->hasSession()) { + \Drupal::request()->getSession()->clear(); + } if (PHP_SAPI !== 'cli' && session_status() === PHP_SESSION_ACTIVE) { session_destroy(); $params = session_get_cookie_params(); diff --git a/core/modules/system/src/Controller/DbUpdateController.php b/core/modules/system/src/Controller/DbUpdateController.php index 9e0a374a4a..dd29d385fd 100644 --- a/core/modules/system/src/Controller/DbUpdateController.php +++ b/core/modules/system/src/Controller/DbUpdateController.php @@ -147,13 +147,13 @@ public function handle($op, Request $request) { update_fix_compatibility(); if ($request->query->get('continue')) { - $_SESSION['update_ignore_warnings'] = TRUE; + $request->getSession()->set('update_ignore_warnings', TRUE); } $regions = []; $requirements = update_check_requirements(); $severity = drupal_requirements_severity($requirements); - if ($severity == REQUIREMENT_ERROR || ($severity == REQUIREMENT_WARNING && empty($_SESSION['update_ignore_warnings']))) { + if ($severity == REQUIREMENT_ERROR || ($severity == REQUIREMENT_WARNING && !$request->getSession()->has('update_ignore_warnings'))) { $regions['sidebar_first'] = $this->updateTasksList('requirements'); $output = $this->requirements($severity, $requirements, $request); } @@ -394,6 +394,11 @@ protected function results(Request $request) { // @todo Simplify with https://www.drupal.org/node/2548095 $base_url = str_replace('/update.php', '', $request->getBaseUrl()); + // Retrieve and remove session information. + $update_results = $request->getSession()->remove('update_results'); + $update_success = $request->getSession()->remove('update_success'); + $request->getSession()->remove('update_ignore_warnings'); + // Report end result. $dblog_exists = $this->moduleHandler->moduleExists('dblog'); if ($dblog_exists && $this->account->hasPermission('access site reports')) { @@ -405,11 +410,11 @@ protected function results(Request $request) { $log_message = $this->t('All errors have been logged.'); } - if (!empty($_SESSION['update_success'])) { + if ($update_success) { $message = '

' . $this->t('Updates were attempted. If you see no failures below, you may proceed happily back to your site. Otherwise, you may need to update your database manually.', [':url' => Url::fromRoute('')->setOption('base_url', $base_url)->toString(TRUE)->getGeneratedUrl()]) . ' ' . $log_message . '

'; } else { - $last = reset($_SESSION['updates_remaining']); + $last = reset($request->getSession()->get('updates_remaining')); list($module, $version) = array_pop($last); $message = '

' . $this->t('The update process was aborted prematurely while running update #@version in @module.module.', [ '@version' => $version, @@ -434,9 +439,9 @@ protected function results(Request $request) { ]; // Output a list of info messages. - if (!empty($_SESSION['update_results'])) { + if (!empty($update_results)) { $all_messages = []; - foreach ($_SESSION['update_results'] as $module => $updates) { + foreach ($update_results as $module => $updates) { if ($module != '#abort') { $module_has_message = FALSE; $info_messages = []; @@ -498,9 +503,6 @@ protected function results(Request $request) { ]; } } - unset($_SESSION['update_results']); - unset($_SESSION['update_success']); - unset($_SESSION['update_ignore_warnings']); return $build; } @@ -569,7 +571,7 @@ protected function triggerBatch(Request $request) { $maintenance_mode = $this->state->get('system.maintenance_mode', FALSE); // Store the current maintenance mode status in the session so that it can // be restored at the end of the batch. - $_SESSION['maintenance_mode'] = $maintenance_mode; + $request->getSession()->set('maintenance_mode', $maintenance_mode); // During the update, always put the site into maintenance mode so that // in-progress schema changes do not affect visiting users. if (empty($maintenance_mode)) { @@ -649,16 +651,16 @@ public static function batchFinished($success, $results, $operations) { // No updates to run, so caches won't get flushed later. Clear them now. drupal_flush_all_caches(); - $_SESSION['update_results'] = $results; - $_SESSION['update_success'] = $success; - $_SESSION['updates_remaining'] = $operations; + $request = \Drupal::request(); + $request->getSession()->set('update_results', $results); + $request->getSession()->set('update_success', $success); + $request->getSession()->set('updates_remaining', $operations); // Now that the update is done, we can put the site back online if it was // previously not in maintenance mode. - if (empty($_SESSION['maintenance_mode'])) { + if (!$request->getSession()->remove('maintenance_mode')) { \Drupal::state()->set('system.maintenance_mode', FALSE); } - unset($_SESSION['maintenance_mode']); } /** diff --git a/core/modules/system/src/Tests/Session/SessionTest.php b/core/modules/system/src/Tests/Session/SessionTest.php index 1be9561b36..396f725279 100644 --- a/core/modules/system/src/Tests/Session/SessionTest.php +++ b/core/modules/system/src/Tests/Session/SessionTest.php @@ -140,7 +140,7 @@ public function testSessionPersistenceOnLogin() { $user = $this->drupalCreateUser(); $this->drupalLogin($user); // Test property added to session object form hook_user_login(). - $this->drupalGet('session-test/get-from-session-object'); + $this->drupalGet('session-test/get'); $this->assertText('foobar', 'Session data is saved in Session() object.', 'Session'); } @@ -311,7 +311,7 @@ public function assertSessionCookie($sent) { } /** - * Assert whether $_SESSION is empty at the beginning of the request. + * Assert whether the user's session is empty at the beginning of the request. */ public function assertSessionEmpty($empty) { if ($empty) { diff --git a/core/modules/system/system.install b/core/modules/system/system.install index a7f964539f..e265eece9c 100644 --- a/core/modules/system/system.install +++ b/core/modules/system/system.install @@ -1132,7 +1132,7 @@ function system_schema() { 'default' => 0, ], 'session' => [ - 'description' => 'The serialized contents of $_SESSION, an array of name/value pairs that persists across page requests by this session ID. Drupal loads $_SESSION from here at the start of each request and saves it at the end.', + 'description' => 'The serialized contents of the user\'s session, an array of name/value pairs that persists across page requests by this session ID. Drupal loads the user\'s session from here at the start of each request and saves it at the end.', 'type' => 'blob', 'not null' => FALSE, 'size' => 'big', diff --git a/core/modules/system/system.module b/core/modules/system/system.module index bb82d4b19f..45db82c31d 100644 --- a/core/modules/system/system.module +++ b/core/modules/system/system.module @@ -430,13 +430,14 @@ function template_preprocess_entity_add_list(&$variables) { /** * Setup a given callback to run via authorize.php with elevated privileges. * - * To use authorize.php, certain variables must be stashed into $_SESSION. This - * function sets up all the necessary $_SESSION variables. The calling function - * should then redirect to authorize.php, using the full path returned by - * system_authorized_get_url(). That initiates the workflow that will eventually - * lead to the callback being invoked. The callback will be invoked at a low - * bootstrap level, without all modules being invoked, so it needs to be careful - * not to assume any code exists. Example (system_authorized_run()): + * To use authorize.php, certain variables must be stashed in the user's + * session. This function sets up all the necessary session variables. The + * calling function should then redirect to authorize.php, using the full path + * returned by system_authorized_get_url(). That initiates the workflow that + * will eventually lead to the callback being invoked. The callback will be + * invoked at a low bootstrap level, without all modules being invoked, so it + * needs to be careful not to assume any code exists. + * Example (system_authorized_run()): * @code * system_authorized_init($callback, $file, $arguments, $page_title); * return new RedirectResponse(system_authorized_get_url()->toString()); @@ -463,20 +464,21 @@ function template_preprocess_entity_add_list(&$variables) { * Nothing, this function just initializes variables in the user's session. */ function system_authorized_init($callback, $file, $arguments = [], $page_title = NULL) { + $request = \Drupal::request(); // First, figure out what file transfer backends the site supports, and put // all of those in the SESSION so that authorize.php has access to all of // them via the class autoloader, even without a full bootstrap. - $_SESSION['authorize_filetransfer_info'] = drupal_get_filetransfer_info(); + $request->getSession()->set('authorize_filetransfer_info', drupal_get_filetransfer_info()); // Now, define the callback to invoke. - $_SESSION['authorize_operation'] = [ + $request->getSession()->set('authorize_operation', [ 'callback' => $callback, 'file' => $file, 'arguments' => $arguments, - ]; + ]); if (isset($page_title)) { - $_SESSION['authorize_page_title'] = $page_title; + $request->getSession()->set('authorize_page_title', $page_title); } } diff --git a/core/modules/system/tests/modules/form_test/src/Form/FormTestStorageForm.php b/core/modules/system/tests/modules/form_test/src/Form/FormTestStorageForm.php index f81658d537..e2aa0b7d35 100644 --- a/core/modules/system/tests/modules/form_test/src/Form/FormTestStorageForm.php +++ b/core/modules/system/tests/modules/form_test/src/Form/FormTestStorageForm.php @@ -37,7 +37,7 @@ public function buildForm(array $form, FormStateInterface $form_state) { if (empty($storage)) { $user_input = $form_state->getUserInput(); if (empty($user_input)) { - $_SESSION['constructions'] = 0; + $this->getRequest()->getSession()->set('constructions', 0); } // Put the initial thing into the storage $storage = [ @@ -49,8 +49,12 @@ public function buildForm(array $form, FormStateInterface $form_state) { $form_state->setStorage($storage); } // Count how often the form is constructed. - $_SESSION['constructions']++; - drupal_set_message("Form constructions: " . $_SESSION['constructions']); + $this->getRequest()->getSession()->set( + 'constructions', + $this->getRequest()->getSession()->get('constructions', 0) + 1 + ); + + drupal_set_message("Form constructions: " . $this->getRequest()->getSession()->get('constructions')); $form['title'] = [ '#type' => 'textfield', @@ -137,7 +141,7 @@ public function continueSubmitForm(array &$form, FormStateInterface $form_state) */ public function submitForm(array &$form, FormStateInterface $form_state) { drupal_set_message("Title: " . Html::escape($form_state->getValue('title'))); - drupal_set_message("Form constructions: " . $_SESSION['constructions']); + drupal_set_message("Form constructions: " . $this->getRequest()->getSession()->get('constructions')); if ($form_state->has(['thing', 'changed'])) { drupal_set_message("The thing has been changed."); } diff --git a/core/modules/system/tests/modules/menu_test/menu_test.services.yml b/core/modules/system/tests/modules/menu_test/menu_test.services.yml index 81f1f50b95..e1a0aa059b 100644 --- a/core/modules/system/tests/modules/menu_test/menu_test.services.yml +++ b/core/modules/system/tests/modules/menu_test/menu_test.services.yml @@ -6,5 +6,6 @@ services: access_check.menu_test_session: class: Drupal\menu_test\Access\AccessCheck + arguments: ['@request_stack'] tags: - { name: access_check, applies_to: _menu_test_session_access } diff --git a/core/modules/system/tests/modules/menu_test/src/Access/AccessCheck.php b/core/modules/system/tests/modules/menu_test/src/Access/AccessCheck.php index 1b67579eba..8ba743e032 100644 --- a/core/modules/system/tests/modules/menu_test/src/Access/AccessCheck.php +++ b/core/modules/system/tests/modules/menu_test/src/Access/AccessCheck.php @@ -4,12 +4,30 @@ use Drupal\Core\Access\AccessResult; use Drupal\Core\Routing\Access\AccessInterface; +use Symfony\Component\HttpFoundation\RequestStack; /** * Checks access based on the 'menu_test' key in session. */ class AccessCheck implements AccessInterface { + /** + * The request stack. + * + * @var \Symfony\Component\HttpFoundation\RequestStack + */ + protected $requestStack; + + /** + * Constructs a new AccessCheck class. + * + * @param \Symfony\Component\HttpFoundation\RequestStack $request_stack + * The request stack. + */ + public function __construct(RequestStack $request_stack) { + $this->requestStack = $request_stack; + } + /** * Check to see if user accessed this page. * @@ -17,12 +35,9 @@ class AccessCheck implements AccessInterface { * The access result. */ public function access() { - if (!isset($_SESSION['menu_test'])) { - $result = AccessResult::allowed(); - } - else { - $result = AccessResult::allowedIf($_SESSION['menu_test'] < 2); - } + $result = AccessResult::allowedIf( + $this->requestStack->getMasterRequest()->getSession()->get('menu_test', 0) < 2 + ); return $result->setCacheMaxAge(0); } diff --git a/core/modules/system/tests/modules/menu_test/src/TestControllers.php b/core/modules/system/tests/modules/menu_test/src/TestControllers.php index 31fb341afb..2ecd4e6c51 100644 --- a/core/modules/system/tests/modules/menu_test/src/TestControllers.php +++ b/core/modules/system/tests/modules/menu_test/src/TestControllers.php @@ -3,6 +3,7 @@ namespace Drupal\menu_test; use Drupal\Component\Utility\SafeMarkup; +use Symfony\Component\HttpFoundation\Request; /** * Controllers for testing the menu integration routing system. @@ -32,13 +33,19 @@ public function test2() { /** * Prints out test data. + * + * @param \Symfony\Component\HttpFoundation\Request $request + * The request. + * + * @return array + * Render array. */ - public function testSession() { - if (!isset($_SESSION['menu_test'])) { - $_SESSION['menu_test'] = 0; - } - $_SESSION['menu_test']++; - return ['#markup' => SafeMarkup::format('Session menu_test is @count', ['@count' => $_SESSION['menu_test']])]; + public function testSession(Request $request) { + $request->getSession()->set( + 'menu_test', + $request->getSession()->get('menu_test', 0) + 1 + ); + return ['#markup' => SafeMarkup::format('Session menu_test is @count', ['@count' => $request->getSession()->get('menu_test')])]; } /** diff --git a/core/modules/system/tests/modules/session_exists_cache_context_test/session_exists_cache_context_test.module b/core/modules/system/tests/modules/session_exists_cache_context_test/session_exists_cache_context_test.module index 60d2452836..2be874da7a 100644 --- a/core/modules/system/tests/modules/session_exists_cache_context_test/session_exists_cache_context_test.module +++ b/core/modules/system/tests/modules/session_exists_cache_context_test/session_exists_cache_context_test.module @@ -23,7 +23,8 @@ function session_exists_cache_context_test_page_top(array &$page_top) { ], ]; - if (\Drupal::request()->query->get('trigger_session')) { - $_SESSION['session_exists_cache_context_test'] = TRUE; + $request = \Drupal::request(); + if ($request->query->get('trigger_session')) { + $request->getSession()->set('session_exists_cache_context_test', TRUE); } } diff --git a/core/modules/system/tests/modules/session_test/session_test.module b/core/modules/system/tests/modules/session_test/session_test.module index b3ceff80a5..7906595541 100644 --- a/core/modules/system/tests/modules/session_test/session_test.module +++ b/core/modules/system/tests/modules/session_test/session_test.module @@ -15,5 +15,5 @@ function session_test_user_login($account) { exit; } // Add some data in the session for retrieval testing purpose. - \Drupal::request()->getSession()->set("session_test_key", "foobar"); + \Drupal::request()->getSession()->set("session_test_value", "foobar"); } diff --git a/core/modules/system/tests/modules/session_test/session_test.routing.yml b/core/modules/system/tests/modules/session_test/session_test.routing.yml index 84978c9474..0a4edbc53d 100644 --- a/core/modules/system/tests/modules/session_test/session_test.routing.yml +++ b/core/modules/system/tests/modules/session_test/session_test.routing.yml @@ -7,15 +7,6 @@ session_test.get: no_cache: TRUE requirements: _access: 'TRUE' -session_test.get_from_session_object: - path: '/session-test/get-from-session-object' - defaults: - _title: 'Session value' - _controller: '\Drupal\session_test\Controller\SessionTestController::getFromSessionObject' - options: - no_cache: TRUE - requirements: - _access: 'TRUE' session_test.id: path: '/session-test/id' defaults: diff --git a/core/modules/system/tests/modules/session_test/src/Controller/SessionTestController.php b/core/modules/system/tests/modules/session_test/src/Controller/SessionTestController.php index 76a5462942..f8b1af8399 100644 --- a/core/modules/system/tests/modules/session_test/src/Controller/SessionTestController.php +++ b/core/modules/system/tests/modules/session_test/src/Controller/SessionTestController.php @@ -12,29 +12,17 @@ */ class SessionTestController extends ControllerBase { - /** - * Prints the stored session value to the screen. - * - * @return string - * A notification message. - */ - public function get() { - return empty($_SESSION['session_test_value']) - ? [] - : ['#markup' => $this->t('The current value of the stored session variable is: %val', ['%val' => $_SESSION['session_test_value']])]; - } - /** * Prints the stored session value to the screen. * * @param \Symfony\Component\HttpFoundation\Request $request * The incoming request. * - * @return string + * @return array * A notification message. */ - public function getFromSessionObject(Request $request) { - $value = $request->getSession()->get("session_test_key"); + public function get(Request $request) { + $value = $request->getSession()->get("session_test_value"); return empty($value) ? [] : ['#markup' => $this->t('The current value of the stored session variable is: %val', ['%val' => $value])]; @@ -50,9 +38,9 @@ public function getFromSessionObject(Request $request) { * A notification message with session ID. */ public function getId(Request $request) { - // Set a value in $_SESSION, so that SessionManager::save() will start - // a session. - $_SESSION['test'] = 'test'; + // Set a value in the user's session, so that SessionManager::save() will + // start a session. + $request->getSession()->set('test', 'test'); $request->getSession()->save(); @@ -73,7 +61,7 @@ public function getIdFromCookie(Request $request) { } /** - * Stores a value in $_SESSION['session_test_value']. + * Stores a value in the user's session. * * @param string $test_value * A session value. @@ -81,8 +69,8 @@ public function getIdFromCookie(Request $request) { * @return string * A notification message. */ - public function set($test_value) { - $_SESSION['session_test_value'] = $test_value; + public function set($test_value, Request $request) { + $request->getSession()->set('session_test_value', $test_value); return ['#markup' => $this->t('The current value of the stored session variable has been set to %val', ['%val' => $test_value])]; } @@ -97,9 +85,9 @@ public function set($test_value) { * @return string * A notification message. */ - public function noSet($test_value) { + public function noSet($test_value, Request $request) { \Drupal::service('session_handler.write_safe')->setSessionWritable(FALSE); - $this->set($test_value); + $this->set($test_value, $request); return ['#markup' => $this->t('session saving was disabled, and then %val was set', ['%val' => $test_value])]; } @@ -149,14 +137,9 @@ public function isLoggedIn() { * The response. */ public function traceHandler(Request $request) { - // Start a session if necessary, set a value and then save and close it. - $request->getSession()->start(); - if (empty($_SESSION['trace-handler'])) { - $_SESSION['trace-handler'] = 1; - } - else { - $_SESSION['trace-handler']++; - } + $session = $request->getSession(); + $session->set('trace-handler', $session->get('trace-handler', 0) + 1); + // Close the session to create the trace. $request->getSession()->save(); // Collect traces and return them in JSON format. diff --git a/core/modules/system/tests/modules/session_test/src/EventSubscriber/SessionTestSubscriber.php b/core/modules/system/tests/modules/session_test/src/EventSubscriber/SessionTestSubscriber.php index 47c8c5b110..625dfe5b8d 100644 --- a/core/modules/system/tests/modules/session_test/src/EventSubscriber/SessionTestSubscriber.php +++ b/core/modules/system/tests/modules/session_test/src/EventSubscriber/SessionTestSubscriber.php @@ -13,7 +13,7 @@ class SessionTestSubscriber implements EventSubscriberInterface { /** - * Stores whether $_SESSION is empty at the beginning of the request. + * Stores whether the user's session is empty at the beginning of the request. * * @var bool */ diff --git a/core/modules/system/tests/src/Functional/System/SystemAuthorizeTest.php b/core/modules/system/tests/src/Functional/System/SystemAuthorizeTest.php index b3f9b310b3..6a6d8d3f26 100644 --- a/core/modules/system/tests/src/Functional/System/SystemAuthorizeTest.php +++ b/core/modules/system/tests/src/Functional/System/SystemAuthorizeTest.php @@ -31,7 +31,7 @@ protected function setUp() { * Initializing authorize.php needs to happen in the child Drupal * installation, not the parent. So, we visit a menu callback provided by * system_test.module which calls system_authorized_init() to initialize the - * $_SESSION inside the test site, not the framework site. This callback + * user's session inside the test site, not the framework site. This callback * redirects to authorize.php when it's done initializing. * * @see system_authorized_init() diff --git a/core/modules/update/src/Form/UpdateReady.php b/core/modules/update/src/Form/UpdateReady.php index 15a9ddd3f5..95947c5d3e 100644 --- a/core/modules/update/src/Form/UpdateReady.php +++ b/core/modules/update/src/Form/UpdateReady.php @@ -118,21 +118,21 @@ public function buildForm(array $form, FormStateInterface $form_state) { * {@inheritdoc} */ public function submitForm(array &$form, FormStateInterface $form_state) { + $session = $this->getRequest()->getSession(); // Store maintenance_mode setting so we can restore it when done. - $_SESSION['maintenance_mode'] = $this->state->get('system.maintenance_mode'); + $session->set('maintenance_mode', $this->state->get('system.maintenance_mode')); if ($form_state->getValue('maintenance_mode') == TRUE) { $this->state->set('system.maintenance_mode', TRUE); } - if (!empty($_SESSION['update_manager_update_projects'])) { + if ($session->has('update_manager_update_projects')) { // Make sure the Updater registry is loaded. drupal_get_updaters(); $updates = []; $directory = _update_manager_extract_directory(); - $projects = $_SESSION['update_manager_update_projects']; - unset($_SESSION['update_manager_update_projects']); + $projects = $session->remove('update_manager_update_projects'); $project_real_location = NULL; foreach ($projects as $project => $url) { diff --git a/core/modules/update/update.authorize.inc b/core/modules/update/update.authorize.inc index 1c2cc60fb2..0e4d14ce0d 100644 --- a/core/modules/update/update.authorize.inc +++ b/core/modules/update/update.authorize.inc @@ -60,7 +60,7 @@ function update_authorize_run_update($filetransfer, $projects) { // Since authorize.php has its own method for setting the page title, set it // manually here rather than passing it in to batch_set() as would normally // be done. - $_SESSION['authorize_page_title'] = t('Installing updates'); + \Drupal::request()->getSession()->set('authorize_page_title', t('Installing updates')); // Invoke the batch via authorize.php. return system_authorized_batch_process(); @@ -114,7 +114,7 @@ function update_authorize_run_install($filetransfer, $project, $updater_name, $l // Since authorize.php has its own method for setting the page title, set it // manually here rather than passing it in to batch_set() as would normally // be done. - $_SESSION['authorize_page_title'] = t('Installing %project', ['%project' => $project]); + \Drupal::request()->getSession()->set('authorize_page_title', t('Installing %project', ['%project' => $project])); // Invoke the batch via authorize.php. return system_authorized_batch_process(); @@ -213,13 +213,16 @@ function update_authorize_update_batch_finished($success, $results) { } } $offline = \Drupal::state()->get('system.maintenance_mode'); + $session = \Drupal::request()->getSession(); + // Unset the variable since it is no longer needed. + $maintenance_mode = $session->remove('maintenance_mode'); if ($success) { // Now that the update completed, we need to clear the available update data // and recompute our status, so prevent show bogus results. _update_authorize_clear_update_status(); // Take the site out of maintenance mode if it was previously that way. - if ($offline && isset($_SESSION['maintenance_mode']) && $_SESSION['maintenance_mode'] == FALSE) { + if ($offline && $maintenance_mode === FALSE) { \Drupal::state()->set('system.maintenance_mode', FALSE); $page_message = [ 'message' => t('Update was completed successfully. Your site has been taken out of maintenance mode.'), @@ -264,15 +267,14 @@ function update_authorize_update_batch_finished($success, $results) { '#access' => $url->access(\Drupal::currentUser()) ]; - // Unset the variable since it is no longer needed. - unset($_SESSION['maintenance_mode']); - // Set all these values into the SESSION so authorize.php can display them. - $_SESSION['authorize_results']['success'] = $success; - $_SESSION['authorize_results']['page_message'] = $page_message; - $_SESSION['authorize_results']['messages'] = $results['log']; - $_SESSION['authorize_results']['tasks'] = $results['tasks']; - $_SESSION['authorize_page_title'] = t('Update manager'); + $session->set('authorize_results', [ + 'success' => $success, + 'page_message' => $page_message, + 'messages' => $results['log'], + 'tasks' => $results['tasks'] + ]); + $session->set('authorize_page_title', t('Update manager')); } /** @@ -296,9 +298,12 @@ function update_authorize_install_batch_finished($success, $results) { } } $offline = \Drupal::state()->get('system.maintenance_mode'); + $session = \Drupal::request()->getSession(); + // Unset the variable since it is no longer needed. + $maintenance_mode = $session->remove('maintenance_mode'); if ($success) { // Take the site out of maintenance mode if it was previously that way. - if ($offline && isset($_SESSION['maintenance_mode']) && $_SESSION['maintenance_mode'] == FALSE) { + if ($offline && $maintenance_mode === FALSE) { \Drupal::state()->set('system.maintenance_mode', FALSE); $page_message = [ 'message' => t('Installation was completed successfully. Your site has been taken out of maintenance mode.'), @@ -325,15 +330,14 @@ function update_authorize_install_batch_finished($success, $results) { ]; } - // Unset the variable since it is no longer needed. - unset($_SESSION['maintenance_mode']); - // Set all these values into the SESSION so authorize.php can display them. - $_SESSION['authorize_results']['success'] = $success; - $_SESSION['authorize_results']['page_message'] = $page_message; - $_SESSION['authorize_results']['messages'] = $results['log']; - $_SESSION['authorize_results']['tasks'] = $results['tasks']; - $_SESSION['authorize_page_title'] = t('Update manager'); + $session->set('authorize_results', [ + 'success' => $success, + 'page_message' => $page_message, + 'messages' => $results['log'], + 'tasks' => $results['tasks'] + ]); + $session->set('authorize_page_title', t('Update manager')); } /** diff --git a/core/modules/update/update.manager.inc b/core/modules/update/update.manager.inc index 2229f0a205..5a6d9816be 100644 --- a/core/modules/update/update.manager.inc +++ b/core/modules/update/update.manager.inc @@ -57,7 +57,7 @@ function update_manager_download_batch_finished($success, $results) { } elseif ($success) { drupal_set_message(t('Updates downloaded successfully.')); - $_SESSION['update_manager_update_projects'] = $results['projects']; + \Drupal::request()->getSession()->set('update_manager_update_projects', $results['projects']); return new RedirectResponse(\Drupal::url('update.confirmation_page', [], ['absolute' => TRUE])); } else { diff --git a/core/modules/user/src/AccountForm.php b/core/modules/user/src/AccountForm.php index d6959681f4..8962c1b51f 100644 --- a/core/modules/user/src/AccountForm.php +++ b/core/modules/user/src/AccountForm.php @@ -118,9 +118,11 @@ public function form(array $form, FormStateInterface $form_state) { // To skip the current password field, the user must have logged in via a // one-time link and have the token in the URL. Store this in $form_state // so it persists even on subsequent Ajax requests. - if (!$form_state->get('user_pass_reset') && ($token = $this->getRequest()->get('pass-reset-token'))) { + $request = $this->getRequest(); + if (!$form_state->get('user_pass_reset') && ($token = $request->get('pass-reset-token'))) { $session_key = 'pass_reset_' . $account->id(); - $user_pass_reset = isset($_SESSION[$session_key]) && Crypt::hashEquals($_SESSION[$session_key], $token); + $session_value = $request->getSession()->get($session_key); + $user_pass_reset = isset($session_value) && Crypt::hashEquals($session_value, $token); $form_state->set('user_pass_reset', $user_pass_reset); } @@ -383,9 +385,7 @@ public function submitForm(array &$form, FormStateInterface $form_state) { $user = $this->getEntity($form_state); // If there's a session set to the users id, remove the password reset tag // since a new password was saved. - if (isset($_SESSION['pass_reset_' . $user->id()])) { - unset($_SESSION['pass_reset_' . $user->id()]); - } + $this->getRequest()->getSession()->remove('pass_reset_' . $user->id()); } } diff --git a/core/modules/user/src/Controller/UserController.php b/core/modules/user/src/Controller/UserController.php index be15fac4ab..77dce9aab6 100644 --- a/core/modules/user/src/Controller/UserController.php +++ b/core/modules/user/src/Controller/UserController.php @@ -192,6 +192,8 @@ public function getResetPassForm(Request $request, $uid) { * The current timestamp. * @param string $hash * Login link hash. + * @param \Symfony\Component\HttpFoundation\Request $request + * The request. * * @return \Symfony\Component\HttpFoundation\RedirectResponse * Returns a redirect to the user edit form if the information is correct. @@ -201,7 +203,7 @@ public function getResetPassForm(Request $request, $uid) { * @throws \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException * If $uid is for a blocked user or invalid user ID. */ - public function resetPassLogin($uid, $timestamp, $hash) { + public function resetPassLogin($uid, $timestamp, $hash, Request $request) { // The current user is not logged in, so check the parameters. $current = REQUEST_TIME; /** @var \Drupal\user\UserInterface $user */ @@ -228,7 +230,7 @@ public function resetPassLogin($uid, $timestamp, $hash) { // Let the user's password be changed without the current password // check. $token = Crypt::randomBytesBase64(55); - $_SESSION['pass_reset_' . $user->id()] = $token; + $request->getSession()->set('pass_reset_' . $user->id(), $token); return $this->redirect( 'entity.user.edit_form', ['user' => $user->id()], diff --git a/core/modules/views/src/Plugin/views/exposed_form/ExposedFormPluginBase.php b/core/modules/views/src/Plugin/views/exposed_form/ExposedFormPluginBase.php index 13d6b1122c..7711b6aa50 100644 --- a/core/modules/views/src/Plugin/views/exposed_form/ExposedFormPluginBase.php +++ b/core/modules/views/src/Plugin/views/exposed_form/ExposedFormPluginBase.php @@ -319,9 +319,12 @@ public function resetForm(&$form, FormStateInterface $form_state) { // remember settings. $display_id = ($this->view->display_handler->isDefaulted('filters')) ? 'default' : $this->view->current_display; - if (isset($_SESSION['views'][$this->view->storage->id()][$display_id])) { - unset($_SESSION['views'][$this->view->storage->id()][$display_id]); + $session = \Drupal::request()->getSession(); + $views_session = $session->get('views', []); + if (isset($views_session[$this->view->storage->id()][$display_id])) { + unset($views_session[$this->view->storage->id()][$display_id]); } + $session->set('views', $views_session); // Set the form to allow redirect. if (empty($this->view->live_preview) && !\Drupal::request()->isXmlHttpRequest()) { diff --git a/core/modules/views/src/Plugin/views/filter/FilterPluginBase.php b/core/modules/views/src/Plugin/views/filter/FilterPluginBase.php index fd273ddfa8..ec652ef849 100644 --- a/core/modules/views/src/Plugin/views/filter/FilterPluginBase.php +++ b/core/modules/views/src/Plugin/views/filter/FilterPluginBase.php @@ -1351,22 +1351,20 @@ public function storeGroupInput($input, $status) { // False means that we got a setting that means to recurse ourselves, // so we should erase whatever happened to be there. - if ($status === FALSE && isset($_SESSION['views'][$this->view->storage->id()][$display_id])) { - $session = &$_SESSION['views'][$this->view->storage->id()][$display_id]; - - if (isset($session[$this->options['group_info']['identifier']])) { - unset($session[$this->options['group_info']['identifier']]); - } + $session = \Drupal::request()->getSession(); + $views_session = $session->get('views', []); + if ($status === FALSE && isset($views_session[$this->view->storage->id()][$display_id])) { + unset($views_session[$this->view->storage->id()][$display_id][$this->options['group_info']['identifier']]); } if ($status !== FALSE) { - if (!isset($_SESSION['views'][$this->view->storage->id()][$display_id])) { - $_SESSION['views'][$this->view->storage->id()][$display_id] = []; + if (!isset($views_session[$this->view->storage->id()][$display_id])) { + $views_session[$this->view->storage->id()][$display_id] = []; } - - $session = &$_SESSION['views'][$this->view->storage->id()][$display_id]; - - $session[$this->options['group_info']['identifier']] = $input[$this->options['group_info']['identifier']]; + $views_session[$this->view->storage->id()][$display_id][$this->options['group_info']['identifier']] = $input[$this->options['group_info']['identifier']]; + } + if (!empty($views_session)) { + $session->set('views', $views_session); } } @@ -1454,29 +1452,34 @@ public function storeExposedInput($input, $status) { // False means that we got a setting that means to recurse ourselves, // so we should erase whatever happened to be there. - if (!$status && isset($_SESSION['views'][$this->view->storage->id()][$display_id])) { - $session = &$_SESSION['views'][$this->view->storage->id()][$display_id]; - if ($operator && isset($session[$this->options['expose']['operator_id']])) { - unset($session[$this->options['expose']['operator_id']]); + $session = \Drupal::request()->getSession(); + $views_session = $session->get('views', []); + if (!$status && isset($views_session[$this->view->storage->id()][$display_id])) { + $session_ref = &$views_session[$this->view->storage->id()][$display_id]; + if ($operator && isset($session_ref[$this->options['expose']['operator_id']])) { + unset($session_ref[$this->options['expose']['operator_id']]); } - if (isset($session[$this->options['expose']['identifier']])) { - unset($session[$this->options['expose']['identifier']]); + if (isset($session_ref[$this->options['expose']['identifier']])) { + unset($session_ref[$this->options['expose']['identifier']]); } } if ($status) { - if (!isset($_SESSION['views'][$this->view->storage->id()][$display_id])) { - $_SESSION['views'][$this->view->storage->id()][$display_id] = []; + if (!isset($views_session[$this->view->storage->id()][$display_id])) { + $views_session[$this->view->storage->id()][$display_id] = []; } - $session = &$_SESSION['views'][$this->view->storage->id()][$display_id]; + $session_ref = &$views_session[$this->view->storage->id()][$display_id]; if ($operator && isset($input[$this->options['expose']['operator_id']])) { - $session[$this->options['expose']['operator_id']] = $input[$this->options['expose']['operator_id']]; + $session_ref[$this->options['expose']['operator_id']] = $input[$this->options['expose']['operator_id']]; } - $session[$this->options['expose']['identifier']] = $input[$this->options['expose']['identifier']]; + $session_ref[$this->options['expose']['identifier']] = $input[$this->options['expose']['identifier']]; + } + if (!empty($views_session)) { + $session->set('views', $views_session); } } diff --git a/core/modules/views/src/ViewExecutable.php b/core/modules/views/src/ViewExecutable.php index 16b89f370e..ad88db2fb9 100644 --- a/core/modules/views/src/ViewExecutable.php +++ b/core/modules/views/src/ViewExecutable.php @@ -705,8 +705,11 @@ public function getExposedInput() { // remember settings. $display_id = ($this->display_handler->isDefaulted('filters')) ? 'default' : $this->current_display; - if (empty($this->exposed_input) && !empty($_SESSION['views'][$this->storage->id()][$display_id])) { - $this->exposed_input = $_SESSION['views'][$this->storage->id()][$display_id]; + if (empty($this->exposed_input) && $this->getRequest()->hasSession()) { + $views_session = $this->getRequest()->getSession()->get('views', []); + if (!empty($views_session[$this->storage->id()][$display_id])) { + $this->exposed_input = $views_session[$this->storage->id()][$display_id]; + } } } diff --git a/core/tests/Drupal/KernelTests/Core/EventSubscriber/IgnoreReplicaSubscriberTest.php b/core/tests/Drupal/KernelTests/Core/EventSubscriber/IgnoreReplicaSubscriberTest.php index 7ce994a944..8a2905f8d0 100644 --- a/core/tests/Drupal/KernelTests/Core/EventSubscriber/IgnoreReplicaSubscriberTest.php +++ b/core/tests/Drupal/KernelTests/Core/EventSubscriber/IgnoreReplicaSubscriberTest.php @@ -4,9 +4,7 @@ use Drupal\Core\Database\Database; use Drupal\Core\EventSubscriber\ReplicaDatabaseIgnoreSubscriber; -use Drupal\Core\DrupalKernel; use Drupal\KernelTests\KernelTestBase; -use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpKernel\HttpKernelInterface; use Symfony\Component\HttpKernel\Event\GetResponseEvent; @@ -27,10 +25,10 @@ public function testSystemInitIgnoresSecondaries() { $connection_info = Database::getConnectionInfo('default'); Database::addConnectionInfo('default', 'replica', $connection_info['default']); + $request = \Drupal::request(); + $request->setSession($this->container->get('session')); db_ignore_replica(); - $class_loader = require \Drupal::root() . '/autoload.php'; - $kernel = new DrupalKernel('testing', $class_loader, FALSE); - $event = new GetResponseEvent($kernel, Request::create('http://example.com'), HttpKernelInterface::MASTER_REQUEST); + $event = new GetResponseEvent($this->container->get('kernel'), $request, HttpKernelInterface::MASTER_REQUEST); $subscriber = new ReplicaDatabaseIgnoreSubscriber(); $subscriber->checkReplicaServer($event);