]> git.mxchange.org Git - friendica.git/blob - src/Util/Temporal.php
0cc759da140c2fd3556eba00a352d7b9cc2ad76a
[friendica.git] / src / Util / Temporal.php
1 <?php
2
3 /**
4  * @file src/Util/Temporal.php
5  */
6
7 namespace Friendica\Util;
8
9 use DateTime;
10 use DateTimeZone;
11 use Friendica\Core\Config;
12 use Friendica\Core\L10n;
13 use Friendica\Core\PConfig;
14
15 require_once 'boot.php';
16 require_once 'include/text.php';
17
18 /**
19  * @brief Temporal class
20  */
21 class Temporal
22 {
23         /**
24          * @brief Two-level sort for timezones.
25          *
26          * @param string $a
27          * @param string $b
28          * @return int
29          */
30         private static function timezoneCompareCallback($a, $b)
31         {
32                 if (strstr($a, '/') && strstr($b, '/')) {
33                         if (L10n::t($a) == L10n::t($b)) {
34                                 return 0;
35                         }
36                         return (L10n::t($a) < L10n::t($b)) ? -1 : 1;
37                 }
38
39                 if (strstr($a, '/')) {
40                         return -1;
41                 } elseif (strstr($b, '/')) {
42                         return 1;
43                 } elseif (L10n::t($a) == L10n::t($b)) {
44                         return 0;
45                 }
46
47                 return (L10n::t($a) < L10n::t($b)) ? -1 : 1;
48         }
49
50         /**
51          * @brief Emit a timezone selector grouped (primarily) by continent
52          *
53          * @param string $current Timezone
54          * @return string Parsed HTML output
55          */
56         public static function getTimezoneSelect($current = 'America/Los_Angeles')
57         {
58                 $timezone_identifiers = DateTimeZone::listIdentifiers();
59
60                 $o = '<select id="timezone_select" name="timezone">';
61
62                 usort($timezone_identifiers, [__CLASS__, 'timezoneCompareCallback']);
63                 $continent = '';
64                 foreach ($timezone_identifiers as $value) {
65                         $ex = explode("/", $value);
66                         if (count($ex) > 1) {
67                                 if ($ex[0] != $continent) {
68                                         if ($continent != '') {
69                                                 $o .= '</optgroup>';
70                                         }
71                                         $continent = $ex[0];
72                                         $o .= '<optgroup label="' . L10n::t($continent) . '">';
73                                 }
74                                 if (count($ex) > 2) {
75                                         $city = substr($value, strpos($value, '/') + 1);
76                                 } else {
77                                         $city = $ex[1];
78                                 }
79                         } else {
80                                 $city = $ex[0];
81                                 if ($continent != L10n::t('Miscellaneous')) {
82                                         $o .= '</optgroup>';
83                                         $continent = L10n::t('Miscellaneous');
84                                         $o .= '<optgroup label="' . L10n::t($continent) . '">';
85                                 }
86                         }
87                         $city = str_replace('_', ' ', L10n::t($city));
88                         $selected = (($value == $current) ? " selected=\"selected\" " : "");
89                         $o .= "<option value=\"$value\" $selected >$city</option>";
90                 }
91                 $o .= '</optgroup></select>';
92                 return $o;
93         }
94
95         /**
96          * @brief Generating a Timezone selector
97          *
98          * Return a select using 'field_select_raw' template, with timezones
99          * grouped (primarily) by continent
100          * arguments follow convention as other field_* template array:
101          * 'name', 'label', $value, 'help'
102          *
103          * @param string $name Name of the selector
104          * @param string $label Label for the selector
105          * @param string $current Timezone
106          * @param string $help Help text
107          *
108          * @return string Parsed HTML
109          */
110         public static function getTimezoneField($name = 'timezone', $label = '', $current = 'America/Los_Angeles', $help = '')
111         {
112                 $options = self::getTimezoneSelect($current);
113                 $options = str_replace('<select id="timezone_select" name="timezone">', '', $options);
114                 $options = str_replace('</select>', '', $options);
115
116                 $tpl = get_markup_template('field_select_raw.tpl');
117                 return replace_macros($tpl, [
118                         '$field' => [$name, $label, $current, $help, $options],
119                 ]);
120         }
121
122         /**
123          * @brief Wrapper for date selector, tailored for use in birthday fields.
124          *
125          * @param string $dob Date of Birth
126          * @return string Formatted HTML
127          */
128         public static function getDateofBirthField($dob)
129         {
130                 $a = get_app();
131
132                 list($year, $month, $day) = sscanf($dob, '%4d-%2d-%2d');
133
134                 if ($dob < '0000-01-01') {
135                         $value = '';
136                 } else {
137                         $value = DateTimeFormat::utc(($year > 1000) ? $dob : '1000-' . $month . '-' . $day, 'Y-m-d');
138                 }
139
140                 $age = (intval($value) ? self::getAgeByTimezone($value, $a->user["timezone"], $a->user["timezone"]) : "");
141
142                 $tpl = get_markup_template("field_input.tpl");
143                 $o = replace_macros($tpl,
144                         [
145                         '$field' => [
146                                 'dob',
147                                 L10n::t('Birthday:'),
148                                 $value,
149                                 intval($age) > 0 ? L10n::t('Age: ') . $age : "",
150                                 '',
151                                 'placeholder="' . L10n::t('YYYY-MM-DD or MM-DD') . '"'
152                         ]
153                 ]);
154
155                 return $o;
156         }
157
158         /**
159          * @brief Returns a date selector
160          *
161          * @param string $min     Unix timestamp of minimum date
162          * @param string $max     Unix timestap of maximum date
163          * @param string $default Unix timestamp of default date
164          * @param string $id      ID and name of datetimepicker (defaults to "datetimepicker")
165          *
166          * @return string Parsed HTML output.
167          */
168         public static function getDateField($min, $max, $default, $id = 'datepicker')
169         {
170                 return self::getDateTimeField($min, $max, $default, '', $id, true, false, '', '');
171         }
172
173         /**
174          * @brief Returns a time selector
175          *
176          * @param string $h  Already selected hour
177          * @param string $m  Already selected minute
178          * @param string $id ID and name of datetimepicker (defaults to "timepicker")
179          *
180          * @return string Parsed HTML output.
181          */
182         public static function getTimeField($h, $m, $id = 'timepicker')
183         {
184                 return self::getDateTimeField(new DateTime(), new DateTime(), new DateTime("$h:$m"), '', $id, false, true);
185         }
186
187         /**
188          * @brief Returns a datetime selector.
189          *
190          * @param DateTime $minDate     Minimum date
191          * @param DateTime $maxDate     Maximum date
192          * @param DateTime $defaultDate Default date
193          * @param string   $id          Id and name of datetimepicker (defaults to "datetimepicker")
194          * @param bool     $pickdate    true to show date picker (default)
195          * @param bool     $picktime    true to show time picker (default)
196          * @param string   $minfrom     set minimum date from picker with id $minfrom (none by default)
197          * @param string   $maxfrom     set maximum date from picker with id $maxfrom (none by default)
198          * @param bool     $required    default false
199          *
200          * @return string Parsed HTML output.
201          *
202          * @todo Once browser support is better this could probably be replaced with
203          * native HTML5 date picker.
204          */
205         public static function getDateTimeField(
206                 DateTime $minDate,
207                 DateTime $maxDate,
208                 DateTime $defaultDate,
209                 $label,
210                 $id       = 'datetimepicker',
211                 $pickdate = true,
212                 $picktime = true,
213                 $minfrom  = '',
214                 $maxfrom  = '',
215                 $required = false)
216         {
217                 // First day of the week (0 = Sunday)
218                 $firstDay = PConfig::get(local_user(), 'system', 'first_day_of_week', 0);
219
220                 $lang = substr(L10n::getCurrentLang(), 0, 2);
221
222                 // Check if the detected language is supported by the picker
223                 if (!in_array($lang,
224                                 ["ar", "ro", "id", "bg", "fa", "ru", "uk", "en", "el", "de", "nl", "tr", "fr", "es", "th", "pl", "pt", "ch", "se", "kr",
225                                 "it", "da", "no", "ja", "vi", "sl", "cs", "hu"])) {
226                         $lang = 'en';
227                 }
228
229                 $o = '';
230                 $dateformat = '';
231
232                 if ($pickdate) {
233                         $dateformat .= 'Y-m-d';
234                 }
235
236                 if ($pickdate && $picktime) {
237                         $dateformat .= ' ';
238                 }
239
240                 if ($picktime) {
241                         $dateformat .= 'H:i';
242                 }
243
244                 $input_text = $defaultDate ? date($dateformat, $defaultDate->getTimestamp()) : '';
245
246                 $readable_format = str_replace(['Y', 'm', 'd', 'H', 'i'], ['yyyy', 'mm', 'dd', 'HH', 'MM'], $dateformat);
247
248                 $tpl = get_markup_template('field_datetime.tpl');
249                 $o .= replace_macros($tpl, [
250                         '$field' => [
251                                 $id,
252                                 $label,
253                                 $input_text,
254                                 '',
255                                 $required ? '*' : '',
256                                 'placeholder="' . $readable_format . '"'
257                         ],
258                         '$datetimepicker' => [
259                                 'minDate' => $minDate,
260                                 'maxDate' => $maxDate,
261                                 'defaultDate' => $defaultDate,
262                                 'dateformat' => $dateformat,
263                                 'firstDay' => $firstDay,
264                                 'lang' => $lang,
265                                 'minfrom' => $minfrom,
266                                 'maxfrom' => $maxfrom,
267                         ]
268                 ]);
269
270                 return $o;
271         }
272
273         /**
274          * @brief Returns a relative date string.
275          *
276          * Implements "3 seconds ago" etc.
277          * Based on $posted_date, (UTC).
278          * Results relative to current timezone.
279          * Limited to range of timestamps.
280          *
281          * @param string $posted_date MySQL-formatted date string (YYYY-MM-DD HH:MM:SS)
282          * @param string $format (optional) Parsed with sprintf()
283          *    <tt>%1$d %2$s ago</tt>, e.g. 22 hours ago, 1 minute ago
284          *
285          * @return string with relative date
286          */
287         public static function getRelativeDate($posted_date, $format = null)
288         {
289                 $localtime = $posted_date . ' UTC';
290
291                 $abs = strtotime($localtime);
292
293                 if (is_null($posted_date) || $posted_date <= NULL_DATE || $abs === false) {
294                         return L10n::t('never');
295                 }
296
297                 $isfuture = false;
298                 $etime = time() - $abs;
299
300                 if ($etime < 1 && $etime >= 0) {
301                         return L10n::t('less than a second ago');
302                 }
303
304                 if ($etime < 0){
305                         $etime = -$etime;
306                         $isfuture = true;
307                 }
308
309                 $a = [12 * 30 * 24 * 60 * 60 => [L10n::t('year'), L10n::t('years')],
310                         30 * 24 * 60 * 60 => [L10n::t('month'), L10n::t('months')],
311                         7 * 24 * 60 * 60 => [L10n::t('week'), L10n::t('weeks')],
312                         24 * 60 * 60 => [L10n::t('day'), L10n::t('days')],
313                         60 * 60 => [L10n::t('hour'), L10n::t('hours')],
314                         60 => [L10n::t('minute'), L10n::t('minutes')],
315                         1 => [L10n::t('second'), L10n::t('seconds')]
316                 ];
317
318                 foreach ($a as $secs => $str) {
319                         $d = $etime / $secs;
320                         if ($d >= 1) {
321                                 $r = round($d);
322                                 // translators - e.g. 22 hours ago, 1 minute ago
323                                 if (!$format) {
324                                         if($isfuture){
325                                                 $format = L10n::t('in %1$d %2$s');
326                                         }
327                                         else {
328                                                 $format = L10n::t('%1$d %2$s ago');
329                                         }
330                                 }
331
332                                 return sprintf($format, $r, (($r == 1) ? $str[0] : $str[1]));
333                         }
334                 }
335         }
336
337         /**
338          * @brief Returns timezone correct age in years.
339          *
340          * Returns the age in years, given a date of birth, the timezone of the person
341          * whose date of birth is provided, and the timezone of the person viewing the
342          * result.
343          *
344          * Why? Bear with me. Let's say I live in Mittagong, Australia, and my birthday
345          * is on New Year's. You live in San Bruno, California.
346          * When exactly are you going to see my age increase?
347          *
348          * A: 5:00 AM Dec 31 San Bruno time. That's precisely when I start celebrating
349          * and become a year older. If you wish me happy birthday on January 1
350          * (San Bruno time), you'll be a day late.
351          *
352          * @param string $dob Date of Birth
353          * @param string $owner_tz (optional) Timezone of the person of interest
354          * @param string $viewer_tz (optional) Timezone of the person viewing
355          *
356          * @return int Age in years
357          */
358         public static function getAgeByTimezone($dob, $owner_tz = '', $viewer_tz = '')
359         {
360                 if (!intval($dob)) {
361                         return 0;
362                 }
363                 if (!$owner_tz) {
364                         $owner_tz = date_default_timezone_get();
365                 }
366                 if (!$viewer_tz) {
367                         $viewer_tz = date_default_timezone_get();
368                 }
369
370                 $birthdate = DateTimeFormat::convert($dob . ' 00:00:00+00:00', $owner_tz, 'UTC', 'Y-m-d');
371                 list($year, $month, $day) = explode("-", $birthdate);
372                 $year_diff  = DateTimeFormat::timezoneNow($viewer_tz, 'Y') - $year;
373                 $curr_month = DateTimeFormat::timezoneNow($viewer_tz, 'm');
374                 $curr_day   = DateTimeFormat::timezoneNow($viewer_tz, 'd');
375
376                 if (($curr_month < $month) || (($curr_month == $month) && ($curr_day < $day))) {
377                         $year_diff--;
378                 }
379
380                 return $year_diff;
381         }
382
383         /**
384          * @brief Get days of a month in a given year.
385          *
386          * Returns number of days in the month of the given year.
387          * $m = 1 is 'January' to match human usage.
388          *
389          * @param int $y Year
390          * @param int $m Month (1=January, 12=December)
391          *
392          * @return int Number of days in the given month
393          */
394         public static function getDaysInMonth($y, $m)
395         {
396                 return date('t', mktime(0, 0, 0, $m, 1, $y));
397         }
398
399         /**
400          * @brief Returns the first day in month for a given month, year.
401          *
402          * Months start at 1.
403          *
404          * @param int $y Year
405          * @param int $m Month (1=January, 12=December)
406          *
407          * @return string day 0 = Sunday through 6 = Saturday
408          */
409         private static function getFirstDayInMonth($y, $m)
410         {
411                 $d = sprintf('%04d-%02d-01 00:00', intval($y), intval($m));
412
413                 return DateTimeFormat::utc($d, 'w');
414         }
415
416         /**
417          * @brief Output a calendar for the given month, year.
418          *
419          * If $links are provided (array), e.g. $links[12] => 'http://mylink' ,
420          * date 12 will be linked appropriately. Today's date is also noted by
421          * altering td class.
422          * Months count from 1.
423          *
424          * @param int    $y Year
425          * @param int    $m Month
426          * @param array  $links (default null)
427          * @param string $class
428          *
429          * @return string
430          *
431          * @todo Provide (prev, next) links, define class variations for different size calendars
432          */
433         public static function getCalendarTable($y = 0, $m = 0, $links = null, $class = '')
434         {
435                 // month table - start at 1 to match human usage.
436                 $mtab = [' ',
437                         'January', 'February', 'March',
438                         'April', 'May', 'June',
439                         'July', 'August', 'September',
440                         'October', 'November', 'December'
441                 ];
442
443                 $thisyear = DateTimeFormat::localNow('Y');
444                 $thismonth = DateTimeFormat::localNow('m');
445                 if (!$y) {
446                         $y = $thisyear;
447                 }
448
449                 if (!$m) {
450                         $m = intval($thismonth);
451                 }
452
453                 $dn = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
454                 $f = self::getFirstDayInMonth($y, $m);
455                 $l = self::getDaysInMonth($y, $m);
456                 $d = 1;
457                 $dow = 0;
458                 $started = false;
459
460                 if (($y == $thisyear) && ($m == $thismonth)) {
461                         $tddate = intval(DateTimeFormat::localNow('j'));
462                 }
463
464                 $str_month = day_translate($mtab[$m]);
465                 $o = '<table class="calendar' . $class . '">';
466                 $o .= "<caption>$str_month $y</caption><tr>";
467                 for ($a = 0; $a < 7; $a ++) {
468                         $o .= '<th>' . mb_substr(day_translate($dn[$a]), 0, 3, 'UTF-8') . '</th>';
469                 }
470
471                 $o .= '</tr><tr>';
472
473                 while ($d <= $l) {
474                         if (($dow == $f) && (!$started)) {
475                                 $started = true;
476                         }
477
478                         $today = (((isset($tddate)) && ($tddate == $d)) ? "class=\"today\" " : '');
479                         $o .= "<td $today>";
480                         $day = str_replace(' ', '&nbsp;', sprintf('%2.2d', $d));
481                         if ($started) {
482                                 if (x($links, $d) !== false) {
483                                         $o .= "<a href=\"{$links[$d]}\">$day</a>";
484                                 } else {
485                                         $o .= $day;
486                                 }
487
488                                 $d ++;
489                         } else {
490                                 $o .= '&nbsp;';
491                         }
492
493                         $o .= '</td>';
494                         $dow ++;
495                         if (($dow == 7) && ($d <= $l)) {
496                                 $dow = 0;
497                                 $o .= '</tr><tr>';
498                         }
499                 }
500
501                 if ($dow) {
502                         for ($a = $dow; $a < 7; $a ++) {
503                                 $o .= '<td>&nbsp;</td>';
504                         }
505                 }
506
507                 $o .= '</tr></table>' . "\r\n";
508
509                 return $o;
510         }
511 }