4 * @file src/Util/Temporal.php
7 namespace Friendica\Util;
12 use Friendica\Core\Config;
13 use Friendica\Core\L10n;
14 use Friendica\Core\PConfig;
16 require_once 'boot.php';
17 require_once 'include/text.php';
20 * @brief Temporal class
24 const ATOM = 'Y-m-d\TH:i:s\Z';
25 const MYSQL = 'Y-m-d H:i:s';
28 * @brief Two-level sort for timezones.
34 private static function timezoneCompareCallback($a, $b)
36 if (strstr($a, '/') && strstr($b, '/')) {
37 if (L10n::t($a) == L10n::t($b)) {
40 return (L10n::t($a) < L10n::t($b)) ? -1 : 1;
43 if (strstr($a, '/')) {
45 } elseif (strstr($b, '/')) {
47 } elseif (L10n::t($a) == L10n::t($b)) {
51 return (L10n::t($a) < L10n::t($b)) ? -1 : 1;
55 * @brief Emit a timezone selector grouped (primarily) by continent
57 * @param string $current Timezone
58 * @return string Parsed HTML output
60 public static function getTimezoneSelect($current = 'America/Los_Angeles')
62 $timezone_identifiers = DateTimeZone::listIdentifiers();
64 $o = '<select id="timezone_select" name="timezone">';
66 usort($timezone_identifiers, [self, 'timezoneCompareCallback']);
68 foreach ($timezone_identifiers as $value) {
69 $ex = explode("/", $value);
71 if ($ex[0] != $continent) {
72 if ($continent != '') {
76 $o .= '<optgroup label="' . L10n::t($continent) . '">';
79 $city = substr($value, strpos($value, '/') + 1);
85 if ($continent != L10n::t('Miscellaneous')) {
87 $continent = L10n::t('Miscellaneous');
88 $o .= '<optgroup label="' . L10n::t($continent) . '">';
91 $city = str_replace('_', ' ', L10n::t($city));
92 $selected = (($value == $current) ? " selected=\"selected\" " : "");
93 $o .= "<option value=\"$value\" $selected >$city</option>";
95 $o .= '</optgroup></select>';
100 * @brief Generating a Timezone selector
102 * Return a select using 'field_select_raw' template, with timezones
103 * grouped (primarily) by continent
104 * arguments follow convention as other field_* template array:
105 * 'name', 'label', $value, 'help'
107 * @param string $name Name of the selector
108 * @param string $label Label for the selector
109 * @param string $current Timezone
110 * @param string $help Help text
112 * @return string Parsed HTML
114 public static function getTimezoneField($name = 'timezone', $label = '', $current = 'America/Los_Angeles', $help = '')
116 $options = self::getTimezoneSelect($current);
117 $options = str_replace('<select id="timezone_select" name="timezone">', '', $options);
118 $options = str_replace('</select>', '', $options);
120 $tpl = get_markup_template('field_select_raw.tpl');
121 return replace_macros($tpl, [
122 '$field' => [$name, $label, $current, $help, $options],
127 * convert() shorthand for UTC.
129 * @param string $time A date/time string
130 * @param string $format DateTime format string or Temporal constant
133 public static function utc($time, $format = self::MYSQL)
135 return self::convert($time, 'UTC', 'UTC', $format);
139 * convert() shorthand for timezoned now.
141 * @param string $format DateTime format string or Temporal constant
144 public static function timezoneNow($timezone, $format = self::MYSQL)
146 return self::convert('now', $timezone, 'UTC', $format);
150 * convert() shorthand for local now.
152 * @param string $format DateTime format string or Temporal constant
155 public static function localNow($format = self::MYSQL)
157 return self::convert('now', date_default_timezone_get(), 'UTC', $format);
161 * convert() shorthand for UTC now.
163 * @param string $format DateTime format string or Temporal constant
166 public static function utcNow($format = self::MYSQL)
168 return self::convert('now', 'UTC', 'UTC', $format);
172 * @brief General purpose date parse/convert/format function.
174 * @param string $s Some parseable date/time string
175 * @param string $tz_to Destination timezone
176 * @param string $tz_from Source timezone
177 * @param string $format Output format recognised from php's DateTime class
178 * http://www.php.net/manual/en/datetime.format.php
180 * @return string Formatted date according to given format
182 public static function convert($s = 'now', $tz_to = 'UTC', $tz_from = 'UTC', $format = self::MYSQL)
184 // Defaults to UTC if nothing is set, but throws an exception if set to empty string.
185 // Provide some sane defaults regardless.
194 if (($s === '') || (!is_string($s))) {
199 * Slight hackish adjustment so that 'zero' datetime actually returns what is intended
200 * otherwise we end up with -0001-11-30 ...
201 * add 32 days so that we at least get year 00, and then hack around the fact that
202 * months and days always start with 1.
204 if (substr($s, 0, 10) <= '0001-01-01') {
205 $d = new DateTime($s . ' + 32 days', new DateTimeZone('UTC'));
206 return str_replace('1', '0', $d->format($format));
210 $from_obj = new DateTimeZone($tz_from);
211 } catch (Exception $e) {
212 $from_obj = new DateTimeZone('UTC');
216 $d = new DateTime($s, $from_obj);
217 } catch (Exception $e) {
218 logger('datetime_convert: exception: ' . $e->getMessage());
219 $d = new DateTime('now', $from_obj);
223 $to_obj = new DateTimeZone($tz_to);
224 } catch (Exception $e) {
225 $to_obj = new DateTimeZone('UTC');
228 $d->setTimeZone($to_obj);
230 return $d->format($format);
234 * @brief Wrapper for date selector, tailored for use in birthday fields.
236 * @param string $dob Date of Birth
237 * @return string Formatted HTML
239 public static function getDateofBirthField($dob)
241 list($year, $month, $day) = sscanf($dob, '%4d-%2d-%2d');
243 if ($dob < '0000-01-01') {
246 $value = self::utc(($year > 1000) ? $dob : '1000-' . $month . '-' . $day, 'Y-m-d');
249 $age = (intval($value) ? age($value, $a->user["timezone"], $a->user["timezone"]) : "");
251 $tpl = get_markup_template("field_input.tpl");
252 $o = replace_macros($tpl,
256 L10n::t('Birthday:'),
258 intval($age) > 0 ? L10n::t('Age: ') . $age : "",
260 'placeholder="' . L10n::t('YYYY-MM-DD or MM-DD') . '"'
268 * @brief Returns a date selector
270 * @param string $min Unix timestamp of minimum date
271 * @param string $max Unix timestap of maximum date
272 * @param string $default Unix timestamp of default date
273 * @param string $id ID and name of datetimepicker (defaults to "datetimepicker")
275 * @return string Parsed HTML output.
277 public static function getDateField($min, $max, $default, $id = 'datepicker')
279 return datetimesel($min, $max, $default, '', $id, true, false, '', '');
283 * @brief Returns a time selector
285 * @param string $h Already selected hour
286 * @param string $m Already selected minute
287 * @param string $id ID and name of datetimepicker (defaults to "timepicker")
289 * @return string Parsed HTML output.
291 public static function getTimeField($h, $m, $id = 'timepicker')
293 return datetimesel(new DateTime(), new DateTime(), new DateTime("$h:$m"), '', $id, false, true);
297 * @brief Returns a datetime selector.
299 * @param string $min Unix timestamp of minimum date
300 * @param string $max Unix timestamp of maximum date
301 * @param string $default Unix timestamp of default date
302 * @param string $id Id and name of datetimepicker (defaults to "datetimepicker")
303 * @param bool $pickdate true to show date picker (default)
304 * @param bool $picktime true to show time picker (default)
305 * @param string $minfrom set minimum date from picker with id $minfrom (none by default)
306 * @param string $maxfrom set maximum date from picker with id $maxfrom (none by default)
307 * @param bool $required default false
309 * @return string Parsed HTML output.
311 * @todo Once browser support is better this could probably be replaced with
312 * native HTML5 date picker.
314 public static function getDateTimeField($min, $max, $default, $label, $id = 'datetimepicker', $pickdate = true,
315 $picktime = true, $minfrom = '', $maxfrom = '', $required = false)
317 // First day of the week (0 = Sunday)
318 $firstDay = PConfig::get(local_user(), 'system', 'first_day_of_week', 0);
320 $lang = substr(L10n::getBrowserLanguage(), 0, 2);
322 // Check if the detected language is supported by the picker
324 ["ar", "ro", "id", "bg", "fa", "ru", "uk", "en", "el", "de", "nl", "tr", "fr", "es", "th", "pl", "pt", "ch", "se", "kr",
325 "it", "da", "no", "ja", "vi", "sl", "cs", "hu"])) {
326 $lang = Config::get('system', 'language', 'en');
333 $dateformat .= 'Y-m-d';
336 if ($pickdate && $picktime) {
341 $dateformat .= 'H:i';
344 $minjs = $min ? ",minDate: new Date({$min->getTimestamp()}*1000), yearStart: " . $min->format('Y') : '';
345 $maxjs = $max ? ",maxDate: new Date({$max->getTimestamp()}*1000), yearEnd: " . $max->format('Y') : '';
347 $input_text = $default ? date($dateformat, $default->getTimestamp()) : '';
348 $defaultdatejs = $default ? ",defaultDate: new Date({$default->getTimestamp()}*1000)" : '';
352 $pickers .= ', datepicker: false';
356 $pickers .= ',timepicker: false';
360 $pickers .= ",dayOfWeekStart: " . $firstDay . ",lang:'" . $lang . "'";
361 if ($minfrom != '') {
362 $extra_js .= "\$('#id_$minfrom').data('xdsoft_datetimepicker').setOptions({onChangeDateTime: function (currentDateTime) { \$('#id_$id').data('xdsoft_datetimepicker').setOptions({minDate: currentDateTime})}})";
365 if ($maxfrom != '') {
366 $extra_js .= "\$('#id_$maxfrom').data('xdsoft_datetimepicker').setOptions({onChangeDateTime: function (currentDateTime) { \$('#id_$id').data('xdsoft_datetimepicker').setOptions({maxDate: currentDateTime})}})";
369 $readable_format = $dateformat;
370 $readable_format = str_replace('Y', 'yyyy', $readable_format);
371 $readable_format = str_replace('m', 'mm', $readable_format);
372 $readable_format = str_replace('d', 'dd', $readable_format);
373 $readable_format = str_replace('H', 'HH', $readable_format);
374 $readable_format = str_replace('i', 'MM', $readable_format);
376 $tpl = get_markup_template('field_input.tpl');
377 $o .= replace_macros($tpl,
384 $required ? '*' : '',
385 'placeholder="' . $readable_format . '"'
389 $o .= "<script type='text/javascript'>";
390 $o .= "\$(function () {var picker = \$('#id_$id').datetimepicker({step:5,format:'$dateformat' $minjs $maxjs $pickers $defaultdatejs}); $extra_js})";
397 * @brief Returns a relative date string.
399 * Implements "3 seconds ago" etc.
400 * Based on $posted_date, (UTC).
401 * Results relative to current timezone.
402 * Limited to range of timestamps.
404 * @param string $posted_date MySQL-formatted date string (YYYY-MM-DD HH:MM:SS)
405 * @param string $format (optional) Parsed with sprintf()
406 * <tt>%1$d %2$s ago</tt>, e.g. 22 hours ago, 1 minute ago
408 * @return string with relative date
410 public static function getRelativeDate($posted_date, $format = null)
412 $localtime = $posted_date . ' UTC';
414 $abs = strtotime($localtime);
416 if (is_null($posted_date) || $posted_date <= NULL_DATE || $abs === false) {
417 return L10n::t('never');
420 $etime = time() - $abs;
423 return L10n::t('less than a second ago');
426 $a = [12 * 30 * 24 * 60 * 60 => [L10n::t('year'), L10n::t('years')],
427 30 * 24 * 60 * 60 => [L10n::t('month'), L10n::t('months')],
428 7 * 24 * 60 * 60 => [L10n::t('week'), L10n::t('weeks')],
429 24 * 60 * 60 => [L10n::t('day'), L10n::t('days')],
430 60 * 60 => [L10n::t('hour'), L10n::t('hours')],
431 60 => [L10n::t('minute'), L10n::t('minutes')],
432 1 => [L10n::t('second'), L10n::t('seconds')]
435 foreach ($a as $secs => $str) {
439 // translators - e.g. 22 hours ago, 1 minute ago
441 $format = L10n::t('%1$d %2$s ago');
444 return sprintf($format, $r, (($r == 1) ? $str[0] : $str[1]));
450 * @brief Returns timezone correct age in years.
452 * Returns the age in years, given a date of birth, the timezone of the person
453 * whose date of birth is provided, and the timezone of the person viewing the
456 * Why? Bear with me. Let's say I live in Mittagong, Australia, and my birthday
457 * is on New Year's. You live in San Bruno, California.
458 * When exactly are you going to see my age increase?
460 * A: 5:00 AM Dec 31 San Bruno time. That's precisely when I start celebrating
461 * and become a year older. If you wish me happy birthday on January 1
462 * (San Bruno time), you'll be a day late.
464 * @param string $dob Date of Birth
465 * @param string $owner_tz (optional) Timezone of the person of interest
466 * @param string $viewer_tz (optional) Timezone of the person viewing
468 * @return int Age in years
470 public static function getAgeByTimezone($dob, $owner_tz = '', $viewer_tz = '')
476 $owner_tz = date_default_timezone_get();
479 $viewer_tz = date_default_timezone_get();
482 $birthdate = self::convert($dob . ' 00:00:00+00:00', $owner_tz, 'UTC', 'Y-m-d');
483 list($year, $month, $day) = explode("-", $birthdate);
484 $year_diff = self::timezoneNow($viewer_tz, 'Y') - $year;
485 $curr_month = self::timezoneNow($viewer_tz, 'm');
486 $curr_day = self::timezoneNow($viewer_tz, 'd');
488 if (($curr_month < $month) || (($curr_month == $month) && ($curr_day < $day))) {
496 * @brief Get days of a month in a given year.
498 * Returns number of days in the month of the given year.
499 * $m = 1 is 'January' to match human usage.
502 * @param int $m Month (1=January, 12=December)
504 * @return int Number of days in the given month
506 public static function getDaysInMonth($y, $m)
508 return date('t', mktime(0, 0, 0, $m, 1, $y));
513 * @brief Returns the first day in month for a given month, year.
518 * @param int $m Month (1=January, 12=December)
520 * @return string day 0 = Sunday through 6 = Saturday
522 public static function getFirstDayInMonth($y, $m)
524 $d = sprintf('%04d-%02d-01 00:00', intval($y), intval($m));
526 return self::utc($d, 'w');
530 * @brief Output a calendar for the given month, year.
532 * If $links are provided (array), e.g. $links[12] => 'http://mylink' ,
533 * date 12 will be linked appropriately. Today's date is also noted by
535 * Months count from 1.
538 * @param int $m Month
539 * @param array $links (default null)
540 * @param string $class
544 * @todo Provide (prev, next) links, define class variations for different size calendars
546 public static function getCalendarTable($y = 0, $m = 0, $links = null, $class = '')
548 // month table - start at 1 to match human usage.
550 'January', 'February', 'March',
551 'April', 'May', 'June',
552 'July', 'August', 'September',
553 'October', 'November', 'December'
556 $thisyear = self::localNow('Y');
557 $thismonth = self::localNow('m');
563 $m = intval($thismonth);
566 $dn = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
567 $f = get_first_dim($y, $m);
568 $l = get_dim($y, $m);
573 if (($y == $thisyear) && ($m == $thismonth)) {
574 $tddate = intval(self::localNow('j'));
577 $str_month = day_translate($mtab[$m]);
578 $o = '<table class="calendar' . $class . '">';
579 $o .= "<caption>$str_month $y</caption><tr>";
580 for ($a = 0; $a < 7; $a ++) {
581 $o .= '<th>' . mb_substr(day_translate($dn[$a]), 0, 3, 'UTF-8') . '</th>';
587 if (($dow == $f) && (!$started)) {
591 $today = (((isset($tddate)) && ($tddate == $d)) ? "class=\"today\" " : '');
593 $day = str_replace(' ', ' ', sprintf('%2.2d', $d));
595 if (x($links, $d) !== false) {
596 $o .= "<a href=\"{$links[$d]}\">$day</a>";
608 if (($dow == 7) && ($d <= $l)) {
615 for ($a = $dow; $a < 7; $a ++) {
616 $o .= '<td> </td>';
620 $o .= '</tr></table>' . "\r\n";