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