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