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