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