]> git.mxchange.org Git - friendica.git/blob - src/Util/Temporal.php
Move NULL_DATE from boot.php to DBA::NULL_DATETIME
[friendica.git] / src / Util / Temporal.php
1 <?php
2
3 /**
4  * @file src/Util/Temporal.php
5  */
6
7 namespace Friendica\Util;
8
9 use DateTime;
10 use DateTimeZone;
11 use Friendica\Core\Config;
12 use Friendica\Core\L10n;
13 use Friendica\Core\PConfig;
14 use Friendica\Database\DBA;
15
16 require_once 'boot.php';
17 require_once 'include/text.php';
18
19 /**
20  * @brief Temporal class
21  */
22 class Temporal
23 {
24         /**
25          * @brief Two-level sort for timezones.
26          *
27          * @param string $a
28          * @param string $b
29          * @return int
30          */
31         private static function timezoneCompareCallback($a, $b)
32         {
33                 if (strstr($a, '/') && strstr($b, '/')) {
34                         if (L10n::t($a) == L10n::t($b)) {
35                                 return 0;
36                         }
37                         return (L10n::t($a) < L10n::t($b)) ? -1 : 1;
38                 }
39
40                 if (strstr($a, '/')) {
41                         return -1;
42                 } elseif (strstr($b, '/')) {
43                         return 1;
44                 } elseif (L10n::t($a) == L10n::t($b)) {
45                         return 0;
46                 }
47
48                 return (L10n::t($a) < L10n::t($b)) ? -1 : 1;
49         }
50
51         /**
52          * @brief Emit a timezone selector grouped (primarily) by continent
53          *
54          * @param string $current Timezone
55          * @return string Parsed HTML output
56          */
57         public static function getTimezoneSelect($current = 'America/Los_Angeles')
58         {
59                 $timezone_identifiers = DateTimeZone::listIdentifiers();
60
61                 $o = '<select id="timezone_select" name="timezone">';
62
63                 usort($timezone_identifiers, [__CLASS__, 'timezoneCompareCallback']);
64                 $continent = '';
65                 foreach ($timezone_identifiers as $value) {
66                         $ex = explode("/", $value);
67                         if (count($ex) > 1) {
68                                 if ($ex[0] != $continent) {
69                                         if ($continent != '') {
70                                                 $o .= '</optgroup>';
71                                         }
72                                         $continent = $ex[0];
73                                         $o .= '<optgroup label="' . L10n::t($continent) . '">';
74                                 }
75                                 if (count($ex) > 2) {
76                                         $city = substr($value, strpos($value, '/') + 1);
77                                 } else {
78                                         $city = $ex[1];
79                                 }
80                         } else {
81                                 $city = $ex[0];
82                                 if ($continent != L10n::t('Miscellaneous')) {
83                                         $o .= '</optgroup>';
84                                         $continent = L10n::t('Miscellaneous');
85                                         $o .= '<optgroup label="' . L10n::t($continent) . '">';
86                                 }
87                         }
88                         $city = str_replace('_', ' ', L10n::t($city));
89                         $selected = (($value == $current) ? " selected=\"selected\" " : "");
90                         $o .= "<option value=\"$value\" $selected >$city</option>";
91                 }
92                 $o .= '</optgroup></select>';
93                 return $o;
94         }
95
96         /**
97          * @brief Generating a Timezone selector
98          *
99          * Return a select using 'field_select_raw' template, with timezones
100          * grouped (primarily) by continent
101          * arguments follow convention as other field_* template array:
102          * 'name', 'label', $value, 'help'
103          *
104          * @param string $name Name of the selector
105          * @param string $label Label for the selector
106          * @param string $current Timezone
107          * @param string $help Help text
108          *
109          * @return string Parsed HTML
110          */
111         public static function getTimezoneField($name = 'timezone', $label = '', $current = 'America/Los_Angeles', $help = '')
112         {
113                 $options = self::getTimezoneSelect($current);
114                 $options = str_replace('<select id="timezone_select" name="timezone">', '', $options);
115                 $options = str_replace('</select>', '', $options);
116
117                 $tpl = get_markup_template('field_select_raw.tpl');
118                 return replace_macros($tpl, [
119                         '$field' => [$name, $label, $current, $help, $options],
120                 ]);
121         }
122
123         /**
124          * @brief Wrapper for date selector, tailored for use in birthday fields.
125          *
126          * @param string $dob Date of Birth
127          * @return string Formatted HTML
128          */
129         public static function getDateofBirthField($dob)
130         {
131                 $a = get_app();
132
133                 list($year, $month, $day) = sscanf($dob, '%4d-%2d-%2d');
134
135                 if ($dob < '0000-01-01') {
136                         $value = '';
137                 } else {
138                         $value = DateTimeFormat::utc(($year > 1000) ? $dob : '1000-' . $month . '-' . $day, 'Y-m-d');
139                 }
140
141                 $age = (intval($value) ? self::getAgeByTimezone($value, $a->user["timezone"], $a->user["timezone"]) : "");
142
143                 $tpl = get_markup_template("field_input.tpl");
144                 $o = replace_macros($tpl,
145                         [
146                         '$field' => [
147                                 'dob',
148                                 L10n::t('Birthday:'),
149                                 $value,
150                                 intval($age) > 0 ? L10n::t('Age: ') . $age : "",
151                                 '',
152                                 'placeholder="' . L10n::t('YYYY-MM-DD or MM-DD') . '"'
153                         ]
154                 ]);
155
156                 return $o;
157         }
158
159         /**
160          * @brief Returns a date selector
161          *
162          * @param string $min     Unix timestamp of minimum date
163          * @param string $max     Unix timestap of maximum date
164          * @param string $default Unix timestamp of default date
165          * @param string $id      ID and name of datetimepicker (defaults to "datetimepicker")
166          *
167          * @return string Parsed HTML output.
168          */
169         public static function getDateField($min, $max, $default, $id = 'datepicker')
170         {
171                 return self::getDateTimeField($min, $max, $default, '', $id, true, false, '', '');
172         }
173
174         /**
175          * @brief Returns a time selector
176          *
177          * @param string $h  Already selected hour
178          * @param string $m  Already selected minute
179          * @param string $id ID and name of datetimepicker (defaults to "timepicker")
180          *
181          * @return string Parsed HTML output.
182          */
183         public static function getTimeField($h, $m, $id = 'timepicker')
184         {
185                 return self::getDateTimeField(new DateTime(), new DateTime(), new DateTime("$h:$m"), '', $id, false, true);
186         }
187
188         /**
189          * @brief Returns a datetime selector.
190          *
191          * @param DateTime $minDate     Minimum date
192          * @param DateTime $maxDate     Maximum date
193          * @param DateTime $defaultDate Default date
194          * @param string   $id          Id and name of datetimepicker (defaults to "datetimepicker")
195          * @param bool     $pickdate    true to show date picker (default)
196          * @param bool     $picktime    true to show time picker (default)
197          * @param string   $minfrom     set minimum date from picker with id $minfrom (none by default)
198          * @param string   $maxfrom     set maximum date from picker with id $maxfrom (none by default)
199          * @param bool     $required    default false
200          *
201          * @return string Parsed HTML output.
202          *
203          * @todo Once browser support is better this could probably be replaced with
204          * native HTML5 date picker.
205          */
206         public static function getDateTimeField(
207                 DateTime $minDate,
208                 DateTime $maxDate,
209                 DateTime $defaultDate,
210                 $label,
211                 $id       = 'datetimepicker',
212                 $pickdate = true,
213                 $picktime = true,
214                 $minfrom  = '',
215                 $maxfrom  = '',
216                 $required = false)
217         {
218                 // First day of the week (0 = Sunday)
219                 $firstDay = PConfig::get(local_user(), 'system', 'first_day_of_week', 0);
220
221                 $lang = substr(L10n::getCurrentLang(), 0, 2);
222
223                 // Check if the detected language is supported by the picker
224                 if (!in_array($lang,
225                                 ["ar", "ro", "id", "bg", "fa", "ru", "uk", "en", "el", "de", "nl", "tr", "fr", "es", "th", "pl", "pt", "ch", "se", "kr",
226                                 "it", "da", "no", "ja", "vi", "sl", "cs", "hu"])) {
227                         $lang = 'en';
228                 }
229
230                 $o = '';
231                 $dateformat = '';
232
233                 if ($pickdate) {
234                         $dateformat .= 'Y-m-d';
235                 }
236
237                 if ($pickdate && $picktime) {
238                         $dateformat .= ' ';
239                 }
240
241                 if ($picktime) {
242                         $dateformat .= 'H:i';
243                 }
244
245                 $input_text = $defaultDate ? date($dateformat, $defaultDate->getTimestamp()) : '';
246
247                 $readable_format = str_replace(['Y', 'm', 'd', 'H', 'i'], ['yyyy', 'mm', 'dd', 'HH', 'MM'], $dateformat);
248
249                 $tpl = get_markup_template('field_datetime.tpl');
250                 $o .= replace_macros($tpl, [
251                         '$field' => [
252                                 $id,
253                                 $label,
254                                 $input_text,
255                                 '',
256                                 $required ? '*' : '',
257                                 'placeholder="' . $readable_format . '"'
258                         ],
259                         '$datetimepicker' => [
260                                 'minDate' => $minDate,
261                                 'maxDate' => $maxDate,
262                                 'defaultDate' => $defaultDate,
263                                 'dateformat' => $dateformat,
264                                 'firstDay' => $firstDay,
265                                 'lang' => $lang,
266                                 'minfrom' => $minfrom,
267                                 'maxfrom' => $maxfrom,
268                         ]
269                 ]);
270
271                 return $o;
272         }
273
274         /**
275          * @brief Returns a relative date string.
276          *
277          * Implements "3 seconds ago" etc.
278          * Based on $posted_date, (UTC).
279          * Results relative to current timezone.
280          * Limited to range of timestamps.
281          *
282          * @param string $posted_date MySQL-formatted date string (YYYY-MM-DD HH:MM:SS)
283          * @param string $format (optional) Parsed with sprintf()
284          *    <tt>%1$d %2$s ago</tt>, e.g. 22 hours ago, 1 minute ago
285          *
286          * @return string with relative date
287          */
288         public static function getRelativeDate($posted_date, $format = null)
289         {
290                 $localtime = $posted_date . ' UTC';
291
292                 $abs = strtotime($localtime);
293
294                 if (is_null($posted_date) || $posted_date <= DBA::NULL_DATETIME || $abs === false) {
295                         return L10n::t('never');
296                 }
297
298                 $isfuture = false;
299                 $etime = time() - $abs;
300
301                 if ($etime < 1 && $etime >= 0) {
302                         return L10n::t('less than a second ago');
303                 }
304
305                 if ($etime < 0){
306                         $etime = -$etime;
307                         $isfuture = true;
308                 }
309
310                 $a = [12 * 30 * 24 * 60 * 60 => [L10n::t('year'), L10n::t('years')],
311                         30 * 24 * 60 * 60 => [L10n::t('month'), L10n::t('months')],
312                         7 * 24 * 60 * 60 => [L10n::t('week'), L10n::t('weeks')],
313                         24 * 60 * 60 => [L10n::t('day'), L10n::t('days')],
314                         60 * 60 => [L10n::t('hour'), L10n::t('hours')],
315                         60 => [L10n::t('minute'), L10n::t('minutes')],
316                         1 => [L10n::t('second'), L10n::t('seconds')]
317                 ];
318
319                 foreach ($a as $secs => $str) {
320                         $d = $etime / $secs;
321                         if ($d >= 1) {
322                                 $r = round($d);
323                                 // translators - e.g. 22 hours ago, 1 minute ago
324                                 if (!$format) {
325                                         if($isfuture){
326                                                 $format = L10n::t('in %1$d %2$s');
327                                         }
328                                         else {
329                                                 $format = L10n::t('%1$d %2$s ago');
330                                         }
331                                 }
332
333                                 return sprintf($format, $r, (($r == 1) ? $str[0] : $str[1]));
334                         }
335                 }
336         }
337
338         /**
339          * @brief Returns timezone correct age in years.
340          *
341          * Returns the age in years, given a date of birth, the timezone of the person
342          * whose date of birth is provided, and the timezone of the person viewing the
343          * result.
344          *
345          * Why? Bear with me. Let's say I live in Mittagong, Australia, and my birthday
346          * is on New Year's. You live in San Bruno, California.
347          * When exactly are you going to see my age increase?
348          *
349          * A: 5:00 AM Dec 31 San Bruno time. That's precisely when I start celebrating
350          * and become a year older. If you wish me happy birthday on January 1
351          * (San Bruno time), you'll be a day late.
352          *
353          * @param string $dob Date of Birth
354          * @param string $owner_tz (optional) Timezone of the person of interest
355          * @param string $viewer_tz (optional) Timezone of the person viewing
356          *
357          * @return int Age in years
358          */
359         public static function getAgeByTimezone($dob, $owner_tz = '', $viewer_tz = '')
360         {
361                 if (!intval($dob)) {
362                         return 0;
363                 }
364                 if (!$owner_tz) {
365                         $owner_tz = date_default_timezone_get();
366                 }
367                 if (!$viewer_tz) {
368                         $viewer_tz = date_default_timezone_get();
369                 }
370
371                 $birthdate = DateTimeFormat::convert($dob . ' 00:00:00+00:00', $owner_tz, 'UTC', 'Y-m-d');
372                 list($year, $month, $day) = explode("-", $birthdate);
373                 $year_diff  = DateTimeFormat::timezoneNow($viewer_tz, 'Y') - $year;
374                 $curr_month = DateTimeFormat::timezoneNow($viewer_tz, 'm');
375                 $curr_day   = DateTimeFormat::timezoneNow($viewer_tz, 'd');
376
377                 if (($curr_month < $month) || (($curr_month == $month) && ($curr_day < $day))) {
378                         $year_diff--;
379                 }
380
381                 return $year_diff;
382         }
383
384         /**
385          * @brief Get days of a month in a given year.
386          *
387          * Returns number of days in the month of the given year.
388          * $m = 1 is 'January' to match human usage.
389          *
390          * @param int $y Year
391          * @param int $m Month (1=January, 12=December)
392          *
393          * @return int Number of days in the given month
394          */
395         public static function getDaysInMonth($y, $m)
396         {
397                 return date('t', mktime(0, 0, 0, $m, 1, $y));
398         }
399
400         /**
401          * @brief Returns the first day in month for a given month, year.
402          *
403          * Months start at 1.
404          *
405          * @param int $y Year
406          * @param int $m Month (1=January, 12=December)
407          *
408          * @return string day 0 = Sunday through 6 = Saturday
409          */
410         private static function getFirstDayInMonth($y, $m)
411         {
412                 $d = sprintf('%04d-%02d-01 00:00', intval($y), intval($m));
413
414                 return DateTimeFormat::utc($d, 'w');
415         }
416
417         /**
418          * @brief Output a calendar for the given month, year.
419          *
420          * If $links are provided (array), e.g. $links[12] => 'http://mylink' ,
421          * date 12 will be linked appropriately. Today's date is also noted by
422          * altering td class.
423          * Months count from 1.
424          *
425          * @param int    $y Year
426          * @param int    $m Month
427          * @param array  $links (default null)
428          * @param string $class
429          *
430          * @return string
431          *
432          * @todo Provide (prev, next) links, define class variations for different size calendars
433          */
434         public static function getCalendarTable($y = 0, $m = 0, $links = null, $class = '')
435         {
436                 // month table - start at 1 to match human usage.
437                 $mtab = [' ',
438                         'January', 'February', 'March',
439                         'April', 'May', 'June',
440                         'July', 'August', 'September',
441                         'October', 'November', 'December'
442                 ];
443
444                 $thisyear = DateTimeFormat::localNow('Y');
445                 $thismonth = DateTimeFormat::localNow('m');
446                 if (!$y) {
447                         $y = $thisyear;
448                 }
449
450                 if (!$m) {
451                         $m = intval($thismonth);
452                 }
453
454                 $dn = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
455                 $f = self::getFirstDayInMonth($y, $m);
456                 $l = self::getDaysInMonth($y, $m);
457                 $d = 1;
458                 $dow = 0;
459                 $started = false;
460
461                 if (($y == $thisyear) && ($m == $thismonth)) {
462                         $tddate = intval(DateTimeFormat::localNow('j'));
463                 }
464
465                 $str_month = day_translate($mtab[$m]);
466                 $o = '<table class="calendar' . $class . '">';
467                 $o .= "<caption>$str_month $y</caption><tr>";
468                 for ($a = 0; $a < 7; $a ++) {
469                         $o .= '<th>' . mb_substr(day_translate($dn[$a]), 0, 3, 'UTF-8') . '</th>';
470                 }
471
472                 $o .= '</tr><tr>';
473
474                 while ($d <= $l) {
475                         if (($dow == $f) && (!$started)) {
476                                 $started = true;
477                         }
478
479                         $today = (((isset($tddate)) && ($tddate == $d)) ? "class=\"today\" " : '');
480                         $o .= "<td $today>";
481                         $day = str_replace(' ', '&nbsp;', sprintf('%2.2d', $d));
482                         if ($started) {
483                                 if (x($links, $d) !== false) {
484                                         $o .= "<a href=\"{$links[$d]}\">$day</a>";
485                                 } else {
486                                         $o .= $day;
487                                 }
488
489                                 $d ++;
490                         } else {
491                                 $o .= '&nbsp;';
492                         }
493
494                         $o .= '</td>';
495                         $dow ++;
496                         if (($dow == 7) && ($d <= $l)) {
497                                 $dow = 0;
498                                 $o .= '</tr><tr>';
499                         }
500                 }
501
502                 if ($dow) {
503                         for ($a = $dow; $a < 7; $a ++) {
504                                 $o .= '<td>&nbsp;</td>';
505                         }
506                 }
507
508                 $o .= '</tr></table>' . "\r\n";
509
510                 return $o;
511         }
512 }