diff --git a/core/authorize.php b/core/authorize.php index a965e60..f312c57 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 b54beb6..02345dc 100644 --- a/core/includes/batch.inc +++ b/core/includes/batch.inc @@ -462,6 +462,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']); @@ -471,10 +472,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); } } } @@ -528,7 +530,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/form.inc b/core/includes/form.inc index ec6b2e8..dce91b7 100644 --- a/core/includes/form.inc +++ b/core/includes/form.inc @@ -605,7 +605,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. @@ -658,11 +658,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 */ @@ -707,7 +708,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 @@ -872,7 +873,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/FileTransfer/Form/FileTransferAuthorizeForm.php b/core/lib/Drupal/Core/FileTransfer/Form/FileTransferAuthorizeForm.php index 4b3da24..5865a48 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)) { $this->messenger()->addError($this->t('Unable to continue, no available methods of file transfer')); 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 df716e3..1ee2e57 100644 --- a/core/lib/Drupal/Core/Form/FormBuilder.php +++ b/core/lib/Drupal/Core/Form/FormBuilder.php @@ -244,11 +244,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/Messenger/LegacyMessenger.php b/core/lib/Drupal/Core/Messenger/LegacyMessenger.php index 35e3609..87ca1f6 100644 --- a/core/lib/Drupal/Core/Messenger/LegacyMessenger.php +++ b/core/lib/Drupal/Core/Messenger/LegacyMessenger.php @@ -135,10 +135,11 @@ protected function getMessengerService() { if (!isset(static::$messages)) { // A "session" was already created, perhaps to simply allow usage of // the previous method core used to store messages, use it. - if (isset($_SESSION)) { - if (!isset($_SESSION['messages'])) { - $_SESSION['messages'] = []; - } + if ($request->hasSession()) { + $request->getSession()->set( + 'messages', + $this->getRequest()->getSession()->remove('messages'); + ); static::$messages = &$_SESSION['messages']; } // Otherwise, just set an empty array. diff --git a/core/lib/Drupal/Core/PageCache/RequestPolicy/NoSessionOpen.php b/core/lib/Drupal/Core/PageCache/RequestPolicy/NoSessionOpen.php index e29ae0b..38e51df 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 user-specific 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/lib/Drupal/Core/Session/SessionManager.php b/core/lib/Drupal/Core/Session/SessionManager.php index 7981398..1a10170 100644 --- a/core/lib/Drupal/Core/Session/SessionManager.php +++ b/core/lib/Drupal/Core/Session/SessionManager.php @@ -131,7 +131,9 @@ public function start() { $this->setId(Crypt::randomBytesBase64()); // Initialize the session global and attach the Symfony session bags. - $_SESSION = []; + if (\Drupal::hasContainer() && \Drupal::request()->hasSession()) { + \Drupal::request()->getSession()->clear(); + } $this->loadSession(); // NativeSessionStorage::loadSession() sets started to TRUE, reset it to @@ -155,7 +157,8 @@ protected function startNow() { if ($this->isCli()) { return FALSE; } - + $request = \Drupal::request(); + if ($this->startedLazy) { // Save current session data before starting it, as PHP will destroy it. $session_data = $_SESSION; @@ -165,7 +168,7 @@ protected function startNow() { // Restore session data. if ($this->startedLazy) { - $_SESSION = $session_data; + $request->getSession()->set($session_data); $this->loadSession(); } @@ -307,12 +310,12 @@ protected function isSessionObsolete() { * user data. */ protected function getSessionDataMask() { - if (empty($_SESSION)) { + if ($request->hasSession()) { return []; } // Start out with a completely filled mask. - $mask = array_fill_keys(array_keys($_SESSION), TRUE); + $mask = array_fill_keys(array_keys($request->hasSession()), TRUE); // Ignore the metadata bag, it does not contain any user data. $mask[$this->metadataBag->getStorageKey()] = FALSE; @@ -323,7 +326,7 @@ protected function getSessionDataMask() { $mask[$key] = !empty($_SESSION[$key]); } - return array_intersect_key($mask, $_SESSION); + return array_intersect_key($mask, $request->hasSession()); } /** 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 67c805b..739825e 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/comment/tests/src/Kernel/CommentDefaultFormatterCacheTagsTest.php b/core/modules/comment/tests/src/Kernel/CommentDefaultFormatterCacheTagsTest.php index bdea71d..4e271c5 100644 --- a/core/modules/comment/tests/src/Kernel/CommentDefaultFormatterCacheTagsTest.php +++ b/core/modules/comment/tests/src/Kernel/CommentDefaultFormatterCacheTagsTest.php @@ -51,6 +51,7 @@ protected function setUp() { $current_user->setAccount($this->createUser([], ['access comments'])); // Install tables and config needed to render comments. + $this->installSchema('system', ['sessions']); $this->installSchema('comment', ['comment_entity_statistics']); $this->installConfig(['system', 'filter', 'comment']); diff --git a/core/modules/dblog/src/Controller/DbLogController.php b/core/modules/dblog/src/Controller/DbLogController.php index 54bc7ea..5e59efd 100644 --- a/core/modules/dblog/src/Controller/DbLogController.php +++ b/core/modules/dblog/src/Controller/DbLogController.php @@ -114,6 +114,8 @@ 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\Core\Render\RendererInterface::render(). @@ -121,9 +123,9 @@ public static function getLogLevelClassMap() { * @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(); @@ -305,12 +307,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; } @@ -320,7 +325,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 e567729..a77aa5c 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(); $this->messenger()->addStatus($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 21619d6..08b7f24 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 6e812bc..7bc969a 100644 --- a/core/modules/file/file.module +++ b/core/modules/file/file.module @@ -780,7 +780,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::messenger()->deleteByType(MessengerInterface::TYPE_ERROR); $upload_location = isset($element['#upload_location']) ? $element['#upload_location'] : FALSE; @@ -790,7 +790,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::messenger()->deleteByType(MessengerInterface::TYPE_ERROR); if (!empty($errors_new)) { diff --git a/core/modules/language/src/Plugin/LanguageNegotiation/LanguageNegotiationSession.php b/core/modules/language/src/Plugin/LanguageNegotiation/LanguageNegotiationSession.php index 971e907..8c3a699 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 cfa3b69..1926b23 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 9a7ad8b..f083f6d 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 2054766..461a4ec 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 9af30b7..29acd24 100644 --- a/core/modules/simpletest/src/TestBase.php +++ b/core/modules/simpletest/src/TestBase.php @@ -1201,7 +1201,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 25a2a70..7fb48c4 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/system.install b/core/modules/system/system.install index 960bb7d..5421cb2 100644 --- a/core/modules/system/system.install +++ b/core/modules/system/system.install @@ -1162,7 +1162,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 57f297b..320d35d 100644 --- a/core/modules/system/system.module +++ b/core/modules/system/system.module @@ -432,13 +432,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()); @@ -465,20 +466,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 5cc09b7..1dddcbe 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']++; - $this->messenger()->addStatus("Form constructions: " . $_SESSION['constructions']); + $this->getRequest()->getSession()->set( + 'constructions', + $this->getRequest()->getSession()->get('constructions', 0) + 1 + ); + + $this->messenger()->addStatus("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) { $this->messenger()->addStatus("Title: " . Html::escape($form_state->getValue('title'))); - $this->messenger()->addStatus("Form constructions: " . $_SESSION['constructions']); + $this->messenger()->addStatus("Form constructions: " . $this->getRequest()->getSession()->get('constructions')); if ($form_state->has(['thing', 'changed'])) { $this->messenger()->addStatus("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 81f1f50..e1a0aa0 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 e87fcfa..cd60aac 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 @@ -3,12 +3,41 @@ namespace Drupal\menu_test\Access; use Drupal\Core\Access\AccessResult; +use Drupal\Core\DependencyInjection\ContainerInjectionInterface; use Drupal\Core\Routing\Access\AccessInterface; +use Symfony\Component\DependencyInjection\ContainerInterface; +use Symfony\Component\HttpFoundation\RequestStack; /** * Checks access based on the 'menu_test' key in session. */ -class AccessCheck implements AccessInterface { +class AccessCheck implements AccessInterface, ContainerInjectionInterface { + + /** + * 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; + } + + /** + * {@inheritdoc} + */ + public static function create(ContainerInterface $container) { + return new static( + $container->get('request_stack') + ); + } /** * Check to see if user accessed this page. @@ -17,12 +46,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->getCurrentRequest()->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 dafaab0..d1339e9 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\Render\FormattableMarkup; +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' => new FormattableMarkup('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' => new FormattableMarkup('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 60d2452..2be874d 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 1555f9c..e1cb4aa 100644 --- a/core/modules/system/tests/modules/session_test/session_test.module +++ b/core/modules/system/tests/modules/session_test/session_test.module @@ -17,5 +17,5 @@ function session_test_user_login(UserInterface $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 84978c9..0a4edbc 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 1094522..8e95858 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 @@ -15,26 +15,14 @@ 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 47c8c5b..625dfe5 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/Session/SessionTest.php b/core/modules/system/tests/src/Functional/Session/SessionTest.php index 0cee31f..ac26801 100644 --- a/core/modules/system/tests/src/Functional/Session/SessionTest.php +++ b/core/modules/system/tests/src/Functional/Session/SessionTest.php @@ -151,7 +151,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'); } @@ -313,7 +313,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/tests/src/Functional/System/SystemAuthorizeTest.php b/core/modules/system/tests/src/Functional/System/SystemAuthorizeTest.php index b3f9b31..6a6d8d3 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 15a9ddd..95947c5 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 fea365a..4f2a2f5 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 2b2aef2..e0b6c22 100644 --- a/core/modules/update/update.manager.inc +++ b/core/modules/update/update.manager.inc @@ -58,7 +58,7 @@ function update_manager_download_batch_finished($success, $results) { } elseif ($success) { \Drupal::messenger()->addStatus(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 20eeabd..ab6d6d1 100644 --- a/core/modules/user/src/AccountForm.php +++ b/core/modules/user/src/AccountForm.php @@ -129,9 +129,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); } @@ -394,9 +396,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 0531668..3981912 100644 --- a/core/modules/user/src/Controller/UserController.php +++ b/core/modules/user/src/Controller/UserController.php @@ -197,6 +197,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. @@ -206,7 +208,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 */ @@ -233,7 +235,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 13d6b11..7711b6a 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 8821ea8..d465166 100644 --- a/core/modules/views/src/Plugin/views/filter/FilterPluginBase.php +++ b/core/modules/views/src/Plugin/views/filter/FilterPluginBase.php @@ -1339,22 +1339,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); } } @@ -1442,29 +1440,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 9ee3704..f00fc52 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/Database/ReplicaKillSwitchTest.php b/core/tests/Drupal/KernelTests/Core/Database/ReplicaKillSwitchTest.php index b2cdf72..a04ae7e 100644 --- a/core/tests/Drupal/KernelTests/Core/Database/ReplicaKillSwitchTest.php +++ b/core/tests/Drupal/KernelTests/Core/Database/ReplicaKillSwitchTest.php @@ -6,7 +6,6 @@ use Drupal\Core\DrupalKernel; use Drupal\Core\Site\Settings; use Drupal\KernelTests\KernelTestBase; -use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpKernel\HttpKernelInterface; use Symfony\Component\HttpKernel\Event\GetResponseEvent; @@ -27,12 +26,14 @@ public function testSystemInitIgnoresSecondaries() { $connection_info = Database::getConnectionInfo('default'); Database::addConnectionInfo('default', 'replica', $connection_info['default']); + $request = \Drupal::request(); + $request->setSession($this->container->get('session')); /** @var \Drupal\Core\Database\ReplicaKillSwitch $service */ $service = \Drupal::service('database.replica_kill_switch'); $service->trigger(); $class_loader = require $this->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($kernel, $request, HttpKernelInterface::MASTER_REQUEST); $service->checkReplicaServer($event); $db1 = Database::getConnection('default', 'default');