]> git.mxchange.org Git - friendica.git/blob - include/datetime.php
Merge branch '3.4.1'
[friendica.git] / include / datetime.php
1 <?php
2
3 // two-level sort for timezones.
4
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;
10         }
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;
15 }}
16
17 // emit a timezone selector grouped (primarily) by continent
18 if(! function_exists('select_timezone')) {
19 function select_timezone($current = 'America/Los_Angeles') {
20
21         $timezone_identifiers = DateTimeZone::listIdentifiers();
22
23         $o ='<select id="timezone_select" name="timezone">';
24
25         usort($timezone_identifiers, 'timezone_cmp');
26         $continent = '';
27         foreach($timezone_identifiers as $value) {
28                 $ex = explode("/", $value);
29                 if(count($ex) > 1) {
30                         if($ex[0] != $continent) {
31                                 if($continent != '')
32                                         $o .= '</optgroup>';
33                                 $continent = $ex[0];
34                                 $o .= '<optgroup label="' . t($continent) . '">';
35                         }
36                         if(count($ex) > 2)
37                                 $city = substr($value,strpos($value,'/')+1);
38                         else
39                                 $city = $ex[1];
40                 }
41                 else {
42                         $city = $ex[0];
43                         if($continent != t('Miscellaneous')) {
44                                 $o .= '</optgroup>';
45                                 $continent = t('Miscellaneous');
46                                 $o .= '<optgroup label="' . t($continent) . '">';       
47                         }
48                 }
49                 $city = str_replace('_', ' ',  t($city));
50                 $selected = (($value == $current) ? " selected=\"selected\" " : "");
51                 $o .= "<option value=\"$value\" $selected >$city</option>";
52         }    
53         $o .= '</optgroup></select>';
54         return $o;
55 }}
56
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);
66         
67         $tpl = get_markup_template('field_select_raw.tpl');
68         return replace_macros($tpl, array(
69                 '$field' => array($name, $label, $current, $help, $options),
70         ));
71         
72 }}
73
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
79
80 if(! function_exists('datetime_convert')) {
81 function datetime_convert($from = 'UTC', $to = 'UTC', $s = 'now', $fmt = "Y-m-d H:i:s") {
82
83         // Defaults to UTC if nothing is set, but throws an exception if set to empty string.
84         // Provide some sane defaults regardless.
85
86         if($from === '')
87                 $from = 'UTC';
88         if($to === '')
89                 $to = 'UTC';
90         if( ($s === '') || (! is_string($s)) )
91                 $s = 'now';
92
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. 
97
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));
101         }
102
103         try {
104                 $from_obj = new DateTimeZone($from);
105         }
106         catch(Exception $e) {
107                 $from_obj = new DateTimeZone('UTC');
108         }
109
110         try {
111                 $d = new DateTime($s, $from_obj);
112         }
113         catch(Exception $e) {
114                 logger('datetime_convert: exception: ' . $e->getMessage());
115                 $d = new DateTime('now', $from_obj);
116         }
117
118         try {
119                 $to_obj = new DateTimeZone($to);
120         }
121         catch(Exception $e) {
122                 $to_obj = new DateTimeZone('UTC');
123         }
124
125         $d->setTimeZone($to_obj);
126         return($d->format($fmt));
127 }}
128
129
130 // wrapper for date selector, tailored for use in birthday fields
131
132 function dob($dob) {
133         list($year,$month,$day) = sscanf($dob,'%4d-%2d-%2d');
134         $f = get_config('system','birthday_input_format');
135         if(! $f)
136                 $f = 'ymd';
137         if($dob === '0000-00-00')
138                 $value = '';
139         else
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');
144 //      else
145 //              $o = datesel($f,mktime(0,0,0,0,0,1900),mktime(),false,'dob');
146         return $o;
147 }
148
149 /**
150  * returns a date selector
151  * @param $format
152  *  format string, e.g. 'ymd' or 'mdy'. Not currently supported
153  * @param $min
154  *  unix timestamp of minimum date
155  * @param $max
156  *  unix timestap of maximum date
157  * @param $default
158  *  unix timestamp of default date
159  * @param $id
160  *  id and name of datetimepicker (defaults to "datetimepicker")
161  */
162 if(! function_exists('datesel')) {
163 function datesel($format, $min, $max, $default, $id = 'datepicker') {
164         return datetimesel($format,$min,$max,$default,$id,true,false, '','');
165 }}
166
167 /**
168  * returns a time selector
169  * @param $format
170  *  format string, e.g. 'ymd' or 'mdy'. Not currently supported
171  * @param $h
172  *  already selected hour
173  * @param $m
174  *  already selected minute
175  * @param $id
176  *  id and name of datetimepicker (defaults to "timepicker")
177  */
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);
181 }}
182
183 /**
184  * @brief Returns a datetime selector.
185  *
186  * @param $format
187  *  format string, e.g. 'ymd' or 'mdy'. Not currently supported
188  * @param $min
189  *  unix timestamp of minimum date
190  * @param $max
191  *  unix timestap of maximum date
192  * @param $default
193  *  unix timestamp of default date
194  * @param string $id
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)
200  * @param $minfrom
201  *  set minimum date from picker with id $minfrom (none by default)
202  * @param $maxfrom
203  *  set maximum date from picker with id $maxfrom (none by default)
204  * @param boolean $required default false
205  * @return string Parsed HTML output.
206  * 
207  * @todo Once browser support is better this could probably be replaced with
208  * native HTML5 date picker.
209  */
210 if(! function_exists('datetimesel')) {
211 function datetimesel($format, $min, $max, $default, $id = 'datetimepicker', $pickdate = true, $picktime = true, $minfrom = '', $maxfrom = '', $required = false) {
212
213         $o = '';
214         $dateformat = '';
215         if($pickdate) $dateformat .= 'Y-m-d';
216         if($pickdate && $picktime) $dateformat .= ' ';
217         if($picktime) $dateformat .= 'H:i';
218         $minjs = $min ? ",minDate: new Date({$min->getTimestamp()}*1000), yearStart: " . $min->format('Y') : '';
219         $maxjs = $max ? ",maxDate: new Date({$max->getTimestamp()}*1000), yearEnd: " . $max->format('Y') : '';
220         
221         $input_text = $default ? 'value="' . date($dateformat, $default->getTimestamp()) . '"' : '';
222         $defaultdatejs = $default ? ",defaultDate: new Date({$default->getTimestamp()}*1000)" : '';
223         $pickers = '';
224         if(!$pickdate) $pickers .= ',datepicker: false';
225         if(!$picktime) $pickers .= ',timepicker: false';
226         $extra_js = '';
227         if($minfrom != '') 
228                 $extra_js .= "\$('#$minfrom').data('xdsoft_datetimepicker').setOptions({onChangeDateTime: function (currentDateTime) { \$('#$id').data('xdsoft_datetimepicker').setOptions({minDate: currentDateTime})}})";
229         if($maxfrom != '') 
230                 $extra_js .= "\$('#$maxfrom').data('xdsoft_datetimepicker').setOptions({onChangeDateTime: function (currentDateTime) { \$('#$id').data('xdsoft_datetimepicker').setOptions({maxDate: currentDateTime})}})";
231         $readable_format = $dateformat;
232         $readable_format = str_replace('Y','yyyy',$readable_format);
233         $readable_format = str_replace('m','mm',$readable_format);
234         $readable_format = str_replace('d','dd',$readable_format);
235         $readable_format = str_replace('H','HH',$readable_format);
236         $readable_format = str_replace('i','MM',$readable_format);
237         $o .= "<div class='date'><input type='text' placeholder='$readable_format' name='$id' id='$id' $input_text />";
238         $o .= '</div>';
239         $o .= "<script type='text/javascript'>\$(function () {var picker = \$('#$id').datetimepicker({step:5,format:'$dateformat' $minjs $maxjs $pickers $defaultdatejs}); $extra_js})</script>";
240         return $o;
241 }}
242
243 // implements "3 seconds ago" etc.
244 // based on $posted_date, (UTC).
245 // Results relative to current timezone
246 // Limited to range of timestamps
247
248 if(! function_exists('relative_date')) {
249 function relative_date($posted_date,$format = null) {
250
251         $localtime = datetime_convert('UTC',date_default_timezone_get(),$posted_date); 
252
253         $abs = strtotime($localtime);
254     
255     if (is_null($posted_date) || $posted_date === '0000-00-00 00:00:00' || $abs === False) {
256                  return t('never');
257         }
258
259         $etime = time() - $abs;
260     
261         if ($etime < 1) {
262                 return t('less than a second ago');
263         }
264     
265         /*
266         $time_append = '';
267         if ($etime >= 86400) {
268                 $time_append = ' ('.$localtime.')';
269         }
270         */
271         
272         $a = array( 12 * 30 * 24 * 60 * 60  =>  array( t('year'),   t('years')),
273                                 30 * 24 * 60 * 60       =>  array( t('month'),  t('months')),
274                                 7  * 24 * 60 * 60       =>  array( t('week'),   t('weeks')),
275                                 24 * 60 * 60            =>  array( t('day'),    t('days')),
276                                 60 * 60                 =>  array( t('hour'),   t('hours')),
277                                 60                      =>  array( t('minute'), t('minutes')),
278                                 1                       =>  array( t('second'), t('seconds'))
279         );
280     
281         foreach ($a as $secs => $str) {
282                 $d = $etime / $secs;
283                 if ($d >= 1) {
284                         $r = round($d);
285                         // translators - e.g. 22 hours ago, 1 minute ago
286                         if(! $format)
287                                 $format = t('%1$d %2$s ago');
288                         return sprintf( $format,$r, (($r == 1) ? $str[0] : $str[1]));
289         }
290     }
291 }}
292
293
294
295 // Returns age in years, given a date of birth,
296 // the timezone of the person whose date of birth is provided,
297 // and the timezone of the person viewing the result.
298 // Why? Bear with me. Let's say I live in Mittagong, Australia, and my 
299 // birthday is on New Year's. You live in San Bruno, California.
300 // When exactly are you going to see my age increase?
301 // A: 5:00 AM Dec 31 San Bruno time. That's precisely when I start 
302 // celebrating and become a year older. If you wish me happy birthday 
303 // on January 1 (San Bruno time), you'll be a day late. 
304    
305 function age($dob,$owner_tz = '',$viewer_tz = '') {
306         if(! intval($dob))
307                 return 0;
308         if(! $owner_tz)
309                 $owner_tz = date_default_timezone_get();
310         if(! $viewer_tz)
311                 $viewer_tz = date_default_timezone_get();
312
313         $birthdate = datetime_convert('UTC',$owner_tz,$dob . ' 00:00:00+00:00','Y-m-d');
314         list($year,$month,$day) = explode("-",$birthdate);
315         $year_diff  = datetime_convert('UTC',$viewer_tz,'now','Y') - $year;
316         $curr_month = datetime_convert('UTC',$viewer_tz,'now','m');
317         $curr_day   = datetime_convert('UTC',$viewer_tz,'now','d');
318
319         if(($curr_month < $month) || (($curr_month == $month) && ($curr_day < $day)))
320                 $year_diff--;
321         return $year_diff;
322 }
323
324
325
326 // Get days in month
327 // get_dim($year, $month);
328 // returns number of days.
329 // $month[1] = 'January'; 
330 //   to match human usage.
331
332 if(! function_exists('get_dim')) {
333 function get_dim($y,$m) {
334
335   $dim = array( 0,
336     31, 28, 31, 30, 31, 30,
337     31, 31, 30, 31, 30, 31);
338  
339   if($m != 2)
340     return $dim[$m];
341   if(((($y % 4) == 0) && (($y % 100) != 0)) || (($y % 400) == 0))
342     return 29;
343   return $dim[2];
344 }}
345
346
347 // Returns the first day in month for a given month, year
348 // get_first_dim($year,$month)
349 // returns 0 = Sunday through 6 = Saturday
350 // Months start at 1.
351
352 if(! function_exists('get_first_dim')) {
353 function get_first_dim($y,$m) {
354   $d = sprintf('%04d-%02d-01 00:00', intval($y), intval($m));
355   return datetime_convert('UTC','UTC',$d,'w');
356 }}
357
358 // output a calendar for the given month, year.
359 // if $links are provided (array), e.g. $links[12] => 'http://mylink' , 
360 // date 12 will be linked appropriately. Today's date is also noted by 
361 // altering td class.
362 // Months count from 1.
363
364
365 // TODO: provide (prev,next) links, define class variations for different size calendars
366
367
368 if(! function_exists('cal')) {
369 function cal($y = 0,$m = 0, $links = false, $class='') {
370
371
372         // month table - start at 1 to match human usage.
373
374         $mtab = array(' ',
375           'January','February','March',
376           'April','May','June',
377           'July','August','September',
378           'October','November','December'
379         ); 
380
381         $thisyear = datetime_convert('UTC',date_default_timezone_get(),'now','Y');
382         $thismonth = datetime_convert('UTC',date_default_timezone_get(),'now','m');
383         if(! $y)
384                 $y = $thisyear;
385         if(! $m)
386                 $m = intval($thismonth);
387
388   $dn = array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday');
389   $f = get_first_dim($y,$m);
390   $l = get_dim($y,$m);
391   $d = 1;
392   $dow = 0;
393   $started = false;
394
395   if(($y == $thisyear) && ($m == $thismonth))
396     $tddate = intval(datetime_convert('UTC',date_default_timezone_get(),'now','j'));
397
398         $str_month = day_translate($mtab[$m]);
399   $o = '<table class="calendar' . $class . '">';
400   $o .= "<caption>$str_month $y</caption><tr>";
401   for($a = 0; $a < 7; $a ++)
402      $o .= '<th>' . mb_substr(day_translate($dn[$a]),0,3,'UTF-8') . '</th>';
403   $o .= '</tr><tr>';
404
405   while($d <= $l) {
406     if(($dow == $f) && (! $started))
407       $started = true;
408     $today = (((isset($tddate)) && ($tddate == $d)) ? "class=\"today\" " : '');
409     $o .= "<td $today>";
410         $day = str_replace(' ','&nbsp;',sprintf('%2.2d', $d));
411     if($started) {
412       if(is_array($links) && isset($links[$d]))
413         $o .=  "<a href=\"{$links[$d]}\">$day</a>";
414       else
415         $o .= $day;
416       $d ++;
417     }
418     else
419       $o .= '&nbsp;';
420     $o .= '</td>';
421     $dow ++;
422     if(($dow == 7) && ($d <= $l)) {
423       $dow = 0;
424       $o .= '</tr><tr>';
425     }
426   }
427   if($dow)
428     for($a = $dow; $a < 7; $a ++)
429        $o .= '<td>&nbsp;</td>';
430   $o .= '</tr></table>'."\r\n";  
431   
432   return $o;
433 }}
434
435
436 function update_contact_birthdays() {
437
438         // This only handles foreign or alien networks where a birthday has been provided.
439         // In-network birthdays are handled within local_delivery
440
441         $r = q("SELECT * FROM contact WHERE `bd` != '' AND `bd` != '0000-00-00' AND SUBSTRING(`bd`,1,4) != `bdyear` ");
442         if(count($r)) {
443                 foreach($r as $rr) {
444
445                         logger('update_contact_birthday: ' . $rr['bd']);
446
447                         $nextbd = datetime_convert('UTC','UTC','now','Y') . substr($rr['bd'],4);
448
449                         /**
450                          *
451                          * Add new birthday event for this person
452                          *
453                          * $bdtext is just a readable placeholder in case the event is shared
454                          * with others. We will replace it during presentation to our $importer
455                          * to contain a sparkle link and perhaps a photo. 
456                          *
457                          */
458                          
459                         $bdtext = sprintf( t('%s\'s birthday'), $rr['name']);
460                         $bdtext2 = sprintf( t('Happy Birthday %s'), ' [url=' . $rr['url'] . ']' . $rr['name'] . '[/url]') ;
461
462
463
464                         $r = q("INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`summary`,`desc`,`type`,`adjust`)
465                                 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%d' ) ",
466                                 intval($rr['uid']),
467                                 intval($rr['id']),
468                                 dbesc(datetime_convert()),
469                                 dbesc(datetime_convert()),
470                                 dbesc(datetime_convert('UTC','UTC', $nextbd)),
471                                 dbesc(datetime_convert('UTC','UTC', $nextbd . ' + 1 day ')),
472                                 dbesc($bdtext),
473                                 dbesc($bdtext2),
474                                 dbesc('birthday'),
475                                 intval(0)
476                         );
477
478
479                         // update bdyear
480
481                         q("UPDATE `contact` SET `bdyear` = '%s', `bd` = '%s' WHERE `uid` = %d AND `id` = %d",
482                                 dbesc(substr($nextbd,0,4)),
483                                 dbesc($nextbd),
484                                 intval($rr['uid']),
485                                 intval($rr['id'])
486                         );
487
488                 }
489         }
490 }