3 * @file include/datetime.php
4 * @brief Some functions for date and time related tasks.
7 use Friendica\Core\Config;
8 use Friendica\Core\L10n;
9 use Friendica\Core\PConfig;
10 use Friendica\Database\DBM;
13 * @brief Two-level sort for timezones.
19 function timezone_cmp($a, $b) {
20 if (strstr($a, '/') && strstr($b, '/')) {
21 if (L10n::t($a) == L10n::t($b)) {
24 return (L10n::t($a) < L10n::t($b)) ? -1 : 1;
27 if (strstr($a, '/')) {
29 } elseif (strstr($b, '/')) {
31 } elseif (L10n::t($a) == L10n::t($b)) {
35 return (L10n::t($a) < L10n::t($b)) ? -1 : 1;
39 * @brief Emit a timezone selector grouped (primarily) by continent
41 * @param string $current Timezone
42 * @return string Parsed HTML output
44 function select_timezone($current = 'America/Los_Angeles') {
46 $timezone_identifiers = DateTimeZone::listIdentifiers();
48 $o ='<select id="timezone_select" name="timezone">';
50 usort($timezone_identifiers, 'timezone_cmp');
52 foreach ($timezone_identifiers as $value) {
53 $ex = explode("/", $value);
55 if ($ex[0] != $continent) {
56 if ($continent != '') {
60 $o .= '<optgroup label="' . L10n::t($continent) . '">';
63 $city = substr($value,strpos($value,'/')+1);
69 if ($continent != L10n::t('Miscellaneous')) {
71 $continent = L10n::t('Miscellaneous');
72 $o .= '<optgroup label="' . L10n::t($continent) . '">';
75 $city = str_replace('_', ' ', L10n::t($city));
76 $selected = (($value == $current) ? " selected=\"selected\" " : "");
77 $o .= "<option value=\"$value\" $selected >$city</option>";
79 $o .= '</optgroup></select>';
86 * @brief Generating a Timezone selector
88 * Return a select using 'field_select_raw' template, with timezones
89 * groupped (primarily) by continent
90 * arguments follow convetion as other field_* template array:
91 * 'name', 'label', $value, 'help'
93 * @param string $name Name of the selector
94 * @param string $label Label for the selector
95 * @param string $current Timezone
96 * @param string $help Help text
98 * @return string Parsed HTML
100 function field_timezone($name='timezone', $label='', $current = 'America/Los_Angeles', $help){
101 $options = select_timezone($current);
102 $options = str_replace('<select id="timezone_select" name="timezone">','', $options);
103 $options = str_replace('</select>','', $options);
105 $tpl = get_markup_template('field_select_raw.tpl');
106 return replace_macros($tpl, [
107 '$field' => [$name, $label, $current, $help, $options],
113 * @brief General purpose date parse/convert function.
115 * @param string $from Source timezone
116 * @param string $to Dest timezone
117 * @param string $s Some parseable date/time string
118 * @param string $fmt Output format recognised from php's DateTime class
119 * http://www.php.net/manual/en/datetime.format.php
121 * @return string Formatted date according to given format
123 function datetime_convert($from = 'UTC', $to = 'UTC', $s = 'now', $fmt = "Y-m-d H:i:s") {
125 // Defaults to UTC if nothing is set, but throws an exception if set to empty string.
126 // Provide some sane defaults regardless.
134 if ( ($s === '') || (! is_string($s)) ) {
139 * Slight hackish adjustment so that 'zero' datetime actually returns what is intended
140 * otherwise we end up with -0001-11-30 ...
141 * add 32 days so that we at least get year 00, and then hack around the fact that
142 * months and days always start with 1.
145 if (substr($s,0,10) <= '0001-01-01') {
146 $d = new DateTime($s . ' + 32 days', new DateTimeZone('UTC'));
147 return str_replace('1','0',$d->format($fmt));
151 $from_obj = new DateTimeZone($from);
152 } catch (Exception $e) {
153 $from_obj = new DateTimeZone('UTC');
157 $d = new DateTime($s, $from_obj);
158 } catch (Exception $e) {
159 logger('datetime_convert: exception: ' . $e->getMessage());
160 $d = new DateTime('now', $from_obj);
164 $to_obj = new DateTimeZone($to);
165 } catch (Exception $e) {
166 $to_obj = new DateTimeZone('UTC');
169 $d->setTimeZone($to_obj);
171 return $d->format($fmt);
176 * @brief Wrapper for date selector, tailored for use in birthday fields.
178 * @param string $dob Date of Birth
179 * @return string Formatted html
183 list($year, $month, $day) = sscanf($dob, '%4d-%2d-%2d');
185 if ($dob <= '0001-01-01') {
188 $value = (($year) ? datetime_convert('UTC','UTC',$dob,'Y-m-d') : datetime_convert('UTC','UTC',$dob,'m-d'));
191 $age = ((intval($value)) ? age($value, $a->user["timezone"], $a->user["timezone"]) : "");
193 $o = replace_macros(get_markup_template("field_input.tpl"), [
198 (((intval($age)) > 0 ) ? L10n::t('Age: ') . $age : ""),
200 'placeholder="' . L10n::t('YYYY-MM-DD or MM-DD') . '"'
204 /// @TODO Old-lost code?
205 // if ($dob && $dob > '0001-01-01')
206 // $o = datesel($f,mktime(0,0,0,0,0,1900),mktime(),mktime(0,0,0,$month,$day,$year), 'dob');
208 // $o = datesel($f,mktime(0,0,0,0,0,1900),mktime(),false,'dob');
214 * @brief Returns a date selector
217 * Unix timestamp of minimum date
219 * Unix timestap of maximum date
220 * @param string $default
221 * Unix timestamp of default date
223 * ID and name of datetimepicker (defaults to "datetimepicker")
225 * @return string Parsed HTML output.
227 function datesel($min, $max, $default, $id = 'datepicker')
229 return datetimesel($min, $max, $default, '', $id, true, false, '', '');
233 * @brief Returns a time selector
236 * Already selected hour
238 * Already selected minute
240 * ID and name of datetimepicker (defaults to "timepicker")
242 * @return string Parsed HTML output.
244 function timesel($h, $m, $id = 'timepicker')
246 return datetimesel(new DateTime(), new DateTime(), new DateTime("$h:$m"), '', $id, false, true);
250 * @brief Returns a datetime selector.
253 * unix timestamp of minimum date
255 * unix timestap of maximum date
256 * @param string $default
257 * unix timestamp of default date
259 * id and name of datetimepicker (defaults to "datetimepicker")
260 * @param bool $pickdate
261 * true to show date picker (default)
262 * @param boolean $picktime
263 * true to show time picker (default)
265 * set minimum date from picker with id $minfrom (none by default)
267 * set maximum date from picker with id $maxfrom (none by default)
268 * @param bool $required default false
270 * @return string Parsed HTML output.
272 * @todo Once browser support is better this could probably be replaced with
273 * native HTML5 date picker.
275 function datetimesel($min, $max, $default, $label, $id = 'datetimepicker', $pickdate = true, $picktime = true, $minfrom = '', $maxfrom = '', $required = false)
277 // First day of the week (0 = Sunday)
278 $firstDay = PConfig::get(local_user(), 'system', 'first_day_of_week', 0);
280 $lang = substr(L10n::getBrowserLanguage(), 0, 2);
282 // Check if the detected language is supported by the picker
283 if (!in_array($lang, ["ar", "ro", "id", "bg", "fa", "ru", "uk", "en", "el", "de", "nl", "tr", "fr", "es", "th", "pl", "pt", "ch", "se", "kr", "it", "da", "no", "ja", "vi", "sl", "cs", "hu"])) {
284 $lang = Config::get('system', 'language', 'en');
291 $dateformat .= 'Y-m-d';
293 if ($pickdate && $picktime) {
297 $dateformat .= 'H:i';
300 $minjs = $min ? ",minDate: new Date({$min->getTimestamp()}*1000), yearStart: " . $min->format('Y') : '';
301 $maxjs = $max ? ",maxDate: new Date({$max->getTimestamp()}*1000), yearEnd: " . $max->format('Y') : '';
303 $input_text = $default ? date($dateformat, $default->getTimestamp()) : '';
304 $defaultdatejs = $default ? ",defaultDate: new Date({$default->getTimestamp()}*1000)" : '';
308 $pickers .= ', datepicker: false';
311 $pickers .= ',timepicker: false';
315 $pickers .= ",dayOfWeekStart: " . $firstDay . ",lang:'" . $lang . "'";
316 if ($minfrom != '') {
317 $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, [
332 '$field' => [$id, $label, $input_text, '', (($required) ? '*' : ''), 'placeholder="' . $readable_format . '"'],
335 $o .= "<script type='text/javascript'>";
336 $o .= "\$(function () {var picker = \$('#id_$id').datetimepicker({step:5,format:'$dateformat' $minjs $maxjs $pickers $defaultdatejs}); $extra_js})";
343 * @brief Returns a relative date string.
345 * Implements "3 seconds ago" etc.
346 * Based on $posted_date, (UTC).
347 * Results relative to current timezone.
348 * Limited to range of timestamps.
350 * @param string $posted_date MySQL-formatted date string (YYYY-MM-DD HH:MM:SS)
351 * @param string $format (optional) Parsed with sprintf()
352 * <tt>%1$d %2$s ago</tt>, e.g. 22 hours ago, 1 minute ago
354 * @return string with relative date
356 function relative_date($posted_date, $format = null) {
358 $localtime = $posted_date . ' UTC';
360 $abs = strtotime($localtime);
362 if (is_null($posted_date) || $posted_date <= NULL_DATE || $abs === false) {
363 return L10n::t('never');
366 $etime = time() - $abs;
369 return L10n::t('less than a second ago');
372 $a = [ 12 * 30 * 24 * 60 * 60 => [L10n::t('year'), L10n::t('years')],
373 30 * 24 * 60 * 60 => [L10n::t('month'), L10n::t('months')],
374 7 * 24 * 60 * 60 => [L10n::t('week'), L10n::t('weeks')],
375 24 * 60 * 60 => [L10n::t('day'), L10n::t('days')],
376 60 * 60 => [L10n::t('hour'), L10n::t('hours')],
377 60 => [L10n::t('minute'), L10n::t('minutes')],
378 1 => [L10n::t('second'), L10n::t('seconds')]
381 foreach ($a as $secs => $str) {
385 // translators - e.g. 22 hours ago, 1 minute ago
387 $format = L10n::t('%1$d %2$s ago');
390 return sprintf($format, $r, (($r == 1) ? $str[0] : $str[1]));
396 * @brief Returns timezone correct age in years.
398 * Returns the age in years, given a date of birth, the timezone of the person
399 * whose date of birth is provided, and the timezone of the person viewing the
402 * Why? Bear with me. Let's say I live in Mittagong, Australia, and my birthday
403 * is on New Year's. You live in San Bruno, California.
404 * When exactly are you going to see my age increase?
406 * A: 5:00 AM Dec 31 San Bruno time. That's precisely when I start celebrating
407 * and become a year older. If you wish me happy birthday on January 1
408 * (San Bruno time), you'll be a day late.
410 * @param string $dob Date of Birth
411 * @param string $owner_tz (optional) Timezone of the person of interest
412 * @param string $viewer_tz (optional) Timezone of the person viewing
414 * @return int Age in years
416 function age($dob, $owner_tz = '', $viewer_tz = '') {
417 if (! intval($dob)) {
421 $owner_tz = date_default_timezone_get();
424 $viewer_tz = date_default_timezone_get();
427 $birthdate = datetime_convert('UTC', $owner_tz,$dob . ' 00:00:00+00:00','Y-m-d');
428 list($year, $month, $day) = explode("-", $birthdate);
429 $year_diff = datetime_convert('UTC',$viewer_tz, 'now', 'Y') - $year;
430 $curr_month = datetime_convert('UTC',$viewer_tz, 'now', 'm');
431 $curr_day = datetime_convert('UTC',$viewer_tz, 'now', 'd');
433 if (($curr_month < $month) || (($curr_month == $month) && ($curr_day < $day))) {
441 * @brief Get days of a month in a given year.
443 * Returns number of days in the month of the given year.
444 * $m = 1 is 'January' to match human usage.
447 * @param int $m Month (1=January, 12=December)
449 * @return int Number of days in the given month
451 function get_dim($y, $m) {
454 31, 28, 31, 30, 31, 30,
455 31, 31, 30, 31, 30, 31];
459 } elseif (((($y % 4) == 0) && (($y % 100) != 0)) || (($y % 400) == 0)) {
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 function get_first_dim($y,$m) {
477 $d = sprintf('%04d-%02d-01 00:00', intval($y), intval($m));
479 return datetime_convert('UTC','UTC',$d,'w');
483 * @brief Output a calendar for the given month, year.
485 * If $links are provided (array), e.g. $links[12] => 'http://mylink' ,
486 * date 12 will be linked appropriately. Today's date is also noted by
488 * Months count from 1.
491 * @param int $m Month
492 * @param array $links (default null)
493 * @param string $class
497 * @todo Provide (prev,next) links, define class variations for different size calendars
499 function cal($y = 0, $m = 0, $links = null, $class = '')
501 // month table - start at 1 to match human usage.
503 'January', 'February', 'March',
504 'April' , 'May' , 'June',
505 'July' , 'August' , 'September',
506 'October', 'November', 'December'
509 $thisyear = datetime_convert('UTC', date_default_timezone_get(), 'now', 'Y');
510 $thismonth = datetime_convert('UTC', date_default_timezone_get(), 'now', 'm');
516 $m = intval($thismonth);
519 $dn = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
520 $f = get_first_dim($y, $m);
521 $l = get_dim($y, $m);
526 if (($y == $thisyear) && ($m == $thismonth)) {
527 $tddate = intval(datetime_convert('UTC', date_default_timezone_get(), 'now', 'j'));
530 $str_month = day_translate($mtab[$m]);
531 $o = '<table class="calendar' . $class . '">';
532 $o .= "<caption>$str_month $y</caption><tr>";
533 for ($a = 0; $a < 7; $a ++) {
534 $o .= '<th>' . mb_substr(day_translate($dn[$a]), 0, 3, 'UTF-8') . '</th>';
540 if (($dow == $f) && (! $started)) {
544 $today = (((isset($tddate)) && ($tddate == $d)) ? "class=\"today\" " : '');
546 $day = str_replace(' ', ' ', sprintf('%2.2d', $d));
548 if (x($links, $d) !== false) {
549 $o .= "<a href=\"{$links[$d]}\">$day</a>";
561 if (($dow == 7) && ($d <= $l)) {
567 for ($a = $dow; $a < 7; $a ++) {
568 $o .= '<td> </td>';
572 $o .= '</tr></table>' . "\r\n";
578 * @brief Create a birthday event.
580 * Update the year and the birthday.
582 function update_contact_birthdays() {
584 // This only handles foreign or alien networks where a birthday has been provided.
585 // In-network birthdays are handled within local_delivery
587 $r = q("SELECT * FROM `contact` WHERE `bd` != '' AND `bd` > '0001-01-01' AND SUBSTRING(`bd`, 1, 4) != `bdyear` ");
588 if (DBM::is_result($r)) {
589 foreach ($r as $rr) {
591 logger('update_contact_birthday: ' . $rr['bd']);
593 $nextbd = datetime_convert('UTC','UTC','now','Y') . substr($rr['bd'], 4);
596 * Add new birthday event for this person
598 * $bdtext is just a readable placeholder in case the event is shared
599 * with others. We will replace it during presentation to our $importer
600 * to contain a sparkle link and perhaps a photo.
603 // Check for duplicates
604 $s = q("SELECT `id` FROM `event` WHERE `uid` = %d AND `cid` = %d AND `start` = '%s' AND `type` = '%s' LIMIT 1",
607 dbesc(datetime_convert('UTC','UTC', $nextbd)),
610 if (DBM::is_result($s)) {
614 $bdtext = sprintf(L10n::t('%s\'s birthday'), $rr['name']);
615 $bdtext2 = sprintf(L10n::t('Happy Birthday %s'), ' [url=' . $rr['url'] . ']' . $rr['name'] . '[/url]') ;
617 q("INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`summary`,`desc`,`type`,`adjust`)
618 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%d' ) ",
621 dbesc(datetime_convert()),
622 dbesc(datetime_convert()),
623 dbesc(datetime_convert('UTC','UTC', $nextbd)),
624 dbesc(datetime_convert('UTC','UTC', $nextbd . ' + 1 day ')),
633 q("UPDATE `contact` SET `bdyear` = '%s', `bd` = '%s' WHERE `uid` = %d AND `id` = %d",
634 dbesc(substr($nextbd,0,4)),