]> git.immae.eu Git - github/shaarli/Shaarli.git/blob - application/TimeZone.php
Apply PHP Code Beautifier on source code for linter automatic fixes
[github/shaarli/Shaarli.git] / application / TimeZone.php
1 <?php
2
3 /**
4 * Generates a list of available timezone continents and cities.
5 *
6 * Two distinct array based on available timezones
7 * and the one selected in the settings:
8 * - (0) continents:
9 * + list of available continents
10 * + special key 'selected' containing the value of the selected timezone's continent
11 * - (1) cities:
12 * + list of available cities associated with their continent
13 * + special key 'selected' containing the value of the selected timezone's city (without the continent)
14 *
15 * Example:
16 * [
17 * [
18 * 'America',
19 * 'Europe',
20 * 'selected' => 'Europe',
21 * ],
22 * [
23 * ['continent' => 'America', 'city' => 'Toronto'],
24 * ['continent' => 'Europe', 'city' => 'Paris'],
25 * 'selected' => 'Paris',
26 * ],
27 * ];
28 *
29 * Notes:
30 * - 'UTC/UTC' is mapped to 'UTC' to form a valid option
31 * - a few timezone cities includes the country/state, such as Argentina/Buenos_Aires
32 * - these arrays are designed to build timezone selects in template files with any HTML structure
33 *
34 * @param array $installedTimeZones List of installed timezones as string
35 * @param string $preselectedTimezone preselected timezone (optional)
36 *
37 * @return array[] continents and cities
38 **/
39 function generateTimeZoneData($installedTimeZones, $preselectedTimezone = '')
40 {
41 if ($preselectedTimezone == 'UTC') {
42 $pcity = $pcontinent = 'UTC';
43 } else {
44 // Try to split the provided timezone
45 $spos = strpos($preselectedTimezone, '/');
46 $pcontinent = substr($preselectedTimezone, 0, $spos);
47 $pcity = substr($preselectedTimezone, $spos + 1);
48 }
49
50 $continents = [];
51 $cities = [];
52 foreach ($installedTimeZones as $tz) {
53 if ($tz == 'UTC') {
54 $tz = 'UTC/UTC';
55 }
56 $spos = strpos($tz, '/');
57
58 // Ignore invalid timezones
59 if ($spos === false) {
60 continue;
61 }
62
63 $continent = substr($tz, 0, $spos);
64 $city = substr($tz, $spos + 1);
65 $cities[] = ['continent' => $continent, 'city' => $city];
66 $continents[$continent] = true;
67 }
68
69 $continents = array_keys($continents);
70 $continents['selected'] = $pcontinent;
71 $cities['selected'] = $pcity;
72
73 return [$continents, $cities];
74 }
75
76 /**
77 * Tells if a continent/city pair form a valid timezone
78 *
79 * Note: 'UTC/UTC' is mapped to 'UTC'
80 *
81 * @param string $continent the timezone continent
82 * @param string $city the timezone city
83 *
84 * @return bool whether continent/city is a valid timezone
85 */
86 function isTimeZoneValid($continent, $city)
87 {
88 return in_array(
89 $continent . '/' . $city,
90 timezone_identifiers_list()
91 );
92 }