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