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\Database\DBA;
16 require_once 'boot.php';
17 require_once 'include/text.php';
20 * @brief Temporal class
25 * @brief Two-level sort for timezones.
31 private static function timezoneCompareCallback($a, $b)
33 if (strstr($a, '/') && strstr($b, '/')) {
34 if (L10n::t($a) == L10n::t($b)) {
37 return (L10n::t($a) < L10n::t($b)) ? -1 : 1;
40 if (strstr($a, '/')) {
42 } elseif (strstr($b, '/')) {
44 } elseif (L10n::t($a) == L10n::t($b)) {
48 return (L10n::t($a) < L10n::t($b)) ? -1 : 1;
52 * @brief Emit a timezone selector grouped (primarily) by continent
54 * @param string $current Timezone
55 * @return string Parsed HTML output
57 public static function getTimezoneSelect($current = 'America/Los_Angeles')
59 $timezone_identifiers = DateTimeZone::listIdentifiers();
61 $o = '<select id="timezone_select" name="timezone">';
63 usort($timezone_identifiers, [__CLASS__, 'timezoneCompareCallback']);
65 foreach ($timezone_identifiers as $value) {
66 $ex = explode("/", $value);
68 if ($ex[0] != $continent) {
69 if ($continent != '') {
73 $o .= '<optgroup label="' . L10n::t($continent) . '">';
76 $city = substr($value, strpos($value, '/') + 1);
82 if ($continent != L10n::t('Miscellaneous')) {
84 $continent = L10n::t('Miscellaneous');
85 $o .= '<optgroup label="' . L10n::t($continent) . '">';
88 $city = str_replace('_', ' ', L10n::t($city));
89 $selected = (($value == $current) ? " selected=\"selected\" " : "");
90 $o .= "<option value=\"$value\" $selected >$city</option>";
92 $o .= '</optgroup></select>';
97 * @brief Generating a Timezone selector
99 * Return a select using 'field_select_raw' template, with timezones
100 * grouped (primarily) by continent
101 * arguments follow convention as other field_* template array:
102 * 'name', 'label', $value, 'help'
104 * @param string $name Name of the selector
105 * @param string $label Label for the selector
106 * @param string $current Timezone
107 * @param string $help Help text
109 * @return string Parsed HTML
111 public static function getTimezoneField($name = 'timezone', $label = '', $current = 'America/Los_Angeles', $help = '')
113 $options = self::getTimezoneSelect($current);
114 $options = str_replace('<select id="timezone_select" name="timezone">', '', $options);
115 $options = str_replace('</select>', '', $options);
117 $tpl = get_markup_template('field_select_raw.tpl');
118 return replace_macros($tpl, [
119 '$field' => [$name, $label, $current, $help, $options],
124 * @brief Wrapper for date selector, tailored for use in birthday fields.
126 * @param string $dob Date of Birth
127 * @return string Formatted HTML
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 = get_markup_template("field_input.tpl");
144 $o = replace_macros($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.
169 public static function getDateField($min, $max, $default, $id = 'datepicker')
171 return self::getDateTimeField($min, $max, $default, '', $id, true, false, '', '');
175 * @brief Returns a time selector
177 * @param string $h Already selected hour
178 * @param string $m Already selected minute
179 * @param string $id ID and name of datetimepicker (defaults to "timepicker")
181 * @return string Parsed HTML output.
183 public static function getTimeField($h, $m, $id = 'timepicker')
185 return self::getDateTimeField(new DateTime(), new DateTime(), new DateTime("$h:$m"), '', $id, false, true);
189 * @brief Returns a datetime selector.
191 * @param DateTime $minDate Minimum date
192 * @param DateTime $maxDate Maximum date
193 * @param DateTime $defaultDate Default date
194 * @param string $id Id and name of datetimepicker (defaults to "datetimepicker")
195 * @param bool $pickdate true to show date picker (default)
196 * @param bool $picktime true to show time picker (default)
197 * @param string $minfrom set minimum date from picker with id $minfrom (none by default)
198 * @param string $maxfrom set maximum date from picker with id $maxfrom (none by default)
199 * @param bool $required default false
201 * @return string Parsed HTML output.
203 * @todo Once browser support is better this could probably be replaced with
204 * native HTML5 date picker.
206 public static function getDateTimeField(
209 DateTime $defaultDate,
211 $id = 'datetimepicker',
218 // First day of the week (0 = Sunday)
219 $firstDay = PConfig::get(local_user(), 'system', 'first_day_of_week', 0);
221 $lang = substr(L10n::getCurrentLang(), 0, 2);
223 // Check if the detected language is supported by the picker
225 ["ar", "ro", "id", "bg", "fa", "ru", "uk", "en", "el", "de", "nl", "tr", "fr", "es", "th", "pl", "pt", "ch", "se", "kr",
226 "it", "da", "no", "ja", "vi", "sl", "cs", "hu"])) {
234 $dateformat .= 'Y-m-d';
237 if ($pickdate && $picktime) {
242 $dateformat .= 'H:i';
245 $input_text = $defaultDate ? date($dateformat, $defaultDate->getTimestamp()) : '';
247 $readable_format = str_replace(['Y', 'm', 'd', 'H', 'i'], ['yyyy', 'mm', 'dd', 'HH', 'MM'], $dateformat);
249 $tpl = get_markup_template('field_datetime.tpl');
250 $o .= replace_macros($tpl, [
256 $required ? '*' : '',
257 'placeholder="' . $readable_format . '"'
259 '$datetimepicker' => [
260 'minDate' => $minDate,
261 'maxDate' => $maxDate,
262 'defaultDate' => $defaultDate,
263 'dateformat' => $dateformat,
264 'firstDay' => $firstDay,
266 'minfrom' => $minfrom,
267 'maxfrom' => $maxfrom,
275 * @brief Returns a relative date string.
277 * Implements "3 seconds ago" etc.
278 * Based on $posted_date, (UTC).
279 * Results relative to current timezone.
280 * Limited to range of timestamps.
282 * @param string $posted_date MySQL-formatted date string (YYYY-MM-DD HH:MM:SS)
283 * @param string $format (optional) Parsed with sprintf()
284 * <tt>%1$d %2$s ago</tt>, e.g. 22 hours ago, 1 minute ago
286 * @return string with relative date
288 public static function getRelativeDate($posted_date, $format = null)
290 $localtime = $posted_date . ' UTC';
292 $abs = strtotime($localtime);
294 if (is_null($posted_date) || $posted_date <= DBA::NULL_DATETIME || $abs === false) {
295 return L10n::t('never');
299 $etime = time() - $abs;
301 if ($etime < 1 && $etime >= 0) {
302 return L10n::t('less than a second ago');
310 $a = [12 * 30 * 24 * 60 * 60 => [L10n::t('year'), L10n::t('years')],
311 30 * 24 * 60 * 60 => [L10n::t('month'), L10n::t('months')],
312 7 * 24 * 60 * 60 => [L10n::t('week'), L10n::t('weeks')],
313 24 * 60 * 60 => [L10n::t('day'), L10n::t('days')],
314 60 * 60 => [L10n::t('hour'), L10n::t('hours')],
315 60 => [L10n::t('minute'), L10n::t('minutes')],
316 1 => [L10n::t('second'), L10n::t('seconds')]
319 foreach ($a as $secs => $str) {
323 // translators - e.g. 22 hours ago, 1 minute ago
326 $format = L10n::t('in %1$d %2$s');
329 $format = L10n::t('%1$d %2$s ago');
333 return sprintf($format, $r, (($r == 1) ? $str[0] : $str[1]));
339 * @brief Returns timezone correct age in years.
341 * Returns the age in years, given a date of birth, the timezone of the person
342 * whose date of birth is provided, and the timezone of the person viewing the
345 * Why? Bear with me. Let's say I live in Mittagong, Australia, and my birthday
346 * is on New Year's. You live in San Bruno, California.
347 * When exactly are you going to see my age increase?
349 * A: 5:00 AM Dec 31 San Bruno time. That's precisely when I start celebrating
350 * and become a year older. If you wish me happy birthday on January 1
351 * (San Bruno time), you'll be a day late.
353 * @param string $dob Date of Birth
354 * @param string $owner_tz (optional) Timezone of the person of interest
355 * @param string $viewer_tz (optional) Timezone of the person viewing
357 * @return int Age in years
359 public static function getAgeByTimezone($dob, $owner_tz = '', $viewer_tz = '')
365 $owner_tz = date_default_timezone_get();
368 $viewer_tz = date_default_timezone_get();
371 $birthdate = DateTimeFormat::convert($dob . ' 00:00:00+00:00', $owner_tz, 'UTC', 'Y-m-d');
372 list($year, $month, $day) = explode("-", $birthdate);
373 $year_diff = DateTimeFormat::timezoneNow($viewer_tz, 'Y') - $year;
374 $curr_month = DateTimeFormat::timezoneNow($viewer_tz, 'm');
375 $curr_day = DateTimeFormat::timezoneNow($viewer_tz, 'd');
377 if (($curr_month < $month) || (($curr_month == $month) && ($curr_day < $day))) {
385 * @brief Get days of a month in a given year.
387 * Returns number of days in the month of the given year.
388 * $m = 1 is 'January' to match human usage.
391 * @param int $m Month (1=January, 12=December)
393 * @return int Number of days in the given month
395 public static function getDaysInMonth($y, $m)
397 return date('t', mktime(0, 0, 0, $m, 1, $y));
401 * @brief Returns the first day in month for a given month, year.
406 * @param int $m Month (1=January, 12=December)
408 * @return string day 0 = Sunday through 6 = Saturday
410 private static function getFirstDayInMonth($y, $m)
412 $d = sprintf('%04d-%02d-01 00:00', intval($y), intval($m));
414 return DateTimeFormat::utc($d, 'w');
418 * @brief Output a calendar for the given month, year.
420 * If $links are provided (array), e.g. $links[12] => 'http://mylink' ,
421 * date 12 will be linked appropriately. Today's date is also noted by
423 * Months count from 1.
426 * @param int $m Month
427 * @param array $links (default null)
428 * @param string $class
432 * @todo Provide (prev, next) links, define class variations for different size calendars
434 public static function getCalendarTable($y = 0, $m = 0, $links = null, $class = '')
436 // month table - start at 1 to match human usage.
438 'January', 'February', 'March',
439 'April', 'May', 'June',
440 'July', 'August', 'September',
441 'October', 'November', 'December'
444 $thisyear = DateTimeFormat::localNow('Y');
445 $thismonth = DateTimeFormat::localNow('m');
451 $m = intval($thismonth);
454 $dn = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
455 $f = self::getFirstDayInMonth($y, $m);
456 $l = self::getDaysInMonth($y, $m);
461 if (($y == $thisyear) && ($m == $thismonth)) {
462 $tddate = intval(DateTimeFormat::localNow('j'));
465 $str_month = day_translate($mtab[$m]);
466 $o = '<table class="calendar' . $class . '">';
467 $o .= "<caption>$str_month $y</caption><tr>";
468 for ($a = 0; $a < 7; $a ++) {
469 $o .= '<th>' . mb_substr(day_translate($dn[$a]), 0, 3, 'UTF-8') . '</th>';
475 if (($dow == $f) && (!$started)) {
479 $today = (((isset($tddate)) && ($tddate == $d)) ? "class=\"today\" " : '');
481 $day = str_replace(' ', ' ', sprintf('%2.2d', $d));
483 if (x($links, $d) !== false) {
484 $o .= "<a href=\"{$links[$d]}\">$day</a>";
496 if (($dow == 7) && ($d <= $l)) {
503 for ($a = $dow; $a < 7; $a ++) {
504 $o .= '<td> </td>';
508 $o .= '</tr></table>' . "\r\n";