]> git.mxchange.org Git - friendica.git/blob - include/datetime.php
Class file relocations
[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, array(
106                 '$field' => array($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         list($year,$month,$day) = sscanf($dob,'%4d-%2d-%2d');
182
183         $f = Config::get('system', 'birthday_input_format');
184         if (! $f) {
185                 $f = 'ymd';
186         }
187         if ($dob <= '0001-01-01') {
188                 $value = '';
189         } else {
190                 $value = (($year) ? datetime_convert('UTC','UTC',$dob,'Y-m-d') : datetime_convert('UTC','UTC',$dob,'m-d'));
191         }
192
193         $age = ((intval($value)) ? age($value, $a->user["timezone"], $a->user["timezone"]) : "");
194
195         $o = replace_macros(get_markup_template("field_input.tpl"), array(
196                 '$field' => array(
197                         'dob',
198                         t('Birthday:'),
199                         $value,
200                         (((intval($age)) > 0 ) ? t('Age: ') . $age : ""),
201                         '',
202                         'placeholder="' . t('YYYY-MM-DD or MM-DD') . '"'
203                 )
204         ));
205
206         /// @TODO Old-lost code?
207 //      if ($dob && $dob > '0001-01-01')
208 //              $o = datesel($f,mktime(0,0,0,0,0,1900),mktime(),mktime(0,0,0,$month,$day,$year), 'dob');
209 //      else
210 //              $o = datesel($f,mktime(0,0,0,0,0,1900),mktime(),false,'dob');
211
212         return $o;
213 }
214
215 /**
216  * @brief Returns a date selector
217  *
218  * @param string $format
219  *  Format string, e.g. 'ymd' or 'mdy'. Not currently supported
220  * @param string $min
221  *  Unix timestamp of minimum date
222  * @param string $max
223  *  Unix timestap of maximum date
224  * @param string $default
225  *  Unix timestamp of default date
226  * @param string $id
227  *  ID and name of datetimepicker (defaults to "datetimepicker")
228  *
229  * @return string Parsed HTML output.
230  */
231 function datesel($format, $min, $max, $default, $id = 'datepicker') {
232         return datetimesel($format, $min, $max, $default, '', $id, true, false, '', '');
233 }
234
235 /**
236  * @brief Returns a time selector
237  *
238  * @param string $format
239  *  Format string, e.g. 'ymd' or 'mdy'. Not currently supported
240  * @param $h
241  *  Already selected hour
242  * @param $m
243  *  Already selected minute
244  * @param string $id
245  *  ID and name of datetimepicker (defaults to "timepicker")
246  *
247  * @return string Parsed HTML output.
248  */
249 function timesel($format, $h, $m, $id = 'timepicker') {
250         return datetimesel($format, new DateTime(), new DateTime(), new DateTime("$h:$m"), '', $id, false, true);
251 }
252
253 /**
254  * @brief Returns a datetime selector.
255  *
256  * @param string $format
257  *  format string, e.g. 'ymd' or 'mdy'. Not currently supported
258  * @param string $min
259  *  unix timestamp of minimum date
260  * @param string $max
261  *  unix timestap of maximum date
262  * @param string $default
263  *  unix timestamp of default date
264  * @param string $id
265  *  id and name of datetimepicker (defaults to "datetimepicker")
266  * @param bool $pickdate
267  *  true to show date picker (default)
268  * @param boolean $picktime
269  *  true to show time picker (default)
270  * @param $minfrom
271  *  set minimum date from picker with id $minfrom (none by default)
272  * @param $maxfrom
273  *  set maximum date from picker with id $maxfrom (none by default)
274  * @param bool $required default false
275  *
276  * @return string Parsed HTML output.
277  *
278  * @todo Once browser support is better this could probably be replaced with
279  * native HTML5 date picker.
280  */
281 function datetimesel($format, $min, $max, $default, $label, $id = 'datetimepicker', $pickdate = true, $picktime = true, $minfrom = '', $maxfrom = '', $required = false) {
282
283         // First day of the week (0 = Sunday)
284         $firstDay = PConfig::get(local_user(), 'system', 'first_day_of_week', 0);
285
286         $lang = substr(get_browser_language(), 0, 2);
287
288         // Check if the detected language is supported by the picker
289         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"))) {
290                 $lang = Config::get('system', 'language', 'en');
291         }
292
293         $o = '';
294         $dateformat = '';
295
296         if ($pickdate) {
297                 $dateformat .= 'Y-m-d';
298         }
299         if ($pickdate && $picktime) {
300                 $dateformat .= ' ';
301         }
302         if ($picktime) {
303                 $dateformat .= 'H:i';
304         }
305
306         $minjs = $min ? ",minDate: new Date({$min->getTimestamp()}*1000), yearStart: " . $min->format('Y') : '';
307         $maxjs = $max ? ",maxDate: new Date({$max->getTimestamp()}*1000), yearEnd: " . $max->format('Y') : '';
308
309         $input_text = $default ? date($dateformat, $default->getTimestamp()) : '';
310         $defaultdatejs = $default ? ",defaultDate: new Date({$default->getTimestamp()}*1000)" : '';
311
312         $pickers = '';
313         if (!$pickdate) {
314                 $pickers .= ', datepicker: false';
315         }
316         if (!$picktime) {
317                 $pickers .= ',timepicker: false';
318         }
319
320         $extra_js = '';
321         $pickers .= ",dayOfWeekStart: " . $firstDay . ",lang:'" . $lang . "'";
322         if ($minfrom != '') {
323                 $extra_js .= "\$('#id_$minfrom').data('xdsoft_datetimepicker').setOptions({onChangeDateTime: function (currentDateTime) { \$('#id_$id').data('xdsoft_datetimepicker').setOptions({minDate: currentDateTime})}})";
324         }
325         if ($maxfrom != '') {
326                 $extra_js .= "\$('#id_$maxfrom').data('xdsoft_datetimepicker').setOptions({onChangeDateTime: function (currentDateTime) { \$('#id_$id').data('xdsoft_datetimepicker').setOptions({maxDate: currentDateTime})}})";
327         }
328
329         $readable_format = $dateformat;
330         $readable_format = str_replace('Y','yyyy',$readable_format);
331         $readable_format = str_replace('m','mm',$readable_format);
332         $readable_format = str_replace('d','dd',$readable_format);
333         $readable_format = str_replace('H','HH',$readable_format);
334         $readable_format = str_replace('i','MM',$readable_format);
335
336         $tpl = get_markup_template('field_input.tpl');
337         $o .= replace_macros($tpl, array(
338                         '$field' => array($id, $label, $input_text, '', (($required) ? '*' : ''), 'placeholder="' . $readable_format . '"'),
339                 ));
340
341         $o .= "<script type='text/javascript'>";
342         $o .= "\$(function () {var picker = \$('#id_$id').datetimepicker({step:5,format:'$dateformat' $minjs $maxjs $pickers $defaultdatejs}); $extra_js})";
343         $o .= "</script>";
344
345         return $o;
346 }
347
348 /**
349  * @brief Returns a relative date string.
350  *
351  * Implements "3 seconds ago" etc.
352  * Based on $posted_date, (UTC).
353  * Results relative to current timezone.
354  * Limited to range of timestamps.
355  *
356  * @param string $posted_date MySQL-formatted date string (YYYY-MM-DD HH:MM:SS)
357  * @param string $format (optional) Parsed with sprintf()
358  *    <tt>%1$d %2$s ago</tt>, e.g. 22 hours ago, 1 minute ago
359  *
360  * @return string with relative date
361  */
362 function relative_date($posted_date, $format = null) {
363
364         $localtime = $posted_date . ' UTC';
365
366         $abs = strtotime($localtime);
367
368         if (is_null($posted_date) || $posted_date <= NULL_DATE || $abs === False) {
369                  return t('never');
370         }
371
372         $etime = time() - $abs;
373
374         if ($etime < 1) {
375                 return t('less than a second ago');
376         }
377
378         $a = array( 12 * 30 * 24 * 60 * 60  =>  array( t('year'),   t('years')),
379                                 30 * 24 * 60 * 60       =>  array( t('month'),  t('months')),
380                                 7  * 24 * 60 * 60       =>  array( t('week'),   t('weeks')),
381                                 24 * 60 * 60            =>  array( t('day'),    t('days')),
382                                 60 * 60                 =>  array( t('hour'),   t('hours')),
383                                 60                      =>  array( t('minute'), t('minutes')),
384                                 1                       =>  array( t('second'), t('seconds'))
385         );
386
387         foreach ($a as $secs => $str) {
388                 $d = $etime / $secs;
389                 if ($d >= 1) {
390                         $r = round($d);
391                         // translators - e.g. 22 hours ago, 1 minute ago
392                         if (!$format) {
393                                 $format = t('%1$d %2$s ago');
394                         }
395
396                         return sprintf($format, $r, (($r == 1) ? $str[0] : $str[1]));
397                 }
398         }
399 }
400
401 /**
402  * @brief Returns timezone correct age in years.
403  *
404  * Returns the age in years, given a date of birth, the timezone of the person
405  * whose date of birth is provided, and the timezone of the person viewing the
406  * result.
407  *
408  * Why? Bear with me. Let's say I live in Mittagong, Australia, and my birthday
409  * is on New Year's. You live in San Bruno, California.
410  * When exactly are you going to see my age increase?
411  *
412  * A: 5:00 AM Dec 31 San Bruno time. That's precisely when I start celebrating
413  * and become a year older. If you wish me happy birthday on January 1
414  * (San Bruno time), you'll be a day late.
415  *
416  * @param string $dob Date of Birth
417  * @param string $owner_tz (optional) Timezone of the person of interest
418  * @param string $viewer_tz (optional) Timezone of the person viewing
419  *
420  * @return int Age in years
421  */
422 function age($dob, $owner_tz = '', $viewer_tz = '') {
423         if (! intval($dob)) {
424                 return 0;
425         }
426         if (! $owner_tz) {
427                 $owner_tz = date_default_timezone_get();
428         }
429         if (! $viewer_tz) {
430                 $viewer_tz = date_default_timezone_get();
431         }
432
433         $birthdate = datetime_convert('UTC', $owner_tz,$dob . ' 00:00:00+00:00','Y-m-d');
434         list($year, $month, $day) = explode("-", $birthdate);
435         $year_diff  = datetime_convert('UTC',$viewer_tz, 'now', 'Y') - $year;
436         $curr_month = datetime_convert('UTC',$viewer_tz, 'now', 'm');
437         $curr_day   = datetime_convert('UTC',$viewer_tz, 'now', 'd');
438
439         if (($curr_month < $month) || (($curr_month == $month) && ($curr_day < $day))) {
440                 $year_diff--;
441         }
442
443         return $year_diff;
444 }
445
446 /**
447  * @brief Get days of a month in a given year.
448  *
449  * Returns number of days in the month of the given year.
450  * $m = 1 is 'January' to match human usage.
451  *
452  * @param int $y Year
453  * @param int $m Month (1=January, 12=December)
454  *
455  * @return int Number of days in the given month
456  */
457 function get_dim($y, $m) {
458
459         $dim = array( 0,
460                 31, 28, 31, 30, 31, 30,
461                 31, 31, 30, 31, 30, 31);
462
463         if ($m != 2) {
464                 return $dim[$m];
465         } elseif (((($y % 4) == 0) && (($y % 100) != 0)) || (($y % 400) == 0)) {
466                 return 29;
467         }
468
469         return $dim[2];
470 }
471
472 /**
473  * @brief Returns the first day in month for a given month, year.
474  *
475  * Months start at 1.
476  *
477  * @param int $y Year
478  * @param int $m Month (1=January, 12=December)
479  *
480  * @return string day 0 = Sunday through 6 = Saturday
481  */
482 function get_first_dim($y,$m) {
483         $d = sprintf('%04d-%02d-01 00:00', intval($y), intval($m));
484
485         return datetime_convert('UTC','UTC',$d,'w');
486 }
487
488 /**
489  * @brief Output a calendar for the given month, year.
490  *
491  * If $links are provided (array), e.g. $links[12] => 'http://mylink' ,
492  * date 12 will be linked appropriately. Today's date is also noted by
493  * altering td class.
494  * Months count from 1.
495  *
496  * @param int $y Year
497  * @param int $m Month
498  * @param bool $links (default false)
499  * @param string $class
500  *
501  * @return string
502  *
503  * @todo Provide (prev,next) links, define class variations for different size calendars
504  */
505 function cal($y = 0,$m = 0, $links = false, $class='') {
506         // month table - start at 1 to match human usage.
507
508         $mtab = array(' ',
509                 'January', 'February', 'March',
510                 'April'  , 'May'     , 'June',
511                 'July'   , 'August'  , 'September',
512                 'October', 'November', 'December'
513         );
514
515         $thisyear = datetime_convert('UTC', date_default_timezone_get(), 'now','Y');
516         $thismonth = datetime_convert('UTC', date_default_timezone_get(), 'now','m');
517         if (! $y) {
518                 $y = $thisyear;
519         }
520         if (! $m) {
521                 $m = intval($thismonth);
522         }
523
524         $dn = array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday');
525         $f = get_first_dim($y,$m);
526         $l = get_dim($y,$m);
527         $d = 1;
528         $dow = 0;
529         $started = false;
530
531         if (($y == $thisyear) && ($m == $thismonth)) {
532                 $tddate = intval(datetime_convert('UTC', date_default_timezone_get(), 'now', 'j'));
533         }
534
535         $str_month = day_translate($mtab[$m]);
536         $o = '<table class="calendar' . $class . '">';
537         $o .= "<caption>$str_month $y</caption><tr>";
538         for ($a = 0; $a < 7; $a ++) {
539                 $o .= '<th>' . mb_substr(day_translate($dn[$a]), 0, 3, 'UTF-8') . '</th>';
540         }
541
542         $o .= '</tr><tr>';
543
544         while ($d <= $l) {
545                 if (($dow == $f) && (! $started)) {
546                         $started = true;
547                 }
548
549                 $today = (((isset($tddate)) && ($tddate == $d)) ? "class=\"today\" " : '');
550                 $o .= "<td $today>";
551                 $day = str_replace(' ', '&nbsp;', sprintf('%2.2d', $d));
552                 if ($started) {
553                         if (is_array($links) && isset($links[$d])) {
554                                 $o .=  "<a href=\"{$links[$d]}\">$day</a>";
555                         } else {
556                                 $o .= $day;
557                         }
558
559                         $d ++;
560                 } else {
561                         $o .= '&nbsp;';
562                 }
563
564                 $o .= '</td>';
565                 $dow ++;
566                 if (($dow == 7) && ($d <= $l)) {
567                         $dow = 0;
568                         $o .= '</tr><tr>';
569                 }
570         }
571         if ($dow) {
572                 for ($a = $dow; $a < 7; $a ++) {
573                         $o .= '<td>&nbsp;</td>';
574                 }
575         }
576
577         $o .= '</tr></table>'."\r\n";
578
579         return $o;
580 }
581
582 /**
583  * @brief Create a birthday event.
584  *
585  * Update the year and the birthday.
586  */
587 function update_contact_birthdays() {
588
589         // This only handles foreign or alien networks where a birthday has been provided.
590         // In-network birthdays are handled within local_delivery
591
592         $r = q("SELECT * FROM `contact` WHERE `bd` != '' AND `bd` > '0001-01-01' AND SUBSTRING(`bd`, 1, 4) != `bdyear` ");
593         if (DBM::is_result($r)) {
594                 foreach ($r as $rr) {
595
596                         logger('update_contact_birthday: ' . $rr['bd']);
597
598                         $nextbd = datetime_convert('UTC','UTC','now','Y') . substr($rr['bd'], 4);
599
600                         /*
601                          * Add new birthday event for this person
602                          *
603                          * $bdtext is just a readable placeholder in case the event is shared
604                          * with others. We will replace it during presentation to our $importer
605                          * to contain a sparkle link and perhaps a photo.
606                          */
607
608                         // Check for duplicates
609                         $s = q("SELECT `id` FROM `event` WHERE `uid` = %d AND `cid` = %d AND `start` = '%s' AND `type` = '%s' LIMIT 1",
610                                 intval($rr['uid']),
611                                 intval($rr['id']),
612                                 dbesc(datetime_convert('UTC','UTC', $nextbd)),
613                                 dbesc('birthday'));
614
615                         if (DBM::is_result($s)) {
616                                 continue;
617                         }
618
619                         $bdtext = sprintf( t('%s\'s birthday'), $rr['name']);
620                         $bdtext2 = sprintf( t('Happy Birthday %s'), ' [url=' . $rr['url'] . ']' . $rr['name'] . '[/url]') ;
621
622                         $r = q("INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`summary`,`desc`,`type`,`adjust`)
623                                 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%d' ) ",
624                                 intval($rr['uid']),
625                                 intval($rr['id']),
626                                 dbesc(datetime_convert()),
627                                 dbesc(datetime_convert()),
628                                 dbesc(datetime_convert('UTC','UTC', $nextbd)),
629                                 dbesc(datetime_convert('UTC','UTC', $nextbd . ' + 1 day ')),
630                                 dbesc($bdtext),
631                                 dbesc($bdtext2),
632                                 dbesc('birthday'),
633                                 intval(0)
634                         );
635
636
637                         // update bdyear
638                         q("UPDATE `contact` SET `bdyear` = '%s', `bd` = '%s' WHERE `uid` = %d AND `id` = %d",
639                                 dbesc(substr($nextbd,0,4)),
640                                 dbesc($nextbd),
641                                 intval($rr['uid']),
642                                 intval($rr['id'])
643                         );
644
645                 }
646         }
647 }