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
109 public static function getTimezoneField($name = 'timezone', $label = '', $current = 'America/Los_Angeles', $help = '')
111 $options = self::getTimezoneSelect($current);
112 $options = str_replace('<select id="timezone_select" name="timezone">', '', $options);
113 $options = str_replace('</select>', '', $options);
115 $tpl = Renderer::getMarkupTemplate('field_select_raw.tpl');
116 return Renderer::replaceMacros($tpl, [
117 '$field' => [$name, $label, $current, $help, $options],
122 * @brief Wrapper for date selector, tailored for use in birthday fields.
124 * @param string $dob Date of Birth
125 * @return string Formatted HTML
127 public static function getDateofBirthField($dob)
131 list($year, $month, $day) = sscanf($dob, '%4d-%2d-%2d');
133 if ($dob < '0000-01-01') {
136 $value = DateTimeFormat::utc(($year > 1000) ? $dob : '1000-' . $month . '-' . $day, 'Y-m-d');
139 $age = (intval($value) ? self::getAgeByTimezone($value, $a->user["timezone"], $a->user["timezone"]) : "");
141 $tpl = Renderer::getMarkupTemplate("field_input.tpl");
142 $o = Renderer::replaceMacros($tpl,
146 L10n::t('Birthday:'),
148 intval($age) > 0 ? L10n::t('Age: ') . $age : "",
150 'placeholder="' . L10n::t('YYYY-MM-DD or MM-DD') . '"'
158 * @brief Returns a date selector
160 * @param string $min Unix timestamp of minimum date
161 * @param string $max Unix timestap of maximum date
162 * @param string $default Unix timestamp of default date
163 * @param string $id ID and name of datetimepicker (defaults to "datetimepicker")
165 * @return string Parsed HTML output.
167 public static function getDateField($min, $max, $default, $id = 'datepicker')
169 return self::getDateTimeField($min, $max, $default, '', $id, true, false, '', '');
173 * @brief Returns a time selector
175 * @param string $h Already selected hour
176 * @param string $m Already selected minute
177 * @param string $id ID and name of datetimepicker (defaults to "timepicker")
179 * @return string Parsed HTML output.
181 public static function getTimeField($h, $m, $id = 'timepicker')
183 return self::getDateTimeField(new DateTime(), new DateTime(), new DateTime("$h:$m"), '', $id, false, true);
187 * @brief Returns a datetime selector.
189 * @param DateTime $minDate Minimum date
190 * @param DateTime $maxDate Maximum date
191 * @param DateTime $defaultDate Default date
192 * @param string $id Id and name of datetimepicker (defaults to "datetimepicker")
193 * @param bool $pickdate true to show date picker (default)
194 * @param bool $picktime true to show time picker (default)
195 * @param string $minfrom set minimum date from picker with id $minfrom (none by default)
196 * @param string $maxfrom set maximum date from picker with id $maxfrom (none by default)
197 * @param bool $required default false
199 * @return string Parsed HTML output.
201 * @todo Once browser support is better this could probably be replaced with
202 * native HTML5 date picker.
204 public static function getDateTimeField(
207 DateTime $defaultDate,
209 $id = 'datetimepicker',
216 // First day of the week (0 = Sunday)
217 $firstDay = PConfig::get(local_user(), 'system', 'first_day_of_week', 0);
219 $lang = substr(L10n::getCurrentLang(), 0, 2);
221 // Check if the detected language is supported by the picker
223 ["ar", "ro", "id", "bg", "fa", "ru", "uk", "en", "el", "de", "nl", "tr", "fr", "es", "th", "pl", "pt", "ch", "se", "kr",
224 "it", "da", "no", "ja", "vi", "sl", "cs", "hu"])) {
232 $dateformat .= 'Y-m-d';
235 if ($pickdate && $picktime) {
240 $dateformat .= 'H:i';
243 $input_text = $defaultDate ? date($dateformat, $defaultDate->getTimestamp()) : '';
245 $readable_format = str_replace(['Y', 'm', 'd', 'H', 'i'], ['yyyy', 'mm', 'dd', 'HH', 'MM'], $dateformat);
247 $tpl = Renderer::getMarkupTemplate('field_datetime.tpl');
248 $o .= Renderer::replaceMacros($tpl, [
254 $required ? '*' : '',
255 'placeholder="' . $readable_format . '"'
257 '$datetimepicker' => [
258 'minDate' => $minDate,
259 'maxDate' => $maxDate,
260 'defaultDate' => $defaultDate,
261 'dateformat' => $dateformat,
262 'firstDay' => $firstDay,
264 'minfrom' => $minfrom,
265 'maxfrom' => $maxfrom,
273 * @brief Returns a relative date string.
275 * Implements "3 seconds ago" etc.
276 * Based on $posted_date, (UTC).
277 * Results relative to current timezone.
278 * Limited to range of timestamps.
280 * @param string $posted_date MySQL-formatted date string (YYYY-MM-DD HH:MM:SS)
281 * @param string $format (optional) Parsed with sprintf()
282 * <tt>%1$d %2$s ago</tt>, e.g. 22 hours ago, 1 minute ago
284 * @return string with relative date
286 public static function getRelativeDate($posted_date, $format = null)
288 $localtime = $posted_date . ' UTC';
290 $abs = strtotime($localtime);
292 if (is_null($posted_date) || $posted_date <= DBA::NULL_DATETIME || $abs === false) {
293 return L10n::t('never');
297 $etime = time() - $abs;
299 if ($etime < 1 && $etime >= 0) {
300 return L10n::t('less than a second ago');
308 $a = [12 * 30 * 24 * 60 * 60 => [L10n::t('year'), L10n::t('years')],
309 30 * 24 * 60 * 60 => [L10n::t('month'), L10n::t('months')],
310 7 * 24 * 60 * 60 => [L10n::t('week'), L10n::t('weeks')],
311 24 * 60 * 60 => [L10n::t('day'), L10n::t('days')],
312 60 * 60 => [L10n::t('hour'), L10n::t('hours')],
313 60 => [L10n::t('minute'), L10n::t('minutes')],
314 1 => [L10n::t('second'), L10n::t('seconds')]
317 foreach ($a as $secs => $str) {
321 // translators - e.g. 22 hours ago, 1 minute ago
324 $format = L10n::t('in %1$d %2$s');
327 $format = L10n::t('%1$d %2$s ago');
331 return sprintf($format, $r, (($r == 1) ? $str[0] : $str[1]));
337 * @brief Returns timezone correct age in years.
339 * Returns the age in years, given a date of birth, the timezone of the person
340 * whose date of birth is provided, and the timezone of the person viewing the
343 * Why? Bear with me. Let's say I live in Mittagong, Australia, and my birthday
344 * is on New Year's. You live in San Bruno, California.
345 * When exactly are you going to see my age increase?
347 * A: 5:00 AM Dec 31 San Bruno time. That's precisely when I start celebrating
348 * and become a year older. If you wish me happy birthday on January 1
349 * (San Bruno time), you'll be a day late.
351 * @param string $dob Date of Birth
352 * @param string $owner_tz (optional) Timezone of the person of interest
353 * @param string $viewer_tz (optional) Timezone of the person viewing
355 * @return int Age in years
357 public static function getAgeByTimezone($dob, $owner_tz = '', $viewer_tz = '')
363 $owner_tz = date_default_timezone_get();
366 $viewer_tz = date_default_timezone_get();
369 $birthdate = DateTimeFormat::convert($dob . ' 00:00:00+00:00', $owner_tz, 'UTC', 'Y-m-d');
370 list($year, $month, $day) = explode("-", $birthdate);
371 $year_diff = DateTimeFormat::timezoneNow($viewer_tz, 'Y') - $year;
372 $curr_month = DateTimeFormat::timezoneNow($viewer_tz, 'm');
373 $curr_day = DateTimeFormat::timezoneNow($viewer_tz, 'd');
375 if (($curr_month < $month) || (($curr_month == $month) && ($curr_day < $day))) {
383 * @brief Get days of a month in a given year.
385 * Returns number of days in the month of the given year.
386 * $m = 1 is 'January' to match human usage.
389 * @param int $m Month (1=January, 12=December)
391 * @return int Number of days in the given month
393 public static function getDaysInMonth($y, $m)
395 return date('t', mktime(0, 0, 0, $m, 1, $y));
399 * @brief Returns the first day in month for a given month, year.
404 * @param int $m Month (1=January, 12=December)
406 * @return string day 0 = Sunday through 6 = Saturday
408 private static function getFirstDayInMonth($y, $m)
410 $d = sprintf('%04d-%02d-01 00:00', intval($y), intval($m));
412 return DateTimeFormat::utc($d, 'w');
416 * @brief Output a calendar for the given month, year.
418 * If $links are provided (array), e.g. $links[12] => 'http://mylink' ,
419 * date 12 will be linked appropriately. Today's date is also noted by
421 * Months count from 1.
424 * @param int $m Month
425 * @param array $links (default null)
426 * @param string $class
430 * @todo Provide (prev, next) links, define class variations for different size calendars
432 public static function getCalendarTable($y = 0, $m = 0, $links = null, $class = '')
434 // month table - start at 1 to match human usage.
436 'January', 'February', 'March',
437 'April', 'May', 'June',
438 'July', 'August', 'September',
439 'October', 'November', 'December'
442 $thisyear = DateTimeFormat::localNow('Y');
443 $thismonth = DateTimeFormat::localNow('m');
449 $m = intval($thismonth);
452 $dn = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
453 $f = self::getFirstDayInMonth($y, $m);
454 $l = self::getDaysInMonth($y, $m);
459 if (($y == $thisyear) && ($m == $thismonth)) {
460 $tddate = intval(DateTimeFormat::localNow('j'));
463 $str_month = L10n::getDay($mtab[$m]);
464 $o = '<table class="calendar' . $class . '">';
465 $o .= "<caption>$str_month $y</caption><tr>";
466 for ($a = 0; $a < 7; $a ++) {
467 $o .= '<th>' . mb_substr(L10n::getDay($dn[$a]), 0, 3, 'UTF-8') . '</th>';
473 if (($dow == $f) && (!$started)) {
477 $today = (((isset($tddate)) && ($tddate == $d)) ? "class=\"today\" " : '');
479 $day = str_replace(' ', ' ', sprintf('%2.2d', $d));
481 if (isset($links[$d])) {
482 $o .= "<a href=\"{$links[$d]}\">$day</a>";
494 if (($dow == 7) && ($d <= $l)) {
501 for ($a = $dow; $a < 7; $a ++) {
502 $o .= '<td> </td>';
506 $o .= '</tr></table>' . "\r\n";