123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112 |
- <?php
- namespace OC;
- use OCP\IConfig;
- use OCP\IDateTimeZone;
- use OCP\ISession;
- use Psr\Log\LoggerInterface;
- class DateTimeZone implements IDateTimeZone {
-
- protected $config;
-
- protected $session;
-
- public function __construct(IConfig $config, ISession $session) {
- $this->config = $config;
- $this->session = $session;
- }
-
- public function getTimeZone($timestamp = false) {
- $timeZone = $this->config->getUserValue($this->session->get('user_id'), 'core', 'timezone', null);
- if ($timeZone === null) {
- if ($this->session->exists('timezone')) {
- return $this->guessTimeZoneFromOffset($this->session->get('timezone'), $timestamp);
- }
- $timeZone = $this->getDefaultTimeZone();
- }
- try {
- return new \DateTimeZone($timeZone);
- } catch (\Exception $e) {
- \OC::$server->get(LoggerInterface::class)->debug('Failed to created DateTimeZone "' . $timeZone . '"', ['app' => 'datetimezone']);
- return new \DateTimeZone($this->getDefaultTimeZone());
- }
- }
-
- protected function guessTimeZoneFromOffset($offset, $timestamp) {
- try {
-
-
-
- if ($offset > 0) {
- $timeZone = 'Etc/GMT-' . $offset;
- } else {
- $timeZone = 'Etc/GMT+' . abs($offset);
- }
- return new \DateTimeZone($timeZone);
- } catch (\Exception $e) {
-
-
- foreach (\DateTimeZone::listIdentifiers() as $timeZone) {
- $dtz = new \DateTimeZone($timeZone);
- $dateTime = new \DateTime();
- if ($timestamp !== false) {
- $dateTime->setTimestamp($timestamp);
- }
- $dtOffset = $dtz->getOffset($dateTime);
- if ($dtOffset == 3600 * $offset) {
- return $dtz;
- }
- }
-
- \OC::$server->get(LoggerInterface::class)->debug('Failed to find DateTimeZone for offset "' . $offset . '"', ['app' => 'datetimezone']);
- return new \DateTimeZone($this->getDefaultTimeZone());
- }
- }
-
- protected function getDefaultTimeZone() {
- $serverTimeZone = date_default_timezone_get();
- return $serverTimeZone ?: 'UTC';
- }
- }
|