4 * @file src/Util/Temporal.php
7 namespace Friendica\Util;
11 use Friendica\Core\L10n;
12 use Friendica\Core\PConfig;
13 use Friendica\Core\Renderer;
14 use Friendica\Database\DBA;
17 * @brief Temporal class
22 * @brief Two-level sort for timezones.
28 private static function timezoneCompareCallback($a, $b)
30 if (strstr($a, '/') && strstr($b, '/')) {
31 if (L10n::t($a) == L10n::t($b)) {
34 return (L10n::t($a) < L10n::t($b)) ? -1 : 1;
37 if (strstr($a, '/')) {
39 } elseif (strstr($b, '/')) {
41 } elseif (L10n::t($a) == L10n::t($b)) {
45 return (L10n::t($a) < L10n::t($b)) ? -1 : 1;
49 * @brief Emit a timezone selector grouped (primarily) by continent
51 * @param string $current Timezone
52 * @return string Parsed HTML output
54 public static function getTimezoneSelect($current = 'America/Los_Angeles')
56 $timezone_identifiers = DateTimeZone::listIdentifiers();
58 $o = '<select id="timezone_select" name="timezone">';
60 usort($timezone_identifiers, [__CLASS__, 'timezoneCompareCallback']);
62 foreach ($timezone_identifiers as $value) {
63 $ex = explode("/", $value);
65 if ($ex[0] != $continent) {
66 if ($continent != '') {
70 $o .= '<optgroup label="' . L10n::t($continent) . '">';
73 $city = substr($value, strpos($value, '/') + 1);
79 if ($continent != L10n::t('Miscellaneous')) {
81 $continent = L10n::t('Miscellaneous');
82 $o .= '<optgroup label="' . L10n::t($continent) . '">';
85 $city = str_replace('_', ' ', L10n::t($city));
86 $selected = (($value == $current) ? " selected=\"selected\" " : "");
87 $o .= "<option value=\"$value\" $selected >$city</option>";
89 $o .= '</optgroup></select>';
94 * @brief Generating a Timezone selector
96 * Return a select using 'field_select_raw' template, with timezones
97 * grouped (primarily) by continent
98 * arguments follow convention as other field_* template array:
99 * 'name', 'label', $value, 'help'
101 * @param string $name Name of the selector
102 * @param string $label Label for the selector
103 * @param string $current Timezone
104 * @param string $help Help text
106 * @return string Parsed HTML
107 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
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
126 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
128 public static function getDateofBirthField($dob)
132 list($year, $month, $day) = sscanf($dob, '%4d-%2d-%2d');
134 if ($dob < '0000-01-01') {
137 $value = DateTimeFormat::utc(($year > 1000) ? $dob : '1000-' . $month . '-' . $day, 'Y-m-d');
140 $age = (intval($value) ? self::getAgeByTimezone($value, $a->user["timezone"], $a->user["timezone"]) : "");
142 $tpl = Renderer::getMarkupTemplate("field_input.tpl");
143 $o = Renderer::replaceMacros($tpl,
147 L10n::t('Birthday:'),
149 intval($age) > 0 ? L10n::t('Age: ') . $age : "",
151 'placeholder="' . L10n::t('YYYY-MM-DD or MM-DD') . '"'
159 * @brief Returns a date selector
161 * @param DateTime $min Minimum date
162 * @param DateTime $max Maximum date
163 * @param DateTime $default Default date
164 * @param string $id ID and name of datetimepicker (defaults to "datetimepicker")
166 * @return string Parsed HTML output.
167 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
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.
184 public static function getTimeField($h, $m, $id = 'timepicker')
186 return self::getDateTimeField(new DateTime(), new DateTime(), new DateTime("$h:$m"), '', $id, false, true);
190 * @brief Returns a datetime selector.
192 * @param DateTime $minDate Minimum date
193 * @param DateTime $maxDate Maximum date
194 * @param DateTime $defaultDate Default date
196 * @param string $id Id and name of datetimepicker (defaults to "datetimepicker")
197 * @param bool $pickdate true to show date picker (default)
198 * @param bool $picktime true to show time picker (default)
199 * @param string $minfrom set minimum date from picker with id $minfrom (none by default)
200 * @param string $maxfrom set maximum date from picker with id $maxfrom (none by default)
201 * @param bool $required default false
203 * @return string Parsed HTML output.
205 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
206 * @todo Once browser support is better this could probably be replaced with
207 * native HTML5 date picker.
209 public static function getDateTimeField(
212 DateTime $defaultDate,
214 $id = 'datetimepicker',
221 // First day of the week (0 = Sunday)
222 $firstDay = PConfig::get(local_user(), 'system', 'first_day_of_week', 0);
224 $lang = substr(L10n::getCurrentLang(), 0, 2);
226 // Check if the detected language is supported by the picker
228 ["ar", "ro", "id", "bg", "fa", "ru", "uk", "en", "el", "de", "nl", "tr", "fr", "es", "th", "pl", "pt", "ch", "se", "kr",
229 "it", "da", "no", "ja", "vi", "sl", "cs", "hu"])) {
237 $dateformat .= 'Y-m-d';
240 if ($pickdate && $picktime) {
245 $dateformat .= 'H:i';
248 $input_text = $defaultDate ? date($dateformat, $defaultDate->getTimestamp()) : '';
250 $readable_format = str_replace(['Y', 'm', 'd', 'H', 'i'], ['yyyy', 'mm', 'dd', 'HH', 'MM'], $dateformat);
252 $tpl = Renderer::getMarkupTemplate('field_datetime.tpl');
253 $o .= Renderer::replaceMacros($tpl, [
259 $required ? '*' : '',
260 'placeholder="' . $readable_format . '"'
262 '$datetimepicker' => [
263 'minDate' => $minDate,
264 'maxDate' => $maxDate,
265 'defaultDate' => $defaultDate,
266 'dateformat' => $dateformat,
267 'firstDay' => $firstDay,
269 'minfrom' => $minfrom,
270 'maxfrom' => $maxfrom,
278 * @brief Returns a relative date string.
280 * Implements "3 seconds ago" etc.
281 * Based on $posted_date, (UTC).
282 * Results relative to current timezone.
283 * Limited to range of timestamps.
285 * @param string $posted_date MySQL-formatted date string (YYYY-MM-DD HH:MM:SS)
286 * @param string $format (optional) Parsed with sprintf()
287 * <tt>%1$d %2$s ago</tt>, e.g. 22 hours ago, 1 minute ago
289 * @return string with relative date
291 public static function getRelativeDate($posted_date, $format = null)
293 $localtime = $posted_date . ' UTC';
295 $abs = strtotime($localtime);
297 if (is_null($posted_date) || $posted_date <= DBA::NULL_DATETIME || $abs === false) {
298 return L10n::t('never');
302 $etime = time() - $abs;
304 if ($etime < 1 && $etime >= 0) {
305 return L10n::t('less than a second ago');
313 $a = [12 * 30 * 24 * 60 * 60 => [L10n::t('year'), L10n::t('years')],
314 30 * 24 * 60 * 60 => [L10n::t('month'), L10n::t('months')],
315 7 * 24 * 60 * 60 => [L10n::t('week'), L10n::t('weeks')],
316 24 * 60 * 60 => [L10n::t('day'), L10n::t('days')],
317 60 * 60 => [L10n::t('hour'), L10n::t('hours')],
318 60 => [L10n::t('minute'), L10n::t('minutes')],
319 1 => [L10n::t('second'), L10n::t('seconds')]
322 foreach ($a as $secs => $str) {
326 // translators - e.g. 22 hours ago, 1 minute ago
329 $format = L10n::t('in %1$d %2$s');
332 $format = L10n::t('%1$d %2$s ago');
336 return sprintf($format, $r, (($r == 1) ? $str[0] : $str[1]));
342 * @brief Returns timezone correct age in years.
344 * Returns the age in years, given a date of birth, the timezone of the person
345 * whose date of birth is provided, and the timezone of the person viewing the
348 * Why? Bear with me. Let's say I live in Mittagong, Australia, and my birthday
349 * is on New Year's. You live in San Bruno, California.
350 * When exactly are you going to see my age increase?
352 * A: 5:00 AM Dec 31 San Bruno time. That's precisely when I start celebrating
353 * and become a year older. If you wish me happy birthday on January 1
354 * (San Bruno time), you'll be a day late.
356 * @param string $dob Date of Birth
357 * @param string $owner_tz (optional) Timezone of the person of interest
358 * @param string $viewer_tz (optional) Timezone of the person viewing
360 * @return int Age in years
363 public static function getAgeByTimezone($dob, $owner_tz = '', $viewer_tz = '')
369 $owner_tz = date_default_timezone_get();
372 $viewer_tz = date_default_timezone_get();
375 $birthdate = DateTimeFormat::convert($dob . ' 00:00:00+00:00', $owner_tz, 'UTC', 'Y-m-d');
376 list($year, $month, $day) = explode("-", $birthdate);
377 $year_diff = DateTimeFormat::timezoneNow($viewer_tz, 'Y') - $year;
378 $curr_month = DateTimeFormat::timezoneNow($viewer_tz, 'm');
379 $curr_day = DateTimeFormat::timezoneNow($viewer_tz, 'd');
381 if (($curr_month < $month) || (($curr_month == $month) && ($curr_day < $day))) {
389 * @brief Get days of a month in a given year.
391 * Returns number of days in the month of the given year.
392 * $m = 1 is 'January' to match human usage.
395 * @param int $m Month (1=January, 12=December)
397 * @return int Number of days in the given month
399 public static function getDaysInMonth($y, $m)
401 return date('t', mktime(0, 0, 0, $m, 1, $y));
405 * @brief Returns the first day in month for a given month, year.
410 * @param int $m Month (1=January, 12=December)
412 * @return string day 0 = Sunday through 6 = Saturday
415 private static function getFirstDayInMonth($y, $m)
417 $d = sprintf('%04d-%02d-01 00:00', intval($y), intval($m));
419 return DateTimeFormat::utc($d, 'w');
423 * @brief Output a calendar for the given month, year.
425 * If $links are provided (array), e.g. $links[12] => 'http://mylink' ,
426 * date 12 will be linked appropriately. Today's date is also noted by
428 * Months count from 1.
431 * @param int $m Month
432 * @param array $links (default null)
433 * @param string $class
438 * @todo Provide (prev, next) links, define class variations for different size calendars
440 public static function getCalendarTable($y = 0, $m = 0, $links = null, $class = '')
442 // month table - start at 1 to match human usage.
444 'January', 'February', 'March',
445 'April', 'May', 'June',
446 'July', 'August', 'September',
447 'October', 'November', 'December'
450 $thisyear = DateTimeFormat::localNow('Y');
451 $thismonth = DateTimeFormat::localNow('m');
457 $m = intval($thismonth);
460 $dn = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
461 $f = self::getFirstDayInMonth($y, $m);
462 $l = self::getDaysInMonth($y, $m);
467 if (($y == $thisyear) && ($m == $thismonth)) {
468 $tddate = intval(DateTimeFormat::localNow('j'));
471 $str_month = L10n::getDay($mtab[$m]);
472 $o = '<table class="calendar' . $class . '">';
473 $o .= "<caption>$str_month $y</caption><tr>";
474 for ($a = 0; $a < 7; $a ++) {
475 $o .= '<th>' . mb_substr(L10n::getDay($dn[$a]), 0, 3, 'UTF-8') . '</th>';
481 if (($dow == $f) && (!$started)) {
485 $today = (((isset($tddate)) && ($tddate == $d)) ? "class=\"today\" " : '');
487 $day = str_replace(' ', ' ', sprintf('%2.2d', $d));
489 if (isset($links[$d])) {
490 $o .= "<a href=\"{$links[$d]}\">$day</a>";
502 if (($dow == 7) && ($d <= $l)) {
509 for ($a = $dow; $a < 7; $a ++) {
510 $o .= '<td> </td>';
514 $o .= '</tr></table>' . "\r\n";