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