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