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