3 * @copyright Copyright (C) 2010-2022, 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;
36 * Two-level sort for timezones.
43 private static function timezoneCompareCallback(string $a, string $b): int
45 if (strstr($a, '/') && strstr($b, '/')) {
46 if (DI::l10n()->t($a) == DI::l10n()->t($b)) {
49 return (DI::l10n()->t($a) < DI::l10n()->t($b)) ? -1 : 1;
52 if (strstr($a, '/')) {
54 } elseif (strstr($b, '/')) {
56 } elseif (DI::l10n()->t($a) == DI::l10n()->t($b)) {
60 return (DI::l10n()->t($a) < DI::l10n()->t($b)) ? -1 : 1;
64 * Emit a timezone selector grouped (primarily) by continent
66 * @param string $current Timezone
68 * @return string Parsed HTML output
70 public static function getTimezoneSelect(string $current = 'America/Los_Angeles'): string
72 $timezone_identifiers = DateTimeZone::listIdentifiers();
74 $o = '<select id="timezone_select" name="timezone">';
76 usort($timezone_identifiers, [__CLASS__, 'timezoneCompareCallback']);
78 foreach ($timezone_identifiers as $value) {
79 $ex = explode("/", $value);
81 if ($ex[0] != $continent) {
82 if ($continent != '') {
86 $o .= '<optgroup label="' . DI::l10n()->t($continent) . '">';
89 $city = substr($value, strpos($value, '/') + 1);
95 if ($continent != DI::l10n()->t('Miscellaneous')) {
97 $continent = DI::l10n()->t('Miscellaneous');
98 $o .= '<optgroup label="' . DI::l10n()->t($continent) . '">';
101 $city = str_replace('_', ' ', DI::l10n()->t($city));
102 $selected = (($value == $current) ? " selected=\"selected\" " : "");
103 $o .= "<option value=\"$value\" $selected >$city</option>";
105 $o .= '</optgroup></select>';
110 * Generating a Timezone selector
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'
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
122 * @return string Parsed HTML
123 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
125 public static function getTimezoneField(string $name = 'timezone', string $label = '', string $current = 'America/Los_Angeles', string $help = ''): string
127 $options = self::getTimezoneSelect($current);
128 $options = str_replace('<select id="timezone_select" name="timezone">', '', $options);
129 $options = str_replace('</select>', '', $options);
131 $tpl = Renderer::getMarkupTemplate('field_select_raw.tpl');
132 return Renderer::replaceMacros($tpl, [
133 '$field' => [$name, $label, $current, $help, $options],
138 * Wrapper for date selector, tailored for use in birthday fields.
140 * @param string $dob Date of Birth
141 * @param string $timezone
143 * @return string Formatted HTML
146 public static function getDateofBirthField(string $dob, string $timezone = 'UTC'): string
148 list($year, $month, $day) = sscanf($dob, '%4d-%2d-%2d');
150 if ($dob < '0000-01-01') {
153 } elseif ($dob < '0001-00-00') {
154 $value = substr($dob, 5);
157 $value = DateTimeFormat::utc($dob, 'Y-m-d');
158 $age = self::getAgeByTimezone($value, $timezone);
161 $tpl = Renderer::getMarkupTemplate("field_input.tpl");
162 $o = Renderer::replaceMacros($tpl,
166 DI::l10n()->t('Birthday:'),
168 intval($age) > 0 ? DI::l10n()->t('Age: ') . DI::l10n()->tt('%d year old', '%d years old', $age) : '',
170 'placeholder="' . DI::l10n()->t('YYYY-MM-DD or MM-DD') . '"'
178 * Returns a date selector
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")
185 * @return string Parsed HTML output.
186 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
188 public static function getDateField(DateTime $min, DateTime $max, DateTime $default, string $id = 'datepicker'): string
190 return self::getDateTimeField($min, $max, $default, '', $id, true, false, '', '');
194 * Returns a time selector
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")
200 * @return string Parsed HTML output.
203 public static function getTimeField(string $h, string $m, string $id = 'timepicker'): string
205 return self::getDateTimeField(new DateTime(), new DateTime(), new DateTime("$h:$m"), '', $id, false, true);
209 * Returns a datetime selector.
211 * @param DateTime $minDate Minimum date
212 * @param DateTime $maxDate Maximum date
213 * @param DateTime $defaultDate Default date
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
222 * @return string Parsed HTML output.
224 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
225 * @todo Once browser support is better this could probably be replaced with
226 * native HTML5 date picker.
228 public static function getDateTimeField(
231 DateTime $defaultDate = null,
233 string $id = 'datetimepicker',
234 bool $pickdate = true,
235 bool $picktime = true,
236 string $minfrom = '',
237 string $maxfrom = '',
238 bool $required = false): string
240 // First day of the week (0 = Sunday)
241 $firstDay = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'first_day_of_week', 0);
243 $lang = substr(DI::l10n()->getCurrentLang(), 0, 2);
245 // Check if the detected language is supported by the picker
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'])) {
256 $dateformat .= 'Y-m-d';
259 if ($pickdate && $picktime) {
264 $dateformat .= 'H:i';
267 $input_text = $defaultDate ? date($dateformat, $defaultDate->getTimestamp()) : '';
269 $readable_format = str_replace(['Y', 'm', 'd', 'H', 'i'], ['yyyy', 'mm', 'dd', 'HH', 'MM'], $dateformat);
271 $tpl = Renderer::getMarkupTemplate('field_datetime.tpl');
272 $o .= Renderer::replaceMacros($tpl, [
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'
282 $required ? '*' : '',
283 'placeholder="' . $readable_format . '"'
285 '$datetimepicker' => [
286 'minDate' => $minDate,
287 'maxDate' => $maxDate,
288 'defaultDate' => $defaultDate,
289 'dateformat' => $dateformat,
290 'firstDay' => $firstDay,
292 'minfrom' => $minfrom,
293 'maxfrom' => $maxfrom,
301 * Returns a relative date string.
303 * Implements "3 seconds ago" etc.
304 * Based on $posted_date, (UTC).
305 * Results relative to current timezone.
306 * Limited to range of timestamps.
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
312 * @return string with relative date
314 public static function getRelativeDate(string $posted_date = null, string $format = null): string
316 if (empty($posted_date) || $posted_date <= DBA::NULL_DATETIME) {
317 return DI::l10n()->t('never');
320 $localtime = $posted_date . ' UTC';
321 $abs = strtotime($localtime);
323 if ($abs === false) {
324 return DI::l10n()->t('never');
328 $etime = time() - $abs;
330 if ($etime < 1 && $etime >= 0) {
331 return DI::l10n()->t('less than a second ago');
340 12 * 30 * 24 * 60 * 60 => [DI::l10n()->t('year'), DI::l10n()->t('years')],
341 30 * 24 * 60 * 60 => [DI::l10n()->t('month'), DI::l10n()->t('months')],
342 7 * 24 * 60 * 60 => [DI::l10n()->t('week'), DI::l10n()->t('weeks')],
343 24 * 60 * 60 => [DI::l10n()->t('day'), DI::l10n()->t('days')],
344 60 * 60 => [DI::l10n()->t('hour'), DI::l10n()->t('hours')],
345 60 => [DI::l10n()->t('minute'), DI::l10n()->t('minutes')],
346 1 => [DI::l10n()->t('second'), DI::l10n()->t('seconds')],
349 foreach ($a as $secs => $str) {
353 // translators - e.g. 22 hours ago, 1 minute ago
356 $format = DI::l10n()->t('in %1$d %2$s');
359 $format = DI::l10n()->t('%1$d %2$s ago');
363 return sprintf($format, $r, (($r == 1) ? $str[0] : $str[1]));
369 * Returns timezone correct age in years.
371 * Returns the age in years, given a date of birth and the timezone of the person
372 * whose date of birth is provided.
374 * @param string $dob Date of Birth
375 * @param string $timezone Timezone of the person of interest
377 * @return int Age in years
380 public static function getAgeByTimezone(string $dob, string $timezone): int
386 $birthdate = new DateTime($dob . ' 00:00:00', new DateTimeZone($timezone));
387 $currentDate = new DateTime('now', new DateTimeZone('UTC'));
389 $interval = $birthdate->diff($currentDate);
391 return (int) $interval->format('%y');
395 * Get days of a month in a given year.
397 * Returns number of days in the month of the given year.
398 * $m = 1 is 'January' to match human usage.
401 * @param int $m Month (1=January, 12=December)
403 * @return int Number of days in the given month
405 public static function getDaysInMonth(int $y, int $m): int
407 return date('t', mktime(0, 0, 0, $m, 1, $y));
411 * Returns the first day in month for a given month, year.
416 * @param int $m Month (1=January, 12=December)
418 * @return string day 0 = Sunday through 6 = Saturday
421 private static function getFirstDayInMonth(int $y, int $m): string
423 $d = sprintf('%04d-%02d-01 00:00', intval($y), intval($m));
425 return DateTimeFormat::utc($d, 'w');
429 * Output a calendar for the given month, year.
431 * If $links are provided (array), e.g. $links[12] => 'http://mylink' ,
432 * date 12 will be linked appropriately. Today's date is also noted by
434 * Months count from 1.
437 * @param int $m Month
438 * @param array $links (default null)
439 * @param string $class
444 * @todo Provide (prev, next) links, define class variations for different size calendars
446 public static function getCalendarTable(int $y = 0, int $m = 0, array $links = null, string $class = ''): string
448 // month table - start at 1 to match human usage.
450 'January', 'February', 'March',
451 'April', 'May', 'June',
452 'July', 'August', 'September',
453 'October', 'November', 'December'
456 $thisyear = DateTimeFormat::localNow('Y');
457 $thismonth = DateTimeFormat::localNow('m');
463 $m = intval($thismonth);
466 $dn = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
467 $f = self::getFirstDayInMonth($y, $m);
468 $l = self::getDaysInMonth($y, $m);
473 if (($y == $thisyear) && ($m == $thismonth)) {
474 $tddate = intval(DateTimeFormat::localNow('j'));
477 $str_month = DI::l10n()->getDay($mtab[$m]);
478 $o = '<table class="calendar' . $class . '">';
479 $o .= "<caption>$str_month $y</caption><tr>";
480 for ($a = 0; $a < 7; $a ++) {
481 $o .= '<th>' . mb_substr(DI::l10n()->getDay($dn[$a]), 0, 3, 'UTF-8') . '</th>';
487 if (($dow == $f) && (!$started)) {
491 $today = (((isset($tddate)) && ($tddate == $d)) ? "class=\"today\" " : '');
493 $day = str_replace(' ', ' ', sprintf('%2.2d', $d));
495 if (isset($links[$d])) {
496 $o .= "<a href=\"{$links[$d]}\">$day</a>";
508 if (($dow == 7) && ($d <= $l)) {
515 for ($a = $dow; $a < 7; $a ++) {
516 $o .= '<td> </td>';
520 $o .= '</tr></table>' . "\r\n";