3 * @copyright Copyright (C) 2010-2023, the Friendica project
5 * @license GNU AGPL version 3 or any later version
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.
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.
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/>.
22 namespace Friendica\Util;
26 use Friendica\Core\Renderer;
27 use Friendica\Database\DBA;
29 use Friendica\Util\Clock\SystemClock;
30 use Psr\Clock\ClockInterface;
38 * Two-level sort for timezones.
45 private static function timezoneCompareCallback(string $a, string $b): int
47 if (strstr($a, '/') && strstr($b, '/')) {
48 if (DI::l10n()->t($a) == DI::l10n()->t($b)) {
51 return (DI::l10n()->t($a) < DI::l10n()->t($b)) ? -1 : 1;
54 if (strstr($a, '/')) {
56 } elseif (strstr($b, '/')) {
58 } elseif (DI::l10n()->t($a) == DI::l10n()->t($b)) {
62 return (DI::l10n()->t($a) < DI::l10n()->t($b)) ? -1 : 1;
66 * Emit a timezone selector grouped (primarily) by continent
68 * @param string $current Timezone
70 * @return string Parsed HTML output
72 public static function getTimezoneSelect(string $current = 'America/Los_Angeles'): string
74 $timezone_identifiers = DateTimeZone::listIdentifiers();
76 $o = '<select id="timezone_select" name="timezone">';
78 usort($timezone_identifiers, [__CLASS__, 'timezoneCompareCallback']);
80 foreach ($timezone_identifiers as $value) {
81 $ex = explode("/", $value);
83 if ($ex[0] != $continent) {
84 if ($continent != '') {
88 $o .= '<optgroup label="' . DI::l10n()->t($continent) . '">';
91 $city = substr($value, strpos($value, '/') + 1);
97 if ($continent != DI::l10n()->t('Miscellaneous')) {
99 $continent = DI::l10n()->t('Miscellaneous');
100 $o .= '<optgroup label="' . DI::l10n()->t($continent) . '">';
103 $city = str_replace('_', ' ', DI::l10n()->t($city));
104 $selected = (($value == $current) ? " selected=\"selected\" " : "");
105 $o .= "<option value=\"$value\" $selected >$city</option>";
107 $o .= '</optgroup></select>';
112 * Generating a Timezone selector
114 * Return a select using 'field_select_raw' template, with timezones
115 * grouped (primarily) by continent
116 * arguments follow convention as other field_* template array:
117 * 'name', 'label', $value, 'help'
119 * @param string $name Name of the selector
120 * @param string $label Label for the selector
121 * @param string $current Timezone
122 * @param string $help Help text
124 * @return string Parsed HTML
125 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
127 public static function getTimezoneField(string $name = 'timezone', string $label = '', string $current = 'America/Los_Angeles', string $help = ''): string
129 $options = self::getTimezoneSelect($current);
130 $options = str_replace('<select id="timezone_select" name="timezone">', '', $options);
131 $options = str_replace('</select>', '', $options);
133 $tpl = Renderer::getMarkupTemplate('field_select_raw.tpl');
134 return Renderer::replaceMacros($tpl, [
135 '$field' => [$name, $label, $current, $help, $options],
140 * Wrapper for date selector, tailored for use in birthday fields.
142 * @param string $dob Date of Birth
143 * @param string $timezone
145 * @return string Formatted HTML
148 public static function getDateofBirthField(string $dob, string $timezone = 'UTC'): string
150 list($year, $month, $day) = sscanf($dob, '%4d-%2d-%2d');
152 if ($dob < '0000-01-01') {
155 } elseif ($dob < '0001-00-00') {
156 $value = substr($dob, 5);
159 $value = DateTimeFormat::utc($dob, 'Y-m-d');
160 $age = self::getAgeByTimezone($value, $timezone);
163 $tpl = Renderer::getMarkupTemplate("field_input.tpl");
164 $o = Renderer::replaceMacros($tpl,
168 DI::l10n()->t('Birthday:'),
170 intval($age) > 0 ? DI::l10n()->t('Age: ') . DI::l10n()->tt('%d year old', '%d years old', $age) : '',
172 'placeholder="' . DI::l10n()->t('YYYY-MM-DD or MM-DD') . '"'
180 * Returns a date selector
182 * @param DateTime $min Minimum date
183 * @param DateTime $max Maximum date
184 * @param DateTime $default Default date
185 * @param string $id ID and name of datetimepicker (defaults to "datetimepicker")
187 * @return string Parsed HTML output.
188 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
190 public static function getDateField(DateTime $min, DateTime $max, DateTime $default, string $id = 'datepicker'): string
192 return self::getDateTimeField($min, $max, $default, '', $id, true, false, '', '');
196 * Returns a time selector
198 * @param string $h Already selected hour
199 * @param string $m Already selected minute
200 * @param string $id ID and name of datetimepicker (defaults to "timepicker")
202 * @return string Parsed HTML output.
205 public static function getTimeField(string $h, string $m, string $id = 'timepicker'): string
207 return self::getDateTimeField(new DateTime(), new DateTime(), new DateTime("$h:$m"), '', $id, false, true);
211 * Returns a datetime selector.
213 * @param DateTime $minDate Minimum date
214 * @param DateTime $maxDate Maximum date
215 * @param DateTime $defaultDate Default date
217 * @param string $id Id and name of datetimepicker (defaults to "datetimepicker")
218 * @param bool $pickdate true to show date picker (default)
219 * @param bool $picktime true to show time picker (default)
220 * @param string $minfrom set minimum date from picker with id $minfrom (none by default)
221 * @param string $maxfrom set maximum date from picker with id $maxfrom (none by default)
222 * @param bool $required default false
224 * @return string Parsed HTML output.
226 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
227 * @todo Once browser support is better this could probably be replaced with
228 * native HTML5 date picker.
230 public static function getDateTimeField(
233 DateTime $defaultDate = null,
235 string $id = 'datetimepicker',
236 bool $pickdate = true,
237 bool $picktime = true,
238 string $minfrom = '',
239 string $maxfrom = '',
240 bool $required = false): string
242 // First day of the week (0 = Sunday)
243 $firstDay = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'calendar', 'first_day_of_week', 0);
245 $lang = substr(DI::l10n()->getCurrentLang(), 0, 2);
247 // Check if the detected language is supported by the picker
249 ['ar', 'ro', 'id', 'bg', 'fa', 'ru', 'uk', 'en', 'el', 'de', 'nl', 'tr', 'fr', 'es', 'th', 'pl', 'pt', 'ch', 'se', 'kr',
250 'it', 'da', 'no', 'ja', 'vi', 'sl', 'cs', 'hu'])) {
258 $dateformat .= 'Y-m-d';
261 if ($pickdate && $picktime) {
266 $dateformat .= 'H:i';
269 $input_text = $defaultDate ? date($dateformat, $defaultDate->getTimestamp()) : '';
271 $readable_format = str_replace(['Y', 'm', 'd', 'H', 'i'], ['yyyy', 'mm', 'dd', 'HH', 'MM'], $dateformat);
273 $tpl = Renderer::getMarkupTemplate('field_datetime.tpl');
274 $o .= Renderer::replaceMacros($tpl, [
280 'Time zone: <strong>%s</strong> <a href="%s">Change in Settings</a>',
281 str_replace('_', ' ', DI::app()->getTimeZone()) . ' (GMT ' . DateTimeFormat::localNow('P') . ')',
282 DI::baseUrl() . '/settings'
284 $required ? '*' : '',
285 'placeholder="' . $readable_format . '"'
287 '$datetimepicker' => [
288 'minDate' => $minDate,
289 'maxDate' => $maxDate,
290 'defaultDate' => $defaultDate,
291 'dateformat' => $dateformat,
292 'firstDay' => $firstDay,
294 'minfrom' => $minfrom,
295 'maxfrom' => $maxfrom,
303 * Returns a relative date string.
305 * Implements "3 seconds ago" etc.
306 * Based on $posted_date, (UTC).
307 * Results relative to current timezone.
308 * Limited to range of timestamps.
310 * @param string|null $posted_date MySQL-formatted date string (YYYY-MM-DD HH:MM:SS)
311 * @param bool $compare_time Compare date (false) or date and time (true). "true" is default.
312 * @param ClockInterface|null $clock
313 * <tt>%1$d %2$s ago</tt>, e.g. 22 hours ago, 1 minute ago
315 * @return string with relative date
317 public static function getRelativeDate(string $posted_date = null, bool $compare_time = true, ClockInterface $clock = null): string
319 if (empty($posted_date) || $posted_date <= DBA::NULL_DATETIME) {
320 return DI::l10n()->t('never');
323 $clock = $clock ?? new SystemClock();
325 $localtime = $posted_date . ' UTC';
326 $abs = strtotime($localtime);
328 if ($abs === false) {
329 return DI::l10n()->t('never');
332 $now = $clock->now()->getTimestamp();
334 if (!$compare_time) {
335 $now = mktime(0, 0, 0, date('m', $now), date('d', $now), date('Y', $now));
336 $abs = mktime(0, 0, 0, date('m', $abs), date('d', $abs), date('Y', $abs));
340 $etime = $now - $abs;
342 if ($etime >= 0 && $etime < 1) {
343 return $compare_time ? DI::l10n()->t('less than a second ago') : DI::l10n()->t('today');
352 12 * 30 * 24 * 60 * 60 => [DI::l10n()->t('year'), DI::l10n()->t('years')],
353 30 * 24 * 60 * 60 => [DI::l10n()->t('month'), DI::l10n()->t('months')],
354 7 * 24 * 60 * 60 => [DI::l10n()->t('week'), DI::l10n()->t('weeks')],
355 24 * 60 * 60 => [DI::l10n()->t('day'), DI::l10n()->t('days')],
356 60 * 60 => [DI::l10n()->t('hour'), DI::l10n()->t('hours')],
357 60 => [DI::l10n()->t('minute'), DI::l10n()->t('minutes')],
358 1 => [DI::l10n()->t('second'), DI::l10n()->t('seconds')],
361 foreach ($a as $secs => $str) {
365 // translators - e.g. 22 hours ago, 1 minute ago
367 $format = DI::l10n()->t('in %1$d %2$s');
370 $format = DI::l10n()->t('%1$d %2$s ago');
373 return sprintf($format, $r, (($r == 1) ? $str[0] : $str[1]));
379 * Returns timezone correct age in years.
381 * Returns the age in years, given a date of birth and the timezone of the person
382 * whose date of birth is provided.
384 * @param string $dob Date of Birth
385 * @param string $timezone Timezone of the person of interest
387 * @return int Age in years
390 public static function getAgeByTimezone(string $dob, string $timezone): int
396 $birthdate = new DateTime($dob . ' 00:00:00', new DateTimeZone($timezone));
397 $currentDate = new DateTime('now', new DateTimeZone('UTC'));
399 $interval = $birthdate->diff($currentDate);
401 return (int) $interval->format('%y');
405 * Get days of a month in a given year.
407 * Returns number of days in the month of the given year.
408 * $m = 1 is 'January' to match human usage.
411 * @param int $m Month (1=January, 12=December)
413 * @return int Number of days in the given month
415 public static function getDaysInMonth(int $y, int $m): int
417 return date('t', mktime(0, 0, 0, $m, 1, $y));
421 * Returns the first day in month for a given month, year.
426 * @param int $m Month (1=January, 12=December)
428 * @return string day 0 = Sunday through 6 = Saturday
431 private static function getFirstDayInMonth(int $y, int $m): string
433 $d = sprintf('%04d-%02d-01 00:00', intval($y), intval($m));
435 return DateTimeFormat::utc($d, 'w');
439 * Output a calendar for the given month, year.
441 * If $links are provided (array), e.g. $links[12] => 'http://mylink' ,
442 * date 12 will be linked appropriately. Today's date is also noted by
444 * Months count from 1.
447 * @param int $m Month
448 * @param array $links (default null)
449 * @param string $class
454 * @todo Provide (prev, next) links, define class variations for different size calendars
456 public static function getCalendarTable(int $y = 0, int $m = 0, array $links = null, string $class = ''): string
458 // month table - start at 1 to match human usage.
460 'January', 'February', 'March',
461 'April', 'May', 'June',
462 'July', 'August', 'September',
463 'October', 'November', 'December'
466 $thisyear = DateTimeFormat::localNow('Y');
467 $thismonth = DateTimeFormat::localNow('m');
473 $m = intval($thismonth);
476 $dn = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
477 $f = self::getFirstDayInMonth($y, $m);
478 $l = self::getDaysInMonth($y, $m);
483 if (($y == $thisyear) && ($m == $thismonth)) {
484 $tddate = intval(DateTimeFormat::localNow('j'));
487 $str_month = DI::l10n()->getDay($mtab[$m]);
488 $o = '<table class="calendar' . $class . '">';
489 $o .= "<caption>$str_month $y</caption><tr>";
490 for ($a = 0; $a < 7; $a ++) {
491 $o .= '<th>' . mb_substr(DI::l10n()->getDay($dn[$a]), 0, 3, 'UTF-8') . '</th>';
497 if (($dow == $f) && (!$started)) {
501 $today = (((isset($tddate)) && ($tddate == $d)) ? "class=\"today\" " : '');
503 $day = str_replace(' ', ' ', sprintf('%2.2d', $d));
505 if (isset($links[$d])) {
506 $o .= "<a href=\"{$links[$d]}\">$day</a>";
518 if (($dow == 7) && ($d <= $l)) {
525 for ($a = $dow; $a < 7; $a ++) {
526 $o .= '<td> </td>';
530 $o .= '</tr></table>' . "\r\n";