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