]> git.mxchange.org Git - friendica.git/blob - include/datetime.php
Merge remote branch 'upstream/master'
[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         $y = datetime_convert('UTC',date_default_timezone_get(),'now','Y');
135         $f = get_config('system','birthday_input_format');
136         if(! $f)
137                 $f = 'ymd';
138         $o = datesel($f,'',1920,$y,true,$year,$month,$day);
139         return $o;
140 }
141
142
143 function datesel_format($f) {
144
145         $o = '';
146
147         if(strlen($f)) {
148                 for($x = 0; $x < strlen($f); $x ++) {
149                         switch($f[$x]) {
150                                 case 'y':
151                                         if(strlen($o))
152                                                 $o .= '-';
153                                         $o .= t('year');                                        
154                                         break;
155                                 case 'm':
156                                         if(strlen($o))
157                                                 $o .= '-';
158                                         $o .= t('month');                                       
159                                         break;
160                                 case 'd':
161                                         if(strlen($o))
162                                                 $o .= '-';
163                                         $o .= t('day');
164                                         break;
165                                 default:
166                                         break;
167                         }
168                 }
169         }
170         return $o;
171 }
172
173
174 // returns a date selector.
175 // $f           = format string, e.g. 'ymd' or 'mdy'
176 // $pre         = prefix (if needed) for HTML name and class fields
177 // $ymin        = first year shown in selector dropdown
178 // $ymax        = last year shown in selector dropdown
179 // $allow_blank = allow an empty response on any field
180 // $y           = already selected year
181 // $m           = already selected month
182 // $d           = already selected day
183
184 if(! function_exists('datesel')) {
185 function datesel($f,$pre,$ymin,$ymax,$allow_blank,$y,$m,$d) {
186
187         $o = '';
188
189         if(strlen($f)) {
190                 for($z = 0; $z < strlen($f); $z ++) {
191                         if($f[$z] === 'y') {
192
193                                 $o .= "<select name=\"{$pre}year\" class=\"{$pre}year\" size=\"1\">";
194                                 if($allow_blank) {
195                                         $sel = (($y == '0000') ? " selected=\"selected\" " : "");
196                                         $o .= "<option value=\"0000\" $sel ></option>";
197                                 }
198
199                                 if($ymax > $ymin) {
200                                         for($x = $ymax; $x >= $ymin; $x --) {
201                                                 $sel = (($x == $y) ? " selected=\"selected\" " : "");
202                                                 $o .= "<option value=\"$x\" $sel>$x</option>";
203                                         }
204                                 }
205                                 else {
206                                         for($x = $ymax; $x <= $ymin; $x ++) {
207                                                 $sel = (($x == $y) ? " selected=\"selected\" " : "");
208                                                 $o .= "<option value=\"$x\" $sel>$x</option>";
209                                         }
210                                 }
211                         }
212                         elseif($f[$z] == 'm') {
213   
214                                 $o .= "</select> <select name=\"{$pre}month\" class=\"{$pre}month\" size=\"1\">";
215                                 for($x = (($allow_blank) ? 0 : 1); $x <= 12; $x ++) {
216                                         $sel = (($x == $m) ? " selected=\"selected\" " : "");
217                                         $y = (($x) ? $x : '');
218                                         $o .= "<option value=\"$x\" $sel>$y</option>";
219                                 }
220                         }
221                         elseif($f[$z] == 'd') {
222
223                                 $o .= "</select> <select name=\"{$pre}day\" class=\"{$pre}day\" size=\"1\">";
224                                 for($x = (($allow_blank) ? 0 : 1); $x <= 31; $x ++) {
225                                         $sel = (($x == $d) ? " selected=\"selected\" " : "");
226                                         $y = (($x) ? $x : '');
227                                         $o .= "<option value=\"$x\" $sel>$y</option>";
228                                 }
229                         }
230                 }
231         }
232
233         $o .= "</select>";
234         return $o;
235 }}
236
237 if(! function_exists('timesel')) {
238 function timesel($pre,$h,$m) {
239
240         $o = '';
241         $o .= "<select name=\"{$pre}hour\" class=\"{$pre}hour\" size=\"1\">";
242         for($x = 0; $x < 24; $x ++) {
243                 $sel = (($x == $h) ? " selected=\"selected\" " : "");
244                 $o .= "<option value=\"$x\" $sel>$x</option>";
245         }
246         $o .= "</select> : <select name=\"{$pre}minute\" class=\"{$pre}minute\" size=\"1\">";
247         for($x = 0; $x < 60; $x ++) {
248                 $sel = (($x == $m) ? " selected=\"selected\" " : "");
249                 $o .= "<option value=\"$x\" $sel>$x</option>";
250         }
251
252         $o .= "</select>";
253         return $o;
254 }}
255
256
257
258
259
260
261
262
263 // implements "3 seconds ago" etc.
264 // based on $posted_date, (UTC).
265 // Results relative to current timezone
266 // Limited to range of timestamps
267
268 if(! function_exists('relative_date')) {
269 function relative_date($posted_date,$format = null) {
270
271         $localtime = datetime_convert('UTC',date_default_timezone_get(),$posted_date); 
272
273         $abs = strtotime($localtime);
274     
275     if (is_null($posted_date) || $posted_date === '0000-00-00 00:00:00' || $abs === False) {
276                  return t('never');
277         }
278
279         $etime = time() - $abs;
280     
281         if ($etime < 1) {
282                 return t('less than a second ago');
283         }
284     
285         $a = array( 12 * 30 * 24 * 60 * 60  =>  array( t('year'),   t('years')),
286                                 30 * 24 * 60 * 60       =>  array( t('month'),  t('months')),
287                                 7  * 24 * 60 * 60       =>  array( t('week'),   t('weeks')),
288                                 24 * 60 * 60            =>  array( t('day'),    t('days')),
289                                 60 * 60                 =>  array( t('hour'),   t('hours')),
290                                 60                      =>  array( t('minute'), t('minutes')),
291                                 1                       =>  array( t('second'), t('seconds'))
292         );
293     
294         foreach ($a as $secs => $str) {
295                 $d = $etime / $secs;
296                 if ($d >= 1) {
297                         $r = round($d);
298                         // translators - e.g. 22 hours ago, 1 minute ago
299                         if(! $format)
300                                 $format = t('%1$d %2$s ago');
301                         return sprintf( $format,$r, (($r == 1) ? $str[0] : $str[1]));
302         }
303     }
304 }}
305
306
307
308 // Returns age in years, given a date of birth,
309 // the timezone of the person whose date of birth is provided,
310 // and the timezone of the person viewing the result.
311 // Why? Bear with me. Let's say I live in Mittagong, Australia, and my 
312 // birthday is on New Year's. You live in San Bruno, California.
313 // When exactly are you going to see my age increase?
314 // A: 5:00 AM Dec 31 San Bruno time. That's precisely when I start 
315 // celebrating and become a year older. If you wish me happy birthday 
316 // on January 1 (San Bruno time), you'll be a day late. 
317    
318 function age($dob,$owner_tz = '',$viewer_tz = '') {
319         if(! intval($dob))
320                 return 0;
321         if(! $owner_tz)
322                 $owner_tz = date_default_timezone_get();
323         if(! $viewer_tz)
324                 $viewer_tz = date_default_timezone_get();
325
326         $birthdate = datetime_convert('UTC',$owner_tz,$dob . ' 00:00:00+00:00','Y-m-d');
327         list($year,$month,$day) = explode("-",$birthdate);
328         $year_diff  = datetime_convert('UTC',$viewer_tz,'now','Y') - $year;
329         $curr_month = datetime_convert('UTC',$viewer_tz,'now','m');
330         $curr_day   = datetime_convert('UTC',$viewer_tz,'now','d');
331
332         if(($curr_month < $month) || (($curr_month == $month) && ($curr_day < $day)))
333                 $year_diff--;
334         return $year_diff;
335 }
336
337
338
339 // Get days in month
340 // get_dim($year, $month);
341 // returns number of days.
342 // $month[1] = 'January'; 
343 //   to match human usage.
344
345 if(! function_exists('get_dim')) {
346 function get_dim($y,$m) {
347
348   $dim = array( 0,
349     31, 28, 31, 30, 31, 30,
350     31, 31, 30, 31, 30, 31);
351  
352   if($m != 2)
353     return $dim[$m];
354   if(((($y % 4) == 0) && (($y % 100) != 0)) || (($y % 400) == 0))
355     return 29;
356   return $dim[2];
357 }}
358
359
360 // Returns the first day in month for a given month, year
361 // get_first_dim($year,$month)
362 // returns 0 = Sunday through 6 = Saturday
363 // Months start at 1.
364
365 if(! function_exists('get_first_dim')) {
366 function get_first_dim($y,$m) {
367   $d = sprintf('%04d-%02d-01 00:00', intval($y), intval($m));
368   return datetime_convert('UTC','UTC',$d,'w');
369 }}
370
371 // output a calendar for the given month, year.
372 // if $links are provided (array), e.g. $links[12] => 'http://mylink' , 
373 // date 12 will be linked appropriately. Today's date is also noted by 
374 // altering td class.
375 // Months count from 1.
376
377
378 // TODO: provide (prev,next) links, define class variations for different size calendars
379
380
381 if(! function_exists('cal')) {
382 function cal($y = 0,$m = 0, $links = false, $class='') {
383
384
385         // month table - start at 1 to match human usage.
386
387         $mtab = array(' ',
388           'January','February','March',
389           'April','May','June',
390           'July','August','September',
391           'October','November','December'
392         ); 
393
394         $thisyear = datetime_convert('UTC',date_default_timezone_get(),'now','Y');
395         $thismonth = datetime_convert('UTC',date_default_timezone_get(),'now','m');
396         if(! $y)
397                 $y = $thisyear;
398         if(! $m)
399                 $m = intval($thismonth);
400
401   $dn = array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday');
402   $f = get_first_dim($y,$m);
403   $l = get_dim($y,$m);
404   $d = 1;
405   $dow = 0;
406   $started = false;
407
408   if(($y == $thisyear) && ($m == $thismonth))
409     $tddate = intval(datetime_convert('UTC',date_default_timezone_get(),'now','j'));
410
411         $str_month = day_translate($mtab[$m]);
412   $o = '<table class="calendar' . $class . '">';
413   $o .= "<caption>$str_month $y</caption><tr>";
414   for($a = 0; $a < 7; $a ++)
415      $o .= '<th>' . mb_substr(day_translate($dn[$a]),0,3,'UTF-8') . '</th>';
416   $o .= '</tr><tr>';
417
418   while($d <= $l) {
419     if(($dow == $f) && (! $started))
420       $started = true;
421     $today = (((isset($tddate)) && ($tddate == $d)) ? "class=\"today\" " : '');
422     $o .= "<td $today>";
423         $day = str_replace(' ','&nbsp;',sprintf('%2.2d', $d));
424     if($started) {
425       if(is_array($links) && isset($links[$d]))
426         $o .=  "<a href=\"{$links[$d]}\">$day</a>";
427       else
428         $o .= $day;
429       $d ++;
430     }
431     else
432       $o .= '&nbsp;';
433     $o .= '</td>';
434     $dow ++;
435     if(($dow == 7) && ($d <= $l)) {
436       $dow = 0;
437       $o .= '</tr><tr>';
438     }
439   }
440   if($dow)
441     for($a = $dow; $a < 7; $a ++)
442        $o .= '<td>&nbsp;</td>';
443   $o .= '</tr></table>'."\r\n";  
444   
445   return $o;
446 }}
447
448
449 function update_contact_birthdays() {
450
451         // This only handles foreign or alien networks where a birthday has been provided.
452         // In-network birthdays are handled within local_delivery
453
454         $r = q("SELECT * FROM contact WHERE `bd` != '' AND `bd` != '0000-00-00' AND SUBSTRING(`bd`,1,4) != `bdyear` ");
455         if(count($r)) {
456                 foreach($r as $rr) {
457
458                         logger('update_contact_birthday: ' . $rr['bd']);
459
460                         $nextbd = datetime_convert('UTC','UTC','now','Y') . substr($rr['bd'],4);
461
462                         /**
463                          *
464                          * Add new birthday event for this person
465                          *
466                          * $bdtext is just a readable placeholder in case the event is shared
467                          * with others. We will replace it during presentation to our $importer
468                          * to contain a sparkle link and perhaps a photo. 
469                          *
470                          */
471                          
472                         $bdtext = sprintf( t('%s\'s birthday'), $rr['name']);
473                         $bdtext2 = sprintf( t('Happy Birthday %s'), ' [url=' . $rr['url'] . ']' . $rr['name'] . '[/url]') ;
474
475
476
477                         $r = q("INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`summary`,`desc`,`type`,`adjust`)
478                                 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%d' ) ",
479                                 intval($rr['uid']),
480                                 intval($rr['id']),
481                                 dbesc(datetime_convert()),
482                                 dbesc(datetime_convert()),
483                                 dbesc(datetime_convert('UTC','UTC', $nextbd)),
484                                 dbesc(datetime_convert('UTC','UTC', $nextbd . ' + 1 day ')),
485                                 dbesc($bdtext),
486                                 dbesc($bdtext2),
487                                 dbesc('birthday'),
488                                 intval(0)
489                         );
490                         
491
492                         // update bdyear
493
494                         q("UPDATE `contact` SET `bdyear` = '%s', `bd` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
495                                 dbesc(substr($nextbd,0,4)),
496                                 dbesc($nextbd),
497                                 intval($rr['uid']),
498                                 intval($rr['id'])
499                         );
500
501                 }
502         }
503 }