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