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;
15 require_once 'boot.php';
16 require_once 'include/text.php';
19 * @brief Temporal class
24 * @brief Two-level sort for timezones.
30 private static function timezoneCompareCallback($a, $b)
32 if (strstr($a, '/') && strstr($b, '/')) {
33 if (L10n::t($a) == L10n::t($b)) {
36 return (L10n::t($a) < L10n::t($b)) ? -1 : 1;
39 if (strstr($a, '/')) {
41 } elseif (strstr($b, '/')) {
43 } elseif (L10n::t($a) == L10n::t($b)) {
47 return (L10n::t($a) < L10n::t($b)) ? -1 : 1;
51 * @brief Emit a timezone selector grouped (primarily) by continent
53 * @param string $current Timezone
54 * @return string Parsed HTML output
56 public static function getTimezoneSelect($current = 'America/Los_Angeles')
58 $timezone_identifiers = DateTimeZone::listIdentifiers();
60 $o = '<select id="timezone_select" name="timezone">';
62 usort($timezone_identifiers, [self, 'timezoneCompareCallback']);
64 foreach ($timezone_identifiers as $value) {
65 $ex = explode("/", $value);
67 if ($ex[0] != $continent) {
68 if ($continent != '') {
72 $o .= '<optgroup label="' . L10n::t($continent) . '">';
75 $city = substr($value, strpos($value, '/') + 1);
81 if ($continent != L10n::t('Miscellaneous')) {
83 $continent = L10n::t('Miscellaneous');
84 $o .= '<optgroup label="' . L10n::t($continent) . '">';
87 $city = str_replace('_', ' ', L10n::t($city));
88 $selected = (($value == $current) ? " selected=\"selected\" " : "");
89 $o .= "<option value=\"$value\" $selected >$city</option>";
91 $o .= '</optgroup></select>';
96 * @brief Generating a Timezone selector
98 * Return a select using 'field_select_raw' template, with timezones
99 * grouped (primarily) by continent
100 * arguments follow convention as other field_* template array:
101 * 'name', 'label', $value, 'help'
103 * @param string $name Name of the selector
104 * @param string $label Label for the selector
105 * @param string $current Timezone
106 * @param string $help Help text
108 * @return string Parsed HTML
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 = get_markup_template('field_select_raw.tpl');
117 return replace_macros($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
128 public static function getDateofBirthField($dob)
130 list($year, $month, $day) = sscanf($dob, '%4d-%2d-%2d');
132 if ($dob < '0000-01-01') {
135 $value = DateTimeFormat::utc(($year > 1000) ? $dob : '1000-' . $month . '-' . $day, 'Y-m-d');
138 $age = (intval($value) ? self::getAgeByTimezone($value, $a->user["timezone"], $a->user["timezone"]) : "");
140 $tpl = get_markup_template("field_input.tpl");
141 $o = replace_macros($tpl,
145 L10n::t('Birthday:'),
147 intval($age) > 0 ? L10n::t('Age: ') . $age : "",
149 'placeholder="' . L10n::t('YYYY-MM-DD or MM-DD') . '"'
157 * @brief Returns a date selector
159 * @param string $min Unix timestamp of minimum date
160 * @param string $max Unix timestap of maximum date
161 * @param string $default Unix timestamp of default date
162 * @param string $id ID and name of datetimepicker (defaults to "datetimepicker")
164 * @return string Parsed HTML output.
166 public static function getDateField($min, $max, $default, $id = 'datepicker')
168 return self::getDateTimeField($min, $max, $default, '', $id, true, false, '', '');
172 * @brief Returns a time selector
174 * @param string $h Already selected hour
175 * @param string $m Already selected minute
176 * @param string $id ID and name of datetimepicker (defaults to "timepicker")
178 * @return string Parsed HTML output.
180 public static function getTimeField($h, $m, $id = 'timepicker')
182 return self::getDateTimeField(new DateTime(), new DateTime(), new DateTime("$h:$m"), '', $id, false, true);
186 * @brief Returns a datetime selector.
188 * @param DateTime $minDate Minimum date
189 * @param DateTime $maxDate Maximum date
190 * @param DateTime $defaultDate Default date
191 * @param string $id Id and name of datetimepicker (defaults to "datetimepicker")
192 * @param bool $pickdate true to show date picker (default)
193 * @param bool $picktime true to show time picker (default)
194 * @param string $minfrom set minimum date from picker with id $minfrom (none by default)
195 * @param string $maxfrom set maximum date from picker with id $maxfrom (none by default)
196 * @param bool $required default false
198 * @return string Parsed HTML output.
200 * @todo Once browser support is better this could probably be replaced with
201 * native HTML5 date picker.
203 public static function getDateTimeField(
206 DateTime $defaultDate,
208 $id = 'datetimepicker',
215 // First day of the week (0 = Sunday)
216 $firstDay = PConfig::get(local_user(), 'system', 'first_day_of_week', 0);
218 $lang = substr(L10n::getBrowserLanguage(), 0, 2);
220 // Check if the detected language is supported by the picker
222 ["ar", "ro", "id", "bg", "fa", "ru", "uk", "en", "el", "de", "nl", "tr", "fr", "es", "th", "pl", "pt", "ch", "se", "kr",
223 "it", "da", "no", "ja", "vi", "sl", "cs", "hu"])) {
224 $lang = Config::get('system', 'language', 'en');
231 $dateformat .= 'Y-m-d';
234 if ($pickdate && $picktime) {
239 $dateformat .= 'H:i';
242 $input_text = $defaultDate ? date($dateformat, $defaultDate->getTimestamp()) : '';
244 $readable_format = str_replace(['Y', 'm', 'd', 'H', 'i'], ['yyyy', 'mm', 'dd', 'HH', 'MM'], $dateformat);
246 $tpl = get_markup_template('field_datetime.tpl');
247 $o .= replace_macros($tpl, [
253 $required ? '*' : '',
254 'placeholder="' . $readable_format . '"'
256 '$datetimepicker' => [
257 'minDate' => $minDate,
258 'maxDate' => $maxDate,
259 'defaultDate' => $defaultDate,
260 'dateformat' => $dateformat,
261 'firstDay' => $firstDay,
263 'minfrom' => $minfrom,
264 'maxfrom' => $maxfrom,
272 * @brief Returns a relative date string.
274 * Implements "3 seconds ago" etc.
275 * Based on $posted_date, (UTC).
276 * Results relative to current timezone.
277 * Limited to range of timestamps.
279 * @param string $posted_date MySQL-formatted date string (YYYY-MM-DD HH:MM:SS)
280 * @param string $format (optional) Parsed with sprintf()
281 * <tt>%1$d %2$s ago</tt>, e.g. 22 hours ago, 1 minute ago
283 * @return string with relative date
285 public static function getRelativeDate($posted_date, $format = null)
287 $localtime = $posted_date . ' UTC';
289 $abs = strtotime($localtime);
291 if (is_null($posted_date) || $posted_date <= NULL_DATE || $abs === false) {
292 return L10n::t('never');
295 $etime = time() - $abs;
298 return L10n::t('less than a second ago');
301 $a = [12 * 30 * 24 * 60 * 60 => [L10n::t('year'), L10n::t('years')],
302 30 * 24 * 60 * 60 => [L10n::t('month'), L10n::t('months')],
303 7 * 24 * 60 * 60 => [L10n::t('week'), L10n::t('weeks')],
304 24 * 60 * 60 => [L10n::t('day'), L10n::t('days')],
305 60 * 60 => [L10n::t('hour'), L10n::t('hours')],
306 60 => [L10n::t('minute'), L10n::t('minutes')],
307 1 => [L10n::t('second'), L10n::t('seconds')]
310 foreach ($a as $secs => $str) {
314 // translators - e.g. 22 hours ago, 1 minute ago
316 $format = L10n::t('%1$d %2$s ago');
319 return sprintf($format, $r, (($r == 1) ? $str[0] : $str[1]));
325 * @brief Returns timezone correct age in years.
327 * Returns the age in years, given a date of birth, the timezone of the person
328 * whose date of birth is provided, and the timezone of the person viewing the
331 * Why? Bear with me. Let's say I live in Mittagong, Australia, and my birthday
332 * is on New Year's. You live in San Bruno, California.
333 * When exactly are you going to see my age increase?
335 * A: 5:00 AM Dec 31 San Bruno time. That's precisely when I start celebrating
336 * and become a year older. If you wish me happy birthday on January 1
337 * (San Bruno time), you'll be a day late.
339 * @param string $dob Date of Birth
340 * @param string $owner_tz (optional) Timezone of the person of interest
341 * @param string $viewer_tz (optional) Timezone of the person viewing
343 * @return int Age in years
345 public static function getAgeByTimezone($dob, $owner_tz = '', $viewer_tz = '')
351 $owner_tz = date_default_timezone_get();
354 $viewer_tz = date_default_timezone_get();
357 $birthdate = DateTimeFormat::convert($dob . ' 00:00:00+00:00', $owner_tz, 'UTC', 'Y-m-d');
358 list($year, $month, $day) = explode("-", $birthdate);
359 $year_diff = DateTimeFormat::timezoneNow($viewer_tz, 'Y') - $year;
360 $curr_month = DateTimeFormat::timezoneNow($viewer_tz, 'm');
361 $curr_day = DateTimeFormat::timezoneNow($viewer_tz, 'd');
363 if (($curr_month < $month) || (($curr_month == $month) && ($curr_day < $day))) {
371 * @brief Get days of a month in a given year.
373 * Returns number of days in the month of the given year.
374 * $m = 1 is 'January' to match human usage.
377 * @param int $m Month (1=January, 12=December)
379 * @return int Number of days in the given month
381 public static function getDaysInMonth($y, $m)
383 return date('t', mktime(0, 0, 0, $m, 1, $y));
387 * @brief Returns the first day in month for a given month, year.
392 * @param int $m Month (1=January, 12=December)
394 * @return string day 0 = Sunday through 6 = Saturday
396 private static function getFirstDayInMonth($y, $m)
398 $d = sprintf('%04d-%02d-01 00:00', intval($y), intval($m));
400 return DateTimeFormat::utc($d, 'w');
404 * @brief Output a calendar for the given month, year.
406 * If $links are provided (array), e.g. $links[12] => 'http://mylink' ,
407 * date 12 will be linked appropriately. Today's date is also noted by
409 * Months count from 1.
412 * @param int $m Month
413 * @param array $links (default null)
414 * @param string $class
418 * @todo Provide (prev, next) links, define class variations for different size calendars
420 public static function getCalendarTable($y = 0, $m = 0, $links = null, $class = '')
422 // month table - start at 1 to match human usage.
424 'January', 'February', 'March',
425 'April', 'May', 'June',
426 'July', 'August', 'September',
427 'October', 'November', 'December'
430 $thisyear = DateTimeFormat::localNow('Y');
431 $thismonth = DateTimeFormat::localNow('m');
437 $m = intval($thismonth);
440 $dn = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
441 $f = self::getFirstDayInMonth($y, $m);
442 $l = self::getDaysInMonth($y, $m);
447 if (($y == $thisyear) && ($m == $thismonth)) {
448 $tddate = intval(DateTimeFormat::localNow('j'));
451 $str_month = day_translate($mtab[$m]);
452 $o = '<table class="calendar' . $class . '">';
453 $o .= "<caption>$str_month $y</caption><tr>";
454 for ($a = 0; $a < 7; $a ++) {
455 $o .= '<th>' . mb_substr(day_translate($dn[$a]), 0, 3, 'UTF-8') . '</th>';
461 if (($dow == $f) && (!$started)) {
465 $today = (((isset($tddate)) && ($tddate == $d)) ? "class=\"today\" " : '');
467 $day = str_replace(' ', ' ', sprintf('%2.2d', $d));
469 if (x($links, $d) !== false) {
470 $o .= "<a href=\"{$links[$d]}\">$day</a>";
482 if (($dow == 7) && ($d <= $l)) {
489 for ($a = $dow; $a < 7; $a ++) {
490 $o .= '<td> </td>';
494 $o .= '</tr></table>' . "\r\n";