[REF][PHP8.1][INTL] Remove dependency on strftime function by using ts to generate...
[civicrm-core.git] / CRM / Utils / Date.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
10 */
11
12 /**
13 *
14 * @package CRM
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
16 */
17
18 /**
19 * Date utilties
20 */
21 class CRM_Utils_Date {
22
23 /**
24 * Format a date by padding it with leading '0'.
25 *
26 * @param array $date
27 * ('Y', 'M', 'd').
28 * @param string $separator
29 * The separator to use when formatting the date.
30 * @param int|string $invalidDate what to return if the date is invalid
31 *
32 * @return string
33 * formatted string for date
34 */
35 public static function format($date, $separator = '', $invalidDate = 0) {
36 if (is_numeric($date) &&
37 ((strlen($date) == 8) || (strlen($date) == 14))
38 ) {
39 return $date;
40 }
41
42 if (!is_array($date) ||
43 CRM_Utils_System::isNull($date) ||
44 empty($date['Y'])
45 ) {
46 return $invalidDate;
47 }
48
49 $date['Y'] = (int ) $date['Y'];
50 if ($date['Y'] < 1000 || $date['Y'] > 2999) {
51 return $invalidDate;
52 }
53
54 if (array_key_exists('m', $date)) {
55 $date['M'] = $date['m'];
56 }
57 elseif (array_key_exists('F', $date)) {
58 $date['M'] = $date['F'];
59 }
60
61 if (!empty($date['M'])) {
62 $date['M'] = (int ) $date['M'];
63 if ($date['M'] < 1 || $date['M'] > 12) {
64 return $invalidDate;
65 }
66 }
67 else {
68 $date['M'] = 1;
69 }
70
71 if (!empty($date['d'])) {
72 $date['d'] = (int ) $date['d'];
73 }
74 else {
75 $date['d'] = 1;
76 }
77
78 if (!checkdate($date['M'], $date['d'], $date['Y'])) {
79 return $invalidDate;
80 }
81
82 $date['M'] = sprintf('%02d', $date['M']);
83 $date['d'] = sprintf('%02d', $date['d']);
84
85 $time = '';
86 if (CRM_Utils_Array::value('H', $date) != NULL ||
87 CRM_Utils_Array::value('h', $date) != NULL ||
88 CRM_Utils_Array::value('i', $date) != NULL ||
89 CRM_Utils_Array::value('s', $date) != NULL
90 ) {
91 // we have time too..
92 if (!empty($date['h'])) {
93 if (CRM_Utils_Array::value('A', $date) == 'PM' or CRM_Utils_Array::value('a', $date) == 'pm') {
94 if ($date['h'] != 12) {
95 $date['h'] = $date['h'] + 12;
96 }
97 }
98 if ((CRM_Utils_Array::value('A', $date) == 'AM' or CRM_Utils_Array::value('a', $date) == 'am') &&
99 CRM_Utils_Array::value('h', $date) == 12
100 ) {
101 $date['h'] = '00';
102 }
103
104 $date['h'] = (int ) $date['h'];
105 }
106 else {
107 $date['h'] = 0;
108 }
109
110 // in 24-hour format the hour is under the 'H' key
111 if (!empty($date['H'])) {
112 $date['H'] = (int) $date['H'];
113 }
114 else {
115 $date['H'] = 0;
116 }
117
118 if (!empty($date['i'])) {
119 $date['i'] = (int ) $date['i'];
120 }
121 else {
122 $date['i'] = 0;
123 }
124
125 if ($date['h'] == 0 && $date['H'] != 0) {
126 $date['h'] = $date['H'];
127 }
128
129 if (!empty($date['s'])) {
130 $date['s'] = (int ) $date['s'];
131 }
132 else {
133 $date['s'] = 0;
134 }
135
136 $date['h'] = sprintf('%02d', $date['h']);
137 $date['i'] = sprintf('%02d', $date['i']);
138 $date['s'] = sprintf('%02d', $date['s']);
139
140 if ($separator) {
141 $time = '&nbsp;';
142 }
143 $time .= $date['h'] . $separator . $date['i'] . $separator . $date['s'];
144 }
145
146 return $date['Y'] . $separator . $date['M'] . $separator . $date['d'] . $time;
147 }
148
149 /**
150 * Return abbreviated weekday names according to the locale.
151 *
152 * Array will be in localized order according to 'weekBegins' setting,
153 * but array keys will always match to:
154 * 0 => Sun
155 * 1 => Mon
156 * etc.
157 *
158 * @return array
159 * 0-based array with abbreviated weekday names
160 *
161 */
162 public static function getAbbrWeekdayNames() {
163 $key = 'abbrDays_' . \CRM_Core_I18n::getLocale();
164 if (empty(\Civi::$statics[__CLASS__][$key])) {
165 $days = [
166 0 => ts('Sun'),
167 1 => ts('Mon'),
168 2 => ts('Tue'),
169 3 => ts('Wed'),
170 4 => ts('Thu'),
171 5 => ts('Fri'),
172 6 => ts('Sat'),
173 ];
174 // First day of the week
175 $firstDay = Civi::settings()->get('weekBegins');
176
177 \Civi::$statics[__CLASS__][$key] = [];
178 for ($i = $firstDay; count(\Civi::$statics[__CLASS__][$key]) < 7; $i = $i > 5 ? 0 : $i + 1) {
179 \Civi::$statics[__CLASS__][$key][$i] = $days[$i];
180 }
181 }
182 return \Civi::$statics[__CLASS__][$key];
183 }
184
185 /**
186 * Return full weekday names according to the locale.
187 *
188 * Array will be in localized order according to 'weekBegins' setting,
189 * but array keys will always match to:
190 * 0 => Sunday
191 * 1 => Monday
192 * etc.
193 *
194 * @return array
195 * 0-based array with full weekday names
196 *
197 */
198 public static function getFullWeekdayNames() {
199 $key = 'fullDays_' . \CRM_Core_I18n::getLocale();
200 if (empty(\Civi::$statics[__CLASS__][$key])) {
201 $days = [
202 0 => ts('Sunday'),
203 1 => ts('Monday'),
204 2 => ts('Tuesday'),
205 3 => ts('Wednesday'),
206 4 => ts('Thursday'),
207 5 => ts('Friday'),
208 6 => ts('Saturday'),
209 ];
210 // First day of the week
211 $firstDay = Civi::settings()->get('weekBegins');
212
213 \Civi::$statics[__CLASS__][$key] = [];
214 for ($i = $firstDay; count(\Civi::$statics[__CLASS__][$key]) < 7; $i = $i > 5 ? 0 : $i + 1) {
215 \Civi::$statics[__CLASS__][$key][$i] = $days[$i];
216 }
217 }
218 return \Civi::$statics[__CLASS__][$key];
219 }
220
221 /**
222 * Return abbreviated month names according to the locale.
223 *
224 * @param bool $month
225 *
226 * @return array
227 * 1-based array with abbreviated month names
228 *
229 */
230 public static function &getAbbrMonthNames($month = FALSE) {
231 $key = 'abbrMonthNames_' . \CRM_Core_I18n::getLocale();
232 if (empty(\Civi::$statics[__CLASS__][$key])) {
233 \Civi::$statics[__CLASS__][$key] = [
234 1 => ts('Jan'),
235 2 => ts('Feb'),
236 3 => ts('Mar'),
237 4 => ts('Apr'),
238 5 => ts('May'),
239 6 => ts('Jun'),
240 7 => ts('Jul'),
241 8 => ts('Aug'),
242 9 => ts('Sep'),
243 10 => ts('Oct'),
244 11 => ts('Nov'),
245 12 => ts('Dec'),
246 ];
247 }
248 if ($month) {
249 return \Civi::$statics[__CLASS__][$key][$month];
250 }
251 return \Civi::$statics[__CLASS__][$key];
252 }
253
254 /**
255 * Return full month names according to the locale.
256 *
257 * @return array
258 * 1-based array with full month names
259 *
260 */
261 public static function &getFullMonthNames() {
262 $key = 'fullMonthNames_' . \CRM_Core_I18n::getLocale();
263 if (empty(\Civi::$statics[__CLASS__][$key])) {
264 // Not relying on strftime because it depends on the operating system
265 // and most people will not have a non-US locale configured out of the box
266 // Ignoring other date names for now, since less visible by default
267 \Civi::$statics[__CLASS__][$key] = [
268 1 => ts('January'),
269 2 => ts('February'),
270 3 => ts('March'),
271 4 => ts('April'),
272 5 => ts('May'),
273 6 => ts('June'),
274 7 => ts('July'),
275 8 => ts('August'),
276 9 => ts('September'),
277 10 => ts('October'),
278 11 => ts('November'),
279 12 => ts('December'),
280 ];
281 }
282
283 return \Civi::$statics[__CLASS__][$key];
284 }
285
286 /**
287 * @param string $string
288 *
289 * @return int
290 */
291 public static function unixTime($string) {
292 if (empty($string)) {
293 return 0;
294 }
295 $parsedDate = date_parse($string);
296 return mktime(CRM_Utils_Array::value('hour', $parsedDate),
297 CRM_Utils_Array::value('minute', $parsedDate),
298 59,
299 CRM_Utils_Array::value('month', $parsedDate),
300 CRM_Utils_Array::value('day', $parsedDate),
301 CRM_Utils_Array::value('year', $parsedDate)
302 );
303 }
304
305 /**
306 * Create a date and time string in a provided format.
307 * %A - Full day name ('Saturday'..'Sunday')
308 * %a - abbreviated day name ('Sat'..'Sun')
309 * %b - abbreviated month name ('Jan'..'Dec')
310 * %B - full month name ('January'..'December')
311 * %d - day of the month as a decimal number, 0-padded ('01'..'31')
312 * %e - day of the month as a decimal number, blank-padded (' 1'..'31')
313 * %E - day of the month as a decimal number ('1'..'31')
314 * %f - English ordinal suffix for the day of the month ('st', 'nd', 'rd', 'th')
315 * %H - hour in 24-hour format, 0-padded ('00'..'23')
316 * %I - hour in 12-hour format, 0-padded ('01'..'12')
317 * %k - hour in 24-hour format, blank-padded (' 0'..'23')
318 * %l - hour in 12-hour format, blank-padded (' 1'..'12')
319 * %m - month as a decimal number, 0-padded ('01'..'12')
320 * %M - minute, 0-padded ('00'..'60')
321 * %p - lowercase ante/post meridiem ('am', 'pm')
322 * %P - uppercase ante/post meridiem ('AM', 'PM')
323 * %Y - year as a decimal number including the century ('2005')
324 *
325 * @param string $dateString
326 * Date and time in 'YYYY-MM-DD hh:mm:ss' format.
327 * @param string $format
328 * The output format.
329 * @param array $dateParts
330 * An array with the desired date parts.
331 *
332 * @return string
333 * the $format-formatted $date
334 */
335 public static function customFormat($dateString, $format = NULL, $dateParts = NULL) {
336 // 1-based (January) month names arrays
337 $abbrMonths = self::getAbbrMonthNames();
338 $fullMonths = self::getFullMonthNames();
339 $fullWeekdayNames = self::getFullWeekdayNames();
340 $abbrWeekdayNames = self::getAbbrWeekdayNames();
341
342 if (!$format) {
343 $config = CRM_Core_Config::singleton();
344
345 if ($dateParts) {
346 if (array_intersect(['h', 'H'], $dateParts)) {
347 $format = $config->dateformatDatetime;
348 }
349 elseif (array_intersect(['d', 'j'], $dateParts)) {
350 $format = $config->dateformatFull;
351 }
352 elseif (array_intersect(['m', 'M'], $dateParts)) {
353 $format = $config->dateformatPartial;
354 }
355 else {
356 $format = $config->dateformatYear;
357 }
358 }
359 else {
360 if (strpos(($dateString ?? ''), '-')) {
361 $month = (int) substr($dateString, 5, 2);
362 $day = (int) substr($dateString, 8, 2);
363 }
364 else {
365 $month = (int) substr(($dateString ?? ''), 4, 2);
366 $day = (int) substr(($dateString ?? ''), 6, 2);
367 }
368
369 if (strlen(($dateString ?? '')) > 10) {
370 $format = $config->dateformatDatetime;
371 }
372 elseif ($day > 0) {
373 $format = $config->dateformatFull;
374 }
375 elseif ($month > 0) {
376 $format = $config->dateformatPartial;
377 }
378 else {
379 $format = $config->dateformatYear;
380 }
381 }
382 }
383
384 if (!CRM_Utils_System::isNull($dateString)) {
385 if (strpos($dateString, '-')) {
386 $year = (int) substr($dateString, 0, 4);
387 $month = (int) substr($dateString, 5, 2);
388 $day = (int) substr($dateString, 8, 2);
389
390 $hour24 = (int) substr($dateString, 11, 2);
391 $minute = (int) substr($dateString, 14, 2);
392 $second = (int) substr($dateString, 17, 2);
393 }
394 else {
395 $year = (int) substr($dateString, 0, 4);
396 $month = (int) substr($dateString, 4, 2);
397 $day = (int) substr($dateString, 6, 2);
398
399 $hour24 = (int) substr($dateString, 8, 2);
400 $minute = (int) substr($dateString, 10, 2);
401 $second = (int) substr($dateString, 12, 2);
402 }
403
404 $dayInt = date('w', strtotime($dateString));
405
406 if ($day % 10 == 1 and $day != 11) {
407 $suffix = 'st';
408 }
409 elseif ($day % 10 == 2 and $day != 12) {
410 $suffix = 'nd';
411 }
412 elseif ($day % 10 == 3 and $day != 13) {
413 $suffix = 'rd';
414 }
415 else {
416 $suffix = 'th';
417 }
418
419 if ($hour24 < 12) {
420 if ($hour24 == 00) {
421 $hour12 = 12;
422 }
423 else {
424 $hour12 = $hour24;
425 }
426 $type = 'AM';
427 }
428 else {
429 if ($hour24 == 12) {
430 $hour12 = 12;
431 }
432 else {
433 $hour12 = $hour24 - 12;
434 }
435 $type = 'PM';
436 }
437
438 $date = [
439 '%A' => $fullWeekdayNames[$dayInt] ?? NULL,
440 '%a' => $abbrWeekdayNames[$dayInt] ?? NULL,
441 '%b' => $abbrMonths[$month] ?? NULL,
442 '%B' => $fullMonths[$month] ?? NULL,
443 '%d' => $day > 9 ? $day : '0' . $day,
444 '%e' => $day > 9 ? $day : ' ' . $day,
445 '%E' => $day,
446 '%f' => $suffix,
447 '%H' => $hour24 > 9 ? $hour24 : '0' . $hour24,
448 '%h' => $hour12 > 9 ? $hour12 : '0' . $hour12,
449 '%I' => $hour12 > 9 ? $hour12 : '0' . $hour12,
450 '%k' => $hour24 > 9 ? $hour24 : ' ' . $hour24,
451 '%l' => $hour12 > 9 ? $hour12 : ' ' . $hour12,
452 '%m' => $month > 9 ? $month : '0' . $month,
453 '%M' => $minute > 9 ? $minute : '0' . $minute,
454 '%i' => $minute > 9 ? $minute : '0' . $minute,
455 '%p' => strtolower($type),
456 '%P' => $type,
457 '%Y' => $year,
458 '%s' => str_pad($second, 2, 0, STR_PAD_LEFT),
459 '%S' => str_pad($second, 2, 0, STR_PAD_LEFT),
460 ];
461
462 return strtr($format, $date);
463 }
464 return '';
465 }
466
467 /**
468 * Format the field according to the site's preferred date format.
469 *
470 * This is likely to look something like December 31st, 2020.
471 *
472 * @param string $date
473 *
474 * @return string
475 */
476 public static function formatDateOnlyLong(string $date):string {
477 return CRM_Utils_Date::customFormat($date, Civi::settings()->get('dateformatFull'));
478 }
479
480 /**
481 * Wrapper for customFormat that takes a timestamp
482 *
483 * @param int $timestamp
484 * Date and time in timestamp format.
485 * @param string $format
486 * The output format.
487 * @param array $dateParts
488 * An array with the desired date parts.
489 *
490 * @return string
491 * the $format-formatted $date
492 */
493 public static function customFormatTs($timestamp, $format = NULL, $dateParts = NULL) {
494 return CRM_Utils_Date::customFormat(date("Y-m-d H:i:s", $timestamp), $format, $dateParts);
495 }
496
497 /**
498 * Converts the date/datetime from MySQL format to ISO format
499 *
500 * @param string $mysql
501 * Date/datetime in MySQL format.
502 *
503 * @return string
504 * date/datetime in ISO format
505 */
506 public static function mysqlToIso($mysql) {
507 $year = substr(($mysql ?? ''), 0, 4);
508 $month = substr(($mysql ?? ''), 4, 2);
509 $day = substr(($mysql ?? ''), 6, 2);
510 $hour = substr(($mysql ?? ''), 8, 2);
511 $minute = substr(($mysql ?? ''), 10, 2);
512 $second = substr(($mysql ?? ''), 12, 2);
513
514 $iso = '';
515 if ($year) {
516 $iso .= "$year";
517 }
518 if ($month) {
519 $iso .= "-$month";
520 if ($day) {
521 $iso .= "-$day";
522 }
523 }
524
525 if ($hour) {
526 $iso .= " $hour";
527 if ($minute) {
528 $iso .= ":$minute";
529 if ($second) {
530 $iso .= ":$second";
531 }
532 }
533 }
534 return $iso;
535 }
536
537 /**
538 * Converts the date/datetime from ISO format to MySQL format
539 * Note that until CRM-14986/ 4.4.7 this was required whenever the pattern $dao->find(TRUE): $dao->save(); was
540 * used to update an object with a date field was used. The DAO now checks for a '-' in date field strings
541 * & runs this function if the - appears - meaning it is likely redundant in the form & BAO layers
542 *
543 * @param string $iso
544 * Date/datetime in ISO format.
545 *
546 * @return string
547 * date/datetime in MySQL format
548 */
549 public static function isoToMysql($iso) {
550 $dropArray = ['-' => '', ':' => '', ' ' => ''];
551 return strtr(($iso ?? ''), $dropArray);
552 }
553
554 /**
555 * Converts the any given date to default date format.
556 *
557 * @param array $params
558 * Has given date-format.
559 * @param int $dateType
560 * Type of date.
561 * @param string $dateParam
562 * Index of params.
563 *
564 * @return bool
565 */
566 public static function convertToDefaultDate(&$params, $dateType, $dateParam) {
567 $now = getdate();
568
569 $value = '';
570 if (!empty($params[$dateParam])) {
571 // suppress hh:mm or hh:mm:ss if it exists CRM-7957
572 $value = preg_replace("/(\s(([01]\d)|[2][0-3])(:([0-5]\d)){1,2})$/", "", $params[$dateParam]);
573 }
574
575 switch ($dateType) {
576 case 1:
577 if (!preg_match('/^\d\d\d\d-?(\d|\d\d)-?(\d|\d\d)$/', $value)) {
578 return FALSE;
579 }
580 break;
581
582 case 2:
583 if (!preg_match('/^(\d|\d\d)[-\/](\d|\d\d)[-\/]\d\d$/', $value)) {
584 return FALSE;
585 }
586 break;
587
588 case 4:
589 if (!preg_match('/^(\d|\d\d)[-\/](\d|\d\d)[-\/]\d\d\d\d$/', $value)) {
590 return FALSE;
591 }
592 break;
593
594 case 8:
595 if (!preg_match('/^[A-Za-z]*.[ \t]?\d\d\,[ \t]?\d\d\d\d$/', $value)) {
596 return FALSE;
597 }
598 break;
599
600 case 16:
601 if (!preg_match('/^\d\d-[A-Za-z]{3}.*-\d\d$/', $value) && !preg_match('/^\d\d[-\/]\d\d[-\/]\d\d$/', $value)) {
602 return FALSE;
603 }
604 break;
605
606 case 32:
607 if (!preg_match('/^(\d|\d\d)[-\/](\d|\d\d)[-\/]\d\d\d\d/', $value)) {
608 return FALSE;
609 }
610 break;
611 }
612
613 if ($dateType == 1) {
614 $formattedDate = explode("-", $value);
615 if (count($formattedDate) == 3) {
616 $year = (int) $formattedDate[0];
617 $month = (int) $formattedDate[1];
618 $day = (int) $formattedDate[2];
619 }
620 elseif (count($formattedDate) == 1 && (strlen($value) == 8)) {
621 return TRUE;
622 }
623 else {
624 return FALSE;
625 }
626 }
627
628 if ($dateType == 2 || $dateType == 4) {
629 $formattedDate = explode("/", $value);
630 if (count($formattedDate) != 3) {
631 $formattedDate = explode("-", $value);
632 }
633 if (count($formattedDate) == 3) {
634 $year = (int) $formattedDate[2];
635 $month = (int) $formattedDate[0];
636 $day = (int) $formattedDate[1];
637 }
638 else {
639 return FALSE;
640 }
641 }
642 if ($dateType == 8) {
643 $dateArray = explode(' ', $value);
644 // ignore comma(,)
645 $dateArray[1] = (int) substr($dateArray[1], 0, 2);
646
647 $monthInt = 0;
648 $fullMonths = self::getFullMonthNames();
649 foreach ($fullMonths as $key => $val) {
650 if (strtolower($dateArray[0]) == strtolower($val)) {
651 $monthInt = $key;
652 break;
653 }
654 }
655 if (!$monthInt) {
656 $abbrMonths = self::getAbbrMonthNames();
657 foreach ($abbrMonths as $key => $val) {
658 if (strtolower(trim($dateArray[0], ".")) == strtolower($val)) {
659 $monthInt = $key;
660 break;
661 }
662 }
663 }
664 $year = (int) $dateArray[2];
665 $day = (int) $dateArray[1];
666 $month = (int) $monthInt;
667 }
668 if ($dateType == 16) {
669 $dateArray = explode('-', $value);
670 if (count($dateArray) != 3) {
671 $dateArray = explode('/', $value);
672 }
673
674 if (count($dateArray) == 3) {
675 $monthInt = 0;
676 $fullMonths = self::getFullMonthNames();
677 foreach ($fullMonths as $key => $val) {
678 if (strtolower($dateArray[1]) == strtolower($val)) {
679 $monthInt = $key;
680 break;
681 }
682 }
683 if (!$monthInt) {
684 $abbrMonths = self::getAbbrMonthNames();
685 foreach ($abbrMonths as $key => $val) {
686 if (strtolower(trim($dateArray[1], ".")) == strtolower($val)) {
687 $monthInt = $key;
688 break;
689 }
690 }
691 }
692 if (!$monthInt) {
693 $monthInt = $dateArray[1];
694 }
695
696 $year = (int) $dateArray[2];
697 $day = (int) $dateArray[0];
698 $month = (int) $monthInt;
699 }
700 else {
701 return FALSE;
702 }
703 }
704 if ($dateType == 32) {
705 $formattedDate = explode("/", $value);
706 if (count($formattedDate) == 3) {
707 $year = (int) $formattedDate[2];
708 $month = (int) $formattedDate[1];
709 $day = (int) $formattedDate[0];
710 }
711 else {
712 return FALSE;
713 }
714 }
715
716 $month = ($month < 10) ? "0" . "$month" : $month;
717 $day = ($day < 10) ? "0" . "$day" : $day;
718
719 $year = (int) $year;
720 if ($year < 100) {
721 $year = substr($now['year'], 0, 2) * 100 + $year;
722 if ($year > ($now['year'] + 5)) {
723 $year = $year - 100;
724 }
725 elseif ($year <= ($now['year'] - 95)) {
726 $year = $year + 100;
727 }
728 }
729
730 if ($params[$dateParam]) {
731 $params[$dateParam] = "$year$month$day";
732 }
733 // if month is invalid return as error
734 if ($month !== '00' && $month <= 12) {
735 return TRUE;
736 }
737 return FALSE;
738 }
739
740 /**
741 * Translate a TTL to a concrete expiration time.
742 *
743 * @param null|int|DateInterval $ttl
744 * @param int $default
745 * The value to use if $ttl is not specified (NULL).
746 * @return int
747 * Timestamp (seconds since epoch).
748 * @throws \CRM_Utils_Cache_InvalidArgumentException
749 */
750 public static function convertCacheTtlToExpires($ttl, $default) {
751 if ($ttl === NULL) {
752 $ttl = $default;
753 }
754
755 if (is_int($ttl)) {
756 return time() + $ttl;
757 }
758 elseif ($ttl instanceof DateInterval) {
759 return date_add(new DateTime(), $ttl)->getTimestamp();
760 }
761 else {
762 throw new CRM_Utils_Cache_InvalidArgumentException("Invalid cache TTL");
763 }
764 }
765
766 /**
767 * Normalize a TTL.
768 *
769 * @param null|int|DateInterval $ttl
770 * @param int $default
771 * The value to use if $ttl is not specified (NULL).
772 * @return int
773 * Seconds until expiration.
774 * @throws \CRM_Utils_Cache_InvalidArgumentException
775 */
776 public static function convertCacheTtl($ttl, $default) {
777 if ($ttl === NULL) {
778 return $default;
779 }
780 elseif (is_int($ttl)) {
781 return $ttl;
782 }
783 elseif ($ttl instanceof DateInterval) {
784 return date_add(new DateTime(), $ttl)->getTimestamp() - time();
785 }
786 else {
787 throw new CRM_Utils_Cache_InvalidArgumentException("Invalid cache TTL");
788 }
789 }
790
791 /**
792 * @param int|false|null $timeStamp
793 *
794 * @return bool|string
795 */
796 public static function currentDBDate($timeStamp = NULL) {
797 return $timeStamp ? date('YmdHis', $timeStamp) : date('YmdHis');
798 }
799
800 /**
801 * @param $date
802 * @param null $now
803 *
804 * @return bool
805 */
806 public static function overdue($date, $now = NULL) {
807 $mysqlDate = self::isoToMysql($date);
808 if (!$now) {
809 $now = self::currentDBDate();
810 }
811 else {
812 $now = self::isoToMysql($now);
813 }
814
815 return !(strtotime($mysqlDate) >= strtotime($now));
816 }
817
818 /**
819 * Get customized today.
820 *
821 * This function is used for getting customized today. To get
822 * actuall today pass 'dayParams' as null. or else pass the day,
823 * month, year values as array values
824 * Example: $dayParams = array(
825 * 'day' => '25', 'month' => '10',
826 * 'year' => '2007' );
827 *
828 * @param array $dayParams of the day, month, year.
829 * Array of the day, month, year.
830 * values.
831 * @param string $format
832 * Expected date format( default.
833 * format is 2007-12-21 )
834 *
835 * @return string
836 * Return the customized today's date (Y-m-d)
837 */
838 public static function getToday($dayParams = NULL, $format = "Y-m-d") {
839 if (is_null($dayParams) || empty($dayParams)) {
840 $today = date($format);
841 }
842 else {
843 $today = date($format, mktime(0, 0, 0,
844 $dayParams['month'],
845 $dayParams['day'],
846 $dayParams['year']
847 ));
848 }
849
850 return $today;
851 }
852
853 /**
854 * Find whether today's date lies in
855 * the given range
856 *
857 * @param date $startDate
858 * Start date for the range.
859 * @param date $endDate
860 * End date for the range.
861 *
862 * @return bool
863 * true if today's date is in the given date range
864 */
865 public static function getRange($startDate, $endDate) {
866 $today = date("Y-m-d");
867 $mysqlStartDate = self::isoToMysql($startDate);
868 $mysqlEndDate = self::isoToMysql($endDate);
869 $mysqlToday = self::isoToMysql($today);
870
871 if ((isset($mysqlStartDate) && isset($mysqlEndDate)) && (($mysqlToday >= $mysqlStartDate) && ($mysqlToday <= $mysqlEndDate))) {
872 return TRUE;
873 }
874 elseif ((isset($mysqlStartDate) && !isset($mysqlEndDate)) && (($mysqlToday >= $mysqlStartDate))) {
875 return TRUE;
876 }
877 elseif ((!isset($mysqlStartDate) && isset($mysqlEndDate)) && (($mysqlToday <= $mysqlEndDate))) {
878 return TRUE;
879 }
880 return FALSE;
881 }
882
883 /**
884 * Get start date and end from
885 * the given relative term and unit
886 *
887 * @param string $relative Relative format in the format term.unit.
888 * Eg: previous.day
889 *
890 * @param string $from
891 * @param string $to
892 * @param string $fromTime
893 * @param string $toTime
894 *
895 * @return array
896 * start date, end date
897 */
898 public static function getFromTo($relative, $from = NULL, $to = NULL, $fromTime = NULL, $toTime = '235959') {
899 if ($relative) {
900 list($term, $unit) = explode('.', $relative, 2);
901 $dateRange = self::relativeToAbsolute($term, $unit);
902 $from = substr(($dateRange['from'] ?? ''), 0, 8);
903 $to = substr(($dateRange['to'] ?? ''), 0, 8);
904 // @todo fix relativeToAbsolute & add tests
905 // relativeToAbsolute returns 8 char date strings
906 // or 14 char date + time strings.
907 // We should use those. However, it turns out to be unreliable.
908 // e.g. this.week does NOT return 235959 for 'from'
909 // so our defaults are more reliable.
910 // Currently relativeToAbsolute only supports 'whole' days so that is ok
911 }
912
913 $from = self::processDate($from, $fromTime);
914 $to = self::processDate($to, $toTime);
915
916 return [$from, $to];
917 }
918
919 /**
920 * Calculate Age in Years if greater than one year else in months.
921 *
922 * @param date $birthDate
923 * Birth Date.
924 * @param date $targetDate
925 * Target Date. (show age on specific date)
926 *
927 * @return array
928 * array $results contains years or months
929 */
930 public static function calculateAge($birthDate, $targetDate = NULL) {
931 $results = [];
932 $formatedBirthDate = CRM_Utils_Date::customFormat($birthDate, '%Y-%m-%d');
933
934 $bDate = explode('-', $formatedBirthDate);
935 $birthYear = $bDate[0];
936 $birthMonth = $bDate[1];
937 $birthDay = $bDate[2];
938 $targetDate = strtotime($targetDate ?? date('Y-m-d'));
939
940 $year_diff = date("Y", $targetDate) - $birthYear;
941
942 // don't calculate age CRM-3143
943 if ($birthYear == '1902') {
944 return $results;
945 }
946 switch ($year_diff) {
947 case 1:
948 $month = (12 - $birthMonth) + date("m", $targetDate);
949 if ($month < 12) {
950 if (date("d", $targetDate) < $birthDay) {
951 $month--;
952 }
953 $results['months'] = $month;
954 }
955 elseif ($month == 12 && (date("d", $targetDate) < $birthDay)) {
956 $results['months'] = $month - 1;
957 }
958 else {
959 $results['years'] = $year_diff;
960 }
961 break;
962
963 case 0:
964 $month = date("m", $targetDate) - $birthMonth;
965 $results['months'] = $month;
966 break;
967
968 default:
969 $results['years'] = $year_diff;
970 if ((date("m", $targetDate) < $birthMonth) || (date("m", $targetDate) == $birthMonth) && (date("d", $targetDate) < $birthDay)) {
971 $results['years']--;
972 }
973 }
974
975 return $results;
976 }
977
978 /**
979 * Calculate next payment date according to provided unit & interval
980 *
981 * @param string $unit
982 * Frequency unit like year,month, week etc.
983 *
984 * @param int $interval
985 * Frequency interval.
986 *
987 * @param array $date
988 * Start date of pledge.
989 *
990 * @param bool $dontCareTime
991 *
992 * @return array
993 * contains new date with added interval
994 */
995 public static function intervalAdd($unit, $interval, $date, $dontCareTime = FALSE) {
996 if (is_array($date)) {
997 $hour = $date['H'] ?? '00';
998 $minute = $date['i'] ?? '00';
999 $second = $date['s'] ?? '00';
1000 $month = $date['M'] ?? NULL;
1001 $day = $date['d'] ?? NULL;
1002 $year = $date['Y'] ?? NULL;
1003 }
1004 else {
1005 extract(date_parse($date));
1006 }
1007 $date = mktime($hour, $minute, $second, $month, $day, $year);
1008 switch ($unit) {
1009 case 'year':
1010 $date = mktime($hour, $minute, $second, $month, $day, $year + $interval);
1011 break;
1012
1013 case 'month':
1014 $date = mktime($hour, $minute, $second, $month + $interval, $day, $year);
1015 break;
1016
1017 case 'week':
1018 $interval = $interval * 7;
1019 $date = mktime($hour, $minute, $second, $month, $day + $interval, $year);
1020 break;
1021
1022 case 'day':
1023 $date = mktime($hour, $minute, $second, $month, $day + $interval, $year);
1024 break;
1025
1026 case 'second':
1027 $date = mktime($hour, $minute, $second + $interval, $month, $day, $year);
1028 break;
1029 }
1030
1031 $scheduleDate = explode("-", date("n-j-Y-H-i-s", $date));
1032
1033 $date = [];
1034 $date['M'] = $scheduleDate[0];
1035 $date['d'] = $scheduleDate[1];
1036 $date['Y'] = $scheduleDate[2];
1037 if ($dontCareTime == FALSE) {
1038 $date['H'] = $scheduleDate[3];
1039 $date['i'] = $scheduleDate[4];
1040 $date['s'] = $scheduleDate[5];
1041 }
1042 return $date;
1043 }
1044
1045 /**
1046 * Get the smarty view presentation mapping for the given format.
1047 *
1048 * Historically it was decided that where the view format is 'dd/mm/yy' or 'mm/dd/yy'
1049 * they should be rendered using a longer date format. This is likely as much to
1050 * do with the earlier date widget being unable to handle some formats as usablity.
1051 * However, we continue to respect this.
1052 *
1053 * @param $format
1054 * Given format ( eg 'M Y', 'Y M' ).
1055 *
1056 * @return string|null
1057 * Smarty translation of the date format. Null is also valid and is translated
1058 * according to the available parts at the smarty layer.
1059 */
1060 public static function getDateFieldViewFormat($format) {
1061 $supportableFormats = [
1062 'mm/dd' => '%B %E%f',
1063 'dd-mm' => '%E%f %B',
1064 'yy-mm' => '%Y %B',
1065 'M yy' => '%b %Y',
1066 'yy' => '%Y',
1067 'dd/mm/yy' => '%E%f %B %Y',
1068 ];
1069
1070 return array_key_exists($format, $supportableFormats) ? $supportableFormats[$format] : self::pickBestSmartyFormat($format);
1071 }
1072
1073 /**
1074 * Pick the smarty format from settings that best matches the time string we have.
1075 *
1076 * For view purposes we historically use the setting that most closely matches the data
1077 * in the format from our settings, as opposed to the setting configured for the field.
1078 *
1079 * @param $format
1080 * @return mixed
1081 */
1082 public static function pickBestSmartyFormat($format) {
1083 if (stristr($format, 'h')) {
1084 return Civi::settings()->get('dateformatDatetime');
1085 }
1086 if (stristr($format, 'd') || stristr($format, 'j')) {
1087 return Civi::settings()->get('dateformatFull');
1088 }
1089 if (stristr($format, 'm')) {
1090 return Civi::settings()->get('dateformatPartial');
1091 }
1092 return Civi::settings()->get('dateformatYear');
1093 }
1094
1095 /**
1096 * Map date plugin and actual format that is used by PHP.
1097 *
1098 * @return array
1099 */
1100 public static function datePluginToPHPFormats() {
1101 $dateInputFormats = [
1102 "mm/dd/yy" => 'm/d/Y',
1103 "dd/mm/yy" => 'd/m/Y',
1104 "yy-mm-dd" => 'Y-m-d',
1105 "dd-mm-yy" => 'd-m-Y',
1106 "dd.mm.yy" => 'd.m.Y',
1107 "M d" => 'M j',
1108 "M d, yy" => 'M j, Y',
1109 "d M yy" => 'j M Y',
1110 "MM d, yy" => 'F j, Y',
1111 "d MM yy" => 'j F Y',
1112 "DD, d MM yy" => 'l, j F Y',
1113 "mm/dd" => 'm/d',
1114 "dd-mm" => 'd-m',
1115 "yy-mm" => 'Y-m',
1116 "M yy" => 'M Y',
1117 "M Y" => 'M Y',
1118 "yy" => 'Y',
1119 ];
1120 return $dateInputFormats;
1121 }
1122
1123 /**
1124 * Resolves the given relative time interval into finite time limits.
1125 *
1126 * @param string $relativeTerm
1127 * Relative time frame: this, previous, previous_1.
1128 * @param int $unit
1129 * Frequency unit like year, month, week etc.
1130 *
1131 * @return array
1132 * start date and end date for the relative time frame
1133 */
1134 public static function relativeToAbsolute($relativeTerm, $unit) {
1135 $now = getdate();
1136 $from = $to = $dateRange = [];
1137 $from['H'] = $from['i'] = $from['s'] = 0;
1138 $relativeTermParts = explode('_', $relativeTerm);
1139 $relativeTermPrefix = $relativeTermParts[0];
1140 $relativeTermSuffix = $relativeTermParts[1] ?? '';
1141
1142 switch ($unit) {
1143 case 'year':
1144 switch ($relativeTerm) {
1145 case 'previous':
1146 $from['M'] = $from['d'] = 1;
1147 $to['d'] = 31;
1148 $to['M'] = 12;
1149 $to['Y'] = $from['Y'] = $now['year'] - 1;
1150 break;
1151
1152 case 'previous_before':
1153 $from['M'] = $from['d'] = 1;
1154 $to['d'] = 31;
1155 $to['M'] = 12;
1156 $to['Y'] = $from['Y'] = $now['year'] - 2;
1157 break;
1158
1159 case 'previous_2':
1160 $from['M'] = $from['d'] = 1;
1161 $to['d'] = 31;
1162 $to['M'] = 12;
1163 $from['Y'] = $now['year'] - 2;
1164 $to['Y'] = $now['year'] - 1;
1165 break;
1166
1167 case 'earlier':
1168 $to['d'] = 31;
1169 $to['M'] = 12;
1170 $to['Y'] = $now['year'] - 1;
1171 unset($from);
1172 break;
1173
1174 case 'greater':
1175 $from['M'] = $from['d'] = 1;
1176 $from['Y'] = $now['year'];
1177 unset($to);
1178 break;
1179
1180 case 'greater_previous':
1181 $from['d'] = 31;
1182 $from['M'] = 12;
1183 $from['Y'] = $now['year'] - 1;
1184 unset($to);
1185 break;
1186
1187 case 'ending':
1188 $to['d'] = $now['mday'];
1189 $to['M'] = $now['mon'];
1190 $to['Y'] = $now['year'];
1191 $to['H'] = 23;
1192 $to['i'] = $to['s'] = 59;
1193 $from = self::intervalAdd('year', -1, $to);
1194 $from = self::intervalAdd('second', 1, $from);
1195 break;
1196
1197 case 'current':
1198 $from['M'] = $from['d'] = 1;
1199 $from['Y'] = $now['year'];
1200 $to['H'] = 23;
1201 $to['i'] = $to['s'] = 59;
1202 $to['d'] = $now['mday'];
1203 $to['M'] = $now['mon'];
1204 $to['Y'] = $now['year'];
1205 break;
1206
1207 case 'ending_2':
1208 $to['d'] = $now['mday'];
1209 $to['M'] = $now['mon'];
1210 $to['Y'] = $now['year'];
1211 $to['H'] = 23;
1212 $to['i'] = $to['s'] = 59;
1213 $from = self::intervalAdd('year', -2, $to);
1214 $from = self::intervalAdd('second', 1, $from);
1215 break;
1216
1217 case 'ending_3':
1218 $to['d'] = $now['mday'];
1219 $to['M'] = $now['mon'];
1220 $to['Y'] = $now['year'];
1221 $to['H'] = 23;
1222 $to['i'] = $to['s'] = 59;
1223 $from = self::intervalAdd('year', -3, $to);
1224 $from = self::intervalAdd('second', 1, $from);
1225 break;
1226
1227 case 'less':
1228 $to['d'] = 31;
1229 $to['M'] = 12;
1230 $to['Y'] = $now['year'];
1231 unset($from);
1232 break;
1233
1234 case 'next':
1235 $from['M'] = $from['d'] = 1;
1236 $to['d'] = 31;
1237 $to['M'] = 12;
1238 $to['Y'] = $from['Y'] = $now['year'] + 1;
1239 break;
1240
1241 case 'starting':
1242 $from['d'] = $now['mday'];
1243 $from['M'] = $now['mon'];
1244 $from['Y'] = $now['year'];
1245 $to['d'] = $now['mday'] - 1;
1246 $to['M'] = $now['mon'];
1247 $to['Y'] = $now['year'] + 1;
1248 break;
1249
1250 default:
1251 switch ($relativeTermPrefix) {
1252
1253 case 'ending':
1254 $to['d'] = $now['mday'];
1255 $to['M'] = $now['mon'];
1256 $to['Y'] = $now['year'];
1257 $to['H'] = 23;
1258 $to['i'] = $to['s'] = 59;
1259 $from = self::intervalAdd('year', -$relativeTermSuffix, $to);
1260 $from = self::intervalAdd('second', 1, $from);
1261 break;
1262
1263 case 'this':
1264 $from['d'] = $from['M'] = 1;
1265 $to['d'] = 31;
1266 $to['M'] = 12;
1267 $to['Y'] = $from['Y'] = $now['year'];
1268 if (is_numeric($relativeTermSuffix)) {
1269 $from['Y'] -= ($relativeTermSuffix - 1);
1270 }
1271 break;
1272 }
1273 break;
1274 }
1275 break;
1276
1277 case 'fiscal_year':
1278 $config = CRM_Core_Config::singleton();
1279 $from['d'] = $config->fiscalYearStart['d'];
1280 $from['M'] = $config->fiscalYearStart['M'];
1281 $fYear = self::calculateFiscalYear($from['d'], $from['M']);
1282 switch ($relativeTermPrefix) {
1283 case 'this':
1284 $from['Y'] = $fYear;
1285 $fiscalYear = mktime(0, 0, 0, $from['M'], $from['d'] - 1, $from['Y'] + 1);
1286 $fiscalEnd = explode('-', date("Y-m-d", $fiscalYear));
1287 $to['d'] = $fiscalEnd['2'];
1288 $to['M'] = $fiscalEnd['1'];
1289 $to['Y'] = $fiscalEnd['0'];
1290 $to['H'] = 23;
1291 $to['i'] = $to['s'] = 59;
1292 if (is_numeric($relativeTermSuffix)) {
1293 $from = self::intervalAdd('year', (-$relativeTermSuffix), $to);
1294 $from = self::intervalAdd('second', 1, $from);
1295 }
1296 break;
1297
1298 case 'previous':
1299 if (!is_numeric($relativeTermSuffix)) {
1300 $from['Y'] = ($relativeTermSuffix === 'before') ? $fYear - 2 : $fYear - 1;
1301 $fiscalYear = mktime(0, 0, 0, $from['M'], $from['d'] - 1, $from['Y'] + 1);
1302 $fiscalEnd = explode('-', date("Y-m-d", $fiscalYear));
1303 $to['d'] = $fiscalEnd['2'];
1304 $to['M'] = $fiscalEnd['1'];
1305 $to['Y'] = $fiscalEnd['0'];
1306 $to['H'] = 23;
1307 $to['i'] = $to['s'] = 59;
1308 }
1309 else {
1310 $from['Y'] = $fYear - $relativeTermSuffix;
1311 $fiscalYear = mktime(0, 0, 0, $from['M'], $from['d'] - 1, $from['Y'] + 1);
1312 $fiscalEnd = explode('-', date("Y-m-d", $fiscalYear));
1313 $to['d'] = $fiscalEnd['2'];
1314 $to['M'] = $fiscalEnd['1'];
1315 $to['Y'] = $fYear;
1316 $to['H'] = 23;
1317 $to['i'] = $to['s'] = 59;
1318 }
1319 break;
1320
1321 case 'next':
1322 $from['Y'] = $fYear + 1;
1323 $fiscalYear = mktime(0, 0, 0, $from['M'], $from['d'] - 1, $from['Y'] + 1);
1324 $fiscalEnd = explode('-', date("Y-m-d", $fiscalYear));
1325 $to['d'] = $fiscalEnd['2'];
1326 $to['M'] = $fiscalEnd['1'];
1327 $to['Y'] = $fiscalEnd['0'];
1328 break;
1329 }
1330 break;
1331
1332 case 'quarter':
1333 switch ($relativeTerm) {
1334 case 'this':
1335
1336 $quarter = ceil($now['mon'] / 3);
1337 $from['d'] = 1;
1338 $from['M'] = (3 * $quarter) - 2;
1339 $to['M'] = 3 * $quarter;
1340 $to['Y'] = $from['Y'] = $now['year'];
1341 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $now['year']));
1342 break;
1343
1344 case 'previous':
1345 $difference = 1;
1346 $quarter = ceil($now['mon'] / 3);
1347 $quarter = $quarter - $difference;
1348 $subtractYear = 0;
1349 if ($quarter <= 0) {
1350 $subtractYear = 1;
1351 $quarter += 4;
1352 }
1353 $from['d'] = 1;
1354 $from['M'] = (3 * $quarter) - 2;
1355 $to['M'] = 3 * $quarter;
1356 $to['Y'] = $from['Y'] = $now['year'] - $subtractYear;
1357 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1358 break;
1359
1360 case 'previous_before':
1361 $difference = 2;
1362 $quarter = ceil($now['mon'] / 3);
1363 $quarter = $quarter - $difference;
1364 $subtractYear = 0;
1365 if ($quarter <= 0) {
1366 $subtractYear = 1;
1367 $quarter += 4;
1368 }
1369 $from['d'] = 1;
1370 $from['M'] = (3 * $quarter) - 2;
1371 $to['M'] = 3 * $quarter;
1372 $to['Y'] = $from['Y'] = $now['year'] - $subtractYear;
1373 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1374 break;
1375
1376 case 'previous_2':
1377 $difference = 2;
1378 $quarter = ceil($now['mon'] / 3);
1379 $current_quarter = $quarter;
1380 $quarter = $quarter - $difference;
1381 $subtractYear = 0;
1382 if ($quarter <= 0) {
1383 $subtractYear = 1;
1384 $quarter += 4;
1385 }
1386 $from['d'] = 1;
1387 $from['M'] = (3 * $quarter) - 2;
1388 switch ($current_quarter) {
1389 case 1:
1390 $to['M'] = (4 * $quarter);
1391 break;
1392
1393 case 2:
1394 $to['M'] = (4 * $quarter) + 3;
1395 break;
1396
1397 case 3:
1398 $to['M'] = (4 * $quarter) + 2;
1399 break;
1400
1401 case 4:
1402 $to['M'] = (4 * $quarter) + 1;
1403 break;
1404 }
1405 $to['Y'] = $from['Y'] = $now['year'] - $subtractYear;
1406 if ($to['M'] > 12) {
1407 $to['M'] = 3 * ($quarter - 3);
1408 $to['Y'] = $now['year'];
1409 }
1410 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1411 break;
1412
1413 case 'earlier':
1414 $quarter = ceil($now['mon'] / 3) - 1;
1415 $subtractYear = 0;
1416 if ($quarter <= 0) {
1417 $subtractYear = 1;
1418 $quarter += 4;
1419 }
1420 $to['M'] = 3 * $quarter;
1421 $to['Y'] = $from['Y'] = $now['year'] - $subtractYear;
1422 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1423 unset($from);
1424 break;
1425
1426 case 'greater':
1427 $quarter = ceil($now['mon'] / 3);
1428 $from['d'] = 1;
1429 $from['M'] = (3 * $quarter) - 2;
1430 $from['Y'] = $now['year'];
1431 unset($to);
1432 break;
1433
1434 case 'greater_previous':
1435 $quarter = ceil($now['mon'] / 3) - 1;
1436 $subtractYear = 0;
1437 if ($quarter <= 0) {
1438 $subtractYear = 1;
1439 $quarter += 4;
1440 }
1441 $from['M'] = 3 * $quarter;
1442 $from['Y'] = $from['Y'] = $now['year'] - $subtractYear;
1443 $from['d'] = date('t', mktime(0, 0, 0, $from['M'], 1, $from['Y']));
1444 unset($to);
1445 break;
1446
1447 case 'ending':
1448 $to['d'] = $now['mday'];
1449 $to['M'] = $now['mon'];
1450 $to['Y'] = $now['year'];
1451 $to['H'] = 23;
1452 $to['i'] = $to['s'] = 59;
1453 $from = self::intervalAdd('day', -90, $to);
1454 $from = self::intervalAdd('second', 1, $from);
1455 break;
1456
1457 case 'current':
1458 $quarter = ceil($now['mon'] / 3);
1459 $from['d'] = 1;
1460 $from['M'] = (3 * $quarter) - 2;
1461 $from['Y'] = $now['year'];
1462 $to['d'] = $now['mday'];
1463 $to['M'] = $now['mon'];
1464 $to['Y'] = $now['year'];
1465 $to['H'] = 23;
1466 $to['i'] = $to['s'] = 59;
1467 break;
1468
1469 case 'less':
1470 $quarter = ceil($now['mon'] / 3);
1471 $to['M'] = 3 * $quarter;
1472 $to['Y'] = $now['year'];
1473 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $now['year']));
1474 unset($from);
1475 break;
1476
1477 case 'next':
1478 $difference = -1;
1479 $subtractYear = 0;
1480 $quarter = ceil($now['mon'] / 3);
1481 $quarter = $quarter - $difference;
1482 // CRM-14550 QA Fix
1483 if ($quarter > 4) {
1484 $now['year'] = $now['year'] + 1;
1485 $quarter = 1;
1486 }
1487 if ($quarter <= 0) {
1488 $subtractYear = 1;
1489 $quarter += 4;
1490 }
1491 $from['d'] = 1;
1492 $from['M'] = (3 * $quarter) - 2;
1493 $to['M'] = 3 * $quarter;
1494 $to['Y'] = $from['Y'] = $now['year'] - $subtractYear;
1495 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1496 break;
1497
1498 case 'starting':
1499 $from['d'] = $now['mday'];
1500 $from['M'] = $now['mon'];
1501 $from['Y'] = $now['year'];
1502 $from['H'] = 00;
1503 $from['i'] = $to['s'] = 00;
1504 $to = self::intervalAdd('day', 90, $from);
1505 $to = self::intervalAdd('second', -1, $to);
1506 break;
1507
1508 default:
1509 if ($relativeTermPrefix === 'ending') {
1510 $to['d'] = $now['mday'];
1511 $to['M'] = $now['mon'];
1512 $to['Y'] = $now['year'];
1513 $to['H'] = 23;
1514 $to['i'] = $to['s'] = 59;
1515 $from = self::intervalAdd('month', -($relativeTermSuffix * 3), $to);
1516 $from = self::intervalAdd('second', 1, $from);
1517 }
1518 }
1519 break;
1520
1521 case 'month':
1522 switch ($relativeTerm) {
1523 case 'this':
1524 $from['d'] = 1;
1525 $to['d'] = date('t', mktime(0, 0, 0, $now['mon'], 1, $now['year']));
1526 $from['M'] = $to['M'] = $now['mon'];
1527 $from['Y'] = $to['Y'] = $now['year'];
1528 break;
1529
1530 case 'previous':
1531 $from['d'] = 1;
1532 if ($now['mon'] == 1) {
1533 $from['M'] = $to['M'] = 12;
1534 $from['Y'] = $to['Y'] = $now['year'] - 1;
1535 }
1536 else {
1537 $from['M'] = $to['M'] = $now['mon'] - 1;
1538 $from['Y'] = $to['Y'] = $now['year'];
1539 }
1540 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1541 break;
1542
1543 case 'previous_before':
1544 $from['d'] = 1;
1545 if ($now['mon'] < 3) {
1546 $from['M'] = $to['M'] = 10 + $now['mon'];
1547 $from['Y'] = $to['Y'] = $now['year'] - 1;
1548 }
1549 else {
1550 $from['M'] = $to['M'] = $now['mon'] - 2;
1551 $from['Y'] = $to['Y'] = $now['year'];
1552 }
1553 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1554 break;
1555
1556 case 'previous_2':
1557 $from['d'] = 1;
1558 if ($now['mon'] < 3) {
1559 $from['M'] = 10 + $now['mon'];
1560 $from['Y'] = $now['year'] - 1;
1561 }
1562 else {
1563 $from['M'] = $now['mon'] - 2;
1564 $from['Y'] = $now['year'];
1565 }
1566
1567 if ($now['mon'] == 1) {
1568 $to['M'] = 12;
1569 $to['Y'] = $now['year'] - 1;
1570 }
1571 else {
1572 $to['M'] = $now['mon'] - 1;
1573 $to['Y'] = $now['year'];
1574 }
1575
1576 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1577 break;
1578
1579 case 'earlier':
1580 // before end of past month
1581 if ($now['mon'] == 1) {
1582 $to['M'] = 12;
1583 $to['Y'] = $now['year'] - 1;
1584 }
1585 else {
1586 $to['M'] = $now['mon'] - 1;
1587 $to['Y'] = $now['year'];
1588 }
1589
1590 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1591 unset($from);
1592 break;
1593
1594 case 'greater':
1595 $from['d'] = 1;
1596 $from['M'] = $now['mon'];
1597 $from['Y'] = $now['year'];
1598 unset($to);
1599 break;
1600
1601 case 'greater_previous':
1602 // from end of past month
1603 if ($now['mon'] == 1) {
1604 $from['M'] = 12;
1605 $from['Y'] = $now['year'] - 1;
1606 }
1607 else {
1608 $from['M'] = $now['mon'] - 1;
1609 $from['Y'] = $now['year'];
1610 }
1611
1612 $from['d'] = date('t', mktime(0, 0, 0, $from['M'], 1, $from['Y']));
1613 unset($to);
1614 break;
1615
1616 case 'ending_2':
1617 $to['d'] = $now['mday'];
1618 $to['M'] = $now['mon'];
1619 $to['Y'] = $now['year'];
1620 $to['H'] = 23;
1621 $to['i'] = $to['s'] = 59;
1622 $from = self::intervalAdd('day', -60, $to);
1623 $from = self::intervalAdd('second', 1, $from);
1624 break;
1625
1626 case 'ending':
1627 $to['d'] = $now['mday'];
1628 $to['M'] = $now['mon'];
1629 $to['Y'] = $now['year'];
1630 $to['H'] = 23;
1631 $to['i'] = $to['s'] = 59;
1632 $from = self::intervalAdd('day', -30, $to);
1633 $from = self::intervalAdd('second', 1, $from);
1634 break;
1635
1636 case 'current':
1637 $from['d'] = 1;
1638 $from['M'] = $now['mon'];
1639 $from['Y'] = $now['year'];
1640 $to['d'] = $now['mday'];
1641 $to['M'] = $now['mon'];
1642 $to['Y'] = $now['year'];
1643 $to['H'] = 23;
1644 $to['i'] = $to['s'] = 59;
1645 break;
1646
1647 case 'less':
1648 // CRM-14550 QA Fix
1649 $to['Y'] = $now['year'];
1650 $to['M'] = $now['mon'];
1651 $to['d'] = date('t', mktime(0, 0, 0, $now['mon'], 1, $now['year']));
1652 unset($from);
1653 break;
1654
1655 case 'next':
1656 $from['d'] = 1;
1657 if ($now['mon'] == 12) {
1658 $from['M'] = $to['M'] = 1;
1659 $from['Y'] = $to['Y'] = $now['year'] + 1;
1660 }
1661 else {
1662 $from['M'] = $to['M'] = $now['mon'] + 1;
1663 $from['Y'] = $to['Y'] = $now['year'];
1664 }
1665 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1666 break;
1667
1668 case 'starting':
1669 $from['d'] = $now['mday'];
1670 $from['M'] = $now['mon'];
1671 $from['Y'] = $now['year'];
1672 $from['H'] = 00;
1673 $from['i'] = $to['s'] = 00;
1674 $to = self::intervalAdd('day', 30, $from);
1675 $to = self::intervalAdd('second', -1, $to);
1676 break;
1677
1678 case 'starting_2':
1679 $from['d'] = $now['mday'];
1680 $from['M'] = $now['mon'];
1681 $from['Y'] = $now['year'];
1682 $from['H'] = 00;
1683 $from['i'] = $to['s'] = 00;
1684 $to = self::intervalAdd('day', 60, $from);
1685 $to = self::intervalAdd('second', -1, $to);
1686 break;
1687
1688 default:
1689 if ($relativeTermPrefix === 'ending') {
1690 $to['d'] = $now['mday'];
1691 $to['M'] = $now['mon'];
1692 $to['Y'] = $now['year'];
1693 $to['H'] = 23;
1694 $to['i'] = $to['s'] = 59;
1695 $from = self::intervalAdd($unit, -$relativeTermSuffix, $to);
1696 $from = self::intervalAdd('second', 1, $from);
1697 }
1698 }
1699 break;
1700
1701 case 'week':
1702 $weekFirst = Civi::settings()->get('weekBegins');
1703 $thisDay = $now['wday'];
1704 if ($weekFirst > $thisDay) {
1705 $diffDay = $thisDay - $weekFirst + 7;
1706 }
1707 else {
1708 $diffDay = $thisDay - $weekFirst;
1709 }
1710 switch ($relativeTerm) {
1711 case 'this':
1712 $from['d'] = $now['mday'];
1713 $from['M'] = $now['mon'];
1714 $from['Y'] = $now['year'];
1715 $from = self::intervalAdd('day', -1 * ($diffDay), $from);
1716 $to = self::intervalAdd('day', 6, $from);
1717 break;
1718
1719 case 'previous':
1720 $from['d'] = $now['mday'];
1721 $from['M'] = $now['mon'];
1722 $from['Y'] = $now['year'];
1723 $from = self::intervalAdd('day', -1 * ($diffDay) - 7, $from);
1724 $to = self::intervalAdd('day', 6, $from);
1725 break;
1726
1727 case 'previous_before':
1728 $from['d'] = $now['mday'];
1729 $from['M'] = $now['mon'];
1730 $from['Y'] = $now['year'];
1731 $from = self::intervalAdd('day', -1 * ($diffDay) - 14, $from);
1732 $to = self::intervalAdd('day', 6, $from);
1733 break;
1734
1735 case 'previous_2':
1736 $from['d'] = $now['mday'];
1737 $from['M'] = $now['mon'];
1738 $from['Y'] = $now['year'];
1739 $from = self::intervalAdd('day', -1 * ($diffDay) - 14, $from);
1740 $to = self::intervalAdd('day', 13, $from);
1741 break;
1742
1743 case 'earlier':
1744 $to['d'] = $now['mday'];
1745 $to['M'] = $now['mon'];
1746 $to['Y'] = $now['year'];
1747 $to = self::intervalAdd('day', -1 * ($diffDay) - 1, $to);
1748 unset($from);
1749 break;
1750
1751 case 'greater':
1752 $from['d'] = $now['mday'];
1753 $from['M'] = $now['mon'];
1754 $from['Y'] = $now['year'];
1755 $from = self::intervalAdd('day', -1 * ($diffDay), $from);
1756 unset($to);
1757 break;
1758
1759 case 'greater_previous':
1760 $from['d'] = $now['mday'];
1761 $from['M'] = $now['mon'];
1762 $from['Y'] = $now['year'];
1763 $from = self::intervalAdd('day', -1 * ($diffDay) - 1, $from);
1764 unset($to);
1765 break;
1766
1767 case 'ending':
1768 $to['d'] = $now['mday'];
1769 $to['M'] = $now['mon'];
1770 $to['Y'] = $now['year'];
1771 $to['H'] = 23;
1772 $to['i'] = $to['s'] = 59;
1773 $from = self::intervalAdd('day', -7, $to);
1774 $from = self::intervalAdd('second', 1, $from);
1775 break;
1776
1777 case 'current':
1778 $from['d'] = $now['mday'];
1779 $from['M'] = $now['mon'];
1780 $from['Y'] = $now['year'];
1781 $from = self::intervalAdd('day', -1 * ($diffDay), $from);
1782 $to['d'] = $now['mday'];
1783 $to['M'] = $now['mon'];
1784 $to['Y'] = $now['year'];
1785 $to['H'] = 23;
1786 $to['i'] = $to['s'] = 59;
1787 break;
1788
1789 case 'less':
1790 $to['d'] = $now['mday'];
1791 $to['M'] = $now['mon'];
1792 $to['Y'] = $now['year'];
1793 // CRM-14550 QA Fix
1794 $to = self::intervalAdd('day', -1 * ($diffDay) + 6, $to);
1795 unset($from);
1796 break;
1797
1798 case 'next':
1799 $from['d'] = $now['mday'];
1800 $from['M'] = $now['mon'];
1801 $from['Y'] = $now['year'];
1802 $from = self::intervalAdd('day', -1 * ($diffDay) + 7, $from);
1803 $to = self::intervalAdd('day', 6, $from);
1804 break;
1805
1806 case 'starting':
1807 $from['d'] = $now['mday'];
1808 $from['M'] = $now['mon'];
1809 $from['Y'] = $now['year'];
1810 $from['H'] = 00;
1811 $from['i'] = $to['s'] = 00;
1812 $to = self::intervalAdd('day', 7, $from);
1813 $to = self::intervalAdd('second', -1, $to);
1814 break;
1815
1816 default:
1817 if ($relativeTermPrefix === 'ending') {
1818 $to['d'] = $now['mday'];
1819 $to['M'] = $now['mon'];
1820 $to['Y'] = $now['year'];
1821 $to['H'] = 23;
1822 $to['i'] = $to['s'] = 59;
1823 $from = self::intervalAdd($unit, -$relativeTermSuffix, $to);
1824 $from = self::intervalAdd('second', 1, $from);
1825 }
1826 }
1827 break;
1828
1829 case 'day':
1830 switch ($relativeTerm) {
1831 case 'this':
1832 $from['d'] = $to['d'] = $now['mday'];
1833 $from['M'] = $to['M'] = $now['mon'];
1834 $from['Y'] = $to['Y'] = $now['year'];
1835 break;
1836
1837 case 'previous':
1838 $from['d'] = $now['mday'];
1839 $from['M'] = $now['mon'];
1840 $from['Y'] = $now['year'];
1841 $from = self::intervalAdd('day', -1, $from);
1842 $to['d'] = $from['d'];
1843 $to['M'] = $from['M'];
1844 $to['Y'] = $from['Y'];
1845 break;
1846
1847 case 'previous_before':
1848 $from['d'] = $now['mday'];
1849 $from['M'] = $now['mon'];
1850 $from['Y'] = $now['year'];
1851 $from = self::intervalAdd('day', -2, $from);
1852 $to['d'] = $from['d'];
1853 $to['M'] = $from['M'];
1854 $to['Y'] = $from['Y'];
1855 break;
1856
1857 case 'previous_2':
1858 $from['d'] = $to['d'] = $now['mday'];
1859 $from['M'] = $to['M'] = $now['mon'];
1860 $from['Y'] = $to['Y'] = $now['year'];
1861 $from = self::intervalAdd('day', -2, $from);
1862 $to = self::intervalAdd('day', -1, $to);
1863 break;
1864
1865 case 'earlier':
1866 $to['d'] = $now['mday'];
1867 $to['M'] = $now['mon'];
1868 $to['Y'] = $now['year'];
1869 $to = self::intervalAdd('day', -1, $to);
1870 unset($from);
1871 break;
1872
1873 case 'greater':
1874 $from['d'] = $now['mday'];
1875 $from['M'] = $now['mon'];
1876 $from['Y'] = $now['year'];
1877 unset($to);
1878 break;
1879
1880 case 'starting':
1881 $to['d'] = $now['mday'];
1882 $to['M'] = $now['mon'];
1883 $to['Y'] = $now['year'];
1884 $to = self::intervalAdd('day', 1, $to);
1885 $from['d'] = $to['d'];
1886 $from['M'] = $to['M'];
1887 $from['Y'] = $to['Y'];
1888 break;
1889
1890 default:
1891 if ($relativeTermPrefix === 'ending') {
1892 $to['d'] = $now['mday'];
1893 $to['M'] = $now['mon'];
1894 $to['Y'] = $now['year'];
1895 $to['H'] = 23;
1896 $to['i'] = $to['s'] = 59;
1897 $from = self::intervalAdd($unit, -$relativeTermSuffix, $to);
1898 $from = self::intervalAdd('second', 1, $from);
1899 }
1900 }
1901 break;
1902 }
1903
1904 $dateRange['from'] = empty($from) ? NULL : self::format($from);
1905 $dateRange['to'] = empty($to) ? NULL : self::format($to);
1906 return $dateRange;
1907 }
1908
1909 /**
1910 * Calculate current fiscal year based on the fiscal month and day.
1911 *
1912 * @param int $fyDate
1913 * Fiscal start date.
1914 *
1915 * @param int $fyMonth
1916 * Fiscal Start Month.
1917 *
1918 * @return int
1919 * $fy Current Fiscal Year
1920 */
1921 public static function calculateFiscalYear($fyDate, $fyMonth) {
1922 $date = date("Y-m-d");
1923 $currentYear = date("Y");
1924
1925 // recalculate the date because month 4::04 make the difference
1926 $fiscalYear = explode('-', date("Y-m-d", mktime(0, 0, 0, $fyMonth, $fyDate, $currentYear)));
1927 $fyDate = $fiscalYear[2];
1928 $fyMonth = $fiscalYear[1];
1929 $fyStartDate = date("Y-m-d", mktime(0, 0, 0, $fyMonth, $fyDate, $currentYear));
1930
1931 if ($fyStartDate > $date) {
1932 $fy = intval(intval($currentYear) - 1);
1933 }
1934 else {
1935 $fy = intval($currentYear);
1936 }
1937 return $fy;
1938 }
1939
1940 /**
1941 * Function to process date, convert to mysql format
1942 *
1943 * @param string $date
1944 * Date string.
1945 * @param string $time
1946 * Time string.
1947 * @param bool|string $returnNullString 'null' needs to be returned
1948 * so that db oject will set null in db
1949 * @param string $format
1950 * Expected return date format.( default is mysql ).
1951 *
1952 * @return string
1953 * date format that is excepted by mysql
1954 */
1955 public static function processDate($date, $time = NULL, $returnNullString = FALSE, $format = 'YmdHis') {
1956 $mysqlDate = NULL;
1957
1958 if ($returnNullString) {
1959 $mysqlDate = 'null';
1960 }
1961
1962 if (trim($date ?? '')) {
1963 $mysqlDate = date($format, strtotime($date . ' ' . $time));
1964 }
1965
1966 return $mysqlDate;
1967 }
1968
1969 /**
1970 * Add the metadata about a date field to the field.
1971 *
1972 * This metadata will work with the call $form->add('datepicker', ...
1973 *
1974 * @param array $fieldMetaData
1975 * @param array $field
1976 *
1977 * @return array
1978 */
1979 public static function addDateMetadataToField($fieldMetaData, $field) {
1980 if (isset($fieldMetaData['html'])) {
1981 $field['html_type'] = $fieldMetaData['html']['type'];
1982 if ($field['html_type'] === 'Select Date') {
1983 if (!isset($field['date_format'])) {
1984 $dateAttributes = CRM_Core_SelectValues::date($fieldMetaData['html']['formatType'], NULL, NULL, NULL, 'Input');
1985 $field['start_date_years'] = $dateAttributes['minYear'];
1986 $field['end_date_years'] = $dateAttributes['maxYear'];
1987 $field['date_format'] = $dateAttributes['format'];
1988 $field['is_datetime_field'] = TRUE;
1989 $field['time_format'] = $dateAttributes['time'];
1990 $field['smarty_view_format'] = $dateAttributes['smarty_view_format'];
1991 }
1992 $field['datepicker']['extra'] = self::getDatePickerExtra($field);
1993 $field['datepicker']['attributes'] = self::getDatePickerAttributes($field);
1994 }
1995 }
1996 return $field;
1997 }
1998
1999 /**
2000 * Get the fields required for the 'extra' parameter when adding a datepicker.
2001 *
2002 * @param array $field
2003 *
2004 * @return array
2005 */
2006 public static function getDatePickerExtra($field) {
2007 $extra = [];
2008 if (isset($field['date_format'])) {
2009 $extra['date'] = $field['date_format'];
2010 $extra['time'] = $field['time_format'];
2011 }
2012 $thisYear = date('Y');
2013 if (isset($field['start_date_years'])) {
2014 $extra['minDate'] = date('Y-m-d', strtotime('-' . ($thisYear - $field['start_date_years']) . ' years'));
2015 }
2016 if (isset($field['end_date_years'])) {
2017 $extra['maxDate'] = date('Y-m-d', strtotime('-' . ($thisYear - $field['end_date_years']) . ' years'));
2018 }
2019 return $extra;
2020 }
2021
2022 /**
2023 * Get the attributes parameters required for datepicker.
2024 *
2025 * @param array $field
2026 * Field metadata
2027 *
2028 * @return array
2029 * Array ready to pass to $this->addForm('datepicker' as attributes.
2030 */
2031 public static function getDatePickerAttributes(&$field) {
2032 $attributes = [];
2033 $dateAttributes = [
2034 'start_date_years' => 'minYear',
2035 'end_date_years' => 'maxYear',
2036 'date_format' => 'format',
2037 ];
2038 foreach ($dateAttributes as $dateAttribute => $mapTo) {
2039 if (isset($field[$dateAttribute])) {
2040 $attributes[$mapTo] = $field[$dateAttribute];
2041 }
2042 }
2043 return $attributes;
2044 }
2045
2046 /**
2047 * Function to convert mysql to date plugin format.
2048 *
2049 * @param string $mysqlDate
2050 * Date string.
2051 *
2052 * @param null $formatType
2053 * @param null $format
2054 * @param null $timeFormat
2055 *
2056 * @return array
2057 * and time
2058 */
2059 public static function setDateDefaults($mysqlDate = NULL, $formatType = NULL, $format = NULL, $timeFormat = NULL) {
2060 // if date is not passed assume it as today
2061 if (!$mysqlDate) {
2062 $mysqlDate = date('Y-m-d G:i:s');
2063 }
2064
2065 $config = CRM_Core_Config::singleton();
2066 if ($formatType) {
2067 // get actual format
2068 $params = ['name' => $formatType];
2069 $values = [];
2070 CRM_Core_DAO::commonRetrieve('CRM_Core_DAO_PreferencesDate', $params, $values);
2071
2072 if ($values['date_format']) {
2073 $format = $values['date_format'];
2074 }
2075
2076 if (isset($values['time_format'])) {
2077 $timeFormat = $values['time_format'];
2078 }
2079 }
2080
2081 $dateFormat = 'm/d/Y';
2082 $date = date($dateFormat, strtotime($mysqlDate));
2083
2084 if (!$timeFormat) {
2085 $timeFormat = $config->timeInputFormat;
2086 }
2087
2088 $actualTimeFormat = "g:iA";
2089 $appendZeroLength = 7;
2090 if ($timeFormat > 1) {
2091 $actualTimeFormat = "G:i";
2092 $appendZeroLength = 5;
2093 }
2094
2095 $time = date($actualTimeFormat, strtotime($mysqlDate));
2096
2097 // need to append zero for hours < 10
2098 if (strlen($time) < $appendZeroLength) {
2099 $time = '0' . $time;
2100 }
2101
2102 return [$date, $time];
2103 }
2104
2105 /**
2106 * Function get date format.
2107 *
2108 * @param string $formatType
2109 * Date name e.g. birth.
2110 *
2111 * @return string
2112 */
2113 public static function getDateFormat($formatType = NULL) {
2114 $format = NULL;
2115 if ($formatType) {
2116 $format = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_PreferencesDate',
2117 $formatType, 'date_format', 'name'
2118 );
2119 }
2120
2121 if (!$format) {
2122 $config = CRM_Core_Config::singleton();
2123 $format = $config->dateInputFormat;
2124 }
2125 return $format;
2126 }
2127
2128 /**
2129 * Date formatting for imports where date format is specified.
2130 *
2131 * Note this is used for imports (only) because the importer can
2132 * specify the format.
2133 *
2134 * Tests are in CRM_Utils_DateTest::testFormatDate
2135 *
2136 * @param $date
2137 * Date string as entered.
2138 * @param $dateType
2139 * One of the constants like CRM_Core_Form_Date::DATE_yyyy_mm_dd.
2140 *
2141 * @return null|string
2142 */
2143 public static function formatDate($date, $dateType) {
2144 if (empty($date)) {
2145 return NULL;
2146 }
2147
2148 // 1. first convert date to default format.
2149 // 2. append time to default formatted date (might be removed during format)
2150 // 3. validate date / date time.
2151 // 4. If date and time then convert to default date time format.
2152
2153 $dateKey = 'date';
2154 $dateParams = [$dateKey => $date];
2155
2156 if (CRM_Utils_Date::convertToDefaultDate($dateParams, $dateType, $dateKey)) {
2157 $dateVal = $dateParams[$dateKey];
2158 if ($dateType == 1) {
2159 $matches = [];
2160 // The seconds part of this regex is not quite right - but it does succeed
2161 // in clarifying whether there is a time component or not - which is all it is meant
2162 // to do.
2163 if (preg_match('/(\s(([01]\d)|[2][0-3]):([0-5]\d):?[0-5]?\d?)$/', $date, $matches)) {
2164 if (strpos($date, '-') !== FALSE) {
2165 $dateVal .= array_shift($matches);
2166 }
2167 if (!CRM_Utils_Rule::dateTime($dateVal)) {
2168 return NULL;
2169 }
2170 $dateVal = CRM_Utils_Date::customFormat(preg_replace("/(:|\s)?/", '', $dateVal), '%Y%m%d%H%i%s');
2171 return $dateVal;
2172 }
2173 }
2174
2175 // validate date.
2176 return CRM_Utils_Rule::date($dateVal) ? $dateVal : NULL;
2177 }
2178
2179 return NULL;
2180 }
2181
2182 /**
2183 * Function to return days of the month.
2184 *
2185 * @return array
2186 */
2187 public static function getCalendarDayOfMonth() {
2188 $month = [];
2189 for ($i = 1; $i <= 31; $i++) {
2190 $month[$i] = $i;
2191 if ($i == 31) {
2192 $month[$i] = $i . ' / Last day of month';
2193 }
2194 }
2195 return $month;
2196 }
2197
2198 /**
2199 * Convert a relative date format to an api field.
2200 *
2201 * @param array $params
2202 * @param string $dateField
2203 * @param bool $isDatePicker
2204 * Non datepicker fields are deprecated. Exterminate Exterminate.
2205 * (but for now handle them).
2206 */
2207 public static function convertFormDateToApiFormat(&$params, $dateField, $isDatePicker = TRUE) {
2208 if (!empty($params[$dateField . '_relative'])) {
2209 $dates = CRM_Utils_Date::getFromTo($params[$dateField . '_relative'], NULL, NULL);
2210 unset($params[$dateField . '_relative']);
2211 }
2212 if (!empty($params[$dateField . '_low'])) {
2213 $dates[0] = $isDatePicker ? $params[$dateField . '_low'] : date('Y-m-d H:i:s', strtotime($params[$dateField . '_low']));
2214 unset($params[$dateField . '_low']);
2215 }
2216 if (!empty($params[$dateField . '_high'])) {
2217 $dates[1] = $isDatePicker ? $params[$dateField . '_high'] : date('Y-m-d 23:59:59', strtotime($params[$dateField . '_high']));
2218 unset($params[$dateField . '_high']);
2219 }
2220 if (empty($dates)) {
2221 return;
2222 }
2223 if (empty($dates[0])) {
2224 $params[$dateField] = ['<=' => $dates[1]];
2225 }
2226 elseif (empty($dates[1])) {
2227 $params[$dateField] = ['>=' => $dates[0]];
2228 }
2229 else {
2230 $params[$dateField] = ['BETWEEN' => $dates];
2231 }
2232 }
2233
2234 /**
2235 * Print out a date object in specified format in local timezone
2236 *
2237 * @param DateTimeObject $dateObject
2238 * @param string $format
2239 * @return string
2240 */
2241 public static function convertDateToLocalTime($dateObject, $format = 'YmdHis') {
2242 $systemTimeZone = new DateTimeZone(CRM_Core_Config::singleton()->userSystem->getTimeZoneString());
2243 $dateObject->setTimezone($systemTimeZone);
2244 return $dateObject->format($format);
2245 }
2246
2247 /**
2248 * Check if the value returned by a date picker has a date section (ie: includes
2249 * a '-' character) if it includes a time section (ie: includes a ':').
2250 *
2251 * @param string $value
2252 * A date/time string input from a datepicker value.
2253 *
2254 * @return bool
2255 * TRUE if valid, FALSE if there is a time without a date.
2256 */
2257 public static function datePickerValueWithTimeHasDate($value) {
2258 // If there's no : (time) or a : and a - (date) then return true
2259 return (
2260 strpos($value, ':') === FALSE
2261 || strpos($value, ':') !== FALSE && strpos($value, '-') !== FALSE
2262 );
2263 }
2264
2265 /**
2266 * Validate start and end dates entered on a form to make sure they are
2267 * logical. Expects the form keys to be start_date and end_date.
2268 *
2269 * @param string $startFormKey
2270 * The form element key of the 'start date'
2271 * @param string $startValue
2272 * The value of the 'start date'
2273 * @param string $endFormKey
2274 * The form element key of the 'end date'
2275 * @param string $endValue
2276 * The value of the 'end date'
2277 *
2278 * @return array|bool
2279 * TRUE if valid, an array of the erroneous form key, and error message to
2280 * use otherwise.
2281 */
2282 public static function validateStartEndDatepickerInputs($startFormKey, $startValue, $endFormKey, $endValue) {
2283
2284 // Check date as well as time is set
2285 if (!empty($startValue) && !self::datePickerValueWithTimeHasDate($startValue)) {
2286 return ['key' => $startFormKey, 'message' => ts('Please enter a date as well as a time.')];
2287 }
2288 if (!empty($endValue) && !self::datePickerValueWithTimeHasDate($endValue)) {
2289 return ['key' => $endFormKey, 'message' => ts('Please enter a date as well as a time.')];
2290 }
2291
2292 // Check end date is after start date
2293 if (!empty($startValue) && !empty($endValue) && $endValue < $startValue) {
2294 return ['key' => $endFormKey, 'message' => ts('The end date should be after the start date.')];
2295 }
2296
2297 return TRUE;
2298 }
2299
2300 }