4 * @file src/Util/Temporal.php
7 namespace Friendica\Util;
11 use Friendica\Core\Config;
12 use Friendica\Core\L10n;
13 use Friendica\Core\PConfig;
14 use Friendica\Core\Renderer;
15 use Friendica\Database\DBA;
18 * @brief Temporal class
23 * @brief Two-level sort for timezones.
29 private static function timezoneCompareCallback($a, $b)
31 if (strstr($a, '/') && strstr($b, '/')) {
32 if (L10n::t($a) == L10n::t($b)) {
35 return (L10n::t($a) < L10n::t($b)) ? -1 : 1;
38 if (strstr($a, '/')) {
40 } elseif (strstr($b, '/')) {
42 } elseif (L10n::t($a) == L10n::t($b)) {
46 return (L10n::t($a) < L10n::t($b)) ? -1 : 1;
50 * @brief Emit a timezone selector grouped (primarily) by continent
52 * @param string $current Timezone
53 * @return string Parsed HTML output
55 public static function getTimezoneSelect($current = 'America/Los_Angeles')
57 $timezone_identifiers = DateTimeZone::listIdentifiers();
59 $o = '<select id="timezone_select" name="timezone">';
61 usort($timezone_identifiers, [__CLASS__, 'timezoneCompareCallback']);
63 foreach ($timezone_identifiers as $value) {
64 $ex = explode("/", $value);
66 if ($ex[0] != $continent) {
67 if ($continent != '') {
71 $o .= '<optgroup label="' . L10n::t($continent) . '">';
74 $city = substr($value, strpos($value, '/') + 1);
80 if ($continent != L10n::t('Miscellaneous')) {
82 $continent = L10n::t('Miscellaneous');
83 $o .= '<optgroup label="' . L10n::t($continent) . '">';
86 $city = str_replace('_', ' ', L10n::t($city));
87 $selected = (($value == $current) ? " selected=\"selected\" " : "");
88 $o .= "<option value=\"$value\" $selected >$city</option>";
90 $o .= '</optgroup></select>';
95 * @brief Generating a Timezone selector
97 * Return a select using 'field_select_raw' template, with timezones
98 * grouped (primarily) by continent
99 * arguments follow convention as other field_* template array:
100 * 'name', 'label', $value, 'help'
102 * @param string $name Name of the selector
103 * @param string $label Label for the selector
104 * @param string $current Timezone
105 * @param string $help Help text
107 * @return string Parsed HTML
108 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
110 public static function getTimezoneField($name = 'timezone', $label = '', $current = 'America/Los_Angeles', $help = '')
112 $options = self::getTimezoneSelect($current);
113 $options = str_replace('<select id="timezone_select" name="timezone">', '', $options);
114 $options = str_replace('</select>', '', $options);
116 $tpl = Renderer::getMarkupTemplate('field_select_raw.tpl');
117 return Renderer::replaceMacros($tpl, [
118 '$field' => [$name, $label, $current, $help, $options],
123 * @brief Wrapper for date selector, tailored for use in birthday fields.
125 * @param string $dob Date of Birth
126 * @return string Formatted HTML
127 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
129 public static function getDateofBirthField($dob)
133 list($year, $month, $day) = sscanf($dob, '%4d-%2d-%2d');
135 if ($dob < '0000-01-01') {
138 $value = DateTimeFormat::utc(($year > 1000) ? $dob : '1000-' . $month . '-' . $day, 'Y-m-d');
141 $age = (intval($value) ? self::getAgeByTimezone($value, $a->user["timezone"], $a->user["timezone"]) : "");
143 $tpl = Renderer::getMarkupTemplate("field_input.tpl");
144 $o = Renderer::replaceMacros($tpl,
148 L10n::t('Birthday:'),
150 intval($age) > 0 ? L10n::t('Age: ') . $age : "",
152 'placeholder="' . L10n::t('YYYY-MM-DD or MM-DD') . '"'
160 * @brief Returns a date selector
162 * @param string $min Unix timestamp of minimum date
163 * @param string $max Unix timestap of maximum date
164 * @param string $default Unix timestamp of 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 * @brief 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 * @brief 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 = PConfig::get(local_user(), 'system', 'first_day_of_week', 0);
225 $lang = substr(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 * @brief 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 L10n::t('never');
303 $etime = time() - $abs;
305 if ($etime < 1 && $etime >= 0) {
306 return L10n::t('less than a second ago');
314 $a = [12 * 30 * 24 * 60 * 60 => [L10n::t('year'), L10n::t('years')],
315 30 * 24 * 60 * 60 => [L10n::t('month'), L10n::t('months')],
316 7 * 24 * 60 * 60 => [L10n::t('week'), L10n::t('weeks')],
317 24 * 60 * 60 => [L10n::t('day'), L10n::t('days')],
318 60 * 60 => [L10n::t('hour'), L10n::t('hours')],
319 60 => [L10n::t('minute'), L10n::t('minutes')],
320 1 => [L10n::t('second'), L10n::t('seconds')]
323 foreach ($a as $secs => $str) {
327 // translators - e.g. 22 hours ago, 1 minute ago
330 $format = L10n::t('in %1$d %2$s');
333 $format = L10n::t('%1$d %2$s ago');
337 return sprintf($format, $r, (($r == 1) ? $str[0] : $str[1]));
343 * @brief Returns timezone correct age in years.
345 * Returns the age in years, given a date of birth, the timezone of the person
346 * whose date of birth is provided, and the timezone of the person viewing the
349 * Why? Bear with me. Let's say I live in Mittagong, Australia, and my birthday
350 * is on New Year's. You live in San Bruno, California.
351 * When exactly are you going to see my age increase?
353 * A: 5:00 AM Dec 31 San Bruno time. That's precisely when I start celebrating
354 * and become a year older. If you wish me happy birthday on January 1
355 * (San Bruno time), you'll be a day late.
357 * @param string $dob Date of Birth
358 * @param string $owner_tz (optional) Timezone of the person of interest
359 * @param string $viewer_tz (optional) Timezone of the person viewing
361 * @return int Age in years
364 public static function getAgeByTimezone($dob, $owner_tz = '', $viewer_tz = '')
370 $owner_tz = date_default_timezone_get();
373 $viewer_tz = date_default_timezone_get();
376 $birthdate = DateTimeFormat::convert($dob . ' 00:00:00+00:00', $owner_tz, 'UTC', 'Y-m-d');
377 list($year, $month, $day) = explode("-", $birthdate);
378 $year_diff = DateTimeFormat::timezoneNow($viewer_tz, 'Y') - $year;
379 $curr_month = DateTimeFormat::timezoneNow($viewer_tz, 'm');
380 $curr_day = DateTimeFormat::timezoneNow($viewer_tz, 'd');
382 if (($curr_month < $month) || (($curr_month == $month) && ($curr_day < $day))) {
390 * @brief Get days of a month in a given year.
392 * Returns number of days in the month of the given year.
393 * $m = 1 is 'January' to match human usage.
396 * @param int $m Month (1=January, 12=December)
398 * @return int Number of days in the given month
400 public static function getDaysInMonth($y, $m)
402 return date('t', mktime(0, 0, 0, $m, 1, $y));
406 * @brief Returns the first day in month for a given month, year.
411 * @param int $m Month (1=January, 12=December)
413 * @return string day 0 = Sunday through 6 = Saturday
416 private static function getFirstDayInMonth($y, $m)
418 $d = sprintf('%04d-%02d-01 00:00', intval($y), intval($m));
420 return DateTimeFormat::utc($d, 'w');
424 * @brief Output a calendar for the given month, year.
426 * If $links are provided (array), e.g. $links[12] => 'http://mylink' ,
427 * date 12 will be linked appropriately. Today's date is also noted by
429 * Months count from 1.
432 * @param int $m Month
433 * @param array $links (default null)
434 * @param string $class
439 * @todo Provide (prev, next) links, define class variations for different size calendars
441 public static function getCalendarTable($y = 0, $m = 0, $links = null, $class = '')
443 // month table - start at 1 to match human usage.
445 'January', 'February', 'March',
446 'April', 'May', 'June',
447 'July', 'August', 'September',
448 'October', 'November', 'December'
451 $thisyear = DateTimeFormat::localNow('Y');
452 $thismonth = DateTimeFormat::localNow('m');
458 $m = intval($thismonth);
461 $dn = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
462 $f = self::getFirstDayInMonth($y, $m);
463 $l = self::getDaysInMonth($y, $m);
468 if (($y == $thisyear) && ($m == $thismonth)) {
469 $tddate = intval(DateTimeFormat::localNow('j'));
472 $str_month = L10n::getDay($mtab[$m]);
473 $o = '<table class="calendar' . $class . '">';
474 $o .= "<caption>$str_month $y</caption><tr>";
475 for ($a = 0; $a < 7; $a ++) {
476 $o .= '<th>' . mb_substr(L10n::getDay($dn[$a]), 0, 3, 'UTF-8') . '</th>';
482 if (($dow == $f) && (!$started)) {
486 $today = (((isset($tddate)) && ($tddate == $d)) ? "class=\"today\" " : '');
488 $day = str_replace(' ', ' ', sprintf('%2.2d', $d));
490 if (isset($links[$d])) {
491 $o .= "<a href=\"{$links[$d]}\">$day</a>";
503 if (($dow == 7) && ($d <= $l)) {
510 for ($a = $dow; $a < 7; $a ++) {
511 $o .= '<td> </td>';
515 $o .= '</tr></table>' . "\r\n";