4 * @file src/Util/Temporal.php
7 namespace Friendica\Util;
11 use Friendica\Core\Renderer;
12 use Friendica\Database\DBA;
21 * Two-level sort for timezones.
27 private static function timezoneCompareCallback($a, $b)
29 if (strstr($a, '/') && strstr($b, '/')) {
30 if (DI::l10n()->t($a) == DI::l10n()->t($b)) {
33 return (DI::l10n()->t($a) < DI::l10n()->t($b)) ? -1 : 1;
36 if (strstr($a, '/')) {
38 } elseif (strstr($b, '/')) {
40 } elseif (DI::l10n()->t($a) == DI::l10n()->t($b)) {
44 return (DI::l10n()->t($a) < DI::l10n()->t($b)) ? -1 : 1;
48 * Emit a timezone selector grouped (primarily) by continent
50 * @param string $current Timezone
51 * @return string Parsed HTML output
53 public static function getTimezoneSelect($current = 'America/Los_Angeles')
55 $timezone_identifiers = DateTimeZone::listIdentifiers();
57 $o = '<select id="timezone_select" name="timezone">';
59 usort($timezone_identifiers, [__CLASS__, 'timezoneCompareCallback']);
61 foreach ($timezone_identifiers as $value) {
62 $ex = explode("/", $value);
64 if ($ex[0] != $continent) {
65 if ($continent != '') {
69 $o .= '<optgroup label="' . DI::l10n()->t($continent) . '">';
72 $city = substr($value, strpos($value, '/') + 1);
78 if ($continent != DI::l10n()->t('Miscellaneous')) {
80 $continent = DI::l10n()->t('Miscellaneous');
81 $o .= '<optgroup label="' . DI::l10n()->t($continent) . '">';
84 $city = str_replace('_', ' ', DI::l10n()->t($city));
85 $selected = (($value == $current) ? " selected=\"selected\" " : "");
86 $o .= "<option value=\"$value\" $selected >$city</option>";
88 $o .= '</optgroup></select>';
93 * Generating a Timezone selector
95 * Return a select using 'field_select_raw' template, with timezones
96 * grouped (primarily) by continent
97 * arguments follow convention as other field_* template array:
98 * 'name', 'label', $value, 'help'
100 * @param string $name Name of the selector
101 * @param string $label Label for the selector
102 * @param string $current Timezone
103 * @param string $help Help text
105 * @return string Parsed HTML
106 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
108 public static function getTimezoneField($name = 'timezone', $label = '', $current = 'America/Los_Angeles', $help = '')
110 $options = self::getTimezoneSelect($current);
111 $options = str_replace('<select id="timezone_select" name="timezone">', '', $options);
112 $options = str_replace('</select>', '', $options);
114 $tpl = Renderer::getMarkupTemplate('field_select_raw.tpl');
115 return Renderer::replaceMacros($tpl, [
116 '$field' => [$name, $label, $current, $help, $options],
121 * Wrapper for date selector, tailored for use in birthday fields.
123 * @param string $dob Date of Birth
124 * @param string $timezone
125 * @return string Formatted HTML
128 public static function getDateofBirthField(string $dob, string $timezone = 'UTC')
130 list($year, $month, $day) = sscanf($dob, '%4d-%2d-%2d');
132 if ($dob < '0000-01-01') {
135 } elseif ($dob < '0001-00-00') {
136 $value = substr($dob, 5);
139 $value = DateTimeFormat::utc($dob, 'Y-m-d');
140 $age = self::getAgeByTimezone($value, $timezone);
143 $tpl = Renderer::getMarkupTemplate("field_input.tpl");
144 $o = Renderer::replaceMacros($tpl,
148 DI::l10n()->t('Birthday:'),
150 intval($age) > 0 ? DI::l10n()->t('Age: ') . DI::l10n()->tt('%d year old', '%d years old', $age) : '',
152 'placeholder="' . DI::l10n()->t('YYYY-MM-DD or MM-DD') . '"'
160 * Returns a date selector
162 * @param DateTime $min Minimum date
163 * @param DateTime $max Maximum date
164 * @param DateTime $default Default date
165 * @param string $id ID and name of datetimepicker (defaults to "datetimepicker")
167 * @return string Parsed HTML output.
168 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
170 public static function getDateField($min, $max, $default, $id = 'datepicker')
172 return self::getDateTimeField($min, $max, $default, '', $id, true, false, '', '');
176 * Returns a time selector
178 * @param string $h Already selected hour
179 * @param string $m Already selected minute
180 * @param string $id ID and name of datetimepicker (defaults to "timepicker")
182 * @return string Parsed HTML output.
185 public static function getTimeField($h, $m, $id = 'timepicker')
187 return self::getDateTimeField(new DateTime(), new DateTime(), new DateTime("$h:$m"), '', $id, false, true);
191 * Returns a datetime selector.
193 * @param DateTime $minDate Minimum date
194 * @param DateTime $maxDate Maximum date
195 * @param DateTime $defaultDate Default date
197 * @param string $id Id and name of datetimepicker (defaults to "datetimepicker")
198 * @param bool $pickdate true to show date picker (default)
199 * @param bool $picktime true to show time picker (default)
200 * @param string $minfrom set minimum date from picker with id $minfrom (none by default)
201 * @param string $maxfrom set maximum date from picker with id $maxfrom (none by default)
202 * @param bool $required default false
204 * @return string Parsed HTML output.
206 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
207 * @todo Once browser support is better this could probably be replaced with
208 * native HTML5 date picker.
210 public static function getDateTimeField(
213 DateTime $defaultDate,
215 $id = 'datetimepicker',
222 // First day of the week (0 = Sunday)
223 $firstDay = DI::pConfig()->get(local_user(), 'system', 'first_day_of_week', 0);
225 $lang = substr(DI::l10n()->getCurrentLang(), 0, 2);
227 // Check if the detected language is supported by the picker
229 ["ar", "ro", "id", "bg", "fa", "ru", "uk", "en", "el", "de", "nl", "tr", "fr", "es", "th", "pl", "pt", "ch", "se", "kr",
230 "it", "da", "no", "ja", "vi", "sl", "cs", "hu"])) {
238 $dateformat .= 'Y-m-d';
241 if ($pickdate && $picktime) {
246 $dateformat .= 'H:i';
249 $input_text = $defaultDate ? date($dateformat, $defaultDate->getTimestamp()) : '';
251 $readable_format = str_replace(['Y', 'm', 'd', 'H', 'i'], ['yyyy', 'mm', 'dd', 'HH', 'MM'], $dateformat);
253 $tpl = Renderer::getMarkupTemplate('field_datetime.tpl');
254 $o .= Renderer::replaceMacros($tpl, [
260 $required ? '*' : '',
261 'placeholder="' . $readable_format . '"'
263 '$datetimepicker' => [
264 'minDate' => $minDate,
265 'maxDate' => $maxDate,
266 'defaultDate' => $defaultDate,
267 'dateformat' => $dateformat,
268 'firstDay' => $firstDay,
270 'minfrom' => $minfrom,
271 'maxfrom' => $maxfrom,
279 * Returns a relative date string.
281 * Implements "3 seconds ago" etc.
282 * Based on $posted_date, (UTC).
283 * Results relative to current timezone.
284 * Limited to range of timestamps.
286 * @param string $posted_date MySQL-formatted date string (YYYY-MM-DD HH:MM:SS)
287 * @param string $format (optional) Parsed with sprintf()
288 * <tt>%1$d %2$s ago</tt>, e.g. 22 hours ago, 1 minute ago
290 * @return string with relative date
292 public static function getRelativeDate($posted_date, $format = null)
294 $localtime = $posted_date . ' UTC';
296 $abs = strtotime($localtime);
298 if (is_null($posted_date) || $posted_date <= DBA::NULL_DATETIME || $abs === false) {
299 return DI::l10n()->t('never');
303 $etime = time() - $abs;
305 if ($etime < 1 && $etime >= 0) {
306 return DI::l10n()->t('less than a second ago');
314 $a = [12 * 30 * 24 * 60 * 60 => [DI::l10n()->t('year'), DI::l10n()->t('years')],
315 30 * 24 * 60 * 60 => [DI::l10n()->t('month'), DI::l10n()->t('months')],
316 7 * 24 * 60 * 60 => [DI::l10n()->t('week'), DI::l10n()->t('weeks')],
317 24 * 60 * 60 => [DI::l10n()->t('day'), DI::l10n()->t('days')],
318 60 * 60 => [DI::l10n()->t('hour'), DI::l10n()->t('hours')],
319 60 => [DI::l10n()->t('minute'), DI::l10n()->t('minutes')],
320 1 => [DI::l10n()->t('second'), DI::l10n()->t('seconds')]
323 foreach ($a as $secs => $str) {
327 // translators - e.g. 22 hours ago, 1 minute ago
330 $format = DI::l10n()->t('in %1$d %2$s');
333 $format = DI::l10n()->t('%1$d %2$s ago');
337 return sprintf($format, $r, (($r == 1) ? $str[0] : $str[1]));
343 * Returns timezone correct age in years.
345 * Returns the age in years, given a date of birth and the timezone of the person
346 * whose date of birth is provided.
348 * @param string $dob Date of Birth
349 * @param string $owner_tz (optional) Timezone of the person of interest
351 * @return int Age in years
354 public static function getAgeByTimezone($dob, $owner_tz = '')
361 $owner_tz = date_default_timezone_get();
364 $birthdate = new DateTime($dob . ' 00:00:00', new DateTimeZone($owner_tz));
365 $currentDate = new DateTime('now', new DateTimeZone('UTC'));
367 $interval = $birthdate->diff($currentDate);
369 return $interval->format('%y');
373 * Get days of a month in a given year.
375 * Returns number of days in the month of the given year.
376 * $m = 1 is 'January' to match human usage.
379 * @param int $m Month (1=January, 12=December)
381 * @return int Number of days in the given month
383 public static function getDaysInMonth($y, $m)
385 return date('t', mktime(0, 0, 0, $m, 1, $y));
389 * Returns the first day in month for a given month, year.
394 * @param int $m Month (1=January, 12=December)
396 * @return string day 0 = Sunday through 6 = Saturday
399 private static function getFirstDayInMonth($y, $m)
401 $d = sprintf('%04d-%02d-01 00:00', intval($y), intval($m));
403 return DateTimeFormat::utc($d, 'w');
407 * Output a calendar for the given month, year.
409 * If $links are provided (array), e.g. $links[12] => 'http://mylink' ,
410 * date 12 will be linked appropriately. Today's date is also noted by
412 * Months count from 1.
415 * @param int $m Month
416 * @param array $links (default null)
417 * @param string $class
422 * @todo Provide (prev, next) links, define class variations for different size calendars
424 public static function getCalendarTable($y = 0, $m = 0, $links = null, $class = '')
426 // month table - start at 1 to match human usage.
428 'January', 'February', 'March',
429 'April', 'May', 'June',
430 'July', 'August', 'September',
431 'October', 'November', 'December'
434 $thisyear = DateTimeFormat::localNow('Y');
435 $thismonth = DateTimeFormat::localNow('m');
441 $m = intval($thismonth);
444 $dn = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
445 $f = self::getFirstDayInMonth($y, $m);
446 $l = self::getDaysInMonth($y, $m);
451 if (($y == $thisyear) && ($m == $thismonth)) {
452 $tddate = intval(DateTimeFormat::localNow('j'));
455 $str_month = DI::l10n()->getDay($mtab[$m]);
456 $o = '<table class="calendar' . $class . '">';
457 $o .= "<caption>$str_month $y</caption><tr>";
458 for ($a = 0; $a < 7; $a ++) {
459 $o .= '<th>' . mb_substr(DI::l10n()->getDay($dn[$a]), 0, 3, 'UTF-8') . '</th>';
465 if (($dow == $f) && (!$started)) {
469 $today = (((isset($tddate)) && ($tddate == $d)) ? "class=\"today\" " : '');
471 $day = str_replace(' ', ' ', sprintf('%2.2d', $d));
473 if (isset($links[$d])) {
474 $o .= "<a href=\"{$links[$d]}\">$day</a>";
486 if (($dow == 7) && ($d <= $l)) {
493 for ($a = $dow; $a < 7; $a ++) {
494 $o .= '<td> </td>';
498 $o .= '</tr></table>' . "\r\n";