]> git.mxchange.org Git - friendica.git/blob - include/datetime.php
ping.php performance: removing datetime_convert
[friendica.git] / include / datetime.php
1 <?php
2 /**
3  * @file include/datetime.php
4  * @brief Some functions for date and time related tasks.
5  */
6
7
8 /**
9  * @brief Two-level sort for timezones.
10  *
11  * @param string $a
12  * @param string $b
13  * @return int
14  */
15 function timezone_cmp($a, $b) {
16         if(strstr($a,'/') && strstr($b,'/')) {
17                 if ( t($a) == t($b)) return 0;
18                 return ( t($a) < t($b)) ? -1 : 1;
19         }
20         if(strstr($a,'/')) return -1;
21         if(strstr($b,'/')) return  1;
22         if ( t($a) == t($b)) return 0;
23
24         return ( t($a) < t($b)) ? -1 : 1;
25 }
26
27 /**
28  * @brief Emit a timezone selector grouped (primarily) by continent
29  * 
30  * @param string $current Timezone
31  * @return string Parsed HTML output
32  */
33 function select_timezone($current = 'America/Los_Angeles') {
34
35         $timezone_identifiers = DateTimeZone::listIdentifiers();
36
37         $o ='<select id="timezone_select" name="timezone">';
38
39         usort($timezone_identifiers, 'timezone_cmp');
40         $continent = '';
41         foreach($timezone_identifiers as $value) {
42                 $ex = explode("/", $value);
43                 if(count($ex) > 1) {
44                         if($ex[0] != $continent) {
45                                 if($continent != '')
46                                         $o .= '</optgroup>';
47                                 $continent = $ex[0];
48                                 $o .= '<optgroup label="' . t($continent) . '">';
49                         }
50                         if(count($ex) > 2)
51                                 $city = substr($value,strpos($value,'/')+1);
52                         else
53                                 $city = $ex[1];
54                 }
55                 else {
56                         $city = $ex[0];
57                         if($continent != t('Miscellaneous')) {
58                                 $o .= '</optgroup>';
59                                 $continent = t('Miscellaneous');
60                                 $o .= '<optgroup label="' . t($continent) . '">';
61                         }
62                 }
63                 $city = str_replace('_', ' ',  t($city));
64                 $selected = (($value == $current) ? " selected=\"selected\" " : "");
65                 $o .= "<option value=\"$value\" $selected >$city</option>";
66         }
67         $o .= '</optgroup></select>';
68         return $o;
69 }
70
71
72
73 /**
74  * @brief Generating a Timezone selector
75  * 
76  * Return a select using 'field_select_raw' template, with timezones
77  * groupped (primarily) by continent
78  * arguments follow convetion as other field_* template array:
79  * 'name', 'label', $value, 'help'
80  * 
81  * @param string $name Name of the selector
82  * @param string $label Label for the selector
83  * @param string $current Timezone
84  * @param string $help Help text
85  * 
86  * @return string Parsed HTML
87  */
88 function field_timezone($name='timezone', $label='', $current = 'America/Los_Angeles', $help){
89         $options = select_timezone($current);
90         $options = str_replace('<select id="timezone_select" name="timezone">','', $options);
91         $options = str_replace('</select>','', $options);
92
93         $tpl = get_markup_template('field_select_raw.tpl');
94         return replace_macros($tpl, array(
95                 '$field' => array($name, $label, $current, $help, $options),
96         ));
97
98 }
99
100 /**
101  * @brief General purpose date parse/convert function.
102  *
103  * @param string $from Source timezone
104  * @param string $to Dest timezone
105  * @param string $s Some parseable date/time string
106  * @param string $fmt Output format recognised from php's DateTime class
107  *   http://www.php.net/manual/en/datetime.format.php
108  * 
109  * @return string Formatted date according to given format
110  */
111 function datetime_convert($from = 'UTC', $to = 'UTC', $s = 'now', $fmt = "Y-m-d H:i:s") {
112
113         // Defaults to UTC if nothing is set, but throws an exception if set to empty string.
114         // Provide some sane defaults regardless.
115
116         if($from === '')
117                 $from = 'UTC';
118         if($to === '')
119                 $to = 'UTC';
120         if( ($s === '') || (! is_string($s)) )
121                 $s = 'now';
122
123         // Slight hackish adjustment so that 'zero' datetime actually returns what is intended
124         // otherwise we end up with -0001-11-30 ...
125         // add 32 days so that we at least get year 00, and then hack around the fact that
126         // months and days always start with 1.
127
128         if(substr($s,0,10) == '0000-00-00') {
129                 $d = new DateTime($s . ' + 32 days', new DateTimeZone('UTC'));
130                 return str_replace('1','0',$d->format($fmt));
131         }
132
133         try {
134                 $from_obj = new DateTimeZone($from);
135         }
136         catch(Exception $e) {
137                 $from_obj = new DateTimeZone('UTC');
138         }
139
140         try {
141                 $d = new DateTime($s, $from_obj);
142         }
143         catch(Exception $e) {
144                 logger('datetime_convert: exception: ' . $e->getMessage());
145                 $d = new DateTime('now', $from_obj);
146         }
147
148         try {
149                 $to_obj = new DateTimeZone($to);
150         }
151         catch(Exception $e) {
152                 $to_obj = new DateTimeZone('UTC');
153         }
154
155         $d->setTimeZone($to_obj);
156
157         return($d->format($fmt));
158 }
159
160
161 /**
162  * @brief Wrapper for date selector, tailored for use in birthday fields.
163  *
164  * @param string $dob Date of Birth
165  * @return string Formatted html
166  */
167 function dob($dob) {
168         list($year,$month,$day) = sscanf($dob,'%4d-%2d-%2d');
169
170         $f = get_config('system','birthday_input_format');
171         if(! $f)
172                 $f = 'ymd';
173         if($dob === '0000-00-00')
174                 $value = '';
175         else
176                 $value = (($year) ? datetime_convert('UTC','UTC',$dob,'Y-m-d') : datetime_convert('UTC','UTC',$dob,'m-d'));
177
178         $age = ((intval($value)) ? age($value, $a->user["timezone"], $a->user["timezone"]) : "");
179
180         $o = replace_macros(get_markup_template("field_input.tpl"), array(
181                 '$field' => array(
182                         'dob',
183                         t('Birthday:'),
184                         $value,
185                         (((intval($age)) > 0 ) ? t('Age: ') . $age : ""),
186                         '',
187                         'placeholder="' . t('YYYY-MM-DD or MM-DD') . '"'
188                 )
189         ));
190
191 //      if ($dob && $dob != '0000-00-00')
192 //              $o = datesel($f,mktime(0,0,0,0,0,1900),mktime(),mktime(0,0,0,$month,$day,$year),'dob');
193 //      else
194 //              $o = datesel($f,mktime(0,0,0,0,0,1900),mktime(),false,'dob');
195
196         return $o;
197 }
198
199 /**
200  * @brief Returns a date selector
201  * 
202  * @param string $format
203  *  Format string, e.g. 'ymd' or 'mdy'. Not currently supported
204  * @param string $min
205  *  Unix timestamp of minimum date
206  * @param string $max
207  *  Unix timestap of maximum date
208  * @param string $default
209  *  Unix timestamp of default date
210  * @param string $id
211  *  ID and name of datetimepicker (defaults to "datetimepicker")
212  * 
213  * @return string Parsed HTML output.
214  */
215 function datesel($format, $min, $max, $default, $id = 'datepicker') {
216         return datetimesel($format,$min,$max,$default,'',$id,true,false, '','');
217 }
218
219 /**
220  * @brief Returns a time selector
221  * 
222  * @param string $format
223  *  Format string, e.g. 'ymd' or 'mdy'. Not currently supported
224  * @param $h
225  *  Already selected hour
226  * @param $m
227  *  Already selected minute
228  * @param string $id
229  *  ID and name of datetimepicker (defaults to "timepicker")
230  * 
231  * @return string Parsed HTML output.
232  */
233 function timesel($format, $h, $m, $id='timepicker') {
234         return datetimesel($format,new DateTime(),new DateTime(),new DateTime("$h:$m"),'',$id,false,true);
235 }
236
237 /**
238  * @brief Returns a datetime selector.
239  *
240  * @param string $format
241  *  format string, e.g. 'ymd' or 'mdy'. Not currently supported
242  * @param string $min
243  *  unix timestamp of minimum date
244  * @param string $max
245  *  unix timestap of maximum date
246  * @param string $default
247  *  unix timestamp of default date
248  * @param string $id
249  *  id and name of datetimepicker (defaults to "datetimepicker")
250  * @param bool $pickdate
251  *  true to show date picker (default)
252  * @param boolean $picktime
253  *  true to show time picker (default)
254  * @param $minfrom
255  *  set minimum date from picker with id $minfrom (none by default)
256  * @param $maxfrom
257  *  set maximum date from picker with id $maxfrom (none by default)
258  * @param bool $required default false
259  * 
260  * @return string Parsed HTML output.
261  *
262  * @todo Once browser support is better this could probably be replaced with
263  * native HTML5 date picker.
264  */
265 function datetimesel($format, $min, $max, $default, $label, $id = 'datetimepicker', $pickdate = true, $picktime = true, $minfrom = '', $maxfrom = '', $required = false) {
266
267         // First day of the week (0 = Sunday)
268         $firstDay = get_pconfig(local_user(),'system','first_day_of_week');
269         if ($firstDay === false) $firstDay=0;
270
271         $lang = substr(get_browser_language(), 0, 2);
272
273         // Check if the detected language is supported by the picker
274         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")))
275                 $lang = ((isset($a->config['system']['language'])) ? $a->config['system']['language'] : 'en');
276
277         $o = '';
278         $dateformat = '';
279
280         if($pickdate) $dateformat .= 'Y-m-d';
281         if($pickdate && $picktime) $dateformat .= ' ';
282         if($picktime) $dateformat .= 'H:i';
283
284         $minjs = $min ? ",minDate: new Date({$min->getTimestamp()}*1000), yearStart: " . $min->format('Y') : '';
285         $maxjs = $max ? ",maxDate: new Date({$max->getTimestamp()}*1000), yearEnd: " . $max->format('Y') : '';
286
287         $input_text = $default ? date($dateformat, $default->getTimestamp()) : '';
288         $defaultdatejs = $default ? ",defaultDate: new Date({$default->getTimestamp()}*1000)" : '';
289
290         $pickers = '';
291         if(!$pickdate) $pickers .= ',datepicker: false';
292         if(!$picktime) $pickers .= ',timepicker: false';
293
294         $extra_js = '';
295         $pickers .= ",dayOfWeekStart: ".$firstDay.",lang:'".$lang."'";
296         if($minfrom != '')
297                 $extra_js .= "\$('#id_$minfrom').data('xdsoft_datetimepicker').setOptions({onChangeDateTime: function (currentDateTime) { \$('#id_$id').data('xdsoft_datetimepicker').setOptions({minDate: currentDateTime})}})";
298         if($maxfrom != '')
299                 $extra_js .= "\$('#id_$maxfrom').data('xdsoft_datetimepicker').setOptions({onChangeDateTime: function (currentDateTime) { \$('#id_$id').data('xdsoft_datetimepicker').setOptions({maxDate: currentDateTime})}})";
300
301         $readable_format = $dateformat;
302         $readable_format = str_replace('Y','yyyy',$readable_format);
303         $readable_format = str_replace('m','mm',$readable_format);
304         $readable_format = str_replace('d','dd',$readable_format);
305         $readable_format = str_replace('H','HH',$readable_format);
306         $readable_format = str_replace('i','MM',$readable_format);
307
308         $tpl = get_markup_template('field_input.tpl');
309         $o .= replace_macros($tpl,array(
310                         '$field' => array($id, $label, $input_text, '', (($required) ? '*' : ''), 'placeholder="' . $readable_format . '"'),
311                 ));
312
313         $o .= "<script type='text/javascript'>";
314         $o .= "\$(function () {var picker = \$('#id_$id').datetimepicker({step:5,format:'$dateformat' $minjs $maxjs $pickers $defaultdatejs}); $extra_js})";
315         $o .= "</script>";
316
317         return $o;
318 }
319
320 /**
321  * @brief Returns a relative date string.
322  *
323  * Implements "3 seconds ago" etc.
324  * Based on $posted_date, (UTC).
325  * Results relative to current timezone.
326  * Limited to range of timestamps.
327  *
328  * @param string $posted_date
329  * @param string $format (optional) Parsed with sprintf()
330  *    <tt>%1$d %2$s ago</tt>, e.g. 22 hours ago, 1 minute ago
331  *
332  * @return string with relative date
333  */
334 function relative_date($posted_date, $format = null) {
335
336         $localtime = $posted_date . ' UTC';
337
338         $abs = strtotime($localtime);
339
340         if (is_null($posted_date) || $posted_date === '0000-00-00 00:00:00' || $abs === False) {
341                  return t('never');
342         }
343
344         $etime = time() - $abs;
345
346         if ($etime < 1) {
347                 return t('less than a second ago');
348         }
349
350         $a = array( 12 * 30 * 24 * 60 * 60  =>  array( t('year'),   t('years')),
351                                 30 * 24 * 60 * 60       =>  array( t('month'),  t('months')),
352                                 7  * 24 * 60 * 60       =>  array( t('week'),   t('weeks')),
353                                 24 * 60 * 60            =>  array( t('day'),    t('days')),
354                                 60 * 60                 =>  array( t('hour'),   t('hours')),
355                                 60                      =>  array( t('minute'), t('minutes')),
356                                 1                       =>  array( t('second'), t('seconds'))
357         );
358
359         foreach ($a as $secs => $str) {
360                 $d = $etime / $secs;
361                 if ($d >= 1) {
362                         $r = round($d);
363                         // translators - e.g. 22 hours ago, 1 minute ago
364                         if(! $format) {
365                                 $format = t('%1$d %2$s ago');
366                         }
367
368                         return sprintf( $format,$r, (($r == 1) ? $str[0] : $str[1]));
369                 }
370         }
371 }
372
373 /**
374  * @brief Returns timezone correct age in years.
375  *
376  * Returns the age in years, given a date of birth, the timezone of the person
377  * whose date of birth is provided, and the timezone of the person viewing the
378  * result.
379  *
380  * Why? Bear with me. Let's say I live in Mittagong, Australia, and my birthday
381  * is on New Year's. You live in San Bruno, California.
382  * When exactly are you going to see my age increase?
383  *
384  * A: 5:00 AM Dec 31 San Bruno time. That's precisely when I start celebrating
385  * and become a year older. If you wish me happy birthday on January 1
386  * (San Bruno time), you'll be a day late.
387  *
388  * @param string $dob Date of Birth
389  * @param string $owner_tz (optional) Timezone of the person of interest
390  * @param string $viewer_tz (optional) Timezone of the person viewing
391  * 
392  * @return int Age in years
393  */
394 function age($dob,$owner_tz = '',$viewer_tz = '') {
395         if(! intval($dob))
396                 return 0;
397         if(! $owner_tz)
398                 $owner_tz = date_default_timezone_get();
399         if(! $viewer_tz)
400                 $viewer_tz = date_default_timezone_get();
401
402         $birthdate = datetime_convert('UTC',$owner_tz,$dob . ' 00:00:00+00:00','Y-m-d');
403         list($year,$month,$day) = explode("-",$birthdate);
404         $year_diff  = datetime_convert('UTC',$viewer_tz,'now','Y') - $year;
405         $curr_month = datetime_convert('UTC',$viewer_tz,'now','m');
406         $curr_day   = datetime_convert('UTC',$viewer_tz,'now','d');
407
408         if(($curr_month < $month) || (($curr_month == $month) && ($curr_day < $day)))
409                 $year_diff--;
410
411         return $year_diff;
412 }
413
414 /**
415  * @brief Get days of a month in a given year.
416  *
417  * Returns number of days in the month of the given year.
418  * $m = 1 is 'January' to match human usage.
419  *
420  * @param int $y Year
421  * @param int $m Month (1=January, 12=December)
422  * 
423  * @return int Number of days in the given month
424  */
425 function get_dim($y,$m) {
426
427         $dim = array( 0,
428                 31, 28, 31, 30, 31, 30,
429                 31, 31, 30, 31, 30, 31);
430
431         if($m != 2)
432                 return $dim[$m];
433
434         if(((($y % 4) == 0) && (($y % 100) != 0)) || (($y % 400) == 0))
435                 return 29;
436
437         return $dim[2];
438 }
439
440 /**
441  * @brief Returns the first day in month for a given month, year.
442  *
443  * Months start at 1.
444  *
445  * @param int $y Year
446  * @param int $m Month (1=January, 12=December)
447  * 
448  * @return string day 0 = Sunday through 6 = Saturday
449  */
450 function get_first_dim($y,$m) {
451         $d = sprintf('%04d-%02d-01 00:00', intval($y), intval($m));
452
453         return datetime_convert('UTC','UTC',$d,'w');
454 }
455
456 /**
457  * @brief Output a calendar for the given month, year.
458  *
459  * If $links are provided (array), e.g. $links[12] => 'http://mylink' ,
460  * date 12 will be linked appropriately. Today's date is also noted by
461  * altering td class.
462  * Months count from 1.
463  *
464  * @param int $y Year
465  * @param int $m Month
466  * @param bool $links (default false)
467  * @param string $class
468  * 
469  * @return string
470  *
471  * @todo Provide (prev,next) links, define class variations for different size calendars
472  */
473 function cal($y = 0,$m = 0, $links = false, $class='') {
474
475
476         // month table - start at 1 to match human usage.
477
478         $mtab = array(' ',
479                 'January','February','March',
480                 'April','May','June',
481                 'July','August','September',
482                 'October','November','December'
483         );
484
485         $thisyear = datetime_convert('UTC',date_default_timezone_get(),'now','Y');
486         $thismonth = datetime_convert('UTC',date_default_timezone_get(),'now','m');
487         if(! $y)
488                 $y = $thisyear;
489         if(! $m)
490                 $m = intval($thismonth);
491
492         $dn = array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday');
493         $f = get_first_dim($y,$m);
494         $l = get_dim($y,$m);
495         $d = 1;
496         $dow = 0;
497         $started = false;
498
499         if(($y == $thisyear) && ($m == $thismonth))
500                 $tddate = intval(datetime_convert('UTC',date_default_timezone_get(),'now','j'));
501
502         $str_month = day_translate($mtab[$m]);
503         $o = '<table class="calendar' . $class . '">';
504         $o .= "<caption>$str_month $y</caption><tr>";
505         for($a = 0; $a < 7; $a ++)
506                 $o .= '<th>' . mb_substr(day_translate($dn[$a]),0,3,'UTF-8') . '</th>';
507
508         $o .= '</tr><tr>';
509
510         while($d <= $l) {
511                 if(($dow == $f) && (! $started))
512                         $started = true;
513
514                 $today = (((isset($tddate)) && ($tddate == $d)) ? "class=\"today\" " : '');
515                 $o .= "<td $today>";
516                 $day = str_replace(' ','&nbsp;',sprintf('%2.2d', $d));
517                 if($started) {
518                         if(is_array($links) && isset($links[$d]))
519                                 $o .=  "<a href=\"{$links[$d]}\">$day</a>";
520                         else
521                                 $o .= $day;
522
523                         $d ++;
524                 } else {
525                         $o .= '&nbsp;';
526                 }
527
528                 $o .= '</td>';
529                 $dow ++;
530                 if(($dow == 7) && ($d <= $l)) {
531                         $dow = 0;
532                         $o .= '</tr><tr>';
533                 }
534         }
535         if($dow)
536                 for($a = $dow; $a < 7; $a ++)
537                         $o .= '<td>&nbsp;</td>';
538
539         $o .= '</tr></table>'."\r\n";
540
541         return $o;
542 }
543
544 /**
545  * @brief Create a birthday event.
546  *
547  * Update the year and the birthday.
548  */
549 function update_contact_birthdays() {
550
551         // This only handles foreign or alien networks where a birthday has been provided.
552         // In-network birthdays are handled within local_delivery
553
554         $r = q("SELECT * FROM contact WHERE `bd` != '' AND `bd` != '0000-00-00' AND SUBSTRING(`bd`,1,4) != `bdyear` ");
555         if(count($r)) {
556                 foreach($r as $rr) {
557
558                         logger('update_contact_birthday: ' . $rr['bd']);
559
560                         $nextbd = datetime_convert('UTC','UTC','now','Y') . substr($rr['bd'],4);
561
562                         /**
563                          *
564                          * Add new birthday event for this person
565                          *
566                          * $bdtext is just a readable placeholder in case the event is shared
567                          * with others. We will replace it during presentation to our $importer
568                          * to contain a sparkle link and perhaps a photo.
569                          *
570                          */
571
572                         $bdtext = sprintf( t('%s\'s birthday'), $rr['name']);
573                         $bdtext2 = sprintf( t('Happy Birthday %s'), ' [url=' . $rr['url'] . ']' . $rr['name'] . '[/url]') ;
574
575                         $r = q("INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`summary`,`desc`,`type`,`adjust`)
576                                 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%d' ) ",
577                                 intval($rr['uid']),
578                                 intval($rr['id']),
579                                 dbesc(datetime_convert()),
580                                 dbesc(datetime_convert()),
581                                 dbesc(datetime_convert('UTC','UTC', $nextbd)),
582                                 dbesc(datetime_convert('UTC','UTC', $nextbd . ' + 1 day ')),
583                                 dbesc($bdtext),
584                                 dbesc($bdtext2),
585                                 dbesc('birthday'),
586                                 intval(0)
587                         );
588
589
590                         // update bdyear
591
592                         q("UPDATE `contact` SET `bdyear` = '%s', `bd` = '%s' WHERE `uid` = %d AND `id` = %d",
593                                 dbesc(substr($nextbd,0,4)),
594                                 dbesc($nextbd),
595                                 intval($rr['uid']),
596                                 intval($rr['id'])
597                         );
598
599                 }
600         }
601 }