3 * @file include/datetime.php
4 * @brief Some functions for date and time related tasks.
9 * @brief Two-level sort for timezones.
15 function timezone_cmp($a, $b) {
16 if(strstr($a,'/') && strstr($b,'/')) {
17 if ( t($a) == t($b)) return 0;
18 return ( t($a) < t($b)) ? -1 : 1;
20 if(strstr($a,'/')) return -1;
21 if(strstr($b,'/')) return 1;
22 if ( t($a) == t($b)) return 0;
24 return ( t($a) < t($b)) ? -1 : 1;
28 * @brief Emit a timezone selector grouped (primarily) by continent
30 * @param string $current Timezone
31 * @return string Parsed HTML output
33 function select_timezone($current = 'America/Los_Angeles') {
35 $timezone_identifiers = DateTimeZone::listIdentifiers();
37 $o ='<select id="timezone_select" name="timezone">';
39 usort($timezone_identifiers, 'timezone_cmp');
41 foreach($timezone_identifiers as $value) {
42 $ex = explode("/", $value);
44 if($ex[0] != $continent) {
48 $o .= '<optgroup label="' . t($continent) . '">';
51 $city = substr($value,strpos($value,'/')+1);
57 if($continent != t('Miscellaneous')) {
59 $continent = t('Miscellaneous');
60 $o .= '<optgroup label="' . t($continent) . '">';
63 $city = str_replace('_', ' ', t($city));
64 $selected = (($value == $current) ? " selected=\"selected\" " : "");
65 $o .= "<option value=\"$value\" $selected >$city</option>";
67 $o .= '</optgroup></select>';
74 * @brief Generating a Timezone selector
76 * Return a select using 'field_select_raw' template, with timezones
77 * groupped (primarily) by continent
78 * arguments follow convetion as other field_* template array:
79 * 'name', 'label', $value, 'help'
81 * @param string $name Name of the selector
82 * @param string $label Label for the selector
83 * @param string $current Timezone
84 * @param string $help Help text
86 * @return string Parsed HTML
88 function field_timezone($name='timezone', $label='', $current = 'America/Los_Angeles', $help){
89 $options = select_timezone($current);
90 $options = str_replace('<select id="timezone_select" name="timezone">','', $options);
91 $options = str_replace('</select>','', $options);
93 $tpl = get_markup_template('field_select_raw.tpl');
94 return replace_macros($tpl, array(
95 '$field' => array($name, $label, $current, $help, $options),
101 * @brief General purpose date parse/convert function.
103 * @param string $from Source timezone
104 * @param string $to Dest timezone
105 * @param string $s Some parseable date/time string
106 * @param string $fmt Output format recognised from php's DateTime class
107 * http://www.php.net/manual/en/datetime.format.php
109 * @return string Formatted date according to given format
111 function datetime_convert($from = 'UTC', $to = 'UTC', $s = 'now', $fmt = "Y-m-d H:i:s") {
113 // Defaults to UTC if nothing is set, but throws an exception if set to empty string.
114 // Provide some sane defaults regardless.
120 if( ($s === '') || (! is_string($s)) )
123 // Slight hackish adjustment so that 'zero' datetime actually returns what is intended
124 // otherwise we end up with -0001-11-30 ...
125 // add 32 days so that we at least get year 00, and then hack around the fact that
126 // months and days always start with 1.
128 if(substr($s,0,10) == '0000-00-00') {
129 $d = new DateTime($s . ' + 32 days', new DateTimeZone('UTC'));
130 return str_replace('1','0',$d->format($fmt));
134 $from_obj = new DateTimeZone($from);
136 catch(Exception $e) {
137 $from_obj = new DateTimeZone('UTC');
141 $d = new DateTime($s, $from_obj);
143 catch(Exception $e) {
144 logger('datetime_convert: exception: ' . $e->getMessage());
145 $d = new DateTime('now', $from_obj);
149 $to_obj = new DateTimeZone($to);
151 catch(Exception $e) {
152 $to_obj = new DateTimeZone('UTC');
155 $d->setTimeZone($to_obj);
157 return($d->format($fmt));
162 * @brief Wrapper for date selector, tailored for use in birthday fields.
164 * @param string $dob Date of Birth
168 list($year,$month,$day) = sscanf($dob,'%4d-%2d-%2d');
170 $f = get_config('system','birthday_input_format');
173 if($dob === '0000-00-00')
176 $value = (($year) ? datetime_convert('UTC','UTC',$dob,'Y-m-d') : datetime_convert('UTC','UTC',$dob,'m-d'));
178 $o = '<input type="text" name="dob" value="' . $value . '" placeholder="' . t('YYYY-MM-DD or MM-DD') . '" />';
180 // if ($dob && $dob != '0000-00-00')
181 // $o = datesel($f,mktime(0,0,0,0,0,1900),mktime(),mktime(0,0,0,$month,$day,$year),'dob');
183 // $o = datesel($f,mktime(0,0,0,0,0,1900),mktime(),false,'dob');
189 * @brief Returns a date selector
191 * @param string $format
192 * Format string, e.g. 'ymd' or 'mdy'. Not currently supported
194 * Unix timestamp of minimum date
196 * Unix timestap of maximum date
197 * @param string $default
198 * Unix timestamp of default date
200 * ID and name of datetimepicker (defaults to "datetimepicker")
202 * @return string Parsed HTML output.
204 function datesel($format, $min, $max, $default, $id = 'datepicker') {
205 return datetimesel($format,$min,$max,$default,'',$id,true,false, '','');
209 * @brief Returns a time selector
211 * @param string $format
212 * Format string, e.g. 'ymd' or 'mdy'. Not currently supported
214 * Already selected hour
216 * Already selected minute
218 * ID and name of datetimepicker (defaults to "timepicker")
220 * @return string Parsed HTML output.
222 function timesel($format, $h, $m, $id='timepicker') {
223 return datetimesel($format,new DateTime(),new DateTime(),new DateTime("$h:$m"),'',$id,false,true);
227 * @brief Returns a datetime selector.
229 * @param string $format
230 * format string, e.g. 'ymd' or 'mdy'. Not currently supported
232 * unix timestamp of minimum date
234 * unix timestap of maximum date
235 * @param string $default
236 * unix timestamp of default date
238 * id and name of datetimepicker (defaults to "datetimepicker")
239 * @param bool $pickdate
240 * true to show date picker (default)
241 * @param boolean $picktime
242 * true to show time picker (default)
244 * set minimum date from picker with id $minfrom (none by default)
246 * set maximum date from picker with id $maxfrom (none by default)
247 * @param bool $required default false
249 * @return string Parsed HTML output.
251 * @todo Once browser support is better this could probably be replaced with
252 * native HTML5 date picker.
254 function datetimesel($format, $min, $max, $default, $label, $id = 'datetimepicker', $pickdate = true, $picktime = true, $minfrom = '', $maxfrom = '', $required = false) {
256 // First day of the week (0 = Sunday)
257 $firstDay = get_pconfig(local_user(),'system','first_day_of_week');
258 if ($firstDay === false) $firstDay=0;
260 $lang = substr(get_browser_language(), 0, 2);
262 // Check if the detected language is supported by the picker
263 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")))
264 $lang = ((isset($a->config['system']['language'])) ? $a->config['system']['language'] : 'en');
269 if($pickdate) $dateformat .= 'Y-m-d';
270 if($pickdate && $picktime) $dateformat .= ' ';
271 if($picktime) $dateformat .= 'H:i';
273 $minjs = $min ? ",minDate: new Date({$min->getTimestamp()}*1000), yearStart: " . $min->format('Y') : '';
274 $maxjs = $max ? ",maxDate: new Date({$max->getTimestamp()}*1000), yearEnd: " . $max->format('Y') : '';
276 $input_text = $default ? date($dateformat, $default->getTimestamp()) : '';
277 $defaultdatejs = $default ? ",defaultDate: new Date({$default->getTimestamp()}*1000)" : '';
280 if(!$pickdate) $pickers .= ',datepicker: false';
281 if(!$picktime) $pickers .= ',timepicker: false';
284 $pickers .= ",dayOfWeekStart: ".$firstDay.",lang:'".$lang."'";
286 $extra_js .= "\$('#id_$minfrom').data('xdsoft_datetimepicker').setOptions({onChangeDateTime: function (currentDateTime) { \$('#id_$id').data('xdsoft_datetimepicker').setOptions({minDate: currentDateTime})}})";
288 $extra_js .= "\$('#id_$maxfrom').data('xdsoft_datetimepicker').setOptions({onChangeDateTime: function (currentDateTime) { \$('#id_$id').data('xdsoft_datetimepicker').setOptions({maxDate: currentDateTime})}})";
290 $readable_format = $dateformat;
291 $readable_format = str_replace('Y','yyyy',$readable_format);
292 $readable_format = str_replace('m','mm',$readable_format);
293 $readable_format = str_replace('d','dd',$readable_format);
294 $readable_format = str_replace('H','HH',$readable_format);
295 $readable_format = str_replace('i','MM',$readable_format);
297 $tpl = get_markup_template('field_input.tpl');
298 $o .= replace_macros($tpl,array(
299 '$field' => array($id, $label, $input_text, '', (($required) ? '*' : ''), 'placeholder="' . $readable_format . '"'),
301 // $o .= "<div class='date'><input type='text' placeholder='$readable_format' name='$id' id='$id' $input_text />";
303 $o .= "<script type='text/javascript'>";
304 $o .= "\$(function () {var picker = \$('#id_$id').datetimepicker({step:5,format:'$dateformat' $minjs $maxjs $pickers $defaultdatejs}); $extra_js})";
311 * @brief Returns a relative date string.
313 * Implements "3 seconds ago" etc.
314 * Based on $posted_date, (UTC).
315 * Results relative to current timezone.
316 * Limited to range of timestamps.
318 * @param string $posted_date
319 * @param string $format (optional) Parsed with sprintf()
320 * <tt>%1$d %2$s ago</tt>, e.g. 22 hours ago, 1 minute ago
322 * @return string with relative date
324 function relative_date($posted_date,$format = null) {
326 $localtime = datetime_convert('UTC',date_default_timezone_get(),$posted_date);
328 $abs = strtotime($localtime);
330 if (is_null($posted_date) || $posted_date === '0000-00-00 00:00:00' || $abs === False) {
334 $etime = time() - $abs;
337 return t('less than a second ago');
342 if ($etime >= 86400) {
343 $time_append = ' ('.$localtime.')';
347 $a = array( 12 * 30 * 24 * 60 * 60 => array( t('year'), t('years')),
348 30 * 24 * 60 * 60 => array( t('month'), t('months')),
349 7 * 24 * 60 * 60 => array( t('week'), t('weeks')),
350 24 * 60 * 60 => array( t('day'), t('days')),
351 60 * 60 => array( t('hour'), t('hours')),
352 60 => array( t('minute'), t('minutes')),
353 1 => array( t('second'), t('seconds'))
356 foreach ($a as $secs => $str) {
360 // translators - e.g. 22 hours ago, 1 minute ago
362 $format = t('%1$d %2$s ago');
364 return sprintf( $format,$r, (($r == 1) ? $str[0] : $str[1]));
370 * @brief Returns timezone correct age in years.
372 * Returns the age in years, given a date of birth, the timezone of the person
373 * whose date of birth is provided, and the timezone of the person viewing the
376 * Why? Bear with me. Let's say I live in Mittagong, Australia, and my birthday
377 * is on New Year's. You live in San Bruno, California.
378 * When exactly are you going to see my age increase?
380 * A: 5:00 AM Dec 31 San Bruno time. That's precisely when I start celebrating
381 * and become a year older. If you wish me happy birthday on January 1
382 * (San Bruno time), you'll be a day late.
384 * @param string $dob Date of Birth
385 * @param string $owner_tz (optional) Timezone of the person of interest
386 * @param string $viewer_tz (optional) Timezone of the person viewing
388 * @return int Age in years
390 function age($dob,$owner_tz = '',$viewer_tz = '') {
394 $owner_tz = date_default_timezone_get();
396 $viewer_tz = date_default_timezone_get();
398 $birthdate = datetime_convert('UTC',$owner_tz,$dob . ' 00:00:00+00:00','Y-m-d');
399 list($year,$month,$day) = explode("-",$birthdate);
400 $year_diff = datetime_convert('UTC',$viewer_tz,'now','Y') - $year;
401 $curr_month = datetime_convert('UTC',$viewer_tz,'now','m');
402 $curr_day = datetime_convert('UTC',$viewer_tz,'now','d');
404 if(($curr_month < $month) || (($curr_month == $month) && ($curr_day < $day)))
411 * @brief Get days of a month in a given year.
413 * Returns number of days in the month of the given year.
414 * $m = 1 is 'January' to match human usage.
417 * @param int $m Month (1=January, 12=December)
419 * @return int Number of days in the given month
421 function get_dim($y,$m) {
424 31, 28, 31, 30, 31, 30,
425 31, 31, 30, 31, 30, 31);
430 if(((($y % 4) == 0) && (($y % 100) != 0)) || (($y % 400) == 0))
437 * @brief Returns the first day in month for a given month, year.
442 * @param int $m Month (1=January, 12=December)
444 * @return string day 0 = Sunday through 6 = Saturday
446 function get_first_dim($y,$m) {
447 $d = sprintf('%04d-%02d-01 00:00', intval($y), intval($m));
449 return datetime_convert('UTC','UTC',$d,'w');
453 * @brief Output a calendar for the given month, year.
455 * If $links are provided (array), e.g. $links[12] => 'http://mylink' ,
456 * date 12 will be linked appropriately. Today's date is also noted by
458 * Months count from 1.
461 * @param int $m Month
462 * @param bool $links (default false)
463 * @param string $class
467 * @todo Provide (prev,next) links, define class variations for different size calendars
469 function cal($y = 0,$m = 0, $links = false, $class='') {
472 // month table - start at 1 to match human usage.
475 'January','February','March',
476 'April','May','June',
477 'July','August','September',
478 'October','November','December'
481 $thisyear = datetime_convert('UTC',date_default_timezone_get(),'now','Y');
482 $thismonth = datetime_convert('UTC',date_default_timezone_get(),'now','m');
486 $m = intval($thismonth);
488 $dn = array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday');
489 $f = get_first_dim($y,$m);
495 if(($y == $thisyear) && ($m == $thismonth))
496 $tddate = intval(datetime_convert('UTC',date_default_timezone_get(),'now','j'));
498 $str_month = day_translate($mtab[$m]);
499 $o = '<table class="calendar' . $class . '">';
500 $o .= "<caption>$str_month $y</caption><tr>";
501 for($a = 0; $a < 7; $a ++)
502 $o .= '<th>' . mb_substr(day_translate($dn[$a]),0,3,'UTF-8') . '</th>';
507 if(($dow == $f) && (! $started))
510 $today = (((isset($tddate)) && ($tddate == $d)) ? "class=\"today\" " : '');
512 $day = str_replace(' ',' ',sprintf('%2.2d', $d));
514 if(is_array($links) && isset($links[$d]))
515 $o .= "<a href=\"{$links[$d]}\">$day</a>";
526 if(($dow == 7) && ($d <= $l)) {
532 for($a = $dow; $a < 7; $a ++)
533 $o .= '<td> </td>';
535 $o .= '</tr></table>'."\r\n";
541 * @brief Create a birthday event.
543 * Update the year and the birthday.
545 function update_contact_birthdays() {
547 // This only handles foreign or alien networks where a birthday has been provided.
548 // In-network birthdays are handled within local_delivery
550 $r = q("SELECT * FROM contact WHERE `bd` != '' AND `bd` != '0000-00-00' AND SUBSTRING(`bd`,1,4) != `bdyear` ");
554 logger('update_contact_birthday: ' . $rr['bd']);
556 $nextbd = datetime_convert('UTC','UTC','now','Y') . substr($rr['bd'],4);
560 * Add new birthday event for this person
562 * $bdtext is just a readable placeholder in case the event is shared
563 * with others. We will replace it during presentation to our $importer
564 * to contain a sparkle link and perhaps a photo.
568 $bdtext = sprintf( t('%s\'s birthday'), $rr['name']);
569 $bdtext2 = sprintf( t('Happy Birthday %s'), ' [url=' . $rr['url'] . ']' . $rr['name'] . '[/url]') ;
571 $r = q("INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`summary`,`desc`,`type`,`adjust`)
572 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%d' ) ",
575 dbesc(datetime_convert()),
576 dbesc(datetime_convert()),
577 dbesc(datetime_convert('UTC','UTC', $nextbd)),
578 dbesc(datetime_convert('UTC','UTC', $nextbd . ' + 1 day ')),
588 q("UPDATE `contact` SET `bdyear` = '%s', `bd` = '%s' WHERE `uid` = %d AND `id` = %d",
589 dbesc(substr($nextbd,0,4)),