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