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