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