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