Fix wrong current month showing on Membership Dashboard
[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 * Wrapper for customFormat that takes a timestamp
443 *
444 * @param int $timestamp
445 * Date and time in timestamp format.
446 * @param string $format
447 * The output format.
448 * @param array $dateParts
449 * An array with the desired date parts.
450 *
451 * @return string
452 * the $format-formatted $date
453 */
454 public static function customFormatTs($timestamp, $format = NULL, $dateParts = NULL) {
455 return CRM_Utils_Date::customFormat(date("Y-m-d H:i:s", $timestamp), $format, $dateParts);
456 }
457
458 /**
459 * Converts the date/datetime from MySQL format to ISO format
460 *
461 * @param string $mysql
462 * Date/datetime in MySQL format.
463 *
464 * @return string
465 * date/datetime in ISO format
466 */
467 public static function mysqlToIso($mysql) {
468 $year = substr($mysql, 0, 4);
469 $month = substr($mysql, 4, 2);
470 $day = substr($mysql, 6, 2);
471 $hour = substr($mysql, 8, 2);
472 $minute = substr($mysql, 10, 2);
473 $second = substr($mysql, 12, 2);
474
475 $iso = '';
476 if ($year) {
477 $iso .= "$year";
478 }
479 if ($month) {
480 $iso .= "-$month";
481 if ($day) {
482 $iso .= "-$day";
483 }
484 }
485
486 if ($hour) {
487 $iso .= " $hour";
488 if ($minute) {
489 $iso .= ":$minute";
490 if ($second) {
491 $iso .= ":$second";
492 }
493 }
494 }
495 return $iso;
496 }
497
498 /**
499 * Converts the date/datetime from ISO format to MySQL format
500 * Note that until CRM-14986/ 4.4.7 this was required whenever the pattern $dao->find(TRUE): $dao->save(); was
501 * used to update an object with a date field was used. The DAO now checks for a '-' in date field strings
502 * & runs this function if the - appears - meaning it is likely redundant in the form & BAO layers
503 *
504 * @param string $iso
505 * Date/datetime in ISO format.
506 *
507 * @return string
508 * date/datetime in MySQL format
509 */
510 public static function isoToMysql($iso) {
511 $dropArray = array('-' => '', ':' => '', ' ' => '');
512 return strtr($iso, $dropArray);
513 }
514
515 /**
516 * Converts the any given date to default date format.
517 *
518 * @param array $params
519 * Has given date-format.
520 * @param int $dateType
521 * Type of date.
522 * @param string $dateParam
523 * Index of params.
524 *
525 * @return bool
526 */
527 public static function convertToDefaultDate(&$params, $dateType, $dateParam) {
528 $now = getdate();
529 $cen = substr($now['year'], 0, 2);
530 $prevCen = $cen - 1;
531
532 $value = NULL;
533 if (!empty($params[$dateParam])) {
534 // suppress hh:mm or hh:mm:ss if it exists CRM-7957
535 $value = preg_replace("/(\s(([01]\d)|[2][0-3])(:([0-5]\d)){1,2})$/", "", $params[$dateParam]);
536 }
537
538 switch ($dateType) {
539 case 1:
540 if (!preg_match('/^\d\d\d\d-?(\d|\d\d)-?(\d|\d\d)$/', $value)) {
541 return FALSE;
542 }
543 break;
544
545 case 2:
546 if (!preg_match('/^(\d|\d\d)[-\/](\d|\d\d)[-\/]\d\d$/', $value)) {
547 return FALSE;
548 }
549 break;
550
551 case 4:
552 if (!preg_match('/^(\d|\d\d)[-\/](\d|\d\d)[-\/]\d\d\d\d$/', $value)) {
553 return FALSE;
554 }
555 break;
556
557 case 8:
558 if (!preg_match('/^[A-Za-z]*.[ \t]?\d\d\,[ \t]?\d\d\d\d$/', $value)) {
559 return FALSE;
560 }
561 break;
562
563 case 16:
564 if (!preg_match('/^\d\d-[A-Za-z]{3}.*-\d\d$/', $value) && !preg_match('/^\d\d[-\/]\d\d[-\/]\d\d$/', $value)) {
565 return FALSE;
566 }
567 break;
568
569 case 32:
570 if (!preg_match('/^(\d|\d\d)[-\/](\d|\d\d)[-\/]\d\d\d\d/', $value)) {
571 return FALSE;
572 }
573 break;
574 }
575
576 if ($dateType == 1) {
577 $formattedDate = explode("-", $value);
578 if (count($formattedDate) == 3) {
579 $year = (int) $formattedDate[0];
580 $month = (int) $formattedDate[1];
581 $day = (int) $formattedDate[2];
582 }
583 elseif (count($formattedDate) == 1 && (strlen($value) == 8)) {
584 return TRUE;
585 }
586 else {
587 return FALSE;
588 }
589 }
590
591 if ($dateType == 2 || $dateType == 4) {
592 $formattedDate = explode("/", $value);
593 if (count($formattedDate) != 3) {
594 $formattedDate = explode("-", $value);
595 }
596 if (count($formattedDate) == 3) {
597 $year = (int) $formattedDate[2];
598 $month = (int) $formattedDate[0];
599 $day = (int) $formattedDate[1];
600 }
601 else {
602 return FALSE;
603 }
604 }
605 if ($dateType == 8) {
606 $dateArray = explode(' ', $value);
607 // ignore comma(,)
608 $dateArray[1] = (int) substr($dateArray[1], 0, 2);
609
610 $monthInt = 0;
611 $fullMonths = self::getFullMonthNames();
612 foreach ($fullMonths as $key => $val) {
613 if (strtolower($dateArray[0]) == strtolower($val)) {
614 $monthInt = $key;
615 break;
616 }
617 }
618 if (!$monthInt) {
619 $abbrMonths = self::getAbbrMonthNames();
620 foreach ($abbrMonths as $key => $val) {
621 if (strtolower(trim($dateArray[0], ".")) == strtolower($val)) {
622 $monthInt = $key;
623 break;
624 }
625 }
626 }
627 $year = (int) $dateArray[2];
628 $day = (int) $dateArray[1];
629 $month = (int) $monthInt;
630 }
631 if ($dateType == 16) {
632 $dateArray = explode('-', $value);
633 if (count($dateArray) != 3) {
634 $dateArray = explode('/', $value);
635 }
636
637 if (count($dateArray) == 3) {
638 $monthInt = 0;
639 $fullMonths = self::getFullMonthNames();
640 foreach ($fullMonths as $key => $val) {
641 if (strtolower($dateArray[1]) == strtolower($val)) {
642 $monthInt = $key;
643 break;
644 }
645 }
646 if (!$monthInt) {
647 $abbrMonths = self::getAbbrMonthNames();
648 foreach ($abbrMonths as $key => $val) {
649 if (strtolower(trim($dateArray[1], ".")) == strtolower($val)) {
650 $monthInt = $key;
651 break;
652 }
653 }
654 }
655 if (!$monthInt) {
656 $monthInt = $dateArray[1];
657 }
658
659 $year = (int) $dateArray[2];
660 $day = (int) $dateArray[0];
661 $month = (int) $monthInt;
662 }
663 else {
664 return FALSE;
665 }
666 }
667 if ($dateType == 32) {
668 $formattedDate = explode("/", $value);
669 if (count($formattedDate) == 3) {
670 $year = (int) $formattedDate[2];
671 $month = (int) $formattedDate[1];
672 $day = (int) $formattedDate[0];
673 }
674 else {
675 return FALSE;
676 }
677 }
678
679 $month = ($month < 10) ? "0" . "$month" : $month;
680 $day = ($day < 10) ? "0" . "$day" : $day;
681
682 $year = (int ) $year;
683 // simple heuristic to determine what century to use
684 // 00 - 20 is always 2000 - 2020
685 // 21 - 99 is always 1921 - 1999
686 if ($year < 21) {
687 $year = (strlen($year) == 1) ? $cen . '0' . $year : $cen . $year;
688 }
689 elseif ($year < 100) {
690 $year = $prevCen . $year;
691 }
692
693 if ($params[$dateParam]) {
694 $params[$dateParam] = "$year$month$day";
695 }
696 // if month is invalid return as error
697 if ($month !== '00' && $month <= 12) {
698 return TRUE;
699 }
700 return FALSE;
701 }
702
703 /**
704 * @param $date
705 *
706 * @return bool
707 */
708 public static function isDate(&$date) {
709 if (CRM_Utils_System::isNull($date)) {
710 return FALSE;
711 }
712 return TRUE;
713 }
714
715 /**
716 * Translate a TTL to a concrete expiration time.
717 *
718 * @param NULL|int|DateInterval $ttl
719 * @param int $default
720 * The value to use if $ttl is not specified (NULL).
721 * @return int
722 * Timestamp (seconds since epoch).
723 * @throws \CRM_Utils_Cache_InvalidArgumentException
724 */
725 public static function convertCacheTtlToExpires($ttl, $default) {
726 if ($ttl === NULL) {
727 $ttl = $default;
728 }
729
730 if (is_int($ttl)) {
731 return time() + $ttl;
732 }
733 elseif ($ttl instanceof DateInterval) {
734 return date_add(new DateTime(), $ttl)->getTimestamp();
735 }
736 else {
737 throw new CRM_Utils_Cache_InvalidArgumentException("Invalid cache TTL");
738 }
739 }
740
741 /**
742 * Normalize a TTL.
743 *
744 * @param NULL|int|DateInterval $ttl
745 * @param int $default
746 * The value to use if $ttl is not specified (NULL).
747 * @return int
748 * Seconds until expiration.
749 * @throws \CRM_Utils_Cache_InvalidArgumentException
750 */
751 public static function convertCacheTtl($ttl, $default) {
752 if ($ttl === NULL) {
753 return $default;
754 }
755 elseif (is_int($ttl)) {
756 return $ttl;
757 }
758 elseif ($ttl instanceof DateInterval) {
759 return date_add(new DateTime(), $ttl)->getTimestamp() - time();
760 }
761 else {
762 throw new CRM_Utils_Cache_InvalidArgumentException("Invalid cache TTL");
763 }
764 }
765
766
767 /**
768 * @param null $timeStamp
769 *
770 * @return bool|string
771 */
772 public static function currentDBDate($timeStamp = NULL) {
773 return $timeStamp ? date('YmdHis', $timeStamp) : date('YmdHis');
774 }
775
776 /**
777 * @param $date
778 * @param null $now
779 *
780 * @return bool
781 */
782 public static function overdue($date, $now = NULL) {
783 $mysqlDate = self::isoToMysql($date);
784 if (!$now) {
785 $now = self::currentDBDate();
786 }
787 else {
788 $now = self::isoToMysql($now);
789 }
790
791 return ($mysqlDate >= $now) ? FALSE : TRUE;
792 }
793
794 /**
795 * Get customized today.
796 *
797 * This function is used for getting customized today. To get
798 * actuall today pass 'dayParams' as null. or else pass the day,
799 * month, year values as array values
800 * Example: $dayParams = array(
801 * 'day' => '25', 'month' => '10',
802 * 'year' => '2007' );
803 *
804 * @param array $dayParams of the day, month, year.
805 * Array of the day, month, year.
806 * values.
807 * @param string $format
808 * Expected date format( default.
809 * format is 2007-12-21 )
810 *
811 * @return string
812 * Return the customized today's date (Y-m-d)
813 */
814 public static function getToday($dayParams = NULL, $format = "Y-m-d") {
815 if (is_null($dayParams) || empty($dayParams)) {
816 $today = date($format);
817 }
818 else {
819 $today = date($format, mktime(0, 0, 0,
820 $dayParams['month'],
821 $dayParams['day'],
822 $dayParams['year']
823 ));
824 }
825
826 return $today;
827 }
828
829 /**
830 * Find whether today's date lies in
831 * the given range
832 *
833 * @param date $startDate
834 * Start date for the range.
835 * @param date $endDate
836 * End date for the range.
837 *
838 * @return bool
839 * true if today's date is in the given date range
840 */
841 public static function getRange($startDate, $endDate) {
842 $today = date("Y-m-d");
843 $mysqlStartDate = self::isoToMysql($startDate);
844 $mysqlEndDate = self::isoToMysql($endDate);
845 $mysqlToday = self::isoToMysql($today);
846
847 if ((isset($mysqlStartDate) && isset($mysqlEndDate)) && (($mysqlToday >= $mysqlStartDate) && ($mysqlToday <= $mysqlEndDate))) {
848 return TRUE;
849 }
850 elseif ((isset($mysqlStartDate) && !isset($mysqlEndDate)) && (($mysqlToday >= $mysqlStartDate))) {
851 return TRUE;
852 }
853 elseif ((!isset($mysqlStartDate) && isset($mysqlEndDate)) && (($mysqlToday <= $mysqlEndDate))) {
854 return TRUE;
855 }
856 return FALSE;
857 }
858
859 /**
860 * Get start date and end from
861 * the given relative term and unit
862 *
863 * @param string $relative Relative format in the format term.unit.
864 * Eg: previous.day
865 *
866 * @param string $from
867 * @param string $to
868 * @param string $fromTime
869 * @param string $toTime
870 *
871 * @return array
872 * start date, end date
873 */
874 public static function getFromTo($relative, $from, $to, $fromTime = NULL, $toTime = '235959') {
875 if ($relative) {
876 list($term, $unit) = explode('.', $relative, 2);
877 $dateRange = self::relativeToAbsolute($term, $unit);
878 $from = substr($dateRange['from'], 0, 8);
879 $to = substr($dateRange['to'], 0, 8);
880 // @todo fix relativeToAbsolute & add tests
881 // relativeToAbsolute returns 8 char date strings
882 // or 14 char date + time strings.
883 // We should use those. However, it turns out to be unreliable.
884 // e.g. this.week does NOT return 235959 for 'from'
885 // so our defaults are more reliable.
886 // Currently relativeToAbsolute only supports 'whole' days so that is ok
887 }
888
889 $from = self::processDate($from, $fromTime);
890 $to = self::processDate($to, $toTime);
891
892 return array($from, $to);
893 }
894
895 /**
896 * Calculate Age in Years if greater than one year else in months.
897 *
898 * @param date $birthDate
899 * Birth Date.
900 *
901 * @return int
902 * array $results contains years or months
903 */
904 static public function calculateAge($birthDate) {
905 $results = array();
906 $formatedBirthDate = CRM_Utils_Date::customFormat($birthDate, '%Y-%m-%d');
907
908 $bDate = explode('-', $formatedBirthDate);
909 $birthYear = $bDate[0];
910 $birthMonth = $bDate[1];
911 $birthDay = $bDate[2];
912 $year_diff = date("Y") - $birthYear;
913
914 // don't calculate age CRM-3143
915 if ($birthYear == '1902') {
916 return $results;
917 }
918
919 switch ($year_diff) {
920 case 1:
921 $month = (12 - $birthMonth) + date("m");
922 if ($month < 12) {
923 if (date("d") < $birthDay) {
924 $month--;
925 }
926 $results['months'] = $month;
927 }
928 elseif ($month == 12 && (date("d") < $birthDay)) {
929 $results['months'] = $month - 1;
930 }
931 else {
932 $results['years'] = $year_diff;
933 }
934 break;
935
936 case 0:
937 $month = date("m") - $birthMonth;
938 $results['months'] = $month;
939 break;
940
941 default:
942 $results['years'] = $year_diff;
943 if ((date("m") < $birthMonth) || (date("m") == $birthMonth) && (date("d") < $birthDay)) {
944 $results['years']--;
945 }
946 }
947
948 return $results;
949 }
950
951 /**
952 * Calculate next payment date according to provided unit & interval
953 *
954 * @param string $unit
955 * Frequency unit like year,month, week etc.
956 *
957 * @param int $interval
958 * Frequency interval.
959 *
960 * @param array $date
961 * Start date of pledge.
962 *
963 * @param bool $dontCareTime
964 *
965 * @return array
966 * contains new date with added interval
967 */
968 public static function intervalAdd($unit, $interval, $date, $dontCareTime = FALSE) {
969 if (is_array($date)) {
970 $hour = CRM_Utils_Array::value('H', $date);
971 $minute = CRM_Utils_Array::value('i', $date);
972 $second = CRM_Utils_Array::value('s', $date);
973 $month = CRM_Utils_Array::value('M', $date);
974 $day = CRM_Utils_Array::value('d', $date);
975 $year = CRM_Utils_Array::value('Y', $date);
976 }
977 else {
978 extract(date_parse($date));
979 }
980 $date = mktime($hour, $minute, $second, $month, $day, $year);
981 switch ($unit) {
982 case 'year':
983 $date = mktime($hour, $minute, $second, $month, $day, $year + $interval);
984 break;
985
986 case 'month':
987 $date = mktime($hour, $minute, $second, $month + $interval, $day, $year);
988 break;
989
990 case 'week':
991 $interval = $interval * 7;
992 $date = mktime($hour, $minute, $second, $month, $day + $interval, $year);
993 break;
994
995 case 'day':
996 $date = mktime($hour, $minute, $second, $month, $day + $interval, $year);
997 break;
998
999 case 'second':
1000 $date = mktime($hour, $minute, $second + $interval, $month, $day, $year);
1001 break;
1002 }
1003
1004 $scheduleDate = explode("-", date("n-j-Y-H-i-s", $date));
1005
1006 $date = array();
1007 $date['M'] = $scheduleDate[0];
1008 $date['d'] = $scheduleDate[1];
1009 $date['Y'] = $scheduleDate[2];
1010 if ($dontCareTime == FALSE) {
1011 $date['H'] = $scheduleDate[3];
1012 $date['i'] = $scheduleDate[4];
1013 $date['s'] = $scheduleDate[5];
1014 }
1015 return $date;
1016 }
1017
1018 /**
1019 * Get the smarty view presentation mapping for the given format.
1020 *
1021 * Historically it was decided that where the view format is 'dd/mm/yy' or 'mm/dd/yy'
1022 * they should be rendered using a longer date format. This is likely as much to
1023 * do with the earlier date widget being unable to handle some formats as usablity.
1024 * However, we continue to respect this.
1025 *
1026 * @param $format
1027 * Given format ( eg 'M Y', 'Y M' ).
1028 *
1029 * @return string|null
1030 * Smarty translation of the date format. Null is also valid and is translated
1031 * according to the available parts at the smarty layer.
1032 */
1033 public static function getDateFieldViewFormat($format) {
1034 $supportableFormats = array(
1035 'mm/dd' => '%B %E%f',
1036 'dd-mm' => '%E%f %B',
1037 'yy-mm' => '%Y %B',
1038 'M yy' => '%b %Y',
1039 'yy' => '%Y',
1040 'dd/mm/yy' => '%E%f %B %Y',
1041 );
1042
1043 return array_key_exists($format, $supportableFormats) ? $supportableFormats[$format] : self::pickBestSmartyFormat($format);
1044 }
1045
1046 /**
1047 * Pick the smarty format from settings that best matches the time string we have.
1048 *
1049 * For view purposes we historically use the setting that most closely matches the data
1050 * in the format from our settings, as opposed to the setting configured for the field.
1051 *
1052 * @param $format
1053 * @return mixed
1054 */
1055 public static function pickBestSmartyFormat($format) {
1056 if (stristr($format, 'h')) {
1057 return Civi::settings()->get('dateformatDatetime');
1058 }
1059 if (stristr($format, 'd') || stristr($format, 'j')) {
1060 return Civi::settings()->get('dateformatFull');
1061 }
1062 if (stristr($format, 'm')) {
1063 return Civi::settings()->get('dateformatPartial');
1064 }
1065 return Civi::settings()->get('dateformatYear');
1066 }
1067
1068 /**
1069 * Map date plugin and actual format that is used by PHP.
1070 *
1071 * @return array
1072 */
1073 public static function datePluginToPHPFormats() {
1074 $dateInputFormats = array(
1075 "mm/dd/yy" => 'm/d/Y',
1076 "dd/mm/yy" => 'd/m/Y',
1077 "yy-mm-dd" => 'Y-m-d',
1078 "dd-mm-yy" => 'd-m-Y',
1079 "dd.mm.yy" => 'd.m.Y',
1080 "M d" => 'M j',
1081 "M d, yy" => 'M j, Y',
1082 "d M yy" => 'j M Y',
1083 "MM d, yy" => 'F j, Y',
1084 "d MM yy" => 'j F Y',
1085 "DD, d MM yy" => 'l, j F Y',
1086 "mm/dd" => 'm/d',
1087 "dd-mm" => 'd-m',
1088 "yy-mm" => 'Y-m',
1089 "M yy" => 'M Y',
1090 "M Y" => 'M Y',
1091 "yy" => 'Y',
1092 );
1093 return $dateInputFormats;
1094 }
1095
1096 /**
1097 * Resolves the given relative time interval into finite time limits.
1098 *
1099 * @param string $relativeTerm
1100 * Relative time frame: this, previous, previous_1.
1101 * @param int $unit
1102 * Frequency unit like year, month, week etc.
1103 *
1104 * @return array
1105 * start date and end date for the relative time frame
1106 */
1107 public static function relativeToAbsolute($relativeTerm, $unit) {
1108 $now = getdate();
1109 $from = $to = $dateRange = array();
1110 $from['H'] = $from['i'] = $from['s'] = 0;
1111 $relativeTermParts = explode('_', $relativeTerm);
1112 $relativeTermPrefix = $relativeTermParts[0];
1113 $relativeTermSuffix = isset($relativeTermParts[1]) ? $relativeTermParts[1] : '';
1114
1115 switch ($unit) {
1116 case 'year':
1117 switch ($relativeTerm) {
1118 case 'this':
1119 $from['d'] = $from['M'] = 1;
1120 $to['d'] = 31;
1121 $to['M'] = 12;
1122 $to['Y'] = $from['Y'] = $now['year'];
1123 break;
1124
1125 case 'previous':
1126 $from['M'] = $from['d'] = 1;
1127 $to['d'] = 31;
1128 $to['M'] = 12;
1129 $to['Y'] = $from['Y'] = $now['year'] - 1;
1130 break;
1131
1132 case 'previous_before':
1133 $from['M'] = $from['d'] = 1;
1134 $to['d'] = 31;
1135 $to['M'] = 12;
1136 $to['Y'] = $from['Y'] = $now['year'] - 2;
1137 break;
1138
1139 case 'previous_2':
1140 $from['M'] = $from['d'] = 1;
1141 $to['d'] = 31;
1142 $to['M'] = 12;
1143 $from['Y'] = $now['year'] - 2;
1144 $to['Y'] = $now['year'] - 1;
1145 break;
1146
1147 case 'earlier':
1148 $to['d'] = 31;
1149 $to['M'] = 12;
1150 $to['Y'] = $now['year'] - 1;
1151 unset($from);
1152 break;
1153
1154 case 'greater':
1155 $from['M'] = $from['d'] = 1;
1156 $from['Y'] = $now['year'];
1157 unset($to);
1158 break;
1159
1160 case 'greater_previous':
1161 $from['d'] = 31;
1162 $from['M'] = 12;
1163 $from['Y'] = $now['year'] - 1;
1164 unset($to);
1165 break;
1166
1167 case 'ending':
1168 $to['d'] = $now['mday'];
1169 $to['M'] = $now['mon'];
1170 $to['Y'] = $now['year'];
1171 $to['H'] = 23;
1172 $to['i'] = $to['s'] = 59;
1173 $from = self::intervalAdd('year', -1, $to);
1174 $from = self::intervalAdd('second', 1, $from);
1175 break;
1176
1177 case 'current':
1178 $from['M'] = $from['d'] = 1;
1179 $from['Y'] = $now['year'];
1180 $to['H'] = 23;
1181 $to['i'] = $to['s'] = 59;
1182 $to['d'] = $now['mday'];
1183 $to['M'] = $now['mon'];
1184 $to['Y'] = $now['year'];
1185 break;
1186
1187 case 'ending_2':
1188 $to['d'] = $now['mday'];
1189 $to['M'] = $now['mon'];
1190 $to['Y'] = $now['year'];
1191 $to['H'] = 23;
1192 $to['i'] = $to['s'] = 59;
1193 $from = self::intervalAdd('year', -2, $to);
1194 $from = self::intervalAdd('second', 1, $from);
1195 break;
1196
1197 case 'ending_3':
1198 $to['d'] = $now['mday'];
1199 $to['M'] = $now['mon'];
1200 $to['Y'] = $now['year'];
1201 $to['H'] = 23;
1202 $to['i'] = $to['s'] = 59;
1203 $from = self::intervalAdd('year', -3, $to);
1204 $from = self::intervalAdd('second', 1, $from);
1205 break;
1206
1207 case 'less':
1208 $to['d'] = 31;
1209 $to['M'] = 12;
1210 $to['Y'] = $now['year'];
1211 unset($from);
1212 break;
1213
1214 case 'next':
1215 $from['M'] = $from['d'] = 1;
1216 $to['d'] = 31;
1217 $to['M'] = 12;
1218 $to['Y'] = $from['Y'] = $now['year'] + 1;
1219 break;
1220
1221 case 'starting':
1222 $from['d'] = $now['mday'];
1223 $from['M'] = $now['mon'];
1224 $from['Y'] = $now['year'];
1225 $to['d'] = $now['mday'] - 1;
1226 $to['M'] = $now['mon'];
1227 $to['Y'] = $now['year'] + 1;
1228 break;
1229 }
1230 break;
1231
1232 case 'fiscal_year':
1233 $config = CRM_Core_Config::singleton();
1234 $from['d'] = $config->fiscalYearStart['d'];
1235 $from['M'] = $config->fiscalYearStart['M'];
1236 $fYear = self::calculateFiscalYear($from['d'], $from['M']);
1237 switch ($relativeTermPrefix) {
1238 case 'this':
1239 $from['Y'] = $fYear;
1240 $fiscalYear = mktime(0, 0, 0, $from['M'], $from['d'] - 1, $from['Y'] + 1);
1241 $fiscalEnd = explode('-', date("Y-m-d", $fiscalYear));
1242
1243 $to['d'] = $fiscalEnd['2'];
1244 $to['M'] = $fiscalEnd['1'];
1245 $to['Y'] = $fiscalEnd['0'];
1246 break;
1247
1248 case 'previous':
1249 if (!is_numeric($relativeTermSuffix)) {
1250 $from['Y'] = ($relativeTermSuffix === 'before') ? $fYear - 2 : $fYear - 1;
1251 $fiscalYear = mktime(0, 0, 0, $from['M'], $from['d'] - 1, $from['Y'] + 1);
1252 $fiscalEnd = explode('-', date("Y-m-d", $fiscalYear));
1253 $to['d'] = $fiscalEnd['2'];
1254 $to['M'] = $fiscalEnd['1'];
1255 $to['Y'] = $fiscalEnd['0'];
1256 }
1257 else {
1258 $from['Y'] = $fYear - $relativeTermSuffix;
1259 $fiscalYear = mktime(0, 0, 0, $from['M'], $from['d'] - 1, $from['Y'] + 1);
1260 $fiscalEnd = explode('-', date("Y-m-d", $fiscalYear));
1261 $to['d'] = $fiscalEnd['2'];
1262 $to['M'] = $fiscalEnd['1'];
1263 $to['Y'] = $fYear;
1264 }
1265 break;
1266
1267 case 'next':
1268 $from['Y'] = $fYear + 1;
1269 $fiscalYear = mktime(0, 0, 0, $from['M'], $from['d'] - 1, $from['Y'] + 1);
1270 $fiscalEnd = explode('-', date("Y-m-d", $fiscalYear));
1271 $to['d'] = $fiscalEnd['2'];
1272 $to['M'] = $fiscalEnd['1'];
1273 $to['Y'] = $fiscalEnd['0'];
1274 break;
1275 }
1276 break;
1277
1278 case 'quarter':
1279 switch ($relativeTerm) {
1280 case 'this':
1281
1282 $quarter = ceil($now['mon'] / 3);
1283 $from['d'] = 1;
1284 $from['M'] = (3 * $quarter) - 2;
1285 $to['M'] = 3 * $quarter;
1286 $to['Y'] = $from['Y'] = $now['year'];
1287 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $now['year']));
1288 break;
1289
1290 case 'previous':
1291 $difference = 1;
1292 $quarter = ceil($now['mon'] / 3);
1293 $quarter = $quarter - $difference;
1294 $subtractYear = 0;
1295 if ($quarter <= 0) {
1296 $subtractYear = 1;
1297 $quarter += 4;
1298 }
1299 $from['d'] = 1;
1300 $from['M'] = (3 * $quarter) - 2;
1301 $to['M'] = 3 * $quarter;
1302 $to['Y'] = $from['Y'] = $now['year'] - $subtractYear;
1303 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1304 break;
1305
1306 case 'previous_before':
1307 $difference = 2;
1308 $quarter = ceil($now['mon'] / 3);
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 $to['M'] = 3 * $quarter;
1318 $to['Y'] = $from['Y'] = $now['year'] - $subtractYear;
1319 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1320 break;
1321
1322 case 'previous_2':
1323 $difference = 2;
1324 $quarter = ceil($now['mon'] / 3);
1325 $current_quarter = $quarter;
1326 $quarter = $quarter - $difference;
1327 $subtractYear = 0;
1328 if ($quarter <= 0) {
1329 $subtractYear = 1;
1330 $quarter += 4;
1331 }
1332 $from['d'] = 1;
1333 $from['M'] = (3 * $quarter) - 2;
1334 switch ($current_quarter) {
1335 case 1:
1336 $to['M'] = (4 * $quarter);
1337 break;
1338
1339 case 2:
1340 $to['M'] = (4 * $quarter) + 3;
1341 break;
1342
1343 case 3:
1344 $to['M'] = (4 * $quarter) + 2;
1345 break;
1346
1347 case 4:
1348 $to['M'] = (4 * $quarter) + 1;
1349 break;
1350 }
1351 $to['Y'] = $from['Y'] = $now['year'] - $subtractYear;
1352 if ($to['M'] > 12) {
1353 $to['M'] = 3 * ($quarter - 3);
1354 $to['Y'] = $now['year'];
1355 }
1356 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1357 break;
1358
1359 case 'earlier':
1360 $quarter = ceil($now['mon'] / 3) - 1;
1361 $subtractYear = 0;
1362 if ($quarter <= 0) {
1363 $subtractYear = 1;
1364 $quarter += 4;
1365 }
1366 $to['M'] = 3 * $quarter;
1367 $to['Y'] = $from['Y'] = $now['year'] - $subtractYear;
1368 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1369 unset($from);
1370 break;
1371
1372 case 'greater':
1373 $quarter = ceil($now['mon'] / 3);
1374 $from['d'] = 1;
1375 $from['M'] = (3 * $quarter) - 2;
1376 $from['Y'] = $now['year'];
1377 unset($to);
1378 break;
1379
1380 case 'greater_previous':
1381 $quarter = ceil($now['mon'] / 3) - 1;
1382 $subtractYear = 0;
1383 if ($quarter <= 0) {
1384 $subtractYear = 1;
1385 $quarter += 4;
1386 }
1387 $from['M'] = 3 * $quarter;
1388 $from['Y'] = $from['Y'] = $now['year'] - $subtractYear;
1389 $from['d'] = date('t', mktime(0, 0, 0, $from['M'], 1, $from['Y']));
1390 unset($to);
1391 break;
1392
1393 case 'ending':
1394 $to['d'] = $now['mday'];
1395 $to['M'] = $now['mon'];
1396 $to['Y'] = $now['year'];
1397 $to['H'] = 23;
1398 $to['i'] = $to['s'] = 59;
1399 $from = self::intervalAdd('day', -90, $to);
1400 $from = self::intervalAdd('second', 1, $from);
1401 break;
1402
1403 case 'current':
1404 $quarter = ceil($now['mon'] / 3);
1405 $from['d'] = 1;
1406 $from['M'] = (3 * $quarter) - 2;
1407 $from['Y'] = $now['year'];
1408 $to['d'] = $now['mday'];
1409 $to['M'] = $now['mon'];
1410 $to['Y'] = $now['year'];
1411 $to['H'] = 23;
1412 $to['i'] = $to['s'] = 59;
1413 break;
1414
1415 case 'less':
1416 $quarter = ceil($now['mon'] / 3);
1417 $to['M'] = 3 * $quarter;
1418 $to['Y'] = $now['year'];
1419 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $now['year']));
1420 unset($from);
1421 break;
1422
1423 case 'next':
1424 $difference = -1;
1425 $subtractYear = 0;
1426 $quarter = ceil($now['mon'] / 3);
1427 $quarter = $quarter - $difference;
1428 // CRM-14550 QA Fix
1429 if ($quarter > 4) {
1430 $now['year'] = $now['year'] + 1;
1431 $quarter = 1;
1432 }
1433 if ($quarter <= 0) {
1434 $subtractYear = 1;
1435 $quarter += 4;
1436 }
1437 $from['d'] = 1;
1438 $from['M'] = (3 * $quarter) - 2;
1439 $to['M'] = 3 * $quarter;
1440 $to['Y'] = $from['Y'] = $now['year'] - $subtractYear;
1441 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1442 break;
1443
1444 case 'starting':
1445 $from['d'] = $now['mday'];
1446 $from['M'] = $now['mon'];
1447 $from['Y'] = $now['year'];
1448 $from['H'] = 00;
1449 $from['i'] = $to['s'] = 00;
1450 $to = self::intervalAdd('day', 90, $from);
1451 $to = self::intervalAdd('second', -1, $to);
1452 break;
1453 }
1454 break;
1455
1456 case 'month':
1457 switch ($relativeTerm) {
1458 case 'this':
1459 $from['d'] = 1;
1460 $to['d'] = date('t', mktime(0, 0, 0, $now['mon'], 1, $now['year']));
1461 $from['M'] = $to['M'] = $now['mon'];
1462 $from['Y'] = $to['Y'] = $now['year'];
1463 break;
1464
1465 case 'previous':
1466 $from['d'] = 1;
1467 if ($now['mon'] == 1) {
1468 $from['M'] = $to['M'] = 12;
1469 $from['Y'] = $to['Y'] = $now['year'] - 1;
1470 }
1471 else {
1472 $from['M'] = $to['M'] = $now['mon'] - 1;
1473 $from['Y'] = $to['Y'] = $now['year'];
1474 }
1475 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1476 break;
1477
1478 case 'previous_before':
1479 $from['d'] = 1;
1480 if ($now['mon'] < 3) {
1481 $from['M'] = $to['M'] = 10 + $now['mon'];
1482 $from['Y'] = $to['Y'] = $now['year'] - 1;
1483 }
1484 else {
1485 $from['M'] = $to['M'] = $now['mon'] - 2;
1486 $from['Y'] = $to['Y'] = $now['year'];
1487 }
1488 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1489 break;
1490
1491 case 'previous_2':
1492 $from['d'] = 1;
1493 if ($now['mon'] < 3) {
1494 $from['M'] = 10 + $now['mon'];
1495 $from['Y'] = $now['year'] - 1;
1496 }
1497 else {
1498 $from['M'] = $now['mon'] - 2;
1499 $from['Y'] = $now['year'];
1500 }
1501
1502 if ($now['mon'] == 1) {
1503 $to['M'] = 12;
1504 $to['Y'] = $now['year'] - 1;
1505 }
1506 else {
1507 $to['M'] = $now['mon'] - 1;
1508 $to['Y'] = $now['year'];
1509 }
1510
1511 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1512 break;
1513
1514 case 'earlier':
1515 // before end of past month
1516 if ($now['mon'] == 1) {
1517 $to['M'] = 12;
1518 $to['Y'] = $now['year'] - 1;
1519 }
1520 else {
1521 $to['M'] = $now['mon'] - 1;
1522 $to['Y'] = $now['year'];
1523 }
1524
1525 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1526 unset($from);
1527 break;
1528
1529 case 'greater':
1530 $from['d'] = 1;
1531 $from['M'] = $now['mon'];;
1532 $from['Y'] = $now['year'];
1533 unset($to);
1534 break;
1535
1536 case 'greater_previous':
1537 // from end of past month
1538 if ($now['mon'] == 1) {
1539 $from['M'] = 12;
1540 $from['Y'] = $now['year'] - 1;
1541 }
1542 else {
1543 $from['M'] = $now['mon'] - 1;
1544 $from['Y'] = $now['year'];
1545 }
1546
1547 $from['d'] = date('t', mktime(0, 0, 0, $from['M'], 1, $from['Y']));
1548 unset($to);
1549 break;
1550
1551 case 'ending_2':
1552 $to['d'] = $now['mday'];
1553 $to['M'] = $now['mon'];
1554 $to['Y'] = $now['year'];
1555 $to['H'] = 23;
1556 $to['i'] = $to['s'] = 59;
1557 $from = self::intervalAdd('day', -60, $to);
1558 $from = self::intervalAdd('second', 1, $from);
1559 break;
1560
1561 case 'ending':
1562 $to['d'] = $now['mday'];
1563 $to['M'] = $now['mon'];
1564 $to['Y'] = $now['year'];
1565 $to['H'] = 23;
1566 $to['i'] = $to['s'] = 59;
1567 $from = self::intervalAdd('day', -30, $to);
1568 $from = self::intervalAdd('second', 1, $from);
1569 break;
1570
1571 case 'current':
1572 $from['d'] = 1;
1573 $from['M'] = $now['mon'];;
1574 $from['Y'] = $now['year'];
1575 $to['d'] = $now['mday'];
1576 $to['M'] = $now['mon'];
1577 $to['Y'] = $now['year'];
1578 $to['H'] = 23;
1579 $to['i'] = $to['s'] = 59;
1580 break;
1581
1582 case 'less':
1583 // CRM-14550 QA Fix
1584 $to['Y'] = $now['year'];
1585 $to['M'] = $now['mon'];
1586 $to['d'] = date('t', mktime(0, 0, 0, $now['mon'], 1, $now['year']));
1587 unset($from);
1588 break;
1589
1590 case 'next':
1591 $from['d'] = 1;
1592 if ($now['mon'] == 12) {
1593 $from['M'] = $to['M'] = 1;
1594 $from['Y'] = $to['Y'] = $now['year'] + 1;
1595 }
1596 else {
1597 $from['M'] = $to['M'] = $now['mon'] + 1;
1598 $from['Y'] = $to['Y'] = $now['year'];
1599 }
1600 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1601 break;
1602
1603 case 'starting':
1604 $from['d'] = $now['mday'];
1605 $from['M'] = $now['mon'];
1606 $from['Y'] = $now['year'];
1607 $from['H'] = 00;
1608 $from['i'] = $to['s'] = 00;
1609 $to = self::intervalAdd('day', 30, $from);
1610 $to = self::intervalAdd('second', -1, $to);
1611 break;
1612
1613 case 'starting_2':
1614 $from['d'] = $now['mday'];
1615 $from['M'] = $now['mon'];
1616 $from['Y'] = $now['year'];
1617 $from['H'] = 00;
1618 $from['i'] = $to['s'] = 00;
1619 $to = self::intervalAdd('day', 60, $from);
1620 $to = self::intervalAdd('second', -1, $to);
1621 break;
1622 }
1623 break;
1624
1625 case 'week':
1626 $weekFirst = Civi::settings()->get('weekBegins');
1627 $thisDay = $now['wday'];
1628 if ($weekFirst > $thisDay) {
1629 $diffDay = $thisDay - $weekFirst + 7;
1630 }
1631 else {
1632 $diffDay = $thisDay - $weekFirst;
1633 }
1634 switch ($relativeTerm) {
1635 case 'this':
1636 $from['d'] = $now['mday'];
1637 $from['M'] = $now['mon'];
1638 $from['Y'] = $now['year'];
1639 $from = self::intervalAdd('day', -1 * ($diffDay), $from);
1640 $to = self::intervalAdd('day', 6, $from);
1641 break;
1642
1643 case 'previous':
1644 $from['d'] = $now['mday'];
1645 $from['M'] = $now['mon'];
1646 $from['Y'] = $now['year'];
1647 $from = self::intervalAdd('day', -1 * ($diffDay) - 7, $from);
1648 $to = self::intervalAdd('day', 6, $from);
1649 break;
1650
1651 case 'previous_before':
1652 $from['d'] = $now['mday'];
1653 $from['M'] = $now['mon'];
1654 $from['Y'] = $now['year'];
1655 $from = self::intervalAdd('day', -1 * ($diffDay) - 14, $from);
1656 $to = self::intervalAdd('day', 6, $from);
1657 break;
1658
1659 case 'previous_2':
1660 $from['d'] = $now['mday'];
1661 $from['M'] = $now['mon'];
1662 $from['Y'] = $now['year'];
1663 $from = self::intervalAdd('day', -1 * ($diffDay) - 14, $from);
1664 $to = self::intervalAdd('day', 13, $from);
1665 break;
1666
1667 case 'earlier':
1668 $to['d'] = $now['mday'];
1669 $to['M'] = $now['mon'];
1670 $to['Y'] = $now['year'];
1671 $to = self::intervalAdd('day', -1 * ($diffDay) - 1, $to);
1672 unset($from);
1673 break;
1674
1675 case 'greater':
1676 $from['d'] = $now['mday'];
1677 $from['M'] = $now['mon'];
1678 $from['Y'] = $now['year'];
1679 $from = self::intervalAdd('day', -1 * ($diffDay), $from);
1680 unset($to);
1681 break;
1682
1683 case 'greater_previous':
1684 $from['d'] = $now['mday'];
1685 $from['M'] = $now['mon'];
1686 $from['Y'] = $now['year'];
1687 $from = self::intervalAdd('day', -1 * ($diffDay) - 1, $from);
1688 unset($to);
1689 break;
1690
1691 case 'ending':
1692 $to['d'] = $now['mday'];
1693 $to['M'] = $now['mon'];
1694 $to['Y'] = $now['year'];
1695 $to['H'] = 23;
1696 $to['i'] = $to['s'] = 59;
1697 $from = self::intervalAdd('day', -7, $to);
1698 $from = self::intervalAdd('second', 1, $from);
1699 break;
1700
1701 case 'current':
1702 $from['d'] = $now['mday'];
1703 $from['M'] = $now['mon'];
1704 $from['Y'] = $now['year'];
1705 $from = self::intervalAdd('day', -1 * ($diffDay), $from);
1706 $to['d'] = $now['mday'];
1707 $to['M'] = $now['mon'];
1708 $to['Y'] = $now['year'];
1709 $to['H'] = 23;
1710 $to['i'] = $to['s'] = 59;
1711 break;
1712
1713 case 'less':
1714 $to['d'] = $now['mday'];
1715 $to['M'] = $now['mon'];
1716 $to['Y'] = $now['year'];
1717 // CRM-14550 QA Fix
1718 $to = self::intervalAdd('day', -1 * ($diffDay) + 6, $to);
1719 unset($from);
1720 break;
1721
1722 case 'next':
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 'starting':
1731 $from['d'] = $now['mday'];
1732 $from['M'] = $now['mon'];
1733 $from['Y'] = $now['year'];
1734 $from['H'] = 00;
1735 $from['i'] = $to['s'] = 00;
1736 $to = self::intervalAdd('day', 7, $from);
1737 $to = self::intervalAdd('second', -1, $to);
1738 break;
1739 }
1740 break;
1741
1742 case 'day':
1743 switch ($relativeTerm) {
1744 case 'this':
1745 $from['d'] = $to['d'] = $now['mday'];
1746 $from['M'] = $to['M'] = $now['mon'];
1747 $from['Y'] = $to['Y'] = $now['year'];
1748 break;
1749
1750 case 'previous':
1751 $from['d'] = $now['mday'];
1752 $from['M'] = $now['mon'];
1753 $from['Y'] = $now['year'];
1754 $from = self::intervalAdd('day', -1, $from);
1755 $to['d'] = $from['d'];
1756 $to['M'] = $from['M'];
1757 $to['Y'] = $from['Y'];
1758 break;
1759
1760 case 'previous_before':
1761 $from['d'] = $now['mday'];
1762 $from['M'] = $now['mon'];
1763 $from['Y'] = $now['year'];
1764 $from = self::intervalAdd('day', -2, $from);
1765 $to['d'] = $from['d'];
1766 $to['M'] = $from['M'];
1767 $to['Y'] = $from['Y'];
1768 break;
1769
1770 case 'previous_2':
1771 $from['d'] = $to['d'] = $now['mday'];
1772 $from['M'] = $to['M'] = $now['mon'];
1773 $from['Y'] = $to['Y'] = $now['year'];
1774 $from = self::intervalAdd('day', -2, $from);
1775 $to = self::intervalAdd('day', -1, $to);
1776 break;
1777
1778 case 'earlier':
1779 $to['d'] = $now['mday'];
1780 $to['M'] = $now['mon'];
1781 $to['Y'] = $now['year'];
1782 unset($from);
1783 break;
1784
1785 case 'greater':
1786 $from['d'] = $now['mday'];
1787 $from['M'] = $now['mon'];;
1788 $from['Y'] = $now['year'];
1789 unset($to);
1790 break;
1791
1792 case 'starting':
1793 $to['d'] = $now['mday'];
1794 $to['M'] = $now['mon'];
1795 $to['Y'] = $now['year'];
1796 $to = self::intervalAdd('day', 1, $to);
1797 $from['d'] = $to['d'];
1798 $from['M'] = $to['M'];
1799 $from['Y'] = $to['Y'];
1800 break;
1801
1802 }
1803 break;
1804 }
1805
1806 foreach (array(
1807 'from',
1808 'to',
1809 ) as $item) {
1810 if (!empty($$item)) {
1811 $dateRange[$item] = self::format($$item);
1812 }
1813 else {
1814 $dateRange[$item] = NULL;
1815 }
1816 }
1817 return $dateRange;
1818 }
1819
1820 /**
1821 * Calculate current fiscal year based on the fiscal month and day.
1822 *
1823 * @param int $fyDate
1824 * Fiscal start date.
1825 *
1826 * @param int $fyMonth
1827 * Fiscal Start Month.
1828 *
1829 * @return int
1830 * $fy Current Fiscal Year
1831 */
1832 public static function calculateFiscalYear($fyDate, $fyMonth) {
1833 $date = date("Y-m-d");
1834 $currentYear = date("Y");
1835
1836 // recalculate the date because month 4::04 make the difference
1837 $fiscalYear = explode('-', date("Y-m-d", mktime(0, 0, 0, $fyMonth, $fyDate, $currentYear)));
1838 $fyDate = $fiscalYear[2];
1839 $fyMonth = $fiscalYear[1];
1840 $fyStartDate = date("Y-m-d", mktime(0, 0, 0, $fyMonth, $fyDate, $currentYear));
1841
1842 if ($fyStartDate > $date) {
1843 $fy = intval(intval($currentYear) - 1);
1844 }
1845 else {
1846 $fy = intval($currentYear);
1847 }
1848 return $fy;
1849 }
1850
1851 /**
1852 * Function to process date, convert to mysql format
1853 *
1854 * @param string $date
1855 * Date string.
1856 * @param string $time
1857 * Time string.
1858 * @param bool|string $returnNullString 'null' needs to be returned
1859 * so that db oject will set null in db
1860 * @param string $format
1861 * Expected return date format.( default is mysql ).
1862 *
1863 * @return string
1864 * date format that is excepted by mysql
1865 */
1866 public static function processDate($date, $time = NULL, $returnNullString = FALSE, $format = 'YmdHis') {
1867 $mysqlDate = NULL;
1868
1869 if ($returnNullString) {
1870 $mysqlDate = 'null';
1871 }
1872
1873 if (trim($date)) {
1874 $mysqlDate = date($format, strtotime($date . ' ' . $time));
1875 }
1876
1877 return $mysqlDate;
1878 }
1879
1880 /**
1881 * Add the metadata about a date field to the field.
1882 *
1883 * This metadata will work with the call $form->add('datepicker', ...
1884 *
1885 * @param array $fieldMetaData
1886 * @param array $field
1887 *
1888 * @return array
1889 */
1890 public static function addDateMetadataToField($fieldMetaData, $field) {
1891 if (isset($fieldMetaData['html'])) {
1892 $field['html_type'] = $fieldMetaData['html']['type'];
1893 if ($field['html_type'] === 'Select Date') {
1894 if (!isset($field['date_format'])) {
1895 $dateAttributes = CRM_Core_SelectValues::date($fieldMetaData['html']['formatType'], NULL, NULL, NULL, 'Input');
1896 $field['start_date_years'] = $dateAttributes['minYear'];
1897 $field['end_date_years'] = $dateAttributes['maxYear'];
1898 $field['date_format'] = $dateAttributes['format'];
1899 $field['is_datetime_field'] = TRUE;
1900 $field['time_format'] = $dateAttributes['time'];
1901 $field['smarty_view_format'] = $dateAttributes['smarty_view_format'];
1902 }
1903 $field['datepicker']['extra'] = self::getDatePickerExtra($field);
1904 $field['datepicker']['attributes'] = self::getDatePickerAttributes($field);
1905 }
1906 }
1907 return $field;
1908 }
1909
1910
1911 /**
1912 * Get the fields required for the 'extra' parameter when adding a datepicker.
1913 *
1914 * @param array $field
1915 *
1916 * @return array
1917 */
1918 public static function getDatePickerExtra($field) {
1919 $extra = array();
1920 if (isset($field['date_format'])) {
1921 $extra['date'] = $field['date_format'];
1922 $extra['time'] = $field['time_format'];
1923 }
1924 $thisYear = date('Y');
1925 if (isset($field['start_date_years'])) {
1926 $extra['minDate'] = date('Y-m-d', strtotime('-' . ($thisYear - $field['start_date_years']) . ' years'));
1927 }
1928 if (isset($field['end_date_years'])) {
1929 $extra['maxDate'] = date('Y-m-d', strtotime('-' . ($thisYear - $field['end_date_years']) . ' years'));
1930 }
1931 return $extra;
1932 }
1933
1934 /**
1935 * Get the attributes parameters required for datepicker.
1936 *
1937 * @param array $field
1938 * Field metadata
1939 *
1940 * @return array
1941 * Array ready to pass to $this->addForm('datepicker' as attributes.
1942 */
1943 public static function getDatePickerAttributes(&$field) {
1944 $attributes = array();
1945 $dateAttributes = array(
1946 'start_date_years' => 'minYear',
1947 'end_date_years' => 'maxYear',
1948 'date_format' => 'format',
1949 );
1950 foreach ($dateAttributes as $dateAttribute => $mapTo) {
1951 if (isset($field[$dateAttribute])) {
1952 $attributes[$mapTo] = $field[$dateAttribute];
1953 }
1954 }
1955 return $attributes;
1956 }
1957
1958 /**
1959 * Function to convert mysql to date plugin format.
1960 *
1961 * @param string $mysqlDate
1962 * Date string.
1963 *
1964 * @param null $formatType
1965 * @param null $format
1966 * @param null $timeFormat
1967 *
1968 * @return array
1969 * and time
1970 */
1971 public static function setDateDefaults($mysqlDate = NULL, $formatType = NULL, $format = NULL, $timeFormat = NULL) {
1972 // if date is not passed assume it as today
1973 if (!$mysqlDate) {
1974 $mysqlDate = date('Y-m-d G:i:s');
1975 }
1976
1977 $config = CRM_Core_Config::singleton();
1978 if ($formatType) {
1979 // get actual format
1980 $params = array('name' => $formatType);
1981 $values = array();
1982 CRM_Core_DAO::commonRetrieve('CRM_Core_DAO_PreferencesDate', $params, $values);
1983
1984 if ($values['date_format']) {
1985 $format = $values['date_format'];
1986 }
1987
1988 if (isset($values['time_format'])) {
1989 $timeFormat = $values['time_format'];
1990 }
1991 }
1992
1993 // now we set display date using js, hence we should always setdefault
1994 // 'm/d/Y' format. So that submitted value is alwats mm/dd/YY format
1995 // note that for date display we dynamically create text field
1996 /*
1997 if ( !$format ) {
1998 $format = $config->dateInputFormat;
1999 }
2000
2001 // get actual format
2002 $actualPHPFormats = CRM_Core_SelectValues::datePluginToPHPFormats( );
2003 $dateFormat = CRM_Utils_Array::value( $format, $actualPHPFormats );
2004 */
2005
2006 $dateFormat = 'm/d/Y';
2007 $date = date($dateFormat, strtotime($mysqlDate));
2008
2009 if (!$timeFormat) {
2010 $timeFormat = $config->timeInputFormat;
2011 }
2012
2013 $actualTimeFormat = "g:iA";
2014 $appendZeroLength = 7;
2015 if ($timeFormat > 1) {
2016 $actualTimeFormat = "G:i";
2017 $appendZeroLength = 5;
2018 }
2019
2020 $time = date($actualTimeFormat, strtotime($mysqlDate));
2021
2022 // need to append zero for hours < 10
2023 if (strlen($time) < $appendZeroLength) {
2024 $time = '0' . $time;
2025 }
2026
2027 return array($date, $time);
2028 }
2029
2030 /**
2031 * Function get date format.
2032 *
2033 * @param string $formatType
2034 * Date name e.g. birth.
2035 *
2036 * @return string
2037 */
2038 public static function getDateFormat($formatType = NULL) {
2039 $format = NULL;
2040 if ($formatType) {
2041 $format = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_PreferencesDate',
2042 $formatType, 'date_format', 'name'
2043 );
2044 }
2045
2046 if (!$format) {
2047 $config = CRM_Core_Config::singleton();
2048 $format = $config->dateInputFormat;
2049 }
2050 return $format;
2051 }
2052
2053 /**
2054 * @param $date
2055 * @param $dateType
2056 *
2057 * @return null|string
2058 */
2059 public static function formatDate($date, $dateType) {
2060 $formattedDate = NULL;
2061 if (empty($date)) {
2062 return $formattedDate;
2063 }
2064
2065 // 1. first convert date to default format.
2066 // 2. append time to default formatted date (might be removed during format)
2067 // 3. validate date / date time.
2068 // 4. If date and time then convert to default date time format.
2069
2070 $dateKey = 'date';
2071 $dateParams = array($dateKey => $date);
2072
2073 if (CRM_Utils_Date::convertToDefaultDate($dateParams, $dateType, $dateKey)) {
2074 $dateVal = $dateParams[$dateKey];
2075 $ruleName = 'date';
2076 if ($dateType == 1) {
2077 $matches = array();
2078 if (preg_match("/(\s(([01]\d)|[2][0-3]):([0-5]\d))$/", $date, $matches)) {
2079 $ruleName = 'dateTime';
2080 if (strpos($date, '-') !== FALSE) {
2081 $dateVal .= array_shift($matches);
2082 }
2083 }
2084 }
2085
2086 // validate date.
2087 $valid = CRM_Utils_Rule::$ruleName($dateVal);
2088
2089 if ($valid) {
2090 // format date and time to default.
2091 if ($ruleName == 'dateTime') {
2092 $dateVal = CRM_Utils_Date::customFormat(preg_replace("/(:|\s)?/", "", $dateVal), '%Y%m%d%H%i');
2093 // hack to add seconds
2094 $dateVal .= '00';
2095 }
2096 $formattedDate = $dateVal;
2097 }
2098 }
2099
2100 return $formattedDate;
2101 }
2102
2103 /**
2104 * Function to return days of the month.
2105 *
2106 * @return array
2107 */
2108 public static function getCalendarDayOfMonth() {
2109 $month = array();
2110 for ($i = 1; $i <= 31; $i++) {
2111 $month[$i] = $i;
2112 if ($i == 31) {
2113 $month[$i] = $i . ' / Last day of month';
2114 }
2115 }
2116 return $month;
2117 }
2118
2119 }