Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
20.97% covered (danger)
20.97%
13 / 62
60.00% covered (warning)
60.00%
6 / 10
CRAP
0.00% covered (danger)
0.00%
0 / 1
UserTimeCorrection
20.97% covered (danger)
20.97%
13 / 62
60.00% covered (warning)
60.00%
6 / 10
474.28
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 getCorrectionType
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getTimeOffset
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getTimeOffsetInterval
80.00% covered (warning)
80.00%
4 / 5
0.00% covered (danger)
0.00%
0 / 1
2.03
 getTimeZone
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 isValid
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 parse
0.00% covered (danger)
0.00%
0 / 40
0.00% covered (danger)
0.00%
0 / 1
210
 formatTimezoneOffset
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
2
 toString
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
42
 __toString
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2
3/**
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License along
15 * with this program; if not, write to the Free Software Foundation, Inc.,
16 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17 * http://www.gnu.org/copyleft/gpl.html
18 *
19 * @file
20 * @author Derk-Jan Hartman <hartman.wiki@gmail.com>
21 */
22
23namespace MediaWiki\User;
24
25use DateInterval;
26use DateTime;
27use DateTimeZone;
28use Exception;
29use MediaWiki\Utils\MWTimestamp;
30use Wikimedia\RequestTimeout\TimeoutException;
31
32/**
33 * Utility class to parse the TimeCorrection string value.
34 *
35 * These values are used to specify the time offset for a user and are stored in
36 * the database as a user preference and returned by the preferences APIs
37 *
38 * The class will correct invalid input and adjusts timezone offsets to applicable dates,
39 * taking into account DST etc.
40 *
41 * @since 1.37
42 */
43class UserTimeCorrection {
44
45    /**
46     * @var string (default) Time correction based on the MediaWiki's system offset from UTC.
47     * The System offset can be configured with wgLocalTimezone and/or wgLocalTZoffset
48     */
49    public const SYSTEM = 'System';
50
51    /** @var string Time correction based on a user defined offset from UTC */
52    public const OFFSET = 'Offset';
53
54    /** @var string Time correction based on a user defined timezone */
55    public const ZONEINFO = 'ZoneInfo';
56
57    /** @var DateTime */
58    private $date;
59
60    /** @var bool */
61    private $valid;
62
63    /** @var string */
64    private $correctionType;
65
66    /** @var int Offset in minutes */
67    private $offset;
68
69    /** @var DateTimeZone|null */
70    private $timeZone;
71
72    /**
73     * @param string $timeCorrection Original time correction string
74     * @param DateTime|null $relativeToDate The date used to calculate the time zone offset of.
75     *            This defaults to the current date and time.
76     * @param int $systemOffset Offset for self::SYSTEM in minutes
77     */
78    public function __construct(
79        string $timeCorrection,
80        DateTime $relativeToDate = null,
81        int $systemOffset = 0
82    ) {
83        $this->date = $relativeToDate ?? new DateTime( '@' . MWTimestamp::time() );
84        $this->valid = false;
85        $this->parse( $timeCorrection, $systemOffset );
86    }
87
88    /**
89     * Get time offset for a user
90     *
91     * @return string Offset that was applied to the user
92     */
93    public function getCorrectionType(): string {
94        return $this->correctionType;
95    }
96
97    /**
98     * Get corresponding time offset for this correction
99     * Note: When correcting dates/times, apply only the offset OR the time zone, not both.
100     * @return int Offset in minutes
101     */
102    public function getTimeOffset(): int {
103        return $this->offset;
104    }
105
106    /**
107     * Get corresponding time offset for this correction
108     * Note: When correcting dates/times, apply only the offset OR the time zone, not both.
109     * @return DateInterval Offset in minutes as a DateInterval
110     */
111    public function getTimeOffsetInterval(): DateInterval {
112        $offset = abs( $this->offset );
113        $interval = new DateInterval( "PT{$offset}M" );
114        if ( $this->offset < 1 ) {
115            $interval->invert = 1;
116        }
117        return $interval;
118    }
119
120    /**
121     * The time zone if known
122     * Note: When correcting dates/times, apply only the offset OR the time zone, not both.
123     * @return DateTimeZone|null
124     */
125    public function getTimeZone(): ?DateTimeZone {
126        return $this->timeZone;
127    }
128
129    /**
130     * Was the original correction specification valid
131     * @return bool
132     */
133    public function isValid(): bool {
134        return $this->valid;
135    }
136
137    /**
138     * Parse the timecorrection string as stored in the database for a user
139     * or as entered into the Preferences form field
140     *
141     * There can be two forms of these strings:
142     * 1. A pipe separated tuple of a maximum of 3 fields
143     *    - Field 1 is the type of offset definition
144     *    - Field 2 is the offset in minutes from UTC (ignored for System type)
145     *      FIXME Since it's ignored, remove the offset from System everywhere.
146     *    - Field 3 is a timezone identifier from the tz database (only required for ZoneInfo type)
147     *    - The offset for a ZoneInfo type is unreliable because of DST.
148     *      After retrieving it from the database, it should be recalculated based on the TZ identifier.
149     *    Examples:
150     *    - System
151     *    - System|60
152     *    - Offset|60
153     *    - ZoneInfo|60|Europe/Amsterdam
154     *
155     * 2. The following form provides an offset in hours and minutes
156     *    This currently should only be used by the preferences input field,
157     *    but historically they were present in the database.
158     *    TODO: write a maintenance script to migrate these old db values
159     *    Examples:
160     *    - 16:00
161     *    - 10
162     *
163     * @param string $timeCorrection
164     * @param int $systemOffset
165     */
166    private function parse( string $timeCorrection, int $systemOffset ) {
167        $data = explode( '|', $timeCorrection, 3 );
168
169        // First handle the case of an actual timezone being specified.
170        if ( $data[0] === self::ZONEINFO ) {
171            try {
172                $this->correctionType = self::ZONEINFO;
173                $this->timeZone = new DateTimeZone( $data[2] );
174                $this->offset = (int)floor( $this->timeZone->getOffset( $this->date ) / 60 );
175                $this->valid = true;
176                return;
177            } catch ( TimeoutException $e ) {
178                throw $e;
179            } catch ( Exception $e ) {
180                // Not a valid/known timezone.
181                // Fall back to any specified offset
182            }
183        }
184
185        // If $timeCorrection is in fact a pipe-separated value, check the
186        // first value.
187        switch ( $data[0] ) {
188            case self::OFFSET:
189            case self::ZONEINFO:
190                $this->correctionType = self::OFFSET;
191                // First value is Offset, so use the specified offset
192                $this->offset = (int)( $data[1] ?? 0 );
193                // If this is ZoneInfo, then we didn't recognize the TimeZone
194                $this->valid = isset( $data[1] ) && $data[0] === self::OFFSET;
195                break;
196            case self::SYSTEM:
197                $this->correctionType = self::SYSTEM;
198                $this->offset = $systemOffset;
199                $this->valid = true;
200                break;
201            default:
202                // $timeCorrection actually isn't a pipe separated value, but instead
203                // a colon separated value. This is only used by the HTMLTimezoneField userinput
204                // but can also still be present in the Db. (but shouldn't be)
205                $this->correctionType = self::OFFSET;
206                $data = explode( ':', $timeCorrection, 2 );
207                if ( count( $data ) >= 2 ) {
208                    // Combination hours and minutes.
209                    $this->offset = abs( (int)$data[0] ) * 60 + (int)$data[1];
210                    if ( (int)$data[0] < 0 ) {
211                        $this->offset *= -1;
212                    }
213                    $this->valid = true;
214                } elseif ( preg_match( '/^[+-]?\d+$/', $data[0] ) ) {
215                    // Just hours.
216                    $this->offset = (int)$data[0] * 60;
217                    $this->valid = true;
218                } else {
219                    // We really don't know this. Fallback to System
220                    $this->correctionType = self::SYSTEM;
221                    $this->offset = $systemOffset;
222                    return;
223                }
224                break;
225        }
226
227        // Max is +14:00 and min is -12:00, see:
228        // https://en.wikipedia.org/wiki/Timezone
229        if ( $this->offset < -12 * 60 || $this->offset > 14 * 60 ) {
230            $this->valid = false;
231        }
232        // 14:00
233        $this->offset = min( $this->offset, 14 * 60 );
234        // -12:00
235        $this->offset = max( $this->offset, -12 * 60 );
236    }
237
238    /**
239     * Converts a timezone offset in minutes (e.g., "120") to an hh:mm string like "+02:00".
240     * @param int $offset
241     * @return string
242     */
243    public static function formatTimezoneOffset( int $offset ): string {
244        $hours = $offset > 0 ? floor( $offset / 60 ) : ceil( $offset / 60 );
245        return sprintf( '%+03d:%02d', $hours, abs( $offset ) % 60 );
246    }
247
248    /**
249     * Note: The string value of this object might not be equal to the original value
250     * @return string a timecorrection string representing this value
251     */
252    public function toString(): string {
253        switch ( $this->correctionType ) {
254            case self::ZONEINFO:
255                if ( $this->timeZone ) {
256                    return "ZoneInfo|{$this->offset}|{$this->timeZone->getName()}";
257                }
258                // If not, fallback:
259            case self::SYSTEM:
260            case self::OFFSET:
261            default:
262                return "{$this->correctionType}|{$this->offset}";
263        }
264    }
265
266    public function __toString() {
267        return $this->toString();
268    }
269}