Merge pull request #11737 from aydun/CRM-21816-relative-dates-in-search
[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 * @param null $timeStamp
700 *
701 * @return bool|string
702 */
703 public static function currentDBDate($timeStamp = NULL) {
704 return $timeStamp ? date('YmdHis', $timeStamp) : date('YmdHis');
705 }
706
707 /**
708 * @param $date
709 * @param null $now
710 *
711 * @return bool
712 */
713 public static function overdue($date, $now = NULL) {
714 $mysqlDate = self::isoToMysql($date);
715 if (!$now) {
716 $now = self::currentDBDate();
717 }
718 else {
719 $now = self::isoToMysql($now);
720 }
721
722 return ($mysqlDate >= $now) ? FALSE : TRUE;
723 }
724
725 /**
726 * Get customized today.
727 *
728 * This function is used for getting customized today. To get
729 * actuall today pass 'dayParams' as null. or else pass the day,
730 * month, year values as array values
731 * Example: $dayParams = array(
732 * 'day' => '25', 'month' => '10',
733 * 'year' => '2007' );
734 *
735 * @param array $dayParams of the day, month, year.
736 * Array of the day, month, year.
737 * values.
738 * @param string $format
739 * Expected date format( default.
740 * format is 2007-12-21 )
741 *
742 * @return string
743 * Return the customized today's date (Y-m-d)
744 */
745 public static function getToday($dayParams = NULL, $format = "Y-m-d") {
746 if (is_null($dayParams) || empty($dayParams)) {
747 $today = date($format);
748 }
749 else {
750 $today = date($format, mktime(0, 0, 0,
751 $dayParams['month'],
752 $dayParams['day'],
753 $dayParams['year']
754 ));
755 }
756
757 return $today;
758 }
759
760 /**
761 * Find whether today's date lies in
762 * the given range
763 *
764 * @param date $startDate
765 * Start date for the range.
766 * @param date $endDate
767 * End date for the range.
768 *
769 * @return bool
770 * true if today's date is in the given date range
771 */
772 public static function getRange($startDate, $endDate) {
773 $today = date("Y-m-d");
774 $mysqlStartDate = self::isoToMysql($startDate);
775 $mysqlEndDate = self::isoToMysql($endDate);
776 $mysqlToday = self::isoToMysql($today);
777
778 if ((isset($mysqlStartDate) && isset($mysqlEndDate)) && (($mysqlToday >= $mysqlStartDate) && ($mysqlToday <= $mysqlEndDate))) {
779 return TRUE;
780 }
781 elseif ((isset($mysqlStartDate) && !isset($mysqlEndDate)) && (($mysqlToday >= $mysqlStartDate))) {
782 return TRUE;
783 }
784 elseif ((!isset($mysqlStartDate) && isset($mysqlEndDate)) && (($mysqlToday <= $mysqlEndDate))) {
785 return TRUE;
786 }
787 return FALSE;
788 }
789
790 /**
791 * Get start date and end from
792 * the given relative term and unit
793 *
794 * @param string $relative Relative format in the format term.unit.
795 * Eg: previous.day
796 *
797 * @param string $from
798 * @param string $to
799 * @param string $fromTime
800 * @param string $toTime
801 *
802 * @return array
803 * start date, end date
804 */
805 public static function getFromTo($relative, $from, $to, $fromTime = NULL, $toTime = '235959') {
806 if ($relative) {
807 list($term, $unit) = explode('.', $relative, 2);
808 $dateRange = self::relativeToAbsolute($term, $unit);
809 $from = substr($dateRange['from'], 0, 8);
810 $to = substr($dateRange['to'], 0, 8);
811 // @todo fix relativeToAbsolute & add tests
812 // relativeToAbsolute returns 8 char date strings
813 // or 14 char date + time strings.
814 // We should use those. However, it turns out to be unreliable.
815 // e.g. this.week does NOT return 235959 for 'from'
816 // so our defaults are more reliable.
817 // Currently relativeToAbsolute only supports 'whole' days so that is ok
818 }
819
820 $from = self::processDate($from, $fromTime);
821 $to = self::processDate($to, $toTime);
822
823 return array($from, $to);
824 }
825
826 /**
827 * Calculate Age in Years if greater than one year else in months.
828 *
829 * @param date $birthDate
830 * Birth Date.
831 *
832 * @return int
833 * array $results contains years or months
834 */
835 static public function calculateAge($birthDate) {
836 $results = array();
837 $formatedBirthDate = CRM_Utils_Date::customFormat($birthDate, '%Y-%m-%d');
838
839 $bDate = explode('-', $formatedBirthDate);
840 $birthYear = $bDate[0];
841 $birthMonth = $bDate[1];
842 $birthDay = $bDate[2];
843 $year_diff = date("Y") - $birthYear;
844
845 // don't calculate age CRM-3143
846 if ($birthYear == '1902') {
847 return $results;
848 }
849
850 switch ($year_diff) {
851 case 1:
852 $month = (12 - $birthMonth) + date("m");
853 if ($month < 12) {
854 if (date("d") < $birthDay) {
855 $month--;
856 }
857 $results['months'] = $month;
858 }
859 elseif ($month == 12 && (date("d") < $birthDay)) {
860 $results['months'] = $month - 1;
861 }
862 else {
863 $results['years'] = $year_diff;
864 }
865 break;
866
867 case 0:
868 $month = date("m") - $birthMonth;
869 $results['months'] = $month;
870 break;
871
872 default:
873 $results['years'] = $year_diff;
874 if ((date("m") < $birthMonth) || (date("m") == $birthMonth) && (date("d") < $birthDay)) {
875 $results['years']--;
876 }
877 }
878
879 return $results;
880 }
881
882 /**
883 * Calculate next payment date according to provided unit & interval
884 *
885 * @param string $unit
886 * Frequency unit like year,month, week etc.
887 *
888 * @param int $interval
889 * Frequency interval.
890 *
891 * @param array $date
892 * Start date of pledge.
893 *
894 * @param bool $dontCareTime
895 *
896 * @return array
897 * contains new date with added interval
898 */
899 public static function intervalAdd($unit, $interval, $date, $dontCareTime = FALSE) {
900 if (is_array($date)) {
901 $hour = CRM_Utils_Array::value('H', $date);
902 $minute = CRM_Utils_Array::value('i', $date);
903 $second = CRM_Utils_Array::value('s', $date);
904 $month = CRM_Utils_Array::value('M', $date);
905 $day = CRM_Utils_Array::value('d', $date);
906 $year = CRM_Utils_Array::value('Y', $date);
907 }
908 else {
909 extract(date_parse($date));
910 }
911 $date = mktime($hour, $minute, $second, $month, $day, $year);
912 switch ($unit) {
913 case 'year':
914 $date = mktime($hour, $minute, $second, $month, $day, $year + $interval);
915 break;
916
917 case 'month':
918 $date = mktime($hour, $minute, $second, $month + $interval, $day, $year);
919 break;
920
921 case 'week':
922 $interval = $interval * 7;
923 $date = mktime($hour, $minute, $second, $month, $day + $interval, $year);
924 break;
925
926 case 'day':
927 $date = mktime($hour, $minute, $second, $month, $day + $interval, $year);
928 break;
929
930 case 'second':
931 $date = mktime($hour, $minute, $second + $interval, $month, $day, $year);
932 break;
933 }
934
935 $scheduleDate = explode("-", date("n-j-Y-H-i-s", $date));
936
937 $date = array();
938 $date['M'] = $scheduleDate[0];
939 $date['d'] = $scheduleDate[1];
940 $date['Y'] = $scheduleDate[2];
941 if ($dontCareTime == FALSE) {
942 $date['H'] = $scheduleDate[3];
943 $date['i'] = $scheduleDate[4];
944 $date['s'] = $scheduleDate[5];
945 }
946 return $date;
947 }
948
949 /**
950 * Get the smarty view presentation mapping for the given format.
951 *
952 * Historically it was decided that where the view format is 'dd/mm/yy' or 'mm/dd/yy'
953 * they should be rendered using a longer date format. This is likely as much to
954 * do with the earlier date widget being unable to handle some formats as usablity.
955 * However, we continue to respect this.
956 *
957 * @param $format
958 * Given format ( eg 'M Y', 'Y M' ).
959 *
960 * @return string|null
961 * Smarty translation of the date format. Null is also valid and is translated
962 * according to the available parts at the smarty layer.
963 */
964 public static function getDateFieldViewFormat($format) {
965 $supportableFormats = array(
966 'mm/dd' => '%B %E%f',
967 'dd-mm' => '%E%f %B',
968 'yy-mm' => '%Y %B',
969 'M yy' => '%b %Y',
970 'yy' => '%Y',
971 'dd/mm/yy' => '%E%f %B %Y',
972 );
973
974 return array_key_exists($format, $supportableFormats) ? $supportableFormats[$format] : self::pickBestSmartyFormat($format);
975 }
976
977 /**
978 * Pick the smarty format from settings that best matches the time string we have.
979 *
980 * For view purposes we historically use the setting that most closely matches the data
981 * in the format from our settings, as opposed to the setting configured for the field.
982 *
983 * @param $format
984 * @return mixed
985 */
986 public static function pickBestSmartyFormat($format) {
987 if (stristr($format, 'h')) {
988 return Civi::settings()->get('dateformatDatetime');
989 }
990 if (stristr($format, 'd') || stristr($format, 'j')) {
991 return Civi::settings()->get('dateformatFull');
992 }
993 if (stristr($format, 'm')) {
994 return Civi::settings()->get('dateformatPartial');
995 }
996 return Civi::settings()->get('dateformatYear');
997 }
998
999 /**
1000 * Map date plugin and actual format that is used by PHP.
1001 *
1002 * @return array
1003 */
1004 public static function datePluginToPHPFormats() {
1005 $dateInputFormats = array(
1006 "mm/dd/yy" => 'm/d/Y',
1007 "dd/mm/yy" => 'd/m/Y',
1008 "yy-mm-dd" => 'Y-m-d',
1009 "dd-mm-yy" => 'd-m-Y',
1010 "dd.mm.yy" => 'd.m.Y',
1011 "M d" => 'M j',
1012 "M d, yy" => 'M j, Y',
1013 "d M yy" => 'j M Y',
1014 "MM d, yy" => 'F j, Y',
1015 "d MM yy" => 'j F Y',
1016 "DD, d MM yy" => 'l, j F Y',
1017 "mm/dd" => 'm/d',
1018 "dd-mm" => 'd-m',
1019 "yy-mm" => 'Y-m',
1020 "M yy" => 'M Y',
1021 "M Y" => 'M Y',
1022 "yy" => 'Y',
1023 );
1024 return $dateInputFormats;
1025 }
1026
1027 /**
1028 * Resolves the given relative time interval into finite time limits.
1029 *
1030 * @param array $relativeTerm
1031 * Relative time frame like this, previous, etc.
1032 * @param int $unit
1033 * Frequency unit like year, month, week etc.
1034 *
1035 * @return array
1036 * start date and end date for the relative time frame
1037 */
1038 public static function relativeToAbsolute($relativeTerm, $unit) {
1039 $now = getdate();
1040 $from = $to = $dateRange = array();
1041 $from['H'] = $from['i'] = $from['s'] = 0;
1042
1043 switch ($unit) {
1044 case 'year':
1045 switch ($relativeTerm) {
1046 case 'this':
1047 $from['d'] = $from['M'] = 1;
1048 $to['d'] = 31;
1049 $to['M'] = 12;
1050 $to['Y'] = $from['Y'] = $now['year'];
1051 break;
1052
1053 case 'previous':
1054 $from['M'] = $from['d'] = 1;
1055 $to['d'] = 31;
1056 $to['M'] = 12;
1057 $to['Y'] = $from['Y'] = $now['year'] - 1;
1058 break;
1059
1060 case 'previous_before':
1061 $from['M'] = $from['d'] = 1;
1062 $to['d'] = 31;
1063 $to['M'] = 12;
1064 $to['Y'] = $from['Y'] = $now['year'] - 2;
1065 break;
1066
1067 case 'previous_2':
1068 $from['M'] = $from['d'] = 1;
1069 $to['d'] = 31;
1070 $to['M'] = 12;
1071 $from['Y'] = $now['year'] - 2;
1072 $to['Y'] = $now['year'] - 1;
1073 break;
1074
1075 case 'earlier':
1076 $to['d'] = 31;
1077 $to['M'] = 12;
1078 $to['Y'] = $now['year'] - 1;
1079 unset($from);
1080 break;
1081
1082 case 'greater':
1083 $from['M'] = $from['d'] = 1;
1084 $from['Y'] = $now['year'];
1085 unset($to);
1086 break;
1087
1088 case 'greater_previous':
1089 $from['d'] = 31;
1090 $from['M'] = 12;
1091 $from['Y'] = $now['year'] - 1;
1092 unset($to);
1093 break;
1094
1095 case 'ending':
1096 $to['d'] = $now['mday'];
1097 $to['M'] = $now['mon'];
1098 $to['Y'] = $now['year'];
1099 $to['H'] = 23;
1100 $to['i'] = $to['s'] = 59;
1101 $from = self::intervalAdd('year', -1, $to);
1102 $from = self::intervalAdd('second', 1, $from);
1103 break;
1104
1105 case 'current':
1106 $from['M'] = $from['d'] = 1;
1107 $from['Y'] = $now['year'];
1108 $to['H'] = 23;
1109 $to['i'] = $to['s'] = 59;
1110 $to['d'] = $now['mday'];
1111 $to['M'] = $now['mon'];
1112 $to['Y'] = $now['year'];
1113 break;
1114
1115 case 'ending_2':
1116 $to['d'] = $now['mday'];
1117 $to['M'] = $now['mon'];
1118 $to['Y'] = $now['year'];
1119 $to['H'] = 23;
1120 $to['i'] = $to['s'] = 59;
1121 $from = self::intervalAdd('year', -2, $to);
1122 $from = self::intervalAdd('second', 1, $from);
1123 break;
1124
1125 case 'ending_3':
1126 $to['d'] = $now['mday'];
1127 $to['M'] = $now['mon'];
1128 $to['Y'] = $now['year'];
1129 $to['H'] = 23;
1130 $to['i'] = $to['s'] = 59;
1131 $from = self::intervalAdd('year', -3, $to);
1132 $from = self::intervalAdd('second', 1, $from);
1133 break;
1134
1135 case 'less':
1136 $to['d'] = 31;
1137 $to['M'] = 12;
1138 $to['Y'] = $now['year'];
1139 unset($from);
1140 break;
1141
1142 case 'next':
1143 $from['M'] = $from['d'] = 1;
1144 $to['d'] = 31;
1145 $to['M'] = 12;
1146 $to['Y'] = $from['Y'] = $now['year'] + 1;
1147 break;
1148
1149 case 'starting':
1150 $from['d'] = $now['mday'];
1151 $from['M'] = $now['mon'];
1152 $from['Y'] = $now['year'];
1153 $to['d'] = $now['mday'] - 1;
1154 $to['M'] = $now['mon'];
1155 $to['Y'] = $now['year'] + 1;
1156 break;
1157 }
1158 break;
1159
1160 case 'fiscal_year':
1161 $config = CRM_Core_Config::singleton();
1162 $from['d'] = $config->fiscalYearStart['d'];
1163 $from['M'] = $config->fiscalYearStart['M'];
1164 $fYear = self::calculateFiscalYear($from['d'], $from['M']);
1165 switch ($relativeTerm) {
1166 case 'this':
1167 $from['Y'] = $fYear;
1168 $fiscalYear = mktime(0, 0, 0, $from['M'], $from['d'] - 1, $from['Y'] + 1);
1169 $fiscalEnd = explode('-', date("Y-m-d", $fiscalYear));
1170
1171 $to['d'] = $fiscalEnd['2'];
1172 $to['M'] = $fiscalEnd['1'];
1173 $to['Y'] = $fiscalEnd['0'];
1174 break;
1175
1176 case 'previous':
1177 $from['Y'] = $fYear - 1;
1178 $fiscalYear = mktime(0, 0, 0, $from['M'], $from['d'] - 1, $from['Y'] + 1);
1179 $fiscalEnd = explode('-', date("Y-m-d", $fiscalYear));
1180 $to['d'] = $fiscalEnd['2'];
1181 $to['M'] = $fiscalEnd['1'];
1182 $to['Y'] = $fiscalEnd['0'];
1183 break;
1184
1185 case 'next':
1186 $from['Y'] = $fYear + 1;
1187 $fiscalYear = mktime(0, 0, 0, $from['M'], $from['d'] - 1, $from['Y'] + 1);
1188 $fiscalEnd = explode('-', date("Y-m-d", $fiscalYear));
1189 $to['d'] = $fiscalEnd['2'];
1190 $to['M'] = $fiscalEnd['1'];
1191 $to['Y'] = $fiscalEnd['0'];
1192 break;
1193 }
1194 break;
1195
1196 case 'quarter':
1197 switch ($relativeTerm) {
1198 case 'this':
1199
1200 $quarter = ceil($now['mon'] / 3);
1201 $from['d'] = 1;
1202 $from['M'] = (3 * $quarter) - 2;
1203 $to['M'] = 3 * $quarter;
1204 $to['Y'] = $from['Y'] = $now['year'];
1205 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $now['year']));
1206 break;
1207
1208 case 'previous':
1209 $difference = 1;
1210 $quarter = ceil($now['mon'] / 3);
1211 $quarter = $quarter - $difference;
1212 $subtractYear = 0;
1213 if ($quarter <= 0) {
1214 $subtractYear = 1;
1215 $quarter += 4;
1216 }
1217 $from['d'] = 1;
1218 $from['M'] = (3 * $quarter) - 2;
1219 $to['M'] = 3 * $quarter;
1220 $to['Y'] = $from['Y'] = $now['year'] - $subtractYear;
1221 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1222 break;
1223
1224 case 'previous_before':
1225 $difference = 2;
1226 $quarter = ceil($now['mon'] / 3);
1227 $quarter = $quarter - $difference;
1228 $subtractYear = 0;
1229 if ($quarter <= 0) {
1230 $subtractYear = 1;
1231 $quarter += 4;
1232 }
1233 $from['d'] = 1;
1234 $from['M'] = (3 * $quarter) - 2;
1235 $to['M'] = 3 * $quarter;
1236 $to['Y'] = $from['Y'] = $now['year'] - $subtractYear;
1237 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1238 break;
1239
1240 case 'previous_2':
1241 $difference = 2;
1242 $quarter = ceil($now['mon'] / 3);
1243 $current_quarter = $quarter;
1244 $quarter = $quarter - $difference;
1245 $subtractYear = 0;
1246 if ($quarter <= 0) {
1247 $subtractYear = 1;
1248 $quarter += 4;
1249 }
1250 $from['d'] = 1;
1251 $from['M'] = (3 * $quarter) - 2;
1252 switch ($current_quarter) {
1253 case 1:
1254 $to['M'] = (4 * $quarter);
1255 break;
1256
1257 case 2:
1258 $to['M'] = (4 * $quarter) + 3;
1259 break;
1260
1261 case 3:
1262 $to['M'] = (4 * $quarter) + 2;
1263 break;
1264
1265 case 4:
1266 $to['M'] = (4 * $quarter) + 1;
1267 break;
1268 }
1269 $to['Y'] = $from['Y'] = $now['year'] - $subtractYear;
1270 if ($to['M'] > 12) {
1271 $to['M'] = 3 * ($quarter - 3);
1272 $to['Y'] = $now['year'];
1273 }
1274 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1275 break;
1276
1277 case 'earlier':
1278 $quarter = ceil($now['mon'] / 3) - 1;
1279 $subtractYear = 0;
1280 if ($quarter <= 0) {
1281 $subtractYear = 1;
1282 $quarter += 4;
1283 }
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 unset($from);
1288 break;
1289
1290 case 'greater':
1291 $quarter = ceil($now['mon'] / 3);
1292 $from['d'] = 1;
1293 $from['M'] = (3 * $quarter) - 2;
1294 $from['Y'] = $now['year'];
1295 unset($to);
1296 break;
1297
1298 case 'greater_previous':
1299 $quarter = ceil($now['mon'] / 3) - 1;
1300 $subtractYear = 0;
1301 if ($quarter <= 0) {
1302 $subtractYear = 1;
1303 $quarter += 4;
1304 }
1305 $from['M'] = 3 * $quarter;
1306 $from['Y'] = $from['Y'] = $now['year'] - $subtractYear;
1307 $from['d'] = date('t', mktime(0, 0, 0, $from['M'], 1, $from['Y']));
1308 unset($to);
1309 break;
1310
1311 case 'ending':
1312 $to['d'] = $now['mday'];
1313 $to['M'] = $now['mon'];
1314 $to['Y'] = $now['year'];
1315 $to['H'] = 23;
1316 $to['i'] = $to['s'] = 59;
1317 $from = self::intervalAdd('day', -90, $to);
1318 $from = self::intervalAdd('second', 1, $from);
1319 break;
1320
1321 case 'current':
1322 $quarter = ceil($now['mon'] / 3);
1323 $from['d'] = 1;
1324 $from['M'] = (3 * $quarter) - 2;
1325 $from['Y'] = $now['year'];
1326 $to['d'] = $now['mday'];
1327 $to['M'] = $now['mon'];
1328 $to['Y'] = $now['year'];
1329 $to['H'] = 23;
1330 $to['i'] = $to['s'] = 59;
1331 break;
1332
1333 case 'less':
1334 $quarter = ceil($now['mon'] / 3);
1335 $to['M'] = 3 * $quarter;
1336 $to['Y'] = $now['year'];
1337 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $now['year']));
1338 unset($from);
1339 break;
1340
1341 case 'next':
1342 $difference = -1;
1343 $subtractYear = 0;
1344 $quarter = ceil($now['mon'] / 3);
1345 $quarter = $quarter - $difference;
1346 // CRM-14550 QA Fix
1347 if ($quarter > 4) {
1348 $now['year'] = $now['year'] + 1;
1349 $quarter = 1;
1350 }
1351 if ($quarter <= 0) {
1352 $subtractYear = 1;
1353 $quarter += 4;
1354 }
1355 $from['d'] = 1;
1356 $from['M'] = (3 * $quarter) - 2;
1357 $to['M'] = 3 * $quarter;
1358 $to['Y'] = $from['Y'] = $now['year'] - $subtractYear;
1359 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1360 break;
1361
1362 case 'starting':
1363 $from['d'] = $now['mday'];
1364 $from['M'] = $now['mon'];
1365 $from['Y'] = $now['year'];
1366 $from['H'] = 00;
1367 $from['i'] = $to['s'] = 00;
1368 $to = self::intervalAdd('day', 90, $from);
1369 $to = self::intervalAdd('second', -1, $to);
1370 break;
1371 }
1372 break;
1373
1374 case 'month':
1375 switch ($relativeTerm) {
1376 case 'this':
1377 $from['d'] = 1;
1378 $to['d'] = date('t', mktime(0, 0, 0, $now['mon'], 1, $now['year']));
1379 $from['M'] = $to['M'] = $now['mon'];
1380 $from['Y'] = $to['Y'] = $now['year'];
1381 break;
1382
1383 case 'previous':
1384 $from['d'] = 1;
1385 if ($now['mon'] == 1) {
1386 $from['M'] = $to['M'] = 12;
1387 $from['Y'] = $to['Y'] = $now['year'] - 1;
1388 }
1389 else {
1390 $from['M'] = $to['M'] = $now['mon'] - 1;
1391 $from['Y'] = $to['Y'] = $now['year'];
1392 }
1393 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1394 break;
1395
1396 case 'previous_before':
1397 $from['d'] = 1;
1398 if ($now['mon'] < 3) {
1399 $from['M'] = $to['M'] = 10 + $now['mon'];
1400 $from['Y'] = $to['Y'] = $now['year'] - 1;
1401 }
1402 else {
1403 $from['M'] = $to['M'] = $now['mon'] - 2;
1404 $from['Y'] = $to['Y'] = $now['year'];
1405 }
1406 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1407 break;
1408
1409 case 'previous_2':
1410 $from['d'] = 1;
1411 if ($now['mon'] < 3) {
1412 $from['M'] = 10 + $now['mon'];
1413 $from['Y'] = $now['year'] - 1;
1414 }
1415 else {
1416 $from['M'] = $now['mon'] - 2;
1417 $from['Y'] = $now['year'];
1418 }
1419
1420 if ($now['mon'] == 1) {
1421 $to['M'] = 12;
1422 $to['Y'] = $now['year'] - 1;
1423 }
1424 else {
1425 $to['M'] = $now['mon'] - 1;
1426 $to['Y'] = $now['year'];
1427 }
1428
1429 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1430 break;
1431
1432 case 'earlier':
1433 // before end of past month
1434 if ($now['mon'] == 1) {
1435 $to['M'] = 12;
1436 $to['Y'] = $now['year'] - 1;
1437 }
1438 else {
1439 $to['M'] = $now['mon'] - 1;
1440 $to['Y'] = $now['year'];
1441 }
1442
1443 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1444 unset($from);
1445 break;
1446
1447 case 'greater':
1448 $from['d'] = 1;
1449 $from['M'] = $now['mon'];;
1450 $from['Y'] = $now['year'];
1451 unset($to);
1452 break;
1453
1454 case 'greater_previous':
1455 // from end of past month
1456 if ($now['mon'] == 1) {
1457 $from['M'] = 12;
1458 $from['Y'] = $now['year'] - 1;
1459 }
1460 else {
1461 $from['M'] = $now['mon'] - 1;
1462 $from['Y'] = $now['year'];
1463 }
1464
1465 $from['d'] = date('t', mktime(0, 0, 0, $from['M'], 1, $from['Y']));
1466 unset($to);
1467 break;
1468
1469 case 'ending_2':
1470 $to['d'] = $now['mday'];
1471 $to['M'] = $now['mon'];
1472 $to['Y'] = $now['year'];
1473 $to['H'] = 23;
1474 $to['i'] = $to['s'] = 59;
1475 $from = self::intervalAdd('day', -60, $to);
1476 $from = self::intervalAdd('second', 1, $from);
1477 break;
1478
1479 case 'ending':
1480 $to['d'] = $now['mday'];
1481 $to['M'] = $now['mon'];
1482 $to['Y'] = $now['year'];
1483 $to['H'] = 23;
1484 $to['i'] = $to['s'] = 59;
1485 $from = self::intervalAdd('day', -30, $to);
1486 $from = self::intervalAdd('second', 1, $from);
1487 break;
1488
1489 case 'current':
1490 $from['d'] = 1;
1491 $from['M'] = $now['mon'];;
1492 $from['Y'] = $now['year'];
1493 $to['d'] = $now['mday'];
1494 $to['M'] = $now['mon'];
1495 $to['Y'] = $now['year'];
1496 $to['H'] = 23;
1497 $to['i'] = $to['s'] = 59;
1498 break;
1499
1500 case 'less':
1501 // CRM-14550 QA Fix
1502 $to['Y'] = $now['year'];
1503 $to['M'] = $now['mon'];
1504 $to['d'] = date('t', mktime(0, 0, 0, $now['mon'], 1, $now['year']));
1505 unset($from);
1506 break;
1507
1508 case 'next':
1509 $from['d'] = 1;
1510 if ($now['mon'] == 12) {
1511 $from['M'] = $to['M'] = 1;
1512 $from['Y'] = $to['Y'] = $now['year'] + 1;
1513 }
1514 else {
1515 $from['M'] = $to['M'] = $now['mon'] + 1;
1516 $from['Y'] = $to['Y'] = $now['year'];
1517 }
1518 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1519 break;
1520
1521 case 'starting':
1522 $from['d'] = $now['mday'];
1523 $from['M'] = $now['mon'];
1524 $from['Y'] = $now['year'];
1525 $from['H'] = 00;
1526 $from['i'] = $to['s'] = 00;
1527 $to = self::intervalAdd('day', 30, $from);
1528 $to = self::intervalAdd('second', -1, $to);
1529 break;
1530
1531 case 'starting_2':
1532 $from['d'] = $now['mday'];
1533 $from['M'] = $now['mon'];
1534 $from['Y'] = $now['year'];
1535 $from['H'] = 00;
1536 $from['i'] = $to['s'] = 00;
1537 $to = self::intervalAdd('day', 60, $from);
1538 $to = self::intervalAdd('second', -1, $to);
1539 break;
1540 }
1541 break;
1542
1543 case 'week':
1544 $weekFirst = Civi::settings()->get('weekBegins');
1545 $thisDay = $now['wday'];
1546 if ($weekFirst > $thisDay) {
1547 $diffDay = $thisDay - $weekFirst + 7;
1548 }
1549 else {
1550 $diffDay = $thisDay - $weekFirst;
1551 }
1552 switch ($relativeTerm) {
1553 case 'this':
1554 $from['d'] = $now['mday'];
1555 $from['M'] = $now['mon'];
1556 $from['Y'] = $now['year'];
1557 $from = self::intervalAdd('day', -1 * ($diffDay), $from);
1558 $to = self::intervalAdd('day', 6, $from);
1559 break;
1560
1561 case 'previous':
1562 $from['d'] = $now['mday'];
1563 $from['M'] = $now['mon'];
1564 $from['Y'] = $now['year'];
1565 $from = self::intervalAdd('day', -1 * ($diffDay) - 7, $from);
1566 $to = self::intervalAdd('day', 6, $from);
1567 break;
1568
1569 case 'previous_before':
1570 $from['d'] = $now['mday'];
1571 $from['M'] = $now['mon'];
1572 $from['Y'] = $now['year'];
1573 $from = self::intervalAdd('day', -1 * ($diffDay) - 14, $from);
1574 $to = self::intervalAdd('day', 6, $from);
1575 break;
1576
1577 case 'previous_2':
1578 $from['d'] = $now['mday'];
1579 $from['M'] = $now['mon'];
1580 $from['Y'] = $now['year'];
1581 $from = self::intervalAdd('day', -1 * ($diffDay) - 14, $from);
1582 $to = self::intervalAdd('day', 13, $from);
1583 break;
1584
1585 case 'earlier':
1586 $to['d'] = $now['mday'];
1587 $to['M'] = $now['mon'];
1588 $to['Y'] = $now['year'];
1589 $to = self::intervalAdd('day', -1 * ($diffDay) - 1, $to);
1590 unset($from);
1591 break;
1592
1593 case 'greater':
1594 $from['d'] = $now['mday'];
1595 $from['M'] = $now['mon'];
1596 $from['Y'] = $now['year'];
1597 $from = self::intervalAdd('day', -1 * ($diffDay), $from);
1598 unset($to);
1599 break;
1600
1601 case 'greater_previous':
1602 $from['d'] = $now['mday'];
1603 $from['M'] = $now['mon'];
1604 $from['Y'] = $now['year'];
1605 $from = self::intervalAdd('day', -1 * ($diffDay) - 1, $from);
1606 unset($to);
1607 break;
1608
1609 case 'ending':
1610 $to['d'] = $now['mday'];
1611 $to['M'] = $now['mon'];
1612 $to['Y'] = $now['year'];
1613 $to['H'] = 23;
1614 $to['i'] = $to['s'] = 59;
1615 $from = self::intervalAdd('day', -7, $to);
1616 $from = self::intervalAdd('second', 1, $from);
1617 break;
1618
1619 case 'current':
1620 $from['d'] = $now['mday'];
1621 $from['M'] = $now['mon'];
1622 $from['Y'] = $now['year'];
1623 $from = self::intervalAdd('day', -1 * ($diffDay), $from);
1624 $to['d'] = $now['mday'];
1625 $to['M'] = $now['mon'];
1626 $to['Y'] = $now['year'];
1627 $to['H'] = 23;
1628 $to['i'] = $to['s'] = 59;
1629 break;
1630
1631 case 'less':
1632 $to['d'] = $now['mday'];
1633 $to['M'] = $now['mon'];
1634 $to['Y'] = $now['year'];
1635 // CRM-14550 QA Fix
1636 $to = self::intervalAdd('day', -1 * ($diffDay) + 6, $to);
1637 unset($from);
1638 break;
1639
1640 case 'next':
1641 $from['d'] = $now['mday'];
1642 $from['M'] = $now['mon'];
1643 $from['Y'] = $now['year'];
1644 $from = self::intervalAdd('day', -1 * ($diffDay) + 7, $from);
1645 $to = self::intervalAdd('day', 6, $from);
1646 break;
1647
1648 case 'starting':
1649 $from['d'] = $now['mday'];
1650 $from['M'] = $now['mon'];
1651 $from['Y'] = $now['year'];
1652 $from['H'] = 00;
1653 $from['i'] = $to['s'] = 00;
1654 $to = self::intervalAdd('day', 7, $from);
1655 $to = self::intervalAdd('second', -1, $to);
1656 break;
1657 }
1658 break;
1659
1660 case 'day':
1661 switch ($relativeTerm) {
1662 case 'this':
1663 $from['d'] = $to['d'] = $now['mday'];
1664 $from['M'] = $to['M'] = $now['mon'];
1665 $from['Y'] = $to['Y'] = $now['year'];
1666 break;
1667
1668 case 'previous':
1669 $from['d'] = $now['mday'];
1670 $from['M'] = $now['mon'];
1671 $from['Y'] = $now['year'];
1672 $from = self::intervalAdd('day', -1, $from);
1673 $to['d'] = $from['d'];
1674 $to['M'] = $from['M'];
1675 $to['Y'] = $from['Y'];
1676 break;
1677
1678 case 'previous_before':
1679 $from['d'] = $now['mday'];
1680 $from['M'] = $now['mon'];
1681 $from['Y'] = $now['year'];
1682 $from = self::intervalAdd('day', -2, $from);
1683 $to['d'] = $from['d'];
1684 $to['M'] = $from['M'];
1685 $to['Y'] = $from['Y'];
1686 break;
1687
1688 case 'previous_2':
1689 $from['d'] = $to['d'] = $now['mday'];
1690 $from['M'] = $to['M'] = $now['mon'];
1691 $from['Y'] = $to['Y'] = $now['year'];
1692 $from = self::intervalAdd('day', -2, $from);
1693 $to = self::intervalAdd('day', -1, $to);
1694 break;
1695
1696 case 'earlier':
1697 $to['d'] = $now['mday'];
1698 $to['M'] = $now['mon'];
1699 $to['Y'] = $now['year'];
1700 unset($from);
1701 break;
1702
1703 case 'greater':
1704 $from['d'] = $now['mday'];
1705 $from['M'] = $now['mon'];;
1706 $from['Y'] = $now['year'];
1707 unset($to);
1708 break;
1709
1710 case 'starting':
1711 $to['d'] = $now['mday'];
1712 $to['M'] = $now['mon'];
1713 $to['Y'] = $now['year'];
1714 $to = self::intervalAdd('day', 1, $to);
1715 $from['d'] = $to['d'];
1716 $from['M'] = $to['M'];
1717 $from['Y'] = $to['Y'];
1718 break;
1719
1720 }
1721 break;
1722 }
1723
1724 foreach (array(
1725 'from',
1726 'to',
1727 ) as $item) {
1728 if (!empty($$item)) {
1729 $dateRange[$item] = self::format($$item);
1730 }
1731 else {
1732 $dateRange[$item] = NULL;
1733 }
1734 }
1735 return $dateRange;
1736 }
1737
1738 /**
1739 * Calculate current fiscal year based on the fiscal month and day.
1740 *
1741 * @param int $fyDate
1742 * Fiscal start date.
1743 *
1744 * @param int $fyMonth
1745 * Fiscal Start Month.
1746 *
1747 * @return int
1748 * $fy Current Fiscl Year
1749 */
1750 public static function calculateFiscalYear($fyDate, $fyMonth) {
1751 $date = date("Y-m-d");
1752 $currentYear = date("Y");
1753
1754 // recalculate the date because month 4::04 make the difference
1755 $fiscalYear = explode('-', date("Y-m-d", mktime(0, 0, 0, $fyMonth, $fyDate, $currentYear)));
1756 $fyDate = $fiscalYear[2];
1757 $fyMonth = $fiscalYear[1];
1758 $fyStartDate = date("Y-m-d", mktime(0, 0, 0, $fyMonth, $fyDate, $currentYear));
1759
1760 if ($fyStartDate > $date) {
1761 $fy = intval(intval($currentYear) - 1);
1762 }
1763 else {
1764 $fy = intval($currentYear);
1765 }
1766 return $fy;
1767 }
1768
1769 /**
1770 * Function to process date, convert to mysql format
1771 *
1772 * @param string $date
1773 * Date string.
1774 * @param string $time
1775 * Time string.
1776 * @param bool|string $returnNullString 'null' needs to be returned
1777 * so that db oject will set null in db
1778 * @param string $format
1779 * Expected return date format.( default is mysql ).
1780 *
1781 * @return string
1782 * date format that is excepted by mysql
1783 */
1784 public static function processDate($date, $time = NULL, $returnNullString = FALSE, $format = 'YmdHis') {
1785 $mysqlDate = NULL;
1786
1787 if ($returnNullString) {
1788 $mysqlDate = 'null';
1789 }
1790
1791 if (trim($date)) {
1792 $mysqlDate = date($format, strtotime($date . ' ' . $time));
1793 }
1794
1795 return $mysqlDate;
1796 }
1797
1798 /**
1799 * Add the metadata about a date field to the field.
1800 *
1801 * This metadata will work with the call $form->add('datepicker', ...
1802 *
1803 * @param array $fieldMetaData
1804 * @param array $field
1805 *
1806 * @return array
1807 */
1808 public static function addDateMetadataToField($fieldMetaData, $field) {
1809 if (isset($fieldMetaData['html'])) {
1810 $field['html_type'] = $fieldMetaData['html']['type'];
1811 if ($field['html_type'] === 'Select Date') {
1812 if (!isset($field['date_format'])) {
1813 $dateAttributes = CRM_Core_SelectValues::date($fieldMetaData['html']['formatType'], NULL, NULL, NULL, 'Input');
1814 $field['start_date_years'] = $dateAttributes['minYear'];
1815 $field['end_date_years'] = $dateAttributes['maxYear'];
1816 $field['date_format'] = $dateAttributes['format'];
1817 $field['is_datetime_field'] = TRUE;
1818 $field['time_format'] = $dateAttributes['time'];
1819 $field['smarty_view_format'] = $dateAttributes['smarty_view_format'];
1820 }
1821 $field['datepicker']['extra'] = self::getDatePickerExtra($field);
1822 $field['datepicker']['attributes'] = self::getDatePickerAttributes($field);
1823 }
1824 }
1825 return $field;
1826 }
1827
1828
1829 /**
1830 * Get the fields required for the 'extra' parameter when adding a datepicker.
1831 *
1832 * @param array $field
1833 *
1834 * @return array
1835 */
1836 public static function getDatePickerExtra($field) {
1837 $extra = array();
1838 if (isset($field['date_format'])) {
1839 $extra['date'] = $field['date_format'];
1840 $extra['time'] = $field['time_format'];
1841 }
1842 $thisYear = date('Y');
1843 if (isset($field['start_date_years'])) {
1844 $extra['minDate'] = date('Y-m-d', strtotime('-' . ($thisYear - $field['start_date_years']) . ' years'));
1845 }
1846 if (isset($field['end_date_years'])) {
1847 $extra['maxDate'] = date('Y-m-d', strtotime('-' . ($thisYear - $field['end_date_years']) . ' years'));
1848 }
1849 return $extra;
1850 }
1851
1852 /**
1853 * Get the attributes parameters required for datepicker.
1854 *
1855 * @param array $field
1856 * Field metadata
1857 *
1858 * @return array
1859 * Array ready to pass to $this->addForm('datepicker' as attributes.
1860 */
1861 public static function getDatePickerAttributes(&$field) {
1862 $attributes = array();
1863 $dateAttributes = array(
1864 'start_date_years' => 'minYear',
1865 'end_date_years' => 'maxYear',
1866 'date_format' => 'format',
1867 );
1868 foreach ($dateAttributes as $dateAttribute => $mapTo) {
1869 if (isset($field[$dateAttribute])) {
1870 $attributes[$mapTo] = $field[$dateAttribute];
1871 }
1872 }
1873 return $attributes;
1874 }
1875
1876 /**
1877 * Function to convert mysql to date plugin format.
1878 *
1879 * @param string $mysqlDate
1880 * Date string.
1881 *
1882 * @param null $formatType
1883 * @param null $format
1884 * @param null $timeFormat
1885 *
1886 * @return array
1887 * and time
1888 */
1889 public static function setDateDefaults($mysqlDate = NULL, $formatType = NULL, $format = NULL, $timeFormat = NULL) {
1890 // if date is not passed assume it as today
1891 if (!$mysqlDate) {
1892 $mysqlDate = date('Y-m-d G:i:s');
1893 }
1894
1895 $config = CRM_Core_Config::singleton();
1896 if ($formatType) {
1897 // get actual format
1898 $params = array('name' => $formatType);
1899 $values = array();
1900 CRM_Core_DAO::commonRetrieve('CRM_Core_DAO_PreferencesDate', $params, $values);
1901
1902 if ($values['date_format']) {
1903 $format = $values['date_format'];
1904 }
1905
1906 if (isset($values['time_format'])) {
1907 $timeFormat = $values['time_format'];
1908 }
1909 }
1910
1911 // now we set display date using js, hence we should always setdefault
1912 // 'm/d/Y' format. So that submitted value is alwats mm/dd/YY format
1913 // note that for date display we dynamically create text field
1914 /*
1915 if ( !$format ) {
1916 $format = $config->dateInputFormat;
1917 }
1918
1919 // get actual format
1920 $actualPHPFormats = CRM_Core_SelectValues::datePluginToPHPFormats( );
1921 $dateFormat = CRM_Utils_Array::value( $format, $actualPHPFormats );
1922 */
1923
1924 $dateFormat = 'm/d/Y';
1925 $date = date($dateFormat, strtotime($mysqlDate));
1926
1927 if (!$timeFormat) {
1928 $timeFormat = $config->timeInputFormat;
1929 }
1930
1931 $actualTimeFormat = "g:iA";
1932 $appendZeroLength = 7;
1933 if ($timeFormat > 1) {
1934 $actualTimeFormat = "G:i";
1935 $appendZeroLength = 5;
1936 }
1937
1938 $time = date($actualTimeFormat, strtotime($mysqlDate));
1939
1940 // need to append zero for hours < 10
1941 if (strlen($time) < $appendZeroLength) {
1942 $time = '0' . $time;
1943 }
1944
1945 return array($date, $time);
1946 }
1947
1948 /**
1949 * Function get date format.
1950 *
1951 * @param string $formatType
1952 * Date name e.g. birth.
1953 *
1954 * @return string
1955 */
1956 public static function getDateFormat($formatType = NULL) {
1957 $format = NULL;
1958 if ($formatType) {
1959 $format = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_PreferencesDate',
1960 $formatType, 'date_format', 'name'
1961 );
1962 }
1963
1964 if (!$format) {
1965 $config = CRM_Core_Config::singleton();
1966 $format = $config->dateInputFormat;
1967 }
1968 return $format;
1969 }
1970
1971 /**
1972 * @param $date
1973 * @param $dateType
1974 *
1975 * @return null|string
1976 */
1977 public static function formatDate($date, $dateType) {
1978 $formattedDate = NULL;
1979 if (empty($date)) {
1980 return $formattedDate;
1981 }
1982
1983 // 1. first convert date to default format.
1984 // 2. append time to default formatted date (might be removed during format)
1985 // 3. validate date / date time.
1986 // 4. If date and time then convert to default date time format.
1987
1988 $dateKey = 'date';
1989 $dateParams = array($dateKey => $date);
1990
1991 if (CRM_Utils_Date::convertToDefaultDate($dateParams, $dateType, $dateKey)) {
1992 $dateVal = $dateParams[$dateKey];
1993 $ruleName = 'date';
1994 if ($dateType == 1) {
1995 $matches = array();
1996 if (preg_match("/(\s(([01]\d)|[2][0-3]):([0-5]\d))$/", $date, $matches)) {
1997 $ruleName = 'dateTime';
1998 if (strpos($date, '-') !== FALSE) {
1999 $dateVal .= array_shift($matches);
2000 }
2001 }
2002 }
2003
2004 // validate date.
2005 $valid = CRM_Utils_Rule::$ruleName($dateVal);
2006
2007 if ($valid) {
2008 // format date and time to default.
2009 if ($ruleName == 'dateTime') {
2010 $dateVal = CRM_Utils_Date::customFormat(preg_replace("/(:|\s)?/", "", $dateVal), '%Y%m%d%H%i');
2011 // hack to add seconds
2012 $dateVal .= '00';
2013 }
2014 $formattedDate = $dateVal;
2015 }
2016 }
2017
2018 return $formattedDate;
2019 }
2020
2021 /**
2022 * Function to return days of the month.
2023 *
2024 * @return array
2025 */
2026 public static function getCalendarDayOfMonth() {
2027 $month = array();
2028 for ($i = 1; $i <= 31; $i++) {
2029 $month[$i] = $i;
2030 if ($i == 31) {
2031 $month[$i] = $i . ' / Last day of month';
2032 }
2033 }
2034 return $month;
2035 }
2036
2037 }