]> git.mxchange.org Git - friendica.git/blob - src/Util/Temporal.php
Merge pull request #11852 from Quix0r/fixes/double-quotes-single
[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(local_user(), '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          *    <tt>%1$d %2$s ago</tt>, e.g. 22 hours ago, 1 minute ago
311          *
312          * @return string with relative date
313          */
314         public static function getRelativeDate(string $posted_date, string $format = null): string
315         {
316                 $localtime = $posted_date . ' UTC';
317
318                 $abs = strtotime($localtime);
319
320                 if (is_null($posted_date) || $posted_date <= DBA::NULL_DATETIME || $abs === false) {
321                         return DI::l10n()->t('never');
322                 }
323
324                 $isfuture = false;
325                 $etime = time() - $abs;
326
327                 if ($etime < 1 && $etime >= 0) {
328                         return DI::l10n()->t('less than a second ago');
329                 }
330
331                 if ($etime < 0){
332                         $etime = -$etime;
333                         $isfuture = true;
334                 }
335
336                 $a = [
337                         12 * 30 * 24 * 60 * 60 => [DI::l10n()->t('year'), DI::l10n()->t('years')],
338                         30 * 24 * 60 * 60 => [DI::l10n()->t('month'), DI::l10n()->t('months')],
339                         7 * 24 * 60 * 60 => [DI::l10n()->t('week'), DI::l10n()->t('weeks')],
340                         24 * 60 * 60 => [DI::l10n()->t('day'), DI::l10n()->t('days')],
341                         60 * 60 => [DI::l10n()->t('hour'), DI::l10n()->t('hours')],
342                         60 => [DI::l10n()->t('minute'), DI::l10n()->t('minutes')],
343                         1 => [DI::l10n()->t('second'), DI::l10n()->t('seconds')],
344                 ];
345
346                 foreach ($a as $secs => $str) {
347                         $d = $etime / $secs;
348                         if ($d >= 1) {
349                                 $r = round($d);
350                                 // translators - e.g. 22 hours ago, 1 minute ago
351                                 if (!$format) {
352                                         if($isfuture){
353                                                 $format = DI::l10n()->t('in %1$d %2$s');
354                                         }
355                                         else {
356                                                 $format = DI::l10n()->t('%1$d %2$s ago');
357                                         }
358                                 }
359
360                                 return sprintf($format, $r, (($r == 1) ? $str[0] : $str[1]));
361                         }
362                 }
363         }
364
365         /**
366          * Returns timezone correct age in years.
367          *
368          * Returns the age in years, given a date of birth and the timezone of the person
369          * whose date of birth is provided.
370          *
371          * @param string $dob      Date of Birth
372          * @param string $timezone Timezone of the person of interest
373          *
374          * @return int Age in years
375          * @throws \Exception
376          */
377         public static function getAgeByTimezone(string $dob, string $timezone): int
378         {
379                 if (!intval($dob)) {
380                         return 0;
381                 }
382
383                 $birthdate = new DateTime($dob . ' 00:00:00', new DateTimeZone($timezone));
384                 $currentDate = new DateTime('now', new DateTimeZone('UTC'));
385
386                 $interval = $birthdate->diff($currentDate);
387
388                 return (int) $interval->format('%y');
389         }
390
391         /**
392          * Get days of a month in a given year.
393          *
394          * Returns number of days in the month of the given year.
395          * $m = 1 is 'January' to match human usage.
396          *
397          * @param int $y Year
398          * @param int $m Month (1=January, 12=December)
399          *
400          * @return int Number of days in the given month
401          */
402         public static function getDaysInMonth(int $y, int $m): int
403         {
404                 return date('t', mktime(0, 0, 0, $m, 1, $y));
405         }
406
407         /**
408          * Returns the first day in month for a given month, year.
409          *
410          * Months start at 1.
411          *
412          * @param int $y Year
413          * @param int $m Month (1=January, 12=December)
414          *
415          * @return string day 0 = Sunday through 6 = Saturday
416          * @throws \Exception
417          */
418         private static function getFirstDayInMonth(int $y, int $m): string
419         {
420                 $d = sprintf('%04d-%02d-01 00:00', intval($y), intval($m));
421
422                 return DateTimeFormat::utc($d, 'w');
423         }
424
425         /**
426          * Output a calendar for the given month, year.
427          *
428          * If $links are provided (array), e.g. $links[12] => 'http://mylink' ,
429          * date 12 will be linked appropriately. Today's date is also noted by
430          * altering td class.
431          * Months count from 1.
432          *
433          * @param int    $y     Year
434          * @param int    $m     Month
435          * @param array  $links (default null)
436          * @param string $class
437          *
438          * @return string
439          *
440          * @throws \Exception
441          * @todo  Provide (prev, next) links, define class variations for different size calendars
442          */
443         public static function getCalendarTable(int $y = 0, int $m = 0, array $links = null, string $class = ''): string
444         {
445                 // month table - start at 1 to match human usage.
446                 $mtab = [' ',
447                         'January', 'February', 'March',
448                         'April', 'May', 'June',
449                         'July', 'August', 'September',
450                         'October', 'November', 'December'
451                 ];
452
453                 $thisyear = DateTimeFormat::localNow('Y');
454                 $thismonth = DateTimeFormat::localNow('m');
455                 if (!$y) {
456                         $y = $thisyear;
457                 }
458
459                 if (!$m) {
460                         $m = intval($thismonth);
461                 }
462
463                 $dn = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
464                 $f = self::getFirstDayInMonth($y, $m);
465                 $l = self::getDaysInMonth($y, $m);
466                 $d = 1;
467                 $dow = 0;
468                 $started = false;
469
470                 if (($y == $thisyear) && ($m == $thismonth)) {
471                         $tddate = intval(DateTimeFormat::localNow('j'));
472                 }
473
474                 $str_month = DI::l10n()->getDay($mtab[$m]);
475                 $o = '<table class="calendar' . $class . '">';
476                 $o .= "<caption>$str_month $y</caption><tr>";
477                 for ($a = 0; $a < 7; $a ++) {
478                         $o .= '<th>' . mb_substr(DI::l10n()->getDay($dn[$a]), 0, 3, 'UTF-8') . '</th>';
479                 }
480
481                 $o .= '</tr><tr>';
482
483                 while ($d <= $l) {
484                         if (($dow == $f) && (!$started)) {
485                                 $started = true;
486                         }
487
488                         $today = (((isset($tddate)) && ($tddate == $d)) ? "class=\"today\" " : '');
489                         $o .= "<td $today>";
490                         $day = str_replace(' ', '&nbsp;', sprintf('%2.2d', $d));
491                         if ($started) {
492                                 if (isset($links[$d])) {
493                                         $o .= "<a href=\"{$links[$d]}\">$day</a>";
494                                 } else {
495                                         $o .= $day;
496                                 }
497
498                                 $d ++;
499                         } else {
500                                 $o .= '&nbsp;';
501                         }
502
503                         $o .= '</td>';
504                         $dow ++;
505                         if (($dow == 7) && ($d <= $l)) {
506                                 $dow = 0;
507                                 $o .= '</tr><tr>';
508                         }
509                 }
510
511                 if ($dow) {
512                         for ($a = $dow; $a < 7; $a ++) {
513                                 $o .= '<td>&nbsp;</td>';
514                         }
515                 }
516
517                 $o .= '</tr></table>' . "\r\n";
518
519                 return $o;
520         }
521 }