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