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