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