Unverified Commit e47700f7 authored by larowlan's avatar larowlan

Issue #3009377 by kim.pepper, andypost, Berdir, alexpott, Wim Leers,...

Issue #3009377 by kim.pepper, andypost, Berdir, alexpott, Wim Leers, mpdonadio, acbramley, larowlan, catch, xjm: Replace drupal_get_user_timezone with a date_default_timezone_get() and an event listener
parent ae23684b
...@@ -1530,6 +1530,7 @@ services: ...@@ -1530,6 +1530,7 @@ services:
arguments: ['@private_key', '@cache.bootstrap', '@cache.static'] arguments: ['@private_key', '@cache.bootstrap', '@cache.static']
current_user: current_user:
class: Drupal\Core\Session\AccountProxy class: Drupal\Core\Session\AccountProxy
arguments: ['@event_dispatcher']
session_configuration: session_configuration:
class: Drupal\Core\Session\SessionConfiguration class: Drupal\Core\Session\SessionConfiguration
arguments: ['%session.storage.options%'] arguments: ['%session.storage.options%']
......
...@@ -564,20 +564,15 @@ function drupal_get_messages($type = NULL, $clear_queue = TRUE) { ...@@ -564,20 +564,15 @@ function drupal_get_messages($type = NULL, $clear_queue = TRUE) {
* *
* @return string * @return string
* The name of the current user's timezone or the name of the default timezone. * The name of the current user's timezone or the name of the default timezone.
*
* @deprecated in drupal:8.8.0 and will be removed from drupal:9.0.0. Use
* date_default_timezone_get() instead.
*
* @see https://www.drupal.org/node/3009387
*/ */
function drupal_get_user_timezone() { function drupal_get_user_timezone() {
$user = \Drupal::currentUser(); @trigger_error('drupal_get_user_timezone() is deprecated in drupal:8.8.0. It will be removed from drupal:9.0.0. Use date_default_timezone_get() instead. See https://www.drupal.org/node/3009387', E_USER_DEPRECATED);
$config = \Drupal::config('system.date'); return date_default_timezone_get();
if ($user && $config->get('timezone.user.configurable') && $user->isAuthenticated() && $user->getTimezone()) {
return $user->getTimezone();
}
else {
// Ignore PHP strict notice if time zone has not yet been set in the php.ini
// configuration.
$config_data_default_timezone = $config->get('timezone.default');
return !empty($config_data_default_timezone) ? $config_data_default_timezone : @date_default_timezone_get();
}
} }
/** /**
......
...@@ -73,7 +73,7 @@ public function __construct($time = 'now', $timezone = NULL, $settings = []) { ...@@ -73,7 +73,7 @@ public function __construct($time = 'now', $timezone = NULL, $settings = []) {
protected function prepareTimezone($timezone) { protected function prepareTimezone($timezone) {
if (empty($timezone)) { if (empty($timezone)) {
// Fallback to user or system default timezone. // Fallback to user or system default timezone.
$timezone = drupal_get_user_timezone(); $timezone = date_default_timezone_get();
} }
return parent::prepareTimezone($timezone); return parent::prepareTimezone($timezone);
} }
......
...@@ -33,7 +33,7 @@ public function getInfo() { ...@@ -33,7 +33,7 @@ public function getInfo() {
'#date_year_range' => '1900:2050', '#date_year_range' => '1900:2050',
'#date_increment' => 1, '#date_increment' => 1,
'#date_date_callbacks' => [], '#date_date_callbacks' => [],
'#date_timezone' => drupal_get_user_timezone(), '#date_timezone' => date_default_timezone_get(),
]; ];
} }
...@@ -149,7 +149,7 @@ public static function valueCallback(&$element, $input, FormStateInterface $form ...@@ -149,7 +149,7 @@ public static function valueCallback(&$element, $input, FormStateInterface $form
* minute. * minute.
* - #date_timezone: The Time Zone Identifier (TZID) to use when displaying * - #date_timezone: The Time Zone Identifier (TZID) to use when displaying
* or interpreting dates, i.e: 'Asia/Kolkata'. Defaults to the value * or interpreting dates, i.e: 'Asia/Kolkata'. Defaults to the value
* returned by drupal_get_user_timezone(). * returned by date_default_timezone_get().
* *
* Example usage: * Example usage:
* @code * @code
......
...@@ -61,7 +61,7 @@ public function getInfo() { ...@@ -61,7 +61,7 @@ public function getInfo() {
'#date_time_callbacks' => [], '#date_time_callbacks' => [],
'#date_year_range' => '1900:2050', '#date_year_range' => '1900:2050',
'#date_increment' => 1, '#date_increment' => 1,
'#date_timezone' => drupal_get_user_timezone(), '#date_timezone' => date_default_timezone_get(),
]; ];
} }
...@@ -190,7 +190,7 @@ public static function valueCallback(&$element, $input, FormStateInterface $form ...@@ -190,7 +190,7 @@ public static function valueCallback(&$element, $input, FormStateInterface $form
* second. * second.
* - #date_timezone: The Time Zone Identifier (TZID) to use when displaying * - #date_timezone: The Time Zone Identifier (TZID) to use when displaying
* or interpreting dates, i.e: 'Asia/Kolkata'. Defaults to the value * or interpreting dates, i.e: 'Asia/Kolkata'. Defaults to the value
* returned by drupal_get_user_timezone(). * returned by date_default_timezone_get().
* *
* Example usage: * Example usage:
* @code * @code
......
...@@ -2,8 +2,8 @@ ...@@ -2,8 +2,8 @@
namespace Drupal\Core\EventSubscriber; namespace Drupal\Core\EventSubscriber;
use Drupal\Core\Authentication\AuthenticationProviderFilterInterface;
use Drupal\Core\Authentication\AuthenticationProviderChallengeInterface; use Drupal\Core\Authentication\AuthenticationProviderChallengeInterface;
use Drupal\Core\Authentication\AuthenticationProviderFilterInterface;
use Drupal\Core\Authentication\AuthenticationProviderInterface; use Drupal\Core\Authentication\AuthenticationProviderInterface;
use Drupal\Core\Session\AccountProxyInterface; use Drupal\Core\Session\AccountProxyInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Symfony\Component\EventDispatcher\EventSubscriberInterface;
...@@ -80,8 +80,6 @@ public function onKernelRequestAuthenticate(GetResponseEvent $event) { ...@@ -80,8 +80,6 @@ public function onKernelRequestAuthenticate(GetResponseEvent $event) {
return; return;
} }
} }
// No account has been set explicitly, initialize the timezone here.
date_default_timezone_set(drupal_get_user_timezone());
} }
} }
......
<?php
namespace Drupal\Core\Session;
/**
* Defines events for the account system.
*
* @see \Drupal\Core\Session\AccountSetEvent
*/
final class AccountEvents {
/**
* Name of the event fired when the current user is set.
*
* This event allows modules to perform an action whenever the current user is
* set. The event listener receives an \Drupal\Core\Session\AccountSetEvent
* instance.
*
* @Event
*
* @see \Drupal\Core\Session\AccountSetEvent
* @see \Drupal\Core\Session\AccountProxyInterface::setAccount()
*
* @var string
*/
const SET_USER = 'account.set';
}
...@@ -2,6 +2,9 @@ ...@@ -2,6 +2,9 @@
namespace Drupal\Core\Session; namespace Drupal\Core\Session;
use Drupal\Core\DependencyInjection\DependencySerializationTrait;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
/** /**
* A proxied implementation of AccountInterface. * A proxied implementation of AccountInterface.
* *
...@@ -15,6 +18,8 @@ ...@@ -15,6 +18,8 @@
*/ */
class AccountProxy implements AccountProxyInterface { class AccountProxy implements AccountProxyInterface {
use DependencySerializationTrait;
/** /**
* The instantiated account. * The instantiated account.
* *
...@@ -39,6 +44,27 @@ class AccountProxy implements AccountProxyInterface { ...@@ -39,6 +44,27 @@ class AccountProxy implements AccountProxyInterface {
*/ */
protected $initialAccountId; protected $initialAccountId;
/**
* Event dispatcher.
*
* @var \Symfony\Component\EventDispatcher\EventDispatcherInterface
*/
protected $eventDispatcher;
/**
* AccountProxy constructor.
*
* @param \Symfony\Component\EventDispatcher\EventDispatcherInterface $eventDispatcher
* Event dispatcher.
*/
public function __construct(EventDispatcherInterface $eventDispatcher = NULL) {
if (!$eventDispatcher) {
@trigger_error('Calling AccountProxy::__construct() without the $eventDispatcher argument is deprecated in drupal:8.8.0. The $eventDispatcher argument will be required in drupal:9.0.0. See https://www.drupal.org/node/3009387', E_USER_DEPRECATED);
$eventDispatcher = \Drupal::service('event_dispatcher');
}
$this->eventDispatcher = $eventDispatcher;
}
/** /**
* {@inheritdoc} * {@inheritdoc}
*/ */
...@@ -50,7 +76,7 @@ public function setAccount(AccountInterface $account) { ...@@ -50,7 +76,7 @@ public function setAccount(AccountInterface $account) {
} }
$this->account = $account; $this->account = $account;
$this->id = $account->id(); $this->id = $account->id();
date_default_timezone_set(drupal_get_user_timezone()); $this->eventDispatcher->dispatch(AccountEvents::SET_USER, new AccountSetEvent($account));
} }
/** /**
......
<?php
namespace Drupal\Core\Session;
use Symfony\Component\EventDispatcher\Event;
/**
* Event fired when an account is set for the current session.
*/
final class AccountSetEvent extends Event {
/**
* The set account.
*
* @var \Drupal\Core\Session\AccountInterface
*/
protected $account;
/**
* AccountSetEvent constructor.
*
* @param \Drupal\Core\Session\AccountInterface $account
* The set account.
*/
public function __construct(AccountInterface $account) {
$this->account = $account;
}
/**
* Gets the account.
*
* @return \Drupal\Core\Session\AccountInterface
* The account.
*/
public function getAccount() {
return $this->account;
}
}
...@@ -55,7 +55,7 @@ public function viewElements(FieldItemListInterface $items, $langcode) { ...@@ -55,7 +55,7 @@ public function viewElements(FieldItemListInterface $items, $langcode) {
*/ */
protected function formatDate($date) { protected function formatDate($date) {
$format = $this->getSetting('date_format'); $format = $this->getSetting('date_format');
$timezone = $this->getSetting('timezone_override'); $timezone = $this->getSetting('timezone_override') ?: $date->getTimezone()->getName();
return $this->dateFormatter->format($date->getTimestamp(), 'custom', $format, $timezone != '' ? $timezone : NULL); return $this->dateFormatter->format($date->getTimestamp(), 'custom', $format, $timezone != '' ? $timezone : NULL);
} }
......
...@@ -160,8 +160,6 @@ public function viewElements(FieldItemListInterface $items, $langcode) { ...@@ -160,8 +160,6 @@ public function viewElements(FieldItemListInterface $items, $langcode) {
* zone applied to it. This method will apply the time zone for the current * zone applied to it. This method will apply the time zone for the current
* user, based on system and user settings. * user, based on system and user settings.
* *
* @see drupal_get_user_timezone()
*
* @param \Drupal\Core\Datetime\DrupalDateTime $date * @param \Drupal\Core\Datetime\DrupalDateTime $date
* A DrupalDateTime object. * A DrupalDateTime object.
*/ */
...@@ -171,7 +169,7 @@ protected function setTimeZone(DrupalDateTime $date) { ...@@ -171,7 +169,7 @@ protected function setTimeZone(DrupalDateTime $date) {
$timezone = DateTimeItemInterface::STORAGE_TIMEZONE; $timezone = DateTimeItemInterface::STORAGE_TIMEZONE;
} }
else { else {
$timezone = drupal_get_user_timezone(); $timezone = date_default_timezone_get();
} }
$date->setTimeZone(timezone_open($timezone)); $date->setTimeZone(timezone_open($timezone));
} }
......
...@@ -42,7 +42,7 @@ public function viewElements(FieldItemListInterface $items, $langcode) { ...@@ -42,7 +42,7 @@ public function viewElements(FieldItemListInterface $items, $langcode) {
*/ */
protected function formatDate($date) { protected function formatDate($date) {
$format = $this->getFieldSetting('datetime_type') == DateTimeItem::DATETIME_TYPE_DATE ? DateTimeItemInterface::DATE_STORAGE_FORMAT : DateTimeItemInterface::DATETIME_STORAGE_FORMAT; $format = $this->getFieldSetting('datetime_type') == DateTimeItem::DATETIME_TYPE_DATE ? DateTimeItemInterface::DATE_STORAGE_FORMAT : DateTimeItemInterface::DATETIME_STORAGE_FORMAT;
$timezone = $this->getSetting('timezone_override'); $timezone = $this->getSetting('timezone_override') ?: $date->getTimezone()->getName();
return $this->dateFormatter->format($date->getTimestamp(), 'custom', $format, $timezone != '' ? $timezone : NULL); return $this->dateFormatter->format($date->getTimestamp(), 'custom', $format, $timezone != '' ? $timezone : NULL);
} }
......
...@@ -95,7 +95,7 @@ public static function processDefaultValue($default_value, FieldableEntityInterf ...@@ -95,7 +95,7 @@ public static function processDefaultValue($default_value, FieldableEntityInterf
if ($definition->getSetting('datetime_type') === DateTimeItem::DATETIME_TYPE_DATE) { if ($definition->getSetting('datetime_type') === DateTimeItem::DATETIME_TYPE_DATE) {
// A default date only value should be in the format used for date // A default date only value should be in the format used for date
// storage but in the user's local timezone. // storage but in the user's local timezone.
$date = new DrupalDateTime($default_value[0]['default_date'], drupal_get_user_timezone()); $date = new DrupalDateTime($default_value[0]['default_date'], date_default_timezone_get());
$format = DateTimeItemInterface::DATE_STORAGE_FORMAT; $format = DateTimeItemInterface::DATE_STORAGE_FORMAT;
} }
else { else {
......
...@@ -22,7 +22,7 @@ public function formElement(FieldItemListInterface $items, $delta, array $elemen ...@@ -22,7 +22,7 @@ public function formElement(FieldItemListInterface $items, $delta, array $elemen
'#type' => 'datetime', '#type' => 'datetime',
'#default_value' => NULL, '#default_value' => NULL,
'#date_increment' => 1, '#date_increment' => 1,
'#date_timezone' => drupal_get_user_timezone(), '#date_timezone' => date_default_timezone_get(),
'#required' => $element['#required'], '#required' => $element['#required'],
]; ];
......
...@@ -151,7 +151,7 @@ protected function opSimple($field) { ...@@ -151,7 +151,7 @@ protected function opSimple($field) {
protected function getTimezone() { protected function getTimezone() {
return $this->dateFormat === DateTimeItemInterface::DATE_STORAGE_FORMAT return $this->dateFormat === DateTimeItemInterface::DATE_STORAGE_FORMAT
? DateTimeItemInterface::STORAGE_TIMEZONE ? DateTimeItemInterface::STORAGE_TIMEZONE
: drupal_get_user_timezone(); : date_default_timezone_get();
} }
/** /**
...@@ -173,7 +173,7 @@ protected function getOffset($time, $timezone) { ...@@ -173,7 +173,7 @@ protected function getOffset($time, $timezone) {
// the user's offset from UTC for use in the query. // the user's offset from UTC for use in the query.
$origin_offset = 0; $origin_offset = 0;
if ($this->dateFormat === DateTimeItemInterface::DATE_STORAGE_FORMAT && $this->value['type'] === 'offset') { if ($this->dateFormat === DateTimeItemInterface::DATE_STORAGE_FORMAT && $this->value['type'] === 'offset') {
$origin_offset = $origin_offset + timezone_offset_get(new \DateTimeZone(drupal_get_user_timezone()), new \DateTime($time, new \DateTimeZone($timezone))); $origin_offset = $origin_offset + timezone_offset_get(new \DateTimeZone(date_default_timezone_get()), new \DateTime($time, new \DateTimeZone($timezone)));
} }
return $origin_offset; return $origin_offset;
......
...@@ -253,7 +253,7 @@ public function testDatetimeField() { ...@@ -253,7 +253,7 @@ public function testDatetimeField() {
$date = new DrupalDateTime($value, 'UTC'); $date = new DrupalDateTime($value, 'UTC');
// Update the timezone to the system default. // Update the timezone to the system default.
$date->setTimezone(timezone_open(drupal_get_user_timezone())); $date->setTimezone(timezone_open(date_default_timezone_get()));
// Submit a valid date and ensure it is accepted. // Submit a valid date and ensure it is accepted.
$date_format = DateFormat::load('html_date')->getPattern(); $date_format = DateFormat::load('html_date')->getPattern();
...@@ -708,7 +708,7 @@ public function testDefaultValue() { ...@@ -708,7 +708,7 @@ public function testDefaultValue() {
// Create a new node to check that datetime field default value is today. // Create a new node to check that datetime field default value is today.
$new_node = Node::create(['type' => 'date_content']); $new_node = Node::create(['type' => 'date_content']);
$expected_date = new DrupalDateTime('now', drupal_get_user_timezone()); $expected_date = new DrupalDateTime('now', date_default_timezone_get());
$this->assertEqual($new_node->get($field_name) $this->assertEqual($new_node->get($field_name)
->offsetGet(0)->value, $expected_date->format(DateTimeItemInterface::DATE_STORAGE_FORMAT)); ->offsetGet(0)->value, $expected_date->format(DateTimeItemInterface::DATE_STORAGE_FORMAT));
...@@ -747,7 +747,7 @@ public function testDefaultValue() { ...@@ -747,7 +747,7 @@ public function testDefaultValue() {
// Create a new node to check that datetime field default value is +90 // Create a new node to check that datetime field default value is +90
// days. // days.
$new_node = Node::create(['type' => 'date_content']); $new_node = Node::create(['type' => 'date_content']);
$expected_date = new DrupalDateTime('+90 days', drupal_get_user_timezone()); $expected_date = new DrupalDateTime('+90 days', date_default_timezone_get());
$this->assertEqual($new_node->get($field_name) $this->assertEqual($new_node->get($field_name)
->offsetGet(0)->value, $expected_date->format(DateTimeItemInterface::DATE_STORAGE_FORMAT)); ->offsetGet(0)->value, $expected_date->format(DateTimeItemInterface::DATE_STORAGE_FORMAT));
......
...@@ -111,7 +111,7 @@ protected function setSiteTimezone($timezone) { ...@@ -111,7 +111,7 @@ protected function setSiteTimezone($timezone) {
* Unix timestamp. * Unix timestamp.
*/ */
protected function getUTCEquivalentOfUserNowAsTimestamp() { protected function getUTCEquivalentOfUserNowAsTimestamp() {
$user_now = new DateTimePlus('now', new \DateTimeZone(drupal_get_user_timezone())); $user_now = new DateTimePlus('now', new \DateTimeZone(date_default_timezone_get()));
$utc_equivalent = new DateTimePlus($user_now->format('Y-m-d H:i:s'), new \DateTimeZone(DateTimeItemInterface::STORAGE_TIMEZONE)); $utc_equivalent = new DateTimePlus($user_now->format('Y-m-d H:i:s'), new \DateTimeZone(DateTimeItemInterface::STORAGE_TIMEZONE));
return $utc_equivalent->getTimestamp(); return $utc_equivalent->getTimestamp();
......
...@@ -62,7 +62,7 @@ public function massageFormValues(array $values, array $form, FormStateInterface ...@@ -62,7 +62,7 @@ public function massageFormValues(array $values, array $form, FormStateInterface
} }
$storage_timezone = new \DateTimeZone(DateTimeItemInterface::STORAGE_TIMEZONE); $storage_timezone = new \DateTimeZone(DateTimeItemInterface::STORAGE_TIMEZONE);
$user_timezone = new \DateTimeZone(drupal_get_user_timezone()); $user_timezone = new \DateTimeZone(date_default_timezone_get());
foreach ($values as &$item) { foreach ($values as &$item) {
if (!empty($item['value']) && $item['value'] instanceof DrupalDateTime) { if (!empty($item['value']) && $item['value'] instanceof DrupalDateTime) {
......
...@@ -304,8 +304,8 @@ public function testDatetimeRangeField() { ...@@ -304,8 +304,8 @@ public function testDatetimeRangeField() {
$end_date = new DrupalDateTime($end_value, 'UTC'); $end_date = new DrupalDateTime($end_value, 'UTC');
// Update the timezone to the system default. // Update the timezone to the system default.
$start_date->setTimezone(timezone_open(drupal_get_user_timezone())); $start_date->setTimezone(timezone_open(date_default_timezone_get()));
$end_date->setTimezone(timezone_open(drupal_get_user_timezone())); $end_date->setTimezone(timezone_open(date_default_timezone_get()));
// Submit a valid date and ensure it is accepted. // Submit a valid date and ensure it is accepted.
$date_format = DateFormat::load('html_date')->getPattern(); $date_format = DateFormat::load('html_date')->getPattern();
...@@ -390,7 +390,7 @@ public function testDatetimeRangeField() { ...@@ -390,7 +390,7 @@ public function testDatetimeRangeField() {
$this->drupalGet('entity_test/add'); $this->drupalGet('entity_test/add');
$value = '2012-12-31 00:00:00'; $value = '2012-12-31 00:00:00';
$start_date = new DrupalDateTime($value, 'UTC'); $start_date = new DrupalDateTime($value, 'UTC');
$start_date->setTimezone(timezone_open(drupal_get_user_timezone())); $start_date->setTimezone(timezone_open(date_default_timezone_get()));
$date_format = DateFormat::load('html_date')->getPattern(); $date_format = DateFormat::load('html_date')->getPattern();
$time_format = DateFormat::load('html_time')->getPattern(); $time_format = DateFormat::load('html_time')->getPattern();
...@@ -478,9 +478,9 @@ public function testAlldayRangeField() { ...@@ -478,9 +478,9 @@ public function testAlldayRangeField() {
// Build up dates in the proper timezone. // Build up dates in the proper timezone.
$value = '2012-12-31 00:00:00'; $value = '2012-12-31 00:00:00';
$start_date = new DrupalDateTime($value, timezone_open(drupal_get_user_timezone())); $start_date = new DrupalDateTime($value, timezone_open(date_default_timezone_get()));
$end_value = '2013-06-06 23:59:59'; $end_value = '2013-06-06 23:59:59';
$end_date = new DrupalDateTime($end_value, timezone_open(drupal_get_user_timezone())); $end_date = new DrupalDateTime($end_value, timezone_open(date_default_timezone_get()));
// Submit a valid date and ensure it is accepted. // Submit a valid date and ensure it is accepted.
$date_format = DateFormat::load('html_date')->getPattern(); $date_format = DateFormat::load('html_date')->getPattern();
...@@ -563,9 +563,9 @@ public function testAlldayRangeField() { ...@@ -563,9 +563,9 @@ public function testAlldayRangeField() {
$this->drupalGet('entity_test/add'); $this->drupalGet('entity_test/add');
$value = '2012-12-31 00:00:00'; $value = '2012-12-31 00:00:00';
$start_date = new DrupalDateTime($value, timezone_open(drupal_get_user_timezone())); $start_date = new DrupalDateTime($value, timezone_open(date_default_timezone_get()));
$end_value = '2012-12-31 23:59:59'; $end_value = '2012-12-31 23:59:59';
$end_date = new DrupalDateTime($end_value, timezone_open(drupal_get_user_timezone())); $end_date = new DrupalDateTime($end_value, timezone_open(date_default_timezone_get()));
$date_format = DateFormat::load('html_date')->getPattern(); $date_format = DateFormat::load('html_date')->getPattern();
$time_format = DateFormat::load('html_time')->getPattern(); $time_format = DateFormat::load('html_time')->getPattern();
......
<?php
namespace Drupal\system;
use Drupal\Core\Config\ConfigCrudEvent;
use Drupal\Core\Config\ConfigEvents;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Session\AccountEvents;
use Drupal\Core\Session\AccountInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\KernelEvents;
/**
* Event handler that resolves time zone based on site and user configuration.
*
* Sets the time zone using date_default_timezone_set().
*
* @see date_default_timezone_set()
*/
class TimeZoneResolver implements EventSubscriberInterface {
/**
* The config.
*
* @var \Drupal\Core\Config\ConfigFactoryInterface
*/
protected $configFactory;
/**
* The current user.
*
* @var \Drupal\Core\Session\AccountInterface
*/
private $currentUser;
/**
* TimeZoneResolver constructor.
*
* @param \Drupal\Core\Session\AccountInterface $current_user
* The current user.
* @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
* The config factory.
*/
public function __construct(AccountInterface $current_user, ConfigFactoryInterface $config_factory) {
$this->configFactory = $config_factory;
$this->currentUser = $current_user;
}
/**
* Sets the default time zone.
*/
public function setDefaultTimeZone() {
if ($time_zone = $this->getTimeZone()) {
date_default_timezone_set($time_zone);
}
}
/**
* Updates the default time zone when time zone config changes.
*
* @param \Drupal\Core\Config\ConfigCrudEvent $event
* The config crud event.
*/
public function onConfigSave(ConfigCrudEvent $event) {
$saved_config = $event->getConfig();
if ($saved_config->getName() === 'system.date' && ($event->isChanged('timezone.default') || $event->isChanged('timezone.user.configurable'))) {
$this->setDefaultTimeZone();
}
}
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents() {
$events[ConfigEvents::SAVE][] = ['onConfigSave', 0];
// The priority for this must run directly after the authentication
// subscriber.
$events[KernelEvents::REQUEST][] = ['setDefaultTimeZone', 299];
$events[AccountEvents::SET_USER][] = ['setDefaultTimeZone'];
return $events;
}
/**
* Gets the time zone based on site and user configuration.
*
* @return string|null
* The time zone, or NULL if nothing is set.
*/
protected function getTimeZone() {
$config = $this->configFactory->get('system.date');
if ($config->get('timezone.user.configurable') && $this->currentUser->isAuthenticated() && $this->currentUser->getTimezone()) {
return $this->currentUser->getTimeZone();
}
elseif ($default_timezone = $config->get('timezone.default')) {
return $default_timezone;
}
return NULL;
}
}
...@@ -43,3 +43,8 @@ services: ...@@ -43,3 +43,8 @@ services:
arguments: ['@theme_handler', '@cache_tags.invalidator'] arguments: ['@theme_handler', '@cache_tags.invalidator']
tags: tags:
- { name: event_subscriber } - { name: event_subscriber }
system.timezone_resolver:
class: Drupal\system\TimeZoneResolver
arguments: ['@current_user', '@config.factory']
tags:
- { name: event_subscriber }