3 * @copyright Copyright (C) 2020, Friendica
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Util;
26 use Friendica\Core\Renderer;
27 use Friendica\Database\DBA;
36 * Two-level sort for timezones.
42 private static function timezoneCompareCallback($a, $b)
44 if (strstr($a, '/') && strstr($b, '/')) {
45 if (DI::l10n()->t($a) == DI::l10n()->t($b)) {
48 return (DI::l10n()->t($a) < DI::l10n()->t($b)) ? -1 : 1;
51 if (strstr($a, '/')) {
53 } elseif (strstr($b, '/')) {
55 } elseif (DI::l10n()->t($a) == DI::l10n()->t($b)) {
59 return (DI::l10n()->t($a) < DI::l10n()->t($b)) ? -1 : 1;
63 * Emit a timezone selector grouped (primarily) by continent
65 * @param string $current Timezone
66 * @return string Parsed HTML output
68 public static function getTimezoneSelect($current = 'America/Los_Angeles')
70 $timezone_identifiers = DateTimeZone::listIdentifiers();
72 $o = '<select id="timezone_select" name="timezone">';
74 usort($timezone_identifiers, [__CLASS__, 'timezoneCompareCallback']);
76 foreach ($timezone_identifiers as $value) {
77 $ex = explode("/", $value);
79 if ($ex[0] != $continent) {
80 if ($continent != '') {
84 $o .= '<optgroup label="' . DI::l10n()->t($continent) . '">';
87 $city = substr($value, strpos($value, '/') + 1);
93 if ($continent != DI::l10n()->t('Miscellaneous')) {
95 $continent = DI::l10n()->t('Miscellaneous');
96 $o .= '<optgroup label="' . DI::l10n()->t($continent) . '">';
99 $city = str_replace('_', ' ', DI::l10n()->t($city));
100 $selected = (($value == $current) ? " selected=\"selected\" " : "");
101 $o .= "<option value=\"$value\" $selected >$city</option>";
103 $o .= '</optgroup></select>';
108 * Generating a Timezone selector
110 * Return a select using 'field_select_raw' template, with timezones
111 * grouped (primarily) by continent
112 * arguments follow convention as other field_* template array:
113 * 'name', 'label', $value, 'help'
115 * @param string $name Name of the selector
116 * @param string $label Label for the selector
117 * @param string $current Timezone
118 * @param string $help Help text
120 * @return string Parsed HTML
121 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
123 public static function getTimezoneField($name = 'timezone', $label = '', $current = 'America/Los_Angeles', $help = '')
125 $options = self::getTimezoneSelect($current);
126 $options = str_replace('<select id="timezone_select" name="timezone">', '', $options);
127 $options = str_replace('</select>', '', $options);
129 $tpl = Renderer::getMarkupTemplate('field_select_raw.tpl');
130 return Renderer::replaceMacros($tpl, [
131 '$field' => [$name, $label, $current, $help, $options],
136 * Wrapper for date selector, tailored for use in birthday fields.
138 * @param string $dob Date of Birth
139 * @param string $timezone
140 * @return string Formatted HTML
143 public static function getDateofBirthField(string $dob, string $timezone = 'UTC')
145 list($year, $month, $day) = sscanf($dob, '%4d-%2d-%2d');
147 if ($dob < '0000-01-01') {
150 } elseif ($dob < '0001-00-00') {
151 $value = substr($dob, 5);
154 $value = DateTimeFormat::utc($dob, 'Y-m-d');
155 $age = self::getAgeByTimezone($value, $timezone);
158 $tpl = Renderer::getMarkupTemplate("field_input.tpl");
159 $o = Renderer::replaceMacros($tpl,
163 DI::l10n()->t('Birthday:'),
165 intval($age) > 0 ? DI::l10n()->t('Age: ') . DI::l10n()->tt('%d year old', '%d years old', $age) : '',
167 'placeholder="' . DI::l10n()->t('YYYY-MM-DD or MM-DD') . '"'
175 * Returns a date selector
177 * @param DateTime $min Minimum date
178 * @param DateTime $max Maximum date
179 * @param DateTime $default Default date
180 * @param string $id ID and name of datetimepicker (defaults to "datetimepicker")
182 * @return string Parsed HTML output.
183 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
185 public static function getDateField($min, $max, $default, $id = 'datepicker')
187 return self::getDateTimeField($min, $max, $default, '', $id, true, false, '', '');
191 * Returns a time selector
193 * @param string $h Already selected hour
194 * @param string $m Already selected minute
195 * @param string $id ID and name of datetimepicker (defaults to "timepicker")
197 * @return string Parsed HTML output.
200 public static function getTimeField($h, $m, $id = 'timepicker')
202 return self::getDateTimeField(new DateTime(), new DateTime(), new DateTime("$h:$m"), '', $id, false, true);
206 * Returns a datetime selector.
208 * @param DateTime $minDate Minimum date
209 * @param DateTime $maxDate Maximum date
210 * @param DateTime $defaultDate Default date
212 * @param string $id Id and name of datetimepicker (defaults to "datetimepicker")
213 * @param bool $pickdate true to show date picker (default)
214 * @param bool $picktime true to show time picker (default)
215 * @param string $minfrom set minimum date from picker with id $minfrom (none by default)
216 * @param string $maxfrom set maximum date from picker with id $maxfrom (none by default)
217 * @param bool $required default false
219 * @return string Parsed HTML output.
221 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
222 * @todo Once browser support is better this could probably be replaced with
223 * native HTML5 date picker.
225 public static function getDateTimeField(
228 DateTime $defaultDate,
230 $id = 'datetimepicker',
237 // First day of the week (0 = Sunday)
238 $firstDay = DI::pConfig()->get(local_user(), 'system', 'first_day_of_week', 0);
240 $lang = substr(DI::l10n()->getCurrentLang(), 0, 2);
242 // Check if the detected language is supported by the picker
244 ["ar", "ro", "id", "bg", "fa", "ru", "uk", "en", "el", "de", "nl", "tr", "fr", "es", "th", "pl", "pt", "ch", "se", "kr",
245 "it", "da", "no", "ja", "vi", "sl", "cs", "hu"])) {
253 $dateformat .= 'Y-m-d';
256 if ($pickdate && $picktime) {
261 $dateformat .= 'H:i';
264 $input_text = $defaultDate ? date($dateformat, $defaultDate->getTimestamp()) : '';
266 $readable_format = str_replace(['Y', 'm', 'd', 'H', 'i'], ['yyyy', 'mm', 'dd', 'HH', 'MM'], $dateformat);
268 $tpl = Renderer::getMarkupTemplate('field_datetime.tpl');
269 $o .= Renderer::replaceMacros($tpl, [
275 $required ? '*' : '',
276 'placeholder="' . $readable_format . '"'
278 '$datetimepicker' => [
279 'minDate' => $minDate,
280 'maxDate' => $maxDate,
281 'defaultDate' => $defaultDate,
282 'dateformat' => $dateformat,
283 'firstDay' => $firstDay,
285 'minfrom' => $minfrom,
286 'maxfrom' => $maxfrom,
294 * Returns a relative date string.
296 * Implements "3 seconds ago" etc.
297 * Based on $posted_date, (UTC).
298 * Results relative to current timezone.
299 * Limited to range of timestamps.
301 * @param string $posted_date MySQL-formatted date string (YYYY-MM-DD HH:MM:SS)
302 * @param string $format (optional) Parsed with sprintf()
303 * <tt>%1$d %2$s ago</tt>, e.g. 22 hours ago, 1 minute ago
305 * @return string with relative date
307 public static function getRelativeDate($posted_date, $format = null)
309 $localtime = $posted_date . ' UTC';
311 $abs = strtotime($localtime);
313 if (is_null($posted_date) || $posted_date <= DBA::NULL_DATETIME || $abs === false) {
314 return DI::l10n()->t('never');
318 $etime = time() - $abs;
320 if ($etime < 1 && $etime >= 0) {
321 return DI::l10n()->t('less than a second ago');
329 $a = [12 * 30 * 24 * 60 * 60 => [DI::l10n()->t('year'), DI::l10n()->t('years')],
330 30 * 24 * 60 * 60 => [DI::l10n()->t('month'), DI::l10n()->t('months')],
331 7 * 24 * 60 * 60 => [DI::l10n()->t('week'), DI::l10n()->t('weeks')],
332 24 * 60 * 60 => [DI::l10n()->t('day'), DI::l10n()->t('days')],
333 60 * 60 => [DI::l10n()->t('hour'), DI::l10n()->t('hours')],
334 60 => [DI::l10n()->t('minute'), DI::l10n()->t('minutes')],
335 1 => [DI::l10n()->t('second'), DI::l10n()->t('seconds')]
338 foreach ($a as $secs => $str) {
342 // translators - e.g. 22 hours ago, 1 minute ago
345 $format = DI::l10n()->t('in %1$d %2$s');
348 $format = DI::l10n()->t('%1$d %2$s ago');
352 return sprintf($format, $r, (($r == 1) ? $str[0] : $str[1]));
358 * Returns timezone correct age in years.
360 * Returns the age in years, given a date of birth and the timezone of the person
361 * whose date of birth is provided.
363 * @param string $dob Date of Birth
364 * @param string $owner_tz (optional) Timezone of the person of interest
366 * @return int Age in years
369 public static function getAgeByTimezone($dob, $owner_tz = '')
376 $owner_tz = date_default_timezone_get();
379 $birthdate = new DateTime($dob . ' 00:00:00', new DateTimeZone($owner_tz));
380 $currentDate = new DateTime('now', new DateTimeZone('UTC'));
382 $interval = $birthdate->diff($currentDate);
384 return $interval->format('%y');
388 * Get days of a month in a given year.
390 * Returns number of days in the month of the given year.
391 * $m = 1 is 'January' to match human usage.
394 * @param int $m Month (1=January, 12=December)
396 * @return int Number of days in the given month
398 public static function getDaysInMonth($y, $m)
400 return date('t', mktime(0, 0, 0, $m, 1, $y));
404 * Returns the first day in month for a given month, year.
409 * @param int $m Month (1=January, 12=December)
411 * @return string day 0 = Sunday through 6 = Saturday
414 private static function getFirstDayInMonth($y, $m)
416 $d = sprintf('%04d-%02d-01 00:00', intval($y), intval($m));
418 return DateTimeFormat::utc($d, 'w');
422 * Output a calendar for the given month, year.
424 * If $links are provided (array), e.g. $links[12] => 'http://mylink' ,
425 * date 12 will be linked appropriately. Today's date is also noted by
427 * Months count from 1.
430 * @param int $m Month
431 * @param array $links (default null)
432 * @param string $class
437 * @todo Provide (prev, next) links, define class variations for different size calendars
439 public static function getCalendarTable($y = 0, $m = 0, $links = null, $class = '')
441 // month table - start at 1 to match human usage.
443 'January', 'February', 'March',
444 'April', 'May', 'June',
445 'July', 'August', 'September',
446 'October', 'November', 'December'
449 $thisyear = DateTimeFormat::localNow('Y');
450 $thismonth = DateTimeFormat::localNow('m');
456 $m = intval($thismonth);
459 $dn = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
460 $f = self::getFirstDayInMonth($y, $m);
461 $l = self::getDaysInMonth($y, $m);
466 if (($y == $thisyear) && ($m == $thismonth)) {
467 $tddate = intval(DateTimeFormat::localNow('j'));
470 $str_month = DI::l10n()->getDay($mtab[$m]);
471 $o = '<table class="calendar' . $class . '">';
472 $o .= "<caption>$str_month $y</caption><tr>";
473 for ($a = 0; $a < 7; $a ++) {
474 $o .= '<th>' . mb_substr(DI::l10n()->getDay($dn[$a]), 0, 3, 'UTF-8') . '</th>';
480 if (($dow == $f) && (!$started)) {
484 $today = (((isset($tddate)) && ($tddate == $d)) ? "class=\"today\" " : '');
486 $day = str_replace(' ', ' ', sprintf('%2.2d', $d));
488 if (isset($links[$d])) {
489 $o .= "<a href=\"{$links[$d]}\">$day</a>";
501 if (($dow == 7) && ($d <= $l)) {
508 for ($a = $dow; $a < 7; $a ++) {
509 $o .= '<td> </td>';
513 $o .= '</tr></table>' . "\r\n";