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