3 * @file include/datetime.php
4 * @brief Some functions for date and time related tasks.
7 use Friendica\Core\Config;
8 use Friendica\Core\PConfig;
11 * @brief Two-level sort for timezones.
17 function timezone_cmp($a, $b) {
18 if (strstr($a, '/') && strstr($b, '/')) {
19 if ( t($a) == t($b)) {
22 return ( t($a) < t($b)) ? -1 : 1;
25 if (strstr($a, '/')) {
27 } elseif (strstr($b, '/')) {
29 } elseif ( t($a) == t($b)) {
33 return ( t($a) < t($b)) ? -1 : 1;
37 * @brief Emit a timezone selector grouped (primarily) by continent
39 * @param string $current Timezone
40 * @return string Parsed HTML output
42 function select_timezone($current = 'America/Los_Angeles') {
44 $timezone_identifiers = DateTimeZone::listIdentifiers();
46 $o ='<select id="timezone_select" name="timezone">';
48 usort($timezone_identifiers, 'timezone_cmp');
50 foreach ($timezone_identifiers as $value) {
51 $ex = explode("/", $value);
53 if ($ex[0] != $continent) {
54 if ($continent != '') {
58 $o .= '<optgroup label="' . t($continent) . '">';
61 $city = substr($value,strpos($value,'/')+1);
67 if ($continent != t('Miscellaneous')) {
69 $continent = t('Miscellaneous');
70 $o .= '<optgroup label="' . t($continent) . '">';
73 $city = str_replace('_', ' ', t($city));
74 $selected = (($value == $current) ? " selected=\"selected\" " : "");
75 $o .= "<option value=\"$value\" $selected >$city</option>";
77 $o .= '</optgroup></select>';
84 * @brief Generating a Timezone selector
86 * Return a select using 'field_select_raw' template, with timezones
87 * groupped (primarily) by continent
88 * arguments follow convetion as other field_* template array:
89 * 'name', 'label', $value, 'help'
91 * @param string $name Name of the selector
92 * @param string $label Label for the selector
93 * @param string $current Timezone
94 * @param string $help Help text
96 * @return string Parsed HTML
98 function field_timezone($name='timezone', $label='', $current = 'America/Los_Angeles', $help){
99 $options = select_timezone($current);
100 $options = str_replace('<select id="timezone_select" name="timezone">','', $options);
101 $options = str_replace('</select>','', $options);
103 $tpl = get_markup_template('field_select_raw.tpl');
104 return replace_macros($tpl, array(
105 '$field' => array($name, $label, $current, $help, $options),
111 * @brief General purpose date parse/convert function.
113 * @param string $from Source timezone
114 * @param string $to Dest timezone
115 * @param string $s Some parseable date/time string
116 * @param string $fmt Output format recognised from php's DateTime class
117 * http://www.php.net/manual/en/datetime.format.php
119 * @return string Formatted date according to given format
121 function datetime_convert($from = 'UTC', $to = 'UTC', $s = 'now', $fmt = "Y-m-d H:i:s") {
123 // Defaults to UTC if nothing is set, but throws an exception if set to empty string.
124 // Provide some sane defaults regardless.
132 if ( ($s === '') || (! is_string($s)) ) {
137 * Slight hackish adjustment so that 'zero' datetime actually returns what is intended
138 * otherwise we end up with -0001-11-30 ...
139 * add 32 days so that we at least get year 00, and then hack around the fact that
140 * months and days always start with 1.
143 if (substr($s,0,10) <= '0001-01-01') {
144 $d = new DateTime($s . ' + 32 days', new DateTimeZone('UTC'));
145 return str_replace('1','0',$d->format($fmt));
149 $from_obj = new DateTimeZone($from);
150 } catch (Exception $e) {
151 $from_obj = new DateTimeZone('UTC');
155 $d = new DateTime($s, $from_obj);
156 } catch (Exception $e) {
157 logger('datetime_convert: exception: ' . $e->getMessage());
158 $d = new DateTime('now', $from_obj);
162 $to_obj = new DateTimeZone($to);
163 } catch (Exception $e) {
164 $to_obj = new DateTimeZone('UTC');
167 $d->setTimeZone($to_obj);
169 return $d->format($fmt);
174 * @brief Wrapper for date selector, tailored for use in birthday fields.
176 * @param string $dob Date of Birth
177 * @return string Formatted html
180 list($year,$month,$day) = sscanf($dob,'%4d-%2d-%2d');
182 $f = Config::get('system', 'birthday_input_format');
186 if ($dob <= '0001-01-01') {
189 $value = (($year) ? datetime_convert('UTC','UTC',$dob,'Y-m-d') : datetime_convert('UTC','UTC',$dob,'m-d'));
192 $age = ((intval($value)) ? age($value, $a->user["timezone"], $a->user["timezone"]) : "");
194 $o = replace_macros(get_markup_template("field_input.tpl"), array(
199 (((intval($age)) > 0 ) ? t('Age: ') . $age : ""),
201 'placeholder="' . t('YYYY-MM-DD or MM-DD') . '"'
205 /// @TODO Old-lost code?
206 // if ($dob && $dob > '0001-01-01')
207 // $o = datesel($f,mktime(0,0,0,0,0,1900),mktime(),mktime(0,0,0,$month,$day,$year), 'dob');
209 // $o = datesel($f,mktime(0,0,0,0,0,1900),mktime(),false,'dob');
215 * @brief Returns a date selector
217 * @param string $format
218 * Format string, e.g. 'ymd' or 'mdy'. Not currently supported
220 * Unix timestamp of minimum date
222 * Unix timestap of maximum date
223 * @param string $default
224 * Unix timestamp of default date
226 * ID and name of datetimepicker (defaults to "datetimepicker")
228 * @return string Parsed HTML output.
230 function datesel($format, $min, $max, $default, $id = 'datepicker') {
231 return datetimesel($format, $min, $max, $default, '', $id, true, false, '', '');
235 * @brief Returns a time selector
237 * @param string $format
238 * Format string, e.g. 'ymd' or 'mdy'. Not currently supported
240 * Already selected hour
242 * Already selected minute
244 * ID and name of datetimepicker (defaults to "timepicker")
246 * @return string Parsed HTML output.
248 function timesel($format, $h, $m, $id = 'timepicker') {
249 return datetimesel($format, new DateTime(), new DateTime(), new DateTime("$h:$m"), '', $id, false, true);
253 * @brief Returns a datetime selector.
255 * @param string $format
256 * format string, e.g. 'ymd' or 'mdy'. Not currently supported
258 * unix timestamp of minimum date
260 * unix timestap of maximum date
261 * @param string $default
262 * unix timestamp of default date
264 * id and name of datetimepicker (defaults to "datetimepicker")
265 * @param bool $pickdate
266 * true to show date picker (default)
267 * @param boolean $picktime
268 * true to show time picker (default)
270 * set minimum date from picker with id $minfrom (none by default)
272 * set maximum date from picker with id $maxfrom (none by default)
273 * @param bool $required default false
275 * @return string Parsed HTML output.
277 * @todo Once browser support is better this could probably be replaced with
278 * native HTML5 date picker.
280 function datetimesel($format, $min, $max, $default, $label, $id = 'datetimepicker', $pickdate = true, $picktime = true, $minfrom = '', $maxfrom = '', $required = false) {
282 // First day of the week (0 = Sunday)
283 $firstDay = PConfig::get(local_user(), 'system', 'first_day_of_week', 0);
285 $lang = substr(get_browser_language(), 0, 2);
287 // Check if the detected language is supported by the picker
288 if (!in_array($lang, array("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"))) {
289 $lang = Config::get('system', 'language', 'en');
296 $dateformat .= 'Y-m-d';
298 if ($pickdate && $picktime) {
302 $dateformat .= 'H:i';
305 $minjs = $min ? ",minDate: new Date({$min->getTimestamp()}*1000), yearStart: " . $min->format('Y') : '';
306 $maxjs = $max ? ",maxDate: new Date({$max->getTimestamp()}*1000), yearEnd: " . $max->format('Y') : '';
308 $input_text = $default ? date($dateformat, $default->getTimestamp()) : '';
309 $defaultdatejs = $default ? ",defaultDate: new Date({$default->getTimestamp()}*1000)" : '';
313 $pickers .= ', datepicker: false';
316 $pickers .= ',timepicker: false';
320 $pickers .= ",dayOfWeekStart: " . $firstDay . ",lang:'" . $lang . "'";
321 if ($minfrom != '') {
322 $extra_js .= "\$('#id_$minfrom').data('xdsoft_datetimepicker').setOptions({onChangeDateTime: function (currentDateTime) { \$('#id_$id').data('xdsoft_datetimepicker').setOptions({minDate: currentDateTime})}})";
324 if ($maxfrom != '') {
325 $extra_js .= "\$('#id_$maxfrom').data('xdsoft_datetimepicker').setOptions({onChangeDateTime: function (currentDateTime) { \$('#id_$id').data('xdsoft_datetimepicker').setOptions({maxDate: currentDateTime})}})";
328 $readable_format = $dateformat;
329 $readable_format = str_replace('Y','yyyy',$readable_format);
330 $readable_format = str_replace('m','mm',$readable_format);
331 $readable_format = str_replace('d','dd',$readable_format);
332 $readable_format = str_replace('H','HH',$readable_format);
333 $readable_format = str_replace('i','MM',$readable_format);
335 $tpl = get_markup_template('field_input.tpl');
336 $o .= replace_macros($tpl, array(
337 '$field' => array($id, $label, $input_text, '', (($required) ? '*' : ''), 'placeholder="' . $readable_format . '"'),
340 $o .= "<script type='text/javascript'>";
341 $o .= "\$(function () {var picker = \$('#id_$id').datetimepicker({step:5,format:'$dateformat' $minjs $maxjs $pickers $defaultdatejs}); $extra_js})";
348 * @brief Returns a relative date string.
350 * Implements "3 seconds ago" etc.
351 * Based on $posted_date, (UTC).
352 * Results relative to current timezone.
353 * Limited to range of timestamps.
355 * @param string $posted_date MySQL-formatted date string (YYYY-MM-DD HH:MM:SS)
356 * @param string $format (optional) Parsed with sprintf()
357 * <tt>%1$d %2$s ago</tt>, e.g. 22 hours ago, 1 minute ago
359 * @return string with relative date
361 function relative_date($posted_date, $format = null) {
363 $localtime = $posted_date . ' UTC';
365 $abs = strtotime($localtime);
367 if (is_null($posted_date) || $posted_date <= NULL_DATE || $abs === False) {
371 $etime = time() - $abs;
374 return t('less than a second ago');
377 $a = array( 12 * 30 * 24 * 60 * 60 => array( t('year'), t('years')),
378 30 * 24 * 60 * 60 => array( t('month'), t('months')),
379 7 * 24 * 60 * 60 => array( t('week'), t('weeks')),
380 24 * 60 * 60 => array( t('day'), t('days')),
381 60 * 60 => array( t('hour'), t('hours')),
382 60 => array( t('minute'), t('minutes')),
383 1 => array( t('second'), t('seconds'))
386 foreach ($a as $secs => $str) {
390 // translators - e.g. 22 hours ago, 1 minute ago
392 $format = t('%1$d %2$s ago');
395 return sprintf($format, $r, (($r == 1) ? $str[0] : $str[1]));
401 * @brief Returns timezone correct age in years.
403 * Returns the age in years, given a date of birth, the timezone of the person
404 * whose date of birth is provided, and the timezone of the person viewing the
407 * Why? Bear with me. Let's say I live in Mittagong, Australia, and my birthday
408 * is on New Year's. You live in San Bruno, California.
409 * When exactly are you going to see my age increase?
411 * A: 5:00 AM Dec 31 San Bruno time. That's precisely when I start celebrating
412 * and become a year older. If you wish me happy birthday on January 1
413 * (San Bruno time), you'll be a day late.
415 * @param string $dob Date of Birth
416 * @param string $owner_tz (optional) Timezone of the person of interest
417 * @param string $viewer_tz (optional) Timezone of the person viewing
419 * @return int Age in years
421 function age($dob, $owner_tz = '', $viewer_tz = '') {
422 if (! intval($dob)) {
426 $owner_tz = date_default_timezone_get();
429 $viewer_tz = date_default_timezone_get();
432 $birthdate = datetime_convert('UTC', $owner_tz,$dob . ' 00:00:00+00:00','Y-m-d');
433 list($year, $month, $day) = explode("-", $birthdate);
434 $year_diff = datetime_convert('UTC',$viewer_tz, 'now', 'Y') - $year;
435 $curr_month = datetime_convert('UTC',$viewer_tz, 'now', 'm');
436 $curr_day = datetime_convert('UTC',$viewer_tz, 'now', 'd');
438 if (($curr_month < $month) || (($curr_month == $month) && ($curr_day < $day))) {
446 * @brief Get days of a month in a given year.
448 * Returns number of days in the month of the given year.
449 * $m = 1 is 'January' to match human usage.
452 * @param int $m Month (1=January, 12=December)
454 * @return int Number of days in the given month
456 function get_dim($y, $m) {
459 31, 28, 31, 30, 31, 30,
460 31, 31, 30, 31, 30, 31);
464 } elseif (((($y % 4) == 0) && (($y % 100) != 0)) || (($y % 400) == 0)) {
472 * @brief Returns the first day in month for a given month, year.
477 * @param int $m Month (1=January, 12=December)
479 * @return string day 0 = Sunday through 6 = Saturday
481 function get_first_dim($y,$m) {
482 $d = sprintf('%04d-%02d-01 00:00', intval($y), intval($m));
484 return datetime_convert('UTC','UTC',$d,'w');
488 * @brief Output a calendar for the given month, year.
490 * If $links are provided (array), e.g. $links[12] => 'http://mylink' ,
491 * date 12 will be linked appropriately. Today's date is also noted by
493 * Months count from 1.
496 * @param int $m Month
497 * @param bool $links (default false)
498 * @param string $class
502 * @todo Provide (prev,next) links, define class variations for different size calendars
504 function cal($y = 0,$m = 0, $links = false, $class='') {
505 // month table - start at 1 to match human usage.
508 'January', 'February', 'March',
509 'April' , 'May' , 'June',
510 'July' , 'August' , 'September',
511 'October', 'November', 'December'
514 $thisyear = datetime_convert('UTC', date_default_timezone_get(), 'now','Y');
515 $thismonth = datetime_convert('UTC', date_default_timezone_get(), 'now','m');
520 $m = intval($thismonth);
523 $dn = array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday');
524 $f = get_first_dim($y,$m);
530 if (($y == $thisyear) && ($m == $thismonth)) {
531 $tddate = intval(datetime_convert('UTC', date_default_timezone_get(), 'now', 'j'));
534 $str_month = day_translate($mtab[$m]);
535 $o = '<table class="calendar' . $class . '">';
536 $o .= "<caption>$str_month $y</caption><tr>";
537 for ($a = 0; $a < 7; $a ++) {
538 $o .= '<th>' . mb_substr(day_translate($dn[$a]), 0, 3, 'UTF-8') . '</th>';
544 if (($dow == $f) && (! $started)) {
548 $today = (((isset($tddate)) && ($tddate == $d)) ? "class=\"today\" " : '');
550 $day = str_replace(' ', ' ', sprintf('%2.2d', $d));
552 if (is_array($links) && isset($links[$d])) {
553 $o .= "<a href=\"{$links[$d]}\">$day</a>";
565 if (($dow == 7) && ($d <= $l)) {
571 for ($a = $dow; $a < 7; $a ++) {
572 $o .= '<td> </td>';
576 $o .= '</tr></table>'."\r\n";
582 * @brief Create a birthday event.
584 * Update the year and the birthday.
586 function update_contact_birthdays() {
588 // This only handles foreign or alien networks where a birthday has been provided.
589 // In-network birthdays are handled within local_delivery
591 $r = q("SELECT * FROM `contact` WHERE `bd` != '' AND `bd` > '0001-01-01' AND SUBSTRING(`bd`, 1, 4) != `bdyear` ");
592 if (dbm::is_result($r)) {
593 foreach ($r as $rr) {
595 logger('update_contact_birthday: ' . $rr['bd']);
597 $nextbd = datetime_convert('UTC','UTC','now','Y') . substr($rr['bd'], 4);
600 * Add new birthday event for this person
602 * $bdtext is just a readable placeholder in case the event is shared
603 * with others. We will replace it during presentation to our $importer
604 * to contain a sparkle link and perhaps a photo.
607 // Check for duplicates
608 $s = q("SELECT `id` FROM `event` WHERE `uid` = %d AND `cid` = %d AND `start` = '%s' AND `type` = '%s' LIMIT 1",
611 dbesc(datetime_convert('UTC','UTC', $nextbd)),
614 if (dbm::is_result($s)) {
618 $bdtext = sprintf( t('%s\'s birthday'), $rr['name']);
619 $bdtext2 = sprintf( t('Happy Birthday %s'), ' [url=' . $rr['url'] . ']' . $rr['name'] . '[/url]') ;
621 $r = q("INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`summary`,`desc`,`type`,`adjust`)
622 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%d' ) ",
625 dbesc(datetime_convert()),
626 dbesc(datetime_convert()),
627 dbesc(datetime_convert('UTC','UTC', $nextbd)),
628 dbesc(datetime_convert('UTC','UTC', $nextbd . ' + 1 day ')),
637 q("UPDATE `contact` SET `bdyear` = '%s', `bd` = '%s' WHERE `uid` = %d AND `id` = %d",
638 dbesc(substr($nextbd,0,4)),