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