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