3 // two-level sort for timezones.
5 if(! function_exists('timezone_cmp')) {
6 function timezone_cmp($a, $b) {
7 if(strstr($a,'/') && strstr($b,'/')) {
8 if ( t($a) == t($b)) return 0;
9 return ( t($a) < t($b)) ? -1 : 1;
11 if(strstr($a,'/')) return -1;
12 if(strstr($b,'/')) return 1;
13 if ( t($a) == t($b)) return 0;
14 return ( t($a) < t($b)) ? -1 : 1;
17 // emit a timezone selector grouped (primarily) by continent
18 if(! function_exists('select_timezone')) {
19 function select_timezone($current = 'America/Los_Angeles') {
21 $timezone_identifiers = DateTimeZone::listIdentifiers();
23 $o ='<select id="timezone_select" name="timezone">';
25 usort($timezone_identifiers, 'timezone_cmp');
27 foreach($timezone_identifiers as $value) {
28 $ex = explode("/", $value);
30 if($ex[0] != $continent) {
34 $o .= '<optgroup label="' . t($continent) . '">';
37 $city = substr($value,strpos($value,'/')+1);
43 if($continent != t('Miscellaneous')) {
45 $continent = t('Miscellaneous');
46 $o .= '<optgroup label="' . t($continent) . '">';
49 $city = str_replace('_', ' ', t($city));
50 $selected = (($value == $current) ? " selected=\"selected\" " : "");
51 $o .= "<option value=\"$value\" $selected >$city</option>";
53 $o .= '</optgroup></select>';
57 // return a select using 'field_select_raw' template, with timezones
58 // groupped (primarily) by continent
59 // arguments follow convetion as other field_* template array:
60 // 'name', 'label', $value, 'help'
61 if (!function_exists('field_timezone')){
62 function field_timezone($name='timezone', $label='', $current = 'America/Los_Angeles', $help){
63 $options = select_timezone($current);
64 $options = str_replace('<select id="timezone_select" name="timezone">','', $options);
65 $options = str_replace('</select>','', $options);
67 $tpl = get_markup_template('field_select_raw.tpl');
68 return replace_macros($tpl, array(
69 '$field' => array($name, $label, $current, $help, $options),
74 // General purpose date parse/convert function.
75 // $from = source timezone
76 // $to = dest timezone
77 // $s = some parseable date/time string
78 // $fmt = output format
80 if(! function_exists('datetime_convert')) {
81 function datetime_convert($from = 'UTC', $to = 'UTC', $s = 'now', $fmt = "Y-m-d H:i:s") {
83 // Defaults to UTC if nothing is set, but throws an exception if set to empty string.
84 // Provide some sane defaults regardless.
90 if( ($s === '') || (! is_string($s)) )
93 // Slight hackish adjustment so that 'zero' datetime actually returns what is intended
94 // otherwise we end up with -0001-11-30 ...
95 // add 32 days so that we at least get year 00, and then hack around the fact that
96 // months and days always start with 1.
98 if(substr($s,0,10) == '0000-00-00') {
99 $d = new DateTime($s . ' + 32 days', new DateTimeZone('UTC'));
100 return str_replace('1','0',$d->format($fmt));
104 $from_obj = new DateTimeZone($from);
106 catch(Exception $e) {
107 $from_obj = new DateTimeZone('UTC');
111 $d = new DateTime($s, $from_obj);
113 catch(Exception $e) {
114 logger('datetime_convert: exception: ' . $e->getMessage());
115 $d = new DateTime('now', $from_obj);
119 $to_obj = new DateTimeZone($to);
121 catch(Exception $e) {
122 $to_obj = new DateTimeZone('UTC');
125 $d->setTimeZone($to_obj);
126 return($d->format($fmt));
130 // wrapper for date selector, tailored for use in birthday fields
133 list($year,$month,$day) = sscanf($dob,'%4d-%2d-%2d');
134 $f = get_config('system','birthday_input_format');
137 if($dob === '0000-00-00')
140 $value = (($year) ? datetime_convert('UTC','UTC',$dob,'Y-m-d') : datetime_convert('UTC','UTC',$dob,'m-d'));
141 $o = '<input type="text" name="dob" value="' . $value . '" placeholder="' . t('YYYY-MM-DD or MM-DD') . '" />';
142 // if ($dob && $dob != '0000-00-00')
143 // $o = datesel($f,mktime(0,0,0,0,0,1900),mktime(),mktime(0,0,0,$month,$day,$year),'dob');
145 // $o = datesel($f,mktime(0,0,0,0,0,1900),mktime(),false,'dob');
150 * returns a date selector
152 * format string, e.g. 'ymd' or 'mdy'. Not currently supported
154 * unix timestamp of minimum date
156 * unix timestap of maximum date
158 * unix timestamp of default date
160 * id and name of datetimepicker (defaults to "datetimepicker")
162 if(! function_exists('datesel')) {
163 function datesel($format, $min, $max, $default, $id = 'datepicker') {
164 return datetimesel($format,$min,$max,$default,$id,true,false, '','');
168 * returns a time selector
170 * format string, e.g. 'ymd' or 'mdy'. Not currently supported
172 * already selected hour
174 * already selected minute
176 * id and name of datetimepicker (defaults to "timepicker")
178 if(! function_exists('timesel')) {
179 function timesel($format, $h, $m, $id='timepicker') {
180 return datetimesel($format,new DateTime(),new DateTime(),new DateTime("$h:$m"),$id,false,true);
184 * @brief Returns a datetime selector.
187 * format string, e.g. 'ymd' or 'mdy'. Not currently supported
189 * unix timestamp of minimum date
191 * unix timestap of maximum date
193 * unix timestamp of default date
195 * id and name of datetimepicker (defaults to "datetimepicker")
196 * @param boolean $pickdate
197 * true to show date picker (default)
198 * @param boolean $picktime
199 * true to show time picker (default)
201 * set minimum date from picker with id $minfrom (none by default)
203 * set maximum date from picker with id $maxfrom (none by default)
204 * @param boolean $required default false
205 * @return string Parsed HTML output.
207 * @todo Once browser support is better this could probably be replaced with
208 * native HTML5 date picker.
210 if(! function_exists('datetimesel')) {
211 function datetimesel($format, $min, $max, $default, $id = 'datetimepicker', $pickdate = true, $picktime = true, $minfrom = '', $maxfrom = '', $required = false) {
215 // First day of the week (0 = Sunday)
216 $firstDay = get_pconfig(local_user(),'system','first_day_of_week');
217 if ($firstDay === false) $firstDay=0;
219 $lang = substr(get_browser_language(), 0, 2);
221 // Check if the detected language is supported by the picker
222 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")))
223 $lang = ((isset($a->config['system']['language'])) ? $a->config['system']['language'] : 'en');
227 if($pickdate) $dateformat .= 'Y-m-d';
228 if($pickdate && $picktime) $dateformat .= ' ';
229 if($picktime) $dateformat .= 'H:i';
230 $minjs = $min ? ",minDate: new Date({$min->getTimestamp()}*1000), yearStart: " . $min->format('Y') : '';
231 $maxjs = $max ? ",maxDate: new Date({$max->getTimestamp()}*1000), yearEnd: " . $max->format('Y') : '';
233 $input_text = $default ? 'value="' . date($dateformat, $default->getTimestamp()) . '"' : '';
234 $defaultdatejs = $default ? ",defaultDate: new Date({$default->getTimestamp()}*1000)" : '';
236 if(!$pickdate) $pickers .= ',datepicker: false';
237 if(!$picktime) $pickers .= ',timepicker: false';
239 $pickers .= ",dayOfWeekStart: ".$firstDay.",lang:'".$lang."'";
241 $extra_js .= "\$('#$minfrom').data('xdsoft_datetimepicker').setOptions({onChangeDateTime: function (currentDateTime) { \$('#$id').data('xdsoft_datetimepicker').setOptions({minDate: currentDateTime})}})";
243 $extra_js .= "\$('#$maxfrom').data('xdsoft_datetimepicker').setOptions({onChangeDateTime: function (currentDateTime) { \$('#$id').data('xdsoft_datetimepicker').setOptions({maxDate: currentDateTime})}})";
244 $readable_format = $dateformat;
245 $readable_format = str_replace('Y','yyyy',$readable_format);
246 $readable_format = str_replace('m','mm',$readable_format);
247 $readable_format = str_replace('d','dd',$readable_format);
248 $readable_format = str_replace('H','HH',$readable_format);
249 $readable_format = str_replace('i','MM',$readable_format);
250 $o .= "<div class='date'><input type='text' placeholder='$readable_format' name='$id' id='$id' $input_text />";
252 $o .= "<script type='text/javascript'>";
253 $o .= "\$(function () {var picker = \$('#$id').datetimepicker({step:5,format:'$dateformat' $minjs $maxjs $pickers $defaultdatejs}); $extra_js})";
258 // implements "3 seconds ago" etc.
259 // based on $posted_date, (UTC).
260 // Results relative to current timezone
261 // Limited to range of timestamps
263 if(! function_exists('relative_date')) {
264 function relative_date($posted_date,$format = null) {
266 $localtime = datetime_convert('UTC',date_default_timezone_get(),$posted_date);
268 $abs = strtotime($localtime);
270 if (is_null($posted_date) || $posted_date === '0000-00-00 00:00:00' || $abs === False) {
274 $etime = time() - $abs;
277 return t('less than a second ago');
282 if ($etime >= 86400) {
283 $time_append = ' ('.$localtime.')';
287 $a = array( 12 * 30 * 24 * 60 * 60 => array( t('year'), t('years')),
288 30 * 24 * 60 * 60 => array( t('month'), t('months')),
289 7 * 24 * 60 * 60 => array( t('week'), t('weeks')),
290 24 * 60 * 60 => array( t('day'), t('days')),
291 60 * 60 => array( t('hour'), t('hours')),
292 60 => array( t('minute'), t('minutes')),
293 1 => array( t('second'), t('seconds'))
296 foreach ($a as $secs => $str) {
300 // translators - e.g. 22 hours ago, 1 minute ago
302 $format = t('%1$d %2$s ago');
303 return sprintf( $format,$r, (($r == 1) ? $str[0] : $str[1]));
310 // Returns age in years, given a date of birth,
311 // the timezone of the person whose date of birth is provided,
312 // and the timezone of the person viewing the result.
313 // Why? Bear with me. Let's say I live in Mittagong, Australia, and my
314 // birthday is on New Year's. You live in San Bruno, California.
315 // When exactly are you going to see my age increase?
316 // A: 5:00 AM Dec 31 San Bruno time. That's precisely when I start
317 // celebrating and become a year older. If you wish me happy birthday
318 // on January 1 (San Bruno time), you'll be a day late.
320 function age($dob,$owner_tz = '',$viewer_tz = '') {
324 $owner_tz = date_default_timezone_get();
326 $viewer_tz = date_default_timezone_get();
328 $birthdate = datetime_convert('UTC',$owner_tz,$dob . ' 00:00:00+00:00','Y-m-d');
329 list($year,$month,$day) = explode("-",$birthdate);
330 $year_diff = datetime_convert('UTC',$viewer_tz,'now','Y') - $year;
331 $curr_month = datetime_convert('UTC',$viewer_tz,'now','m');
332 $curr_day = datetime_convert('UTC',$viewer_tz,'now','d');
334 if(($curr_month < $month) || (($curr_month == $month) && ($curr_day < $day)))
342 // get_dim($year, $month);
343 // returns number of days.
344 // $month[1] = 'January';
345 // to match human usage.
347 if(! function_exists('get_dim')) {
348 function get_dim($y,$m) {
351 31, 28, 31, 30, 31, 30,
352 31, 31, 30, 31, 30, 31);
356 if(((($y % 4) == 0) && (($y % 100) != 0)) || (($y % 400) == 0))
362 // Returns the first day in month for a given month, year
363 // get_first_dim($year,$month)
364 // returns 0 = Sunday through 6 = Saturday
365 // Months start at 1.
367 if(! function_exists('get_first_dim')) {
368 function get_first_dim($y,$m) {
369 $d = sprintf('%04d-%02d-01 00:00', intval($y), intval($m));
370 return datetime_convert('UTC','UTC',$d,'w');
373 // output a calendar for the given month, year.
374 // if $links are provided (array), e.g. $links[12] => 'http://mylink' ,
375 // date 12 will be linked appropriately. Today's date is also noted by
376 // altering td class.
377 // Months count from 1.
380 // TODO: provide (prev,next) links, define class variations for different size calendars
383 if(! function_exists('cal')) {
384 function cal($y = 0,$m = 0, $links = false, $class='') {
387 // month table - start at 1 to match human usage.
390 'January','February','March',
391 'April','May','June',
392 'July','August','September',
393 'October','November','December'
396 $thisyear = datetime_convert('UTC',date_default_timezone_get(),'now','Y');
397 $thismonth = datetime_convert('UTC',date_default_timezone_get(),'now','m');
401 $m = intval($thismonth);
403 $dn = array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday');
404 $f = get_first_dim($y,$m);
410 if(($y == $thisyear) && ($m == $thismonth))
411 $tddate = intval(datetime_convert('UTC',date_default_timezone_get(),'now','j'));
413 $str_month = day_translate($mtab[$m]);
414 $o = '<table class="calendar' . $class . '">';
415 $o .= "<caption>$str_month $y</caption><tr>";
416 for($a = 0; $a < 7; $a ++)
417 $o .= '<th>' . mb_substr(day_translate($dn[$a]),0,3,'UTF-8') . '</th>';
421 if(($dow == $f) && (! $started))
423 $today = (((isset($tddate)) && ($tddate == $d)) ? "class=\"today\" " : '');
425 $day = str_replace(' ',' ',sprintf('%2.2d', $d));
427 if(is_array($links) && isset($links[$d]))
428 $o .= "<a href=\"{$links[$d]}\">$day</a>";
437 if(($dow == 7) && ($d <= $l)) {
443 for($a = $dow; $a < 7; $a ++)
444 $o .= '<td> </td>';
445 $o .= '</tr></table>'."\r\n";
451 function update_contact_birthdays() {
453 // This only handles foreign or alien networks where a birthday has been provided.
454 // In-network birthdays are handled within local_delivery
456 $r = q("SELECT * FROM contact WHERE `bd` != '' AND `bd` != '0000-00-00' AND SUBSTRING(`bd`,1,4) != `bdyear` ");
460 logger('update_contact_birthday: ' . $rr['bd']);
462 $nextbd = datetime_convert('UTC','UTC','now','Y') . substr($rr['bd'],4);
466 * Add new birthday event for this person
468 * $bdtext is just a readable placeholder in case the event is shared
469 * with others. We will replace it during presentation to our $importer
470 * to contain a sparkle link and perhaps a photo.
474 $bdtext = sprintf( t('%s\'s birthday'), $rr['name']);
475 $bdtext2 = sprintf( t('Happy Birthday %s'), ' [url=' . $rr['url'] . ']' . $rr['name'] . '[/url]') ;
479 $r = q("INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`summary`,`desc`,`type`,`adjust`)
480 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%d' ) ",
483 dbesc(datetime_convert()),
484 dbesc(datetime_convert()),
485 dbesc(datetime_convert('UTC','UTC', $nextbd)),
486 dbesc(datetime_convert('UTC','UTC', $nextbd . ' + 1 day ')),
496 q("UPDATE `contact` SET `bdyear` = '%s', `bd` = '%s' WHERE `uid` = %d AND `id` = %d",
497 dbesc(substr($nextbd,0,4)),