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