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
26 * @brief Two-level sort for timezones.
32 private static function timezoneCompareCallback($a, $b)
34 if (strstr($a, '/') && strstr($b, '/')) {
35 if (L10n::t($a) == L10n::t($b)) {
38 return (L10n::t($a) < L10n::t($b)) ? -1 : 1;
41 if (strstr($a, '/')) {
43 } elseif (strstr($b, '/')) {
45 } elseif (L10n::t($a) == L10n::t($b)) {
49 return (L10n::t($a) < L10n::t($b)) ? -1 : 1;
53 * @brief Emit a timezone selector grouped (primarily) by continent
55 * @param string $current Timezone
56 * @return string Parsed HTML output
58 public static function getTimezoneSelect($current = 'America/Los_Angeles')
60 $timezone_identifiers = DateTimeZone::listIdentifiers();
62 $o = '<select id="timezone_select" name="timezone">';
64 usort($timezone_identifiers, [self, 'timezoneCompareCallback']);
66 foreach ($timezone_identifiers as $value) {
67 $ex = explode("/", $value);
69 if ($ex[0] != $continent) {
70 if ($continent != '') {
74 $o .= '<optgroup label="' . L10n::t($continent) . '">';
77 $city = substr($value, strpos($value, '/') + 1);
83 if ($continent != L10n::t('Miscellaneous')) {
85 $continent = L10n::t('Miscellaneous');
86 $o .= '<optgroup label="' . L10n::t($continent) . '">';
89 $city = str_replace('_', ' ', L10n::t($city));
90 $selected = (($value == $current) ? " selected=\"selected\" " : "");
91 $o .= "<option value=\"$value\" $selected >$city</option>";
93 $o .= '</optgroup></select>';
98 * @brief Generating a Timezone selector
100 * Return a select using 'field_select_raw' template, with timezones
101 * grouped (primarily) by continent
102 * arguments follow convention as other field_* template array:
103 * 'name', 'label', $value, 'help'
105 * @param string $name Name of the selector
106 * @param string $label Label for the selector
107 * @param string $current Timezone
108 * @param string $help Help text
110 * @return string Parsed HTML
112 public static function getTimezoneField($name = 'timezone', $label = '', $current = 'America/Los_Angeles', $help = '')
114 $options = Temporal::getTimezoneSelect($current);
115 $options = str_replace('<select id="timezone_select" name="timezone">', '', $options);
116 $options = str_replace('</select>', '', $options);
118 $tpl = get_markup_template('field_select_raw.tpl');
119 return replace_macros($tpl, [
120 '$field' => [$name, $label, $current, $help, $options],
125 * @brief General purpose date parse/convert function.
127 * @param string $s Some parseable date/time string
128 * @param string $from Source timezone
129 * @param string $to Dest timezone
130 * @param string $fmt Output format recognised from php's DateTime class
131 * http://www.php.net/manual/en/datetime.format.php
133 * @return string Formatted date according to given format
135 public static function convert($s = 'now', $to = 'UTC', $from = 'UTC', $fmt = "Y-m-d H:i:s")
137 // Defaults to UTC if nothing is set, but throws an exception if set to empty string.
138 // Provide some sane defaults regardless.
147 if (($s === '') || (!is_string($s))) {
152 * Slight hackish adjustment so that 'zero' datetime actually returns what is intended
153 * otherwise we end up with -0001-11-30 ...
154 * add 32 days so that we at least get year 00, and then hack around the fact that
155 * months and days always start with 1.
158 if (substr($s, 0, 10) <= '0001-01-01') {
159 $d = new DateTime($s . ' + 32 days', new DateTimeZone('UTC'));
160 return str_replace('1', '0', $d->format($fmt));
164 $from_obj = new DateTimeZone($from);
165 } catch (Exception $e) {
166 $from_obj = new DateTimeZone('UTC');
170 $d = new DateTime($s, $from_obj);
171 } catch (Exception $e) {
172 logger('datetime_convert: exception: ' . $e->getMessage());
173 $d = new DateTime('now', $from_obj);
177 $to_obj = new DateTimeZone($to);
178 } catch (Exception $e) {
179 $to_obj = new DateTimeZone('UTC');
182 $d->setTimeZone($to_obj);
184 return $d->format($fmt);
188 * @brief Wrapper for date selector, tailored for use in birthday fields.
190 * @param string $dob Date of Birth
191 * @return string Formatted HTML
193 public static function getDateofBirthField($dob)
195 list($year, $month, $day) = sscanf($dob, '%4d-%2d-%2d');
197 if ($dob < '0000-01-01') {
200 $value = Temporal::convert(($year > 1000) ? $dob : '1000-' . $month . '-' . $day, 'UTC', 'UTC', 'Y-m-d');
203 $age = (intval($value) ? age($value, $a->user["timezone"], $a->user["timezone"]) : "");
205 $tpl = get_markup_template("field_input.tpl");
206 $o = replace_macros($tpl,
210 L10n::t('Birthday:'),
212 intval($age) > 0 ? L10n::t('Age: ') . $age : "",
214 'placeholder="' . L10n::t('YYYY-MM-DD or MM-DD') . '"'
222 * @brief Returns a date selector
224 * @param string $min Unix timestamp of minimum date
225 * @param string $max Unix timestap of maximum date
226 * @param string $default Unix timestamp of default date
227 * @param string $id ID and name of datetimepicker (defaults to "datetimepicker")
229 * @return string Parsed HTML output.
231 public static function getDateField($min, $max, $default, $id = 'datepicker')
233 return datetimesel($min, $max, $default, '', $id, true, false, '', '');
237 * @brief Returns a time selector
239 * @param string $h Already selected hour
240 * @param string $m Already selected minute
241 * @param string $id ID and name of datetimepicker (defaults to "timepicker")
243 * @return string Parsed HTML output.
245 public static function getTimeField($h, $m, $id = 'timepicker')
247 return datetimesel(new DateTime(), new DateTime(), new DateTime("$h:$m"), '', $id, false, true);
251 * @brief Returns a datetime selector.
253 * @param string $min Unix timestamp of minimum date
254 * @param string $max Unix timestamp of maximum date
255 * @param string $default Unix timestamp of default date
256 * @param string $id Id and name of datetimepicker (defaults to "datetimepicker")
257 * @param bool $pickdate true to show date picker (default)
258 * @param bool $picktime true to show time picker (default)
259 * @param string $minfrom set minimum date from picker with id $minfrom (none by default)
260 * @param string $maxfrom set maximum date from picker with id $maxfrom (none by default)
261 * @param bool $required default false
263 * @return string Parsed HTML output.
265 * @todo Once browser support is better this could probably be replaced with
266 * native HTML5 date picker.
268 public static function getDateTimeField($min, $max, $default, $label, $id = 'datetimepicker', $pickdate = true,
269 $picktime = true, $minfrom = '', $maxfrom = '', $required = false)
271 // First day of the week (0 = Sunday)
272 $firstDay = PConfig::get(local_user(), 'system', 'first_day_of_week', 0);
274 $lang = substr(L10n::getBrowserLanguage(), 0, 2);
276 // Check if the detected language is supported by the picker
278 ["ar", "ro", "id", "bg", "fa", "ru", "uk", "en", "el", "de", "nl", "tr", "fr", "es", "th", "pl", "pt", "ch", "se", "kr",
279 "it", "da", "no", "ja", "vi", "sl", "cs", "hu"])) {
280 $lang = Config::get('system', 'language', 'en');
287 $dateformat .= 'Y-m-d';
290 if ($pickdate && $picktime) {
295 $dateformat .= 'H:i';
298 $minjs = $min ? ",minDate: new Date({$min->getTimestamp()}*1000), yearStart: " . $min->format('Y') : '';
299 $maxjs = $max ? ",maxDate: new Date({$max->getTimestamp()}*1000), yearEnd: " . $max->format('Y') : '';
301 $input_text = $default ? date($dateformat, $default->getTimestamp()) : '';
302 $defaultdatejs = $default ? ",defaultDate: new Date({$default->getTimestamp()}*1000)" : '';
306 $pickers .= ', datepicker: false';
310 $pickers .= ',timepicker: false';
314 $pickers .= ",dayOfWeekStart: " . $firstDay . ",lang:'" . $lang . "'";
315 if ($minfrom != '') {
316 $extra_js .= "\$('#id_$minfrom').data('xdsoft_datetimepicker').setOptions({onChangeDateTime: function (currentDateTime) { \$('#id_$id').data('xdsoft_datetimepicker').setOptions({minDate: currentDateTime})}})";
319 if ($maxfrom != '') {
320 $extra_js .= "\$('#id_$maxfrom').data('xdsoft_datetimepicker').setOptions({onChangeDateTime: function (currentDateTime) { \$('#id_$id').data('xdsoft_datetimepicker').setOptions({maxDate: currentDateTime})}})";
323 $readable_format = $dateformat;
324 $readable_format = str_replace('Y', 'yyyy', $readable_format);
325 $readable_format = str_replace('m', 'mm', $readable_format);
326 $readable_format = str_replace('d', 'dd', $readable_format);
327 $readable_format = str_replace('H', 'HH', $readable_format);
328 $readable_format = str_replace('i', 'MM', $readable_format);
330 $tpl = get_markup_template('field_input.tpl');
331 $o .= replace_macros($tpl,
338 $required ? '*' : '',
339 'placeholder="' . $readable_format . '"'
343 $o .= "<script type='text/javascript'>";
344 $o .= "\$(function () {var picker = \$('#id_$id').datetimepicker({step:5,format:'$dateformat' $minjs $maxjs $pickers $defaultdatejs}); $extra_js})";
351 * @brief Returns a relative date string.
353 * Implements "3 seconds ago" etc.
354 * Based on $posted_date, (UTC).
355 * Results relative to current timezone.
356 * Limited to range of timestamps.
358 * @param string $posted_date MySQL-formatted date string (YYYY-MM-DD HH:MM:SS)
359 * @param string $format (optional) Parsed with sprintf()
360 * <tt>%1$d %2$s ago</tt>, e.g. 22 hours ago, 1 minute ago
362 * @return string with relative date
364 public static function getRelativeDate($posted_date, $format = null)
366 $localtime = $posted_date . ' UTC';
368 $abs = strtotime($localtime);
370 if (is_null($posted_date) || $posted_date <= NULL_DATE || $abs === false) {
371 return L10n::t('never');
374 $etime = time() - $abs;
377 return L10n::t('less than a second ago');
380 $a = [12 * 30 * 24 * 60 * 60 => [L10n::t('year'), L10n::t('years')],
381 30 * 24 * 60 * 60 => [L10n::t('month'), L10n::t('months')],
382 7 * 24 * 60 * 60 => [L10n::t('week'), L10n::t('weeks')],
383 24 * 60 * 60 => [L10n::t('day'), L10n::t('days')],
384 60 * 60 => [L10n::t('hour'), L10n::t('hours')],
385 60 => [L10n::t('minute'), L10n::t('minutes')],
386 1 => [L10n::t('second'), L10n::t('seconds')]
389 foreach ($a as $secs => $str) {
393 // translators - e.g. 22 hours ago, 1 minute ago
395 $format = L10n::t('%1$d %2$s ago');
398 return sprintf($format, $r, (($r == 1) ? $str[0] : $str[1]));
404 * @brief Returns timezone correct age in years.
406 * Returns the age in years, given a date of birth, the timezone of the person
407 * whose date of birth is provided, and the timezone of the person viewing the
410 * Why? Bear with me. Let's say I live in Mittagong, Australia, and my birthday
411 * is on New Year's. You live in San Bruno, California.
412 * When exactly are you going to see my age increase?
414 * A: 5:00 AM Dec 31 San Bruno time. That's precisely when I start celebrating
415 * and become a year older. If you wish me happy birthday on January 1
416 * (San Bruno time), you'll be a day late.
418 * @param string $dob Date of Birth
419 * @param string $owner_tz (optional) Timezone of the person of interest
420 * @param string $viewer_tz (optional) Timezone of the person viewing
422 * @return int Age in years
424 public static function getAgeByTimezone($dob, $owner_tz = '', $viewer_tz = '')
430 $owner_tz = date_default_timezone_get();
433 $viewer_tz = date_default_timezone_get();
436 $birthdate = Temporal::convert($dob . ' 00:00:00+00:00', $owner_tz, 'UTC', 'Y-m-d');
437 list($year, $month, $day) = explode("-", $birthdate);
438 $year_diff = Temporal::convert('now', $viewer_tz, 'UTC', 'Y') - $year;
439 $curr_month = Temporal::convert('now', $viewer_tz, 'UTC', 'm');
440 $curr_day = Temporal::convert('now', $viewer_tz, 'UTC', 'd');
442 if (($curr_month < $month) || (($curr_month == $month) && ($curr_day < $day))) {
450 * @brief Get days of a month in a given year.
452 * Returns number of days in the month of the given year.
453 * $m = 1 is 'January' to match human usage.
456 * @param int $m Month (1=January, 12=December)
458 * @return int Number of days in the given month
460 public static function getDaysInMonth($y, $m)
462 return date('t', mktime(0, 0, 0, $m, 1, $y));
467 * @brief Returns the first day in month for a given month, year.
472 * @param int $m Month (1=January, 12=December)
474 * @return string day 0 = Sunday through 6 = Saturday
476 public static function getFirstDayInMonth($y, $m)
478 $d = sprintf('%04d-%02d-01 00:00', intval($y), intval($m));
480 return Temporal::convert($d, 'UTC', 'UTC', 'w');
484 * @brief Output a calendar for the given month, year.
486 * If $links are provided (array), e.g. $links[12] => 'http://mylink' ,
487 * date 12 will be linked appropriately. Today's date is also noted by
489 * Months count from 1.
492 * @param int $m Month
493 * @param array $links (default null)
494 * @param string $class
498 * @todo Provide (prev, next) links, define class variations for different size calendars
500 public static function getCalendarTable($y = 0, $m = 0, $links = null, $class = '')
502 // month table - start at 1 to match human usage.
504 'January', 'February', 'March',
505 'April', 'May', 'June',
506 'July', 'August', 'September',
507 'October', 'November', 'December'
510 $thisyear = Temporal::convert('now', date_default_timezone_get(), 'UTC', 'Y');
511 $thismonth = Temporal::convert('now', date_default_timezone_get(), 'UTC', 'm');
517 $m = intval($thismonth);
520 $dn = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
521 $f = get_first_dim($y, $m);
522 $l = get_dim($y, $m);
527 if (($y == $thisyear) && ($m == $thismonth)) {
528 $tddate = intval(Temporal::convert('now', date_default_timezone_get(), 'UTC', 'j'));
531 $str_month = day_translate($mtab[$m]);
532 $o = '<table class="calendar' . $class . '">';
533 $o .= "<caption>$str_month $y</caption><tr>";
534 for ($a = 0; $a < 7; $a ++) {
535 $o .= '<th>' . mb_substr(day_translate($dn[$a]), 0, 3, 'UTF-8') . '</th>';
541 if (($dow == $f) && (!$started)) {
545 $today = (((isset($tddate)) && ($tddate == $d)) ? "class=\"today\" " : '');
547 $day = str_replace(' ', ' ', sprintf('%2.2d', $d));
549 if (x($links, $d) !== false) {
550 $o .= "<a href=\"{$links[$d]}\">$day</a>";
562 if (($dow == 7) && ($d <= $l)) {
569 for ($a = $dow; $a < 7; $a ++) {
570 $o .= '<td> </td>';
574 $o .= '</tr></table>' . "\r\n";