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\Core\Session;
28 use Friendica\Database\DBA;
37 * Two-level sort for timezones.
44 private static function timezoneCompareCallback(string $a, string $b): int
46 if (strstr($a, '/') && strstr($b, '/')) {
47 if (DI::l10n()->t($a) == DI::l10n()->t($b)) {
50 return (DI::l10n()->t($a) < DI::l10n()->t($b)) ? -1 : 1;
53 if (strstr($a, '/')) {
55 } elseif (strstr($b, '/')) {
57 } elseif (DI::l10n()->t($a) == DI::l10n()->t($b)) {
61 return (DI::l10n()->t($a) < DI::l10n()->t($b)) ? -1 : 1;
65 * Emit a timezone selector grouped (primarily) by continent
67 * @param string $current Timezone
69 * @return string Parsed HTML output
71 public static function getTimezoneSelect(string $current = 'America/Los_Angeles'): string
73 $timezone_identifiers = DateTimeZone::listIdentifiers();
75 $o = '<select id="timezone_select" name="timezone">';
77 usort($timezone_identifiers, [__CLASS__, 'timezoneCompareCallback']);
79 foreach ($timezone_identifiers as $value) {
80 $ex = explode("/", $value);
82 if ($ex[0] != $continent) {
83 if ($continent != '') {
87 $o .= '<optgroup label="' . DI::l10n()->t($continent) . '">';
90 $city = substr($value, strpos($value, '/') + 1);
96 if ($continent != DI::l10n()->t('Miscellaneous')) {
98 $continent = DI::l10n()->t('Miscellaneous');
99 $o .= '<optgroup label="' . DI::l10n()->t($continent) . '">';
102 $city = str_replace('_', ' ', DI::l10n()->t($city));
103 $selected = (($value == $current) ? " selected=\"selected\" " : "");
104 $o .= "<option value=\"$value\" $selected >$city</option>";
106 $o .= '</optgroup></select>';
111 * Generating a Timezone selector
113 * Return a select using 'field_select_raw' template, with timezones
114 * grouped (primarily) by continent
115 * arguments follow convention as other field_* template array:
116 * 'name', 'label', $value, 'help'
118 * @param string $name Name of the selector
119 * @param string $label Label for the selector
120 * @param string $current Timezone
121 * @param string $help Help text
123 * @return string Parsed HTML
124 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
126 public static function getTimezoneField(string $name = 'timezone', string $label = '', string $current = 'America/Los_Angeles', string $help = ''): string
128 $options = self::getTimezoneSelect($current);
129 $options = str_replace('<select id="timezone_select" name="timezone">', '', $options);
130 $options = str_replace('</select>', '', $options);
132 $tpl = Renderer::getMarkupTemplate('field_select_raw.tpl');
133 return Renderer::replaceMacros($tpl, [
134 '$field' => [$name, $label, $current, $help, $options],
139 * Wrapper for date selector, tailored for use in birthday fields.
141 * @param string $dob Date of Birth
142 * @param string $timezone
144 * @return string Formatted HTML
147 public static function getDateofBirthField(string $dob, string $timezone = 'UTC'): string
149 list($year, $month, $day) = sscanf($dob, '%4d-%2d-%2d');
151 if ($dob < '0000-01-01') {
154 } elseif ($dob < '0001-00-00') {
155 $value = substr($dob, 5);
158 $value = DateTimeFormat::utc($dob, 'Y-m-d');
159 $age = self::getAgeByTimezone($value, $timezone);
162 $tpl = Renderer::getMarkupTemplate("field_input.tpl");
163 $o = Renderer::replaceMacros($tpl,
167 DI::l10n()->t('Birthday:'),
169 intval($age) > 0 ? DI::l10n()->t('Age: ') . DI::l10n()->tt('%d year old', '%d years old', $age) : '',
171 'placeholder="' . DI::l10n()->t('YYYY-MM-DD or MM-DD') . '"'
179 * Returns a date selector
181 * @param DateTime $min Minimum date
182 * @param DateTime $max Maximum date
183 * @param DateTime $default Default date
184 * @param string $id ID and name of datetimepicker (defaults to "datetimepicker")
186 * @return string Parsed HTML output.
187 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
189 public static function getDateField(DateTime $min, DateTime $max, DateTime $default, string $id = 'datepicker'): string
191 return self::getDateTimeField($min, $max, $default, '', $id, true, false, '', '');
195 * Returns a time selector
197 * @param string $h Already selected hour
198 * @param string $m Already selected minute
199 * @param string $id ID and name of datetimepicker (defaults to "timepicker")
201 * @return string Parsed HTML output.
204 public static function getTimeField(string $h, string $m, string $id = 'timepicker'): string
206 return self::getDateTimeField(new DateTime(), new DateTime(), new DateTime("$h:$m"), '', $id, false, true);
210 * Returns a datetime selector.
212 * @param DateTime $minDate Minimum date
213 * @param DateTime $maxDate Maximum date
214 * @param DateTime $defaultDate Default date
216 * @param string $id Id and name of datetimepicker (defaults to "datetimepicker")
217 * @param bool $pickdate true to show date picker (default)
218 * @param bool $picktime true to show time picker (default)
219 * @param string $minfrom set minimum date from picker with id $minfrom (none by default)
220 * @param string $maxfrom set maximum date from picker with id $maxfrom (none by default)
221 * @param bool $required default false
223 * @return string Parsed HTML output.
225 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
226 * @todo Once browser support is better this could probably be replaced with
227 * native HTML5 date picker.
229 public static function getDateTimeField(
232 DateTime $defaultDate = null,
234 string $id = 'datetimepicker',
235 bool $pickdate = true,
236 bool $picktime = true,
237 string $minfrom = '',
238 string $maxfrom = '',
239 bool $required = false): string
241 // First day of the week (0 = Sunday)
242 $firstDay = DI::pConfig()->get(Session::getLocalUser(), 'system', 'first_day_of_week', 0);
244 $lang = substr(DI::l10n()->getCurrentLang(), 0, 2);
246 // Check if the detected language is supported by the picker
248 ['ar', 'ro', 'id', 'bg', 'fa', 'ru', 'uk', 'en', 'el', 'de', 'nl', 'tr', 'fr', 'es', 'th', 'pl', 'pt', 'ch', 'se', 'kr',
249 'it', 'da', 'no', 'ja', 'vi', 'sl', 'cs', 'hu'])) {
257 $dateformat .= 'Y-m-d';
260 if ($pickdate && $picktime) {
265 $dateformat .= 'H:i';
268 $input_text = $defaultDate ? date($dateformat, $defaultDate->getTimestamp()) : '';
270 $readable_format = str_replace(['Y', 'm', 'd', 'H', 'i'], ['yyyy', 'mm', 'dd', 'HH', 'MM'], $dateformat);
272 $tpl = Renderer::getMarkupTemplate('field_datetime.tpl');
273 $o .= Renderer::replaceMacros($tpl, [
279 'Time zone: <strong>%s</strong> <a href="%s">Change in Settings</a>',
280 str_replace('_', ' ', DI::app()->getTimeZone()) . ' (GMT ' . DateTimeFormat::localNow('P') . ')',
281 DI::baseUrl() . '/settings'
283 $required ? '*' : '',
284 'placeholder="' . $readable_format . '"'
286 '$datetimepicker' => [
287 'minDate' => $minDate,
288 'maxDate' => $maxDate,
289 'defaultDate' => $defaultDate,
290 'dateformat' => $dateformat,
291 'firstDay' => $firstDay,
293 'minfrom' => $minfrom,
294 'maxfrom' => $maxfrom,
302 * Returns a relative date string.
304 * Implements "3 seconds ago" etc.
305 * Based on $posted_date, (UTC).
306 * Results relative to current timezone.
307 * Limited to range of timestamps.
309 * @param string $posted_date MySQL-formatted date string (YYYY-MM-DD HH:MM:SS)
310 * @param string $format (optional) Parsed with sprintf()
311 * <tt>%1$d %2$s ago</tt>, e.g. 22 hours ago, 1 minute ago
313 * @return string with relative date
315 public static function getRelativeDate(string $posted_date = null, string $format = null): string
317 if (empty($posted_date) || $posted_date <= DBA::NULL_DATETIME) {
318 return DI::l10n()->t('never');
321 $localtime = $posted_date . ' UTC';
322 $abs = strtotime($localtime);
324 if ($abs === false) {
325 return DI::l10n()->t('never');
329 $etime = time() - $abs;
331 if ($etime < 1 && $etime >= 0) {
332 return DI::l10n()->t('less than a second ago');
341 12 * 30 * 24 * 60 * 60 => [DI::l10n()->t('year'), DI::l10n()->t('years')],
342 30 * 24 * 60 * 60 => [DI::l10n()->t('month'), DI::l10n()->t('months')],
343 7 * 24 * 60 * 60 => [DI::l10n()->t('week'), DI::l10n()->t('weeks')],
344 24 * 60 * 60 => [DI::l10n()->t('day'), DI::l10n()->t('days')],
345 60 * 60 => [DI::l10n()->t('hour'), DI::l10n()->t('hours')],
346 60 => [DI::l10n()->t('minute'), DI::l10n()->t('minutes')],
347 1 => [DI::l10n()->t('second'), DI::l10n()->t('seconds')],
350 foreach ($a as $secs => $str) {
354 // translators - e.g. 22 hours ago, 1 minute ago
357 $format = DI::l10n()->t('in %1$d %2$s');
360 $format = DI::l10n()->t('%1$d %2$s ago');
364 return sprintf($format, $r, (($r == 1) ? $str[0] : $str[1]));
370 * Returns timezone correct age in years.
372 * Returns the age in years, given a date of birth and the timezone of the person
373 * whose date of birth is provided.
375 * @param string $dob Date of Birth
376 * @param string $timezone Timezone of the person of interest
378 * @return int Age in years
381 public static function getAgeByTimezone(string $dob, string $timezone): int
387 $birthdate = new DateTime($dob . ' 00:00:00', new DateTimeZone($timezone));
388 $currentDate = new DateTime('now', new DateTimeZone('UTC'));
390 $interval = $birthdate->diff($currentDate);
392 return (int) $interval->format('%y');
396 * Get days of a month in a given year.
398 * Returns number of days in the month of the given year.
399 * $m = 1 is 'January' to match human usage.
402 * @param int $m Month (1=January, 12=December)
404 * @return int Number of days in the given month
406 public static function getDaysInMonth(int $y, int $m): int
408 return date('t', mktime(0, 0, 0, $m, 1, $y));
412 * Returns the first day in month for a given month, year.
417 * @param int $m Month (1=January, 12=December)
419 * @return string day 0 = Sunday through 6 = Saturday
422 private static function getFirstDayInMonth(int $y, int $m): string
424 $d = sprintf('%04d-%02d-01 00:00', intval($y), intval($m));
426 return DateTimeFormat::utc($d, 'w');
430 * Output a calendar for the given month, year.
432 * If $links are provided (array), e.g. $links[12] => 'http://mylink' ,
433 * date 12 will be linked appropriately. Today's date is also noted by
435 * Months count from 1.
438 * @param int $m Month
439 * @param array $links (default null)
440 * @param string $class
445 * @todo Provide (prev, next) links, define class variations for different size calendars
447 public static function getCalendarTable(int $y = 0, int $m = 0, array $links = null, string $class = ''): string
449 // month table - start at 1 to match human usage.
451 'January', 'February', 'March',
452 'April', 'May', 'June',
453 'July', 'August', 'September',
454 'October', 'November', 'December'
457 $thisyear = DateTimeFormat::localNow('Y');
458 $thismonth = DateTimeFormat::localNow('m');
464 $m = intval($thismonth);
467 $dn = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
468 $f = self::getFirstDayInMonth($y, $m);
469 $l = self::getDaysInMonth($y, $m);
474 if (($y == $thisyear) && ($m == $thismonth)) {
475 $tddate = intval(DateTimeFormat::localNow('j'));
478 $str_month = DI::l10n()->getDay($mtab[$m]);
479 $o = '<table class="calendar' . $class . '">';
480 $o .= "<caption>$str_month $y</caption><tr>";
481 for ($a = 0; $a < 7; $a ++) {
482 $o .= '<th>' . mb_substr(DI::l10n()->getDay($dn[$a]), 0, 3, 'UTF-8') . '</th>';
488 if (($dow == $f) && (!$started)) {
492 $today = (((isset($tddate)) && ($tddate == $d)) ? "class=\"today\" " : '');
494 $day = str_replace(' ', ' ', sprintf('%2.2d', $d));
496 if (isset($links[$d])) {
497 $o .= "<a href=\"{$links[$d]}\">$day</a>";
509 if (($dow == 7) && ($d <= $l)) {
516 for ($a = $dow; $a < 7; $a ++) {
517 $o .= '<td> </td>';
521 $o .= '</tr></table>' . "\r\n";