Introduce preference filters
[lhc/web/wiklou.git] / includes / preferences / TimezoneFilter.php
1 <?php
2 /**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
17 *
18 * @file
19 */
20
21 namespace MediaWiki\Preferences;
22
23 use DateTimeZone;
24 use Exception;
25
26 class TimezoneFilter implements Filter {
27
28 /**
29 * @inheritDoc
30 */
31 public function filterForForm( $value ) {
32 return $value;
33 }
34
35 /**
36 * @inheritDoc
37 */
38 public function filterFromForm( $tz ) {
39 $data = explode( '|', $tz, 3 );
40 switch ( $data[0] ) {
41 case 'ZoneInfo':
42 $valid = false;
43
44 if ( count( $data ) === 3 ) {
45 // Make sure this timezone exists
46 try {
47 new DateTimeZone( $data[2] );
48 // If the constructor didn't throw, we know it's valid
49 $valid = true;
50 } catch ( Exception $e ) {
51 // Not a valid timezone
52 }
53 }
54
55 if ( !$valid ) {
56 // If the supplied timezone doesn't exist, fall back to the encoded offset
57 return 'Offset|' . intval( $tz[1] );
58 }
59 return $tz;
60 case 'System':
61 return $tz;
62 default:
63 $data = explode( ':', $tz, 2 );
64 if ( count( $data ) == 2 ) {
65 $data[0] = intval( $data[0] );
66 $data[1] = intval( $data[1] );
67 $minDiff = abs( $data[0] ) * 60 + $data[1];
68 if ( $data[0] < 0 ) {
69 $minDiff = - $minDiff;
70 }
71 } else {
72 $minDiff = intval( $data[0] ) * 60;
73 }
74
75 # Max is +14:00 and min is -12:00, see:
76 # https://en.wikipedia.org/wiki/Timezone
77 # 14:00
78 $minDiff = min( $minDiff, 840 );
79 # -12:00
80 $minDiff = max( $minDiff, -720 );
81 return 'Offset|' . $minDiff;
82 }
83 }
84 }