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