]> git.mxchange.org Git - friendica.git/blob - src/Util/Temporal.php
Model/Photo: use self select functions, reuse backend, fix quotes, add delete()
[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          */
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          * @return string Formatted HTML
126          */
127         public static function getDateofBirthField($dob)
128         {
129                 $a = \get_app();
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, $a->user["timezone"], $a->user["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 string $min     Unix timestamp of minimum date
161          * @param string $max     Unix timestap of maximum date
162          * @param string $default Unix timestamp of default date
163          * @param string $id      ID and name of datetimepicker (defaults to "datetimepicker")
164          *
165          * @return string Parsed HTML output.
166          */
167         public static function getDateField($min, $max, $default, $id = 'datepicker')
168         {
169                 return self::getDateTimeField($min, $max, $default, '', $id, true, false, '', '');
170         }
171
172         /**
173          * @brief Returns a time selector
174          *
175          * @param string $h  Already selected hour
176          * @param string $m  Already selected minute
177          * @param string $id ID and name of datetimepicker (defaults to "timepicker")
178          *
179          * @return string Parsed HTML output.
180          */
181         public static function getTimeField($h, $m, $id = 'timepicker')
182         {
183                 return self::getDateTimeField(new DateTime(), new DateTime(), new DateTime("$h:$m"), '', $id, false, true);
184         }
185
186         /**
187          * @brief Returns a datetime selector.
188          *
189          * @param DateTime $minDate     Minimum date
190          * @param DateTime $maxDate     Maximum date
191          * @param DateTime $defaultDate Default date
192          * @param string   $id          Id and name of datetimepicker (defaults to "datetimepicker")
193          * @param bool     $pickdate    true to show date picker (default)
194          * @param bool     $picktime    true to show time picker (default)
195          * @param string   $minfrom     set minimum date from picker with id $minfrom (none by default)
196          * @param string   $maxfrom     set maximum date from picker with id $maxfrom (none by default)
197          * @param bool     $required    default false
198          *
199          * @return string Parsed HTML output.
200          *
201          * @todo Once browser support is better this could probably be replaced with
202          * native HTML5 date picker.
203          */
204         public static function getDateTimeField(
205                 DateTime $minDate,
206                 DateTime $maxDate,
207                 DateTime $defaultDate,
208                 $label,
209                 $id       = 'datetimepicker',
210                 $pickdate = true,
211                 $picktime = true,
212                 $minfrom  = '',
213                 $maxfrom  = '',
214                 $required = false)
215         {
216                 // First day of the week (0 = Sunday)
217                 $firstDay = PConfig::get(local_user(), 'system', 'first_day_of_week', 0);
218
219                 $lang = substr(L10n::getCurrentLang(), 0, 2);
220
221                 // Check if the detected language is supported by the picker
222                 if (!in_array($lang,
223                                 ["ar", "ro", "id", "bg", "fa", "ru", "uk", "en", "el", "de", "nl", "tr", "fr", "es", "th", "pl", "pt", "ch", "se", "kr",
224                                 "it", "da", "no", "ja", "vi", "sl", "cs", "hu"])) {
225                         $lang = 'en';
226                 }
227
228                 $o = '';
229                 $dateformat = '';
230
231                 if ($pickdate) {
232                         $dateformat .= 'Y-m-d';
233                 }
234
235                 if ($pickdate && $picktime) {
236                         $dateformat .= ' ';
237                 }
238
239                 if ($picktime) {
240                         $dateformat .= 'H:i';
241                 }
242
243                 $input_text = $defaultDate ? date($dateformat, $defaultDate->getTimestamp()) : '';
244
245                 $readable_format = str_replace(['Y', 'm', 'd', 'H', 'i'], ['yyyy', 'mm', 'dd', 'HH', 'MM'], $dateformat);
246
247                 $tpl = Renderer::getMarkupTemplate('field_datetime.tpl');
248                 $o .= Renderer::replaceMacros($tpl, [
249                         '$field' => [
250                                 $id,
251                                 $label,
252                                 $input_text,
253                                 '',
254                                 $required ? '*' : '',
255                                 'placeholder="' . $readable_format . '"'
256                         ],
257                         '$datetimepicker' => [
258                                 'minDate' => $minDate,
259                                 'maxDate' => $maxDate,
260                                 'defaultDate' => $defaultDate,
261                                 'dateformat' => $dateformat,
262                                 'firstDay' => $firstDay,
263                                 'lang' => $lang,
264                                 'minfrom' => $minfrom,
265                                 'maxfrom' => $maxfrom,
266                         ]
267                 ]);
268
269                 return $o;
270         }
271
272         /**
273          * @brief Returns a relative date string.
274          *
275          * Implements "3 seconds ago" etc.
276          * Based on $posted_date, (UTC).
277          * Results relative to current timezone.
278          * Limited to range of timestamps.
279          *
280          * @param string $posted_date MySQL-formatted date string (YYYY-MM-DD HH:MM:SS)
281          * @param string $format (optional) Parsed with sprintf()
282          *    <tt>%1$d %2$s ago</tt>, e.g. 22 hours ago, 1 minute ago
283          *
284          * @return string with relative date
285          */
286         public static function getRelativeDate($posted_date, $format = null)
287         {
288                 $localtime = $posted_date . ' UTC';
289
290                 $abs = strtotime($localtime);
291
292                 if (is_null($posted_date) || $posted_date <= DBA::NULL_DATETIME || $abs === false) {
293                         return L10n::t('never');
294                 }
295
296                 $isfuture = false;
297                 $etime = time() - $abs;
298
299                 if ($etime < 1 && $etime >= 0) {
300                         return L10n::t('less than a second ago');
301                 }
302
303                 if ($etime < 0){
304                         $etime = -$etime;
305                         $isfuture = true;
306                 }
307
308                 $a = [12 * 30 * 24 * 60 * 60 => [L10n::t('year'), L10n::t('years')],
309                         30 * 24 * 60 * 60 => [L10n::t('month'), L10n::t('months')],
310                         7 * 24 * 60 * 60 => [L10n::t('week'), L10n::t('weeks')],
311                         24 * 60 * 60 => [L10n::t('day'), L10n::t('days')],
312                         60 * 60 => [L10n::t('hour'), L10n::t('hours')],
313                         60 => [L10n::t('minute'), L10n::t('minutes')],
314                         1 => [L10n::t('second'), L10n::t('seconds')]
315                 ];
316
317                 foreach ($a as $secs => $str) {
318                         $d = $etime / $secs;
319                         if ($d >= 1) {
320                                 $r = round($d);
321                                 // translators - e.g. 22 hours ago, 1 minute ago
322                                 if (!$format) {
323                                         if($isfuture){
324                                                 $format = L10n::t('in %1$d %2$s');
325                                         }
326                                         else {
327                                                 $format = L10n::t('%1$d %2$s ago');
328                                         }
329                                 }
330
331                                 return sprintf($format, $r, (($r == 1) ? $str[0] : $str[1]));
332                         }
333                 }
334         }
335
336         /**
337          * @brief Returns timezone correct age in years.
338          *
339          * Returns the age in years, given a date of birth, the timezone of the person
340          * whose date of birth is provided, and the timezone of the person viewing the
341          * result.
342          *
343          * Why? Bear with me. Let's say I live in Mittagong, Australia, and my birthday
344          * is on New Year's. You live in San Bruno, California.
345          * When exactly are you going to see my age increase?
346          *
347          * A: 5:00 AM Dec 31 San Bruno time. That's precisely when I start celebrating
348          * and become a year older. If you wish me happy birthday on January 1
349          * (San Bruno time), you'll be a day late.
350          *
351          * @param string $dob Date of Birth
352          * @param string $owner_tz (optional) Timezone of the person of interest
353          * @param string $viewer_tz (optional) Timezone of the person viewing
354          *
355          * @return int Age in years
356          */
357         public static function getAgeByTimezone($dob, $owner_tz = '', $viewer_tz = '')
358         {
359                 if (!intval($dob)) {
360                         return 0;
361                 }
362                 if (!$owner_tz) {
363                         $owner_tz = date_default_timezone_get();
364                 }
365                 if (!$viewer_tz) {
366                         $viewer_tz = date_default_timezone_get();
367                 }
368
369                 $birthdate = DateTimeFormat::convert($dob . ' 00:00:00+00:00', $owner_tz, 'UTC', 'Y-m-d');
370                 list($year, $month, $day) = explode("-", $birthdate);
371                 $year_diff  = DateTimeFormat::timezoneNow($viewer_tz, 'Y') - $year;
372                 $curr_month = DateTimeFormat::timezoneNow($viewer_tz, 'm');
373                 $curr_day   = DateTimeFormat::timezoneNow($viewer_tz, 'd');
374
375                 if (($curr_month < $month) || (($curr_month == $month) && ($curr_day < $day))) {
376                         $year_diff--;
377                 }
378
379                 return $year_diff;
380         }
381
382         /**
383          * @brief Get days of a month in a given year.
384          *
385          * Returns number of days in the month of the given year.
386          * $m = 1 is 'January' to match human usage.
387          *
388          * @param int $y Year
389          * @param int $m Month (1=January, 12=December)
390          *
391          * @return int Number of days in the given month
392          */
393         public static function getDaysInMonth($y, $m)
394         {
395                 return date('t', mktime(0, 0, 0, $m, 1, $y));
396         }
397
398         /**
399          * @brief Returns the first day in month for a given month, year.
400          *
401          * Months start at 1.
402          *
403          * @param int $y Year
404          * @param int $m Month (1=January, 12=December)
405          *
406          * @return string day 0 = Sunday through 6 = Saturday
407          */
408         private static function getFirstDayInMonth($y, $m)
409         {
410                 $d = sprintf('%04d-%02d-01 00:00', intval($y), intval($m));
411
412                 return DateTimeFormat::utc($d, 'w');
413         }
414
415         /**
416          * @brief Output a calendar for the given month, year.
417          *
418          * If $links are provided (array), e.g. $links[12] => 'http://mylink' ,
419          * date 12 will be linked appropriately. Today's date is also noted by
420          * altering td class.
421          * Months count from 1.
422          *
423          * @param int    $y Year
424          * @param int    $m Month
425          * @param array  $links (default null)
426          * @param string $class
427          *
428          * @return string
429          *
430          * @todo Provide (prev, next) links, define class variations for different size calendars
431          */
432         public static function getCalendarTable($y = 0, $m = 0, $links = null, $class = '')
433         {
434                 // month table - start at 1 to match human usage.
435                 $mtab = [' ',
436                         'January', 'February', 'March',
437                         'April', 'May', 'June',
438                         'July', 'August', 'September',
439                         'October', 'November', 'December'
440                 ];
441
442                 $thisyear = DateTimeFormat::localNow('Y');
443                 $thismonth = DateTimeFormat::localNow('m');
444                 if (!$y) {
445                         $y = $thisyear;
446                 }
447
448                 if (!$m) {
449                         $m = intval($thismonth);
450                 }
451
452                 $dn = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
453                 $f = self::getFirstDayInMonth($y, $m);
454                 $l = self::getDaysInMonth($y, $m);
455                 $d = 1;
456                 $dow = 0;
457                 $started = false;
458
459                 if (($y == $thisyear) && ($m == $thismonth)) {
460                         $tddate = intval(DateTimeFormat::localNow('j'));
461                 }
462
463                 $str_month = L10n::getDay($mtab[$m]);
464                 $o = '<table class="calendar' . $class . '">';
465                 $o .= "<caption>$str_month $y</caption><tr>";
466                 for ($a = 0; $a < 7; $a ++) {
467                         $o .= '<th>' . mb_substr(L10n::getDay($dn[$a]), 0, 3, 'UTF-8') . '</th>';
468                 }
469
470                 $o .= '</tr><tr>';
471
472                 while ($d <= $l) {
473                         if (($dow == $f) && (!$started)) {
474                                 $started = true;
475                         }
476
477                         $today = (((isset($tddate)) && ($tddate == $d)) ? "class=\"today\" " : '');
478                         $o .= "<td $today>";
479                         $day = str_replace(' ', '&nbsp;', sprintf('%2.2d', $d));
480                         if ($started) {
481                                 if (isset($links[$d])) {
482                                         $o .= "<a href=\"{$links[$d]}\">$day</a>";
483                                 } else {
484                                         $o .= $day;
485                                 }
486
487                                 $d ++;
488                         } else {
489                                 $o .= '&nbsp;';
490                         }
491
492                         $o .= '</td>';
493                         $dow ++;
494                         if (($dow == 7) && ($d <= $l)) {
495                                 $dow = 0;
496                                 $o .= '</tr><tr>';
497                         }
498                 }
499
500                 if ($dow) {
501                         for ($a = $dow; $a < 7; $a ++) {
502                                 $o .= '<td>&nbsp;</td>';
503                         }
504                 }
505
506                 $o .= '</tr></table>' . "\r\n";
507
508                 return $o;
509         }
510 }