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