From 5842c912a9632ec877f8417b7f9cd5e82018f39d Mon Sep 17 00:00:00 2001 From: rxu Date: Wed, 18 Mar 2020 23:11:42 +0700 Subject: [PATCH] [ticket/13426] Improve user timezone initialization PHPBB3-13426 --- phpBB/phpbb/user.php | 46 ++++++++++++++++++++++++++++++++------------ 1 file changed, 34 insertions(+), 12 deletions(-) diff --git a/phpBB/phpbb/user.php b/phpBB/phpbb/user.php index 096e6d42c1..e8ec5849fd 100644 --- a/phpBB/phpbb/user.php +++ b/phpBB/phpbb/user.php @@ -227,15 +227,7 @@ class user extends \phpbb\session $this->language->set_user_language($user_lang_name); - try - { - $this->timezone = new \DateTimeZone($user_timezone); - } - catch (\Exception $e) - { - // If the timezone the user has selected is invalid, we fall back to UTC. - $this->timezone = new \DateTimeZone('UTC'); - } + $this->create_timezone($user_timezone); $this->add_lang($lang_set); unset($lang_set); @@ -635,7 +627,7 @@ class user extends \phpbb\session if (!$format_date_override) { $time = new $this->datetime($this, '@' . (int) $gmepoch, $utc); - $time->setTimezone($this->timezone); + $time->setTimezone($this->create_timezone()); return $time->format($format, $forcedate); } @@ -645,6 +637,36 @@ class user extends \phpbb\session } } + /** + * Create a DateTimeZone object in the context of the current user + * + * @param string $user_timezone Time zone of the current user. + * @return DateTimeZone DateTimeZone object linked to the current users locale + */ + public function create_timezone($user_timezone = null) + { + if (!$this->timezone) + { + if (!$user_timezone) + { + global $config; + $user_timezone = ($this->data['user_id'] != ANONYMOUS) ? $this->data['user_timezone'] : $config['board_timezone']; + } + + try + { + $this->timezone = new \DateTimeZone($user_timezone); + } + catch (\Exception $e) + { + // If the timezone the user has selected is invalid, we fall back to UTC. + $this->timezone = new \DateTimeZone('UTC'); + } + } + + return $this->timezone; + } + /** * Create a \phpbb\datetime object in the context of the current user * @@ -655,7 +677,7 @@ class user extends \phpbb\session */ public function create_datetime($time = 'now', \DateTimeZone $timezone = null) { - $timezone = $timezone ?: $this->timezone; + $timezone = $timezone ?: $this->create_timezone(); return new $this->datetime($this, $time, $timezone); } @@ -669,7 +691,7 @@ class user extends \phpbb\session */ public function get_timestamp_from_format($format, $time, \DateTimeZone $timezone = null) { - $timezone = $timezone ?: $this->timezone; + $timezone = $timezone ?: $this->create_timezone(); $date = \DateTime::createFromFormat($format, $time, $timezone); return ($date !== false) ? $date->format('U') : false; }