Merge pull request #13258 from eileenmcnaughton/isam
[civicrm-core.git] / CRM / Utils / Date.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
fee14197 4 | CiviCRM version 5 |
6a488035 5 +--------------------------------------------------------------------+
8c9251b3 6 | Copyright CiviCRM LLC (c) 2004-2018 |
6a488035
TO
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 +--------------------------------------------------------------------+
e70a7fc0 26 */
6a488035
TO
27
28/**
29 *
30 * @package CRM
8c9251b3 31 * @copyright CiviCRM LLC (c) 2004-2018
6a488035
TO
32 */
33
34/**
35 * Date utilties
36 */
37class CRM_Utils_Date {
38
39 /**
100fef9d 40 * Format a date by padding it with leading '0'.
6a488035 41 *
77855840
TO
42 * @param array $date
43 * ('Y', 'M', 'd').
44 * @param string $separator
45 * The seperator to use when formatting the date.
f4aaa82a 46 * @param int|string $invalidDate what to return if the date is invalid
6a488035 47 *
a6c01b45
CW
48 * @return string
49 * formatted string for date
6a488035 50 */
00be9182 51 public static function format($date, $separator = '', $invalidDate = 0) {
6a488035
TO
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
a7488080 77 if (!empty($date['M'])) {
6a488035
TO
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
a7488080 87 if (!empty($date['d'])) {
6a488035
TO
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..
a7488080 108 if (!empty($date['h'])) {
6a488035
TO
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
a7488080 127 if (!empty($date['H'])) {
6a488035
TO
128 $date['H'] = (int) $date['H'];
129 }
130 else {
131 $date['H'] = 0;
132 }
133
a7488080 134 if (!empty($date['i'])) {
6a488035
TO
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
a7488080 145 if (!empty($date['s'])) {
6a488035
TO
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 /**
fe482240 166 * Return abbreviated weekday names according to the locale.
6a488035 167 *
1ef73b88
CW
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 *
a6c01b45
CW
174 * @return array
175 * 0-based array with abbreviated weekday names
6a488035 176 *
6a488035 177 */
1ef73b88
CW
178 public static function getAbbrWeekdayNames() {
179 static $days = array();
180 if (!$days) {
181 // First day of the week
aaffa79f 182 $firstDay = Civi::settings()->get('weekBegins');
6a488035
TO
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();
41ff54d3 187 for ($i = $firstDay; count($days) < 7; $i = $i > 5 ? 0 : $i + 1) {
1ef73b88 188 $days[$i] = strftime('%a', mktime(0, 0, 0, 6, $i, 1970));
6a488035
TO
189 }
190 }
1ef73b88 191 return $days;
6a488035
TO
192 }
193
194 /**
fe482240 195 * Return full weekday names according to the locale.
6a488035 196 *
1ef73b88
CW
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 *
a6c01b45
CW
203 * @return array
204 * 0-based array with full weekday names
6a488035 205 *
6a488035 206 */
1ef73b88
CW
207 public static function getFullWeekdayNames() {
208 static $days = array();
209 if (!$days) {
210 // First day of the week
aaffa79f 211 $firstDay = Civi::settings()->get('weekBegins');
6a488035
TO
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();
41ff54d3 216 for ($i = $firstDay; count($days) < 7; $i = $i > 5 ? 0 : $i + 1) {
1ef73b88 217 $days[$i] = strftime('%A', mktime(0, 0, 0, 6, $i, 1970));
6a488035
TO
218 }
219 }
1ef73b88 220 return $days;
6a488035
TO
221 }
222
223 /**
fe482240 224 * Return abbreviated month names according to the locale.
6a488035 225 *
f4aaa82a
EM
226 * @param bool $month
227 *
a6c01b45
CW
228 * @return array
229 * 1-based array with abbreviated month names
6a488035 230 *
6a488035 231 */
00be9182 232 public static function &getAbbrMonthNames($month = FALSE) {
6a488035
TO
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 /**
fe482240 249 * Return full month names according to the locale.
6a488035 250 *
a6c01b45
CW
251 * @return array
252 * 1-based array with full month names
6a488035 253 *
6a488035 254 */
00be9182 255 public static function &getFullMonthNames() {
6a488035
TO
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
5bc392e6
EM
268 /**
269 * @param $string
270 *
271 * @return int
272 */
00be9182 273 public static function unixTime($string) {
6a488035
TO
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 /**
fe482240 288 * Create a date and time string in a provided format.
6a488035
TO
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 *
77855840
TO
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.
6a488035 312 *
a6c01b45
CW
313 * @return string
314 * the $format-formatted $date
6a488035 315 */
00be9182 316 public static function customFormat($dateString, $format = NULL, $dateParts = NULL) {
6a488035
TO
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
35fa23f8 363 if (!CRM_Utils_System::isNull($dateString)) {
6a488035 364 if (strpos($dateString, '-')) {
353ffa53 365 $year = (int) substr($dateString, 0, 4);
6a488035 366 $month = (int) substr($dateString, 5, 2);
353ffa53 367 $day = (int) substr($dateString, 8, 2);
6a488035
TO
368
369 $hour24 = (int) substr($dateString, 11, 2);
370 $minute = (int) substr($dateString, 14, 2);
371 }
372 else {
353ffa53 373 $year = (int) substr($dateString, 0, 4);
6a488035 374 $month = (int) substr($dateString, 4, 2);
353ffa53 375 $day = (int) substr($dateString, 6, 2);
6a488035
TO
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
d2f262da
AS
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
6a488035 458 /**
100fef9d 459 * Converts the date/datetime from MySQL format to ISO format
6a488035 460 *
77855840
TO
461 * @param string $mysql
462 * Date/datetime in MySQL format.
6a488035 463 *
a6c01b45
CW
464 * @return string
465 * date/datetime in ISO format
6a488035 466 */
00be9182 467 public static function mysqlToIso($mysql) {
353ffa53
TO
468 $year = substr($mysql, 0, 4);
469 $month = substr($mysql, 4, 2);
470 $day = substr($mysql, 6, 2);
471 $hour = substr($mysql, 8, 2);
6a488035
TO
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 /**
100fef9d 499 * Converts the date/datetime from ISO format to MySQL format
5d9f6898
EM
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
6a488035 503 *
77855840
TO
504 * @param string $iso
505 * Date/datetime in ISO format.
6a488035 506 *
a6c01b45
CW
507 * @return string
508 * date/datetime in MySQL format
6a488035 509 */
00be9182 510 public static function isoToMysql($iso) {
6a488035
TO
511 $dropArray = array('-' => '', ':' => '', ' ' => '');
512 return strtr($iso, $dropArray);
513 }
514
515 /**
100fef9d 516 * Converts the any given date to default date format.
6a488035 517 *
77855840
TO
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.
f4aaa82a
EM
524 *
525 * @return bool
6a488035 526 */
00be9182 527 public static function convertToDefaultDate(&$params, $dateType, $dateParam) {
353ffa53
TO
528 $now = getdate();
529 $cen = substr($now['year'], 0, 2);
6a488035
TO
530 $prevCen = $cen - 1;
531
532 $value = NULL;
a7488080 533 if (!empty($params[$dateParam])) {
6a488035
TO
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) {
353ffa53 579 $year = (int) $formattedDate[0];
6a488035 580 $month = (int) $formattedDate[1];
353ffa53 581 $day = (int) $formattedDate[2];
6a488035
TO
582 }
583 elseif (count($formattedDate) == 1 && (strlen($value) == 8)) {
584 return TRUE;
585 }
586 else {
587 return FALSE;
588 }
589 }
590
6a488035
TO
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) {
353ffa53 597 $year = (int) $formattedDate[2];
6a488035 598 $month = (int) $formattedDate[0];
353ffa53 599 $day = (int) $formattedDate[1];
6a488035
TO
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 }
353ffa53
TO
627 $year = (int) $dateArray[2];
628 $day = (int) $dateArray[1];
6a488035
TO
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
353ffa53
TO
659 $year = (int) $dateArray[2];
660 $day = (int) $dateArray[0];
6a488035
TO
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) {
353ffa53 670 $year = (int) $formattedDate[2];
6a488035 671 $month = (int) $formattedDate[1];
353ffa53 672 $day = (int) $formattedDate[0];
6a488035
TO
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 }
50bfb460 696 // if month is invalid return as error
6a488035
TO
697 if ($month !== '00' && $month <= 12) {
698 return TRUE;
699 }
700 return FALSE;
701 }
702
5bc392e6
EM
703 /**
704 * @param $date
705 *
706 * @return bool
707 */
00be9182 708 public static function isDate(&$date) {
6a488035
TO
709 if (CRM_Utils_System::isNull($date)) {
710 return FALSE;
711 }
712 return TRUE;
713 }
714
e73e7ec8
TO
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
5bc392e6
EM
767 /**
768 * @param null $timeStamp
769 *
770 * @return bool|string
771 */
00be9182 772 public static function currentDBDate($timeStamp = NULL) {
6a488035
TO
773 return $timeStamp ? date('YmdHis', $timeStamp) : date('YmdHis');
774 }
775
5bc392e6
EM
776 /**
777 * @param $date
778 * @param null $now
779 *
780 * @return bool
781 */
00be9182 782 public static function overdue($date, $now = NULL) {
6a488035
TO
783 $mysqlDate = self::isoToMysql($date);
784 if (!$now) {
785 $now = self::currentDBDate();
786 }
787 else {
788 $now = self::isoToMysql($now);
789 }
790
ff25152a 791 return (strtotime($mysqlDate) >= strtotime($now)) ? FALSE : TRUE;
6a488035
TO
792 }
793
794 /**
fe482240 795 * Get customized today.
6a488035
TO
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(
353ffa53 801 * 'day' => '25', 'month' => '10',
6a488035
TO
802 * 'year' => '2007' );
803 *
d5cc0fc2 804 * @param array $dayParams of the day, month, year.
77855840 805 * Array of the day, month, year.
6a488035 806 * values.
77855840
TO
807 * @param string $format
808 * Expected date format( default.
6a488035
TO
809 * format is 2007-12-21 )
810 *
a6c01b45 811 * @return string
b44e3f84 812 * Return the customized today's date (Y-m-d)
6a488035 813 */
00be9182 814 public static function getToday($dayParams = NULL, $format = "Y-m-d") {
6a488035
TO
815 if (is_null($dayParams) || empty($dayParams)) {
816 $today = date($format);
817 }
818 else {
819 $today = date($format, mktime(0, 0, 0,
353ffa53
TO
820 $dayParams['month'],
821 $dayParams['day'],
822 $dayParams['year']
823 ));
6a488035
TO
824 }
825
826 return $today;
827 }
828
829 /**
100fef9d 830 * Find whether today's date lies in
6a488035
TO
831 * the given range
832 *
77855840
TO
833 * @param date $startDate
834 * Start date for the range.
835 * @param date $endDate
836 * End date for the range.
6a488035 837 *
72b3a70c
CW
838 * @return bool
839 * true if today's date is in the given date range
6a488035 840 */
00be9182 841 public static function getRange($startDate, $endDate) {
353ffa53 842 $today = date("Y-m-d");
6a488035 843 $mysqlStartDate = self::isoToMysql($startDate);
353ffa53
TO
844 $mysqlEndDate = self::isoToMysql($endDate);
845 $mysqlToday = self::isoToMysql($today);
6a488035
TO
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 /**
100fef9d 860 * Get start date and end from
6a488035
TO
861 * the given relative term and unit
862 *
7ec58d2b
J
863 * @param string $relative Relative format in the format term.unit.
864 * Eg: previous.day
f4aaa82a 865 *
819e6707
J
866 * @param string $from
867 * @param string $to
868 * @param string $fromTime
869 * @param string $toTime
6a488035 870 *
a6c01b45
CW
871 * @return array
872 * start date, end date
6a488035 873 */
819e6707 874 public static function getFromTo($relative, $from, $to, $fromTime = NULL, $toTime = '235959') {
6a488035 875 if ($relative) {
819e6707 876 list($term, $unit) = explode('.', $relative, 2);
6a488035 877 $dateRange = self::relativeToAbsolute($term, $unit);
819e6707 878 $from = substr($dateRange['from'], 0, 8);
6a488035 879 $to = substr($dateRange['to'], 0, 8);
7ec58d2b
J
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
6a488035
TO
887 }
888
819e6707
J
889 $from = self::processDate($from, $fromTime);
890 $to = self::processDate($to, $toTime);
6a488035
TO
891
892 return array($from, $to);
893 }
894
895 /**
fe482240 896 * Calculate Age in Years if greater than one year else in months.
6a488035 897 *
77855840
TO
898 * @param date $birthDate
899 * Birth Date.
6a488035 900 *
a6c01b45
CW
901 * @return int
902 * array $results contains years or months
6a488035
TO
903 */
904 static public function calculateAge($birthDate) {
905 $results = array();
906 $formatedBirthDate = CRM_Utils_Date::customFormat($birthDate, '%Y-%m-%d');
907
353ffa53
TO
908 $bDate = explode('-', $formatedBirthDate);
909 $birthYear = $bDate[0];
6a488035 910 $birthMonth = $bDate[1];
353ffa53
TO
911 $birthDay = $bDate[2];
912 $year_diff = date("Y") - $birthYear;
6a488035
TO
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 /**
100fef9d 952 * Calculate next payment date according to provided unit & interval
6a488035 953 *
77855840
TO
954 * @param string $unit
955 * Frequency unit like year,month, week etc.
6a488035 956 *
77855840
TO
957 * @param int $interval
958 * Frequency interval.
6a488035 959 *
77855840
TO
960 * @param array $date
961 * Start date of pledge.
f4aaa82a
EM
962 *
963 * @param bool $dontCareTime
6a488035 964 *
a6c01b45
CW
965 * @return array
966 * contains new date with added interval
6a488035 967 */
00be9182 968 public static function intervalAdd($unit, $interval, $date, $dontCareTime = FALSE) {
6a488035 969 if (is_array($date)) {
353ffa53 970 $hour = CRM_Utils_Array::value('H', $date);
6a488035
TO
971 $minute = CRM_Utils_Array::value('i', $date);
972 $second = CRM_Utils_Array::value('s', $date);
353ffa53
TO
973 $month = CRM_Utils_Array::value('M', $date);
974 $day = CRM_Utils_Array::value('d', $date);
975 $year = CRM_Utils_Array::value('Y', $date);
6a488035
TO
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
353ffa53 1006 $date = array();
6a488035
TO
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 /**
ed0ca248 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.
6a488035 1025 *
77855840
TO
1026 * @param $format
1027 * Given format ( eg 'M Y', 'Y M' ).
f4aaa82a 1028 *
ed0ca248 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.
6a488035 1032 */
ed0ca248 1033 public static function getDateFieldViewFormat($format) {
6a488035
TO
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
ed0ca248 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');
6a488035 1064 }
ed0ca248 1065 return Civi::settings()->get('dateformatYear');
1066 }
6a488035 1067
ed0ca248 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',
2732685b 1090 "M Y" => 'M Y',
ed0ca248 1091 "yy" => 'Y',
1092 );
1093 return $dateInputFormats;
6a488035
TO
1094 }
1095
1096 /**
fe482240 1097 * Resolves the given relative time interval into finite time limits.
6a488035 1098 *
1e60a380 1099 * @param string $relativeTerm
1100 * Relative time frame: this, previous, previous_1.
77855840
TO
1101 * @param int $unit
1102 * Frequency unit like year, month, week etc.
6a488035 1103 *
a6c01b45
CW
1104 * @return array
1105 * start date and end date for the relative time frame
6a488035 1106 */
00be9182 1107 public static function relativeToAbsolute($relativeTerm, $unit) {
353ffa53
TO
1108 $now = getdate();
1109 $from = $to = $dateRange = array();
6a488035 1110 $from['H'] = $from['i'] = $from['s'] = 0;
1e60a380 1111 $relativeTermParts = explode('_', $relativeTerm);
1112 $relativeTermPrefix = $relativeTermParts[0];
1113 $relativeTermSuffix = isset($relativeTermParts[1]) ? $relativeTermParts[1] : '';
6a488035
TO
1114
1115 switch ($unit) {
1116 case 'year':
1117 switch ($relativeTerm) {
1118 case 'this':
1119 $from['d'] = $from['M'] = 1;
353ffa53
TO
1120 $to['d'] = 31;
1121 $to['M'] = 12;
1122 $to['Y'] = $from['Y'] = $now['year'];
6a488035
TO
1123 break;
1124
1125 case 'previous':
1126 $from['M'] = $from['d'] = 1;
353ffa53
TO
1127 $to['d'] = 31;
1128 $to['M'] = 12;
1129 $to['Y'] = $from['Y'] = $now['year'] - 1;
6a488035
TO
1130 break;
1131
1132 case 'previous_before':
1133 $from['M'] = $from['d'] = 1;
353ffa53
TO
1134 $to['d'] = 31;
1135 $to['M'] = 12;
1136 $to['Y'] = $from['Y'] = $now['year'] - 2;
6a488035
TO
1137 break;
1138
1139 case 'previous_2':
1140 $from['M'] = $from['d'] = 1;
353ffa53
TO
1141 $to['d'] = 31;
1142 $to['M'] = 12;
6a488035 1143 $from['Y'] = $now['year'] - 2;
353ffa53 1144 $to['Y'] = $now['year'] - 1;
6a488035
TO
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
52f15bd6 1160 case 'greater_previous':
1161 $from['d'] = 31;
1162 $from['M'] = 12;
1163 $from['Y'] = $now['year'] - 1;
1164 unset($to);
1165 break;
1166
6a488035
TO
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;
353ffa53
TO
1173 $from = self::intervalAdd('year', -1, $to);
1174 $from = self::intervalAdd('second', 1, $from);
6a488035 1175 break;
e902edd1 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;
e2c3163d 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;
353ffa53
TO
1193 $from = self::intervalAdd('year', -2, $to);
1194 $from = self::intervalAdd('second', 1, $from);
e2c3163d 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;
353ffa53
TO
1203 $from = self::intervalAdd('year', -3, $to);
1204 $from = self::intervalAdd('second', 1, $from);
e2c3163d 1205 break;
c5670e9e 1206
1207 case 'less':
353ffa53
TO
1208 $to['d'] = 31;
1209 $to['M'] = 12;
1210 $to['Y'] = $now['year'];
c5670e9e 1211 unset($from);
1212 break;
1213
1214 case 'next':
1215 $from['M'] = $from['d'] = 1;
353ffa53
TO
1216 $to['d'] = 31;
1217 $to['M'] = 12;
1218 $to['Y'] = $from['Y'] = $now['year'] + 1;
c5670e9e 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;
ad336d61 1229
1230 default:
1231 if ($relativeTermPrefix === 'ending') {
1232 $to['d'] = $now['mday'];
1233 $to['M'] = $now['mon'];
1234 $to['Y'] = $now['year'];
1235 $to['H'] = 23;
1236 $to['i'] = $to['s'] = 59;
1237 $from = self::intervalAdd('year', -$relativeTermSuffix, $to);
1238 $from = self::intervalAdd('second', 1, $from);
1239 }
6a488035
TO
1240 }
1241 break;
1242
1243 case 'fiscal_year':
353ffa53 1244 $config = CRM_Core_Config::singleton();
6a488035
TO
1245 $from['d'] = $config->fiscalYearStart['d'];
1246 $from['M'] = $config->fiscalYearStart['M'];
353ffa53 1247 $fYear = self::calculateFiscalYear($from['d'], $from['M']);
1e60a380 1248 switch ($relativeTermPrefix) {
6a488035 1249 case 'this':
353ffa53 1250 $from['Y'] = $fYear;
5eb3092f 1251 $fiscalYear = mktime(0, 0, 0, $from['M'], $from['d'] - 1, $from['Y'] + 1);
353ffa53 1252 $fiscalEnd = explode('-', date("Y-m-d", $fiscalYear));
6a488035
TO
1253
1254 $to['d'] = $fiscalEnd['2'];
1255 $to['M'] = $fiscalEnd['1'];
1256 $to['Y'] = $fiscalEnd['0'];
1257 break;
1258
1259 case 'previous':
1e60a380 1260 if (!is_numeric($relativeTermSuffix)) {
1261 $from['Y'] = ($relativeTermSuffix === 'before') ? $fYear - 2 : $fYear - 1;
1262 $fiscalYear = mktime(0, 0, 0, $from['M'], $from['d'] - 1, $from['Y'] + 1);
1263 $fiscalEnd = explode('-', date("Y-m-d", $fiscalYear));
1264 $to['d'] = $fiscalEnd['2'];
1265 $to['M'] = $fiscalEnd['1'];
1266 $to['Y'] = $fiscalEnd['0'];
1267 }
1268 else {
1269 $from['Y'] = $fYear - $relativeTermSuffix;
1270 $fiscalYear = mktime(0, 0, 0, $from['M'], $from['d'] - 1, $from['Y'] + 1);
1271 $fiscalEnd = explode('-', date("Y-m-d", $fiscalYear));
1272 $to['d'] = $fiscalEnd['2'];
1273 $to['M'] = $fiscalEnd['1'];
1274 $to['Y'] = $fYear;
1275 }
c5670e9e 1276 break;
6a488035 1277
c5670e9e 1278 case 'next':
353ffa53 1279 $from['Y'] = $fYear + 1;
5eb3092f 1280 $fiscalYear = mktime(0, 0, 0, $from['M'], $from['d'] - 1, $from['Y'] + 1);
353ffa53 1281 $fiscalEnd = explode('-', date("Y-m-d", $fiscalYear));
6a488035
TO
1282 $to['d'] = $fiscalEnd['2'];
1283 $to['M'] = $fiscalEnd['1'];
1284 $to['Y'] = $fiscalEnd['0'];
1285 break;
1286 }
1287 break;
1288
1289 case 'quarter':
1290 switch ($relativeTerm) {
1291 case 'this':
1292
353ffa53 1293 $quarter = ceil($now['mon'] / 3);
6a488035
TO
1294 $from['d'] = 1;
1295 $from['M'] = (3 * $quarter) - 2;
353ffa53
TO
1296 $to['M'] = 3 * $quarter;
1297 $to['Y'] = $from['Y'] = $now['year'];
1298 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $now['year']));
6a488035
TO
1299 break;
1300
1301 case 'previous':
353ffa53
TO
1302 $difference = 1;
1303 $quarter = ceil($now['mon'] / 3);
1304 $quarter = $quarter - $difference;
6a488035
TO
1305 $subtractYear = 0;
1306 if ($quarter <= 0) {
1307 $subtractYear = 1;
1308 $quarter += 4;
1309 }
1310 $from['d'] = 1;
1311 $from['M'] = (3 * $quarter) - 2;
353ffa53
TO
1312 $to['M'] = 3 * $quarter;
1313 $to['Y'] = $from['Y'] = $now['year'] - $subtractYear;
1314 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
6a488035
TO
1315 break;
1316
1317 case 'previous_before':
1318 $difference = 2;
353ffa53
TO
1319 $quarter = ceil($now['mon'] / 3);
1320 $quarter = $quarter - $difference;
d75f2f47 1321 $subtractYear = 0;
6a488035
TO
1322 if ($quarter <= 0) {
1323 $subtractYear = 1;
1324 $quarter += 4;
1325 }
1326 $from['d'] = 1;
1327 $from['M'] = (3 * $quarter) - 2;
353ffa53
TO
1328 $to['M'] = 3 * $quarter;
1329 $to['Y'] = $from['Y'] = $now['year'] - $subtractYear;
1330 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
6a488035
TO
1331 break;
1332
1333 case 'previous_2':
353ffa53
TO
1334 $difference = 2;
1335 $quarter = ceil($now['mon'] / 3);
6a488035 1336 $current_quarter = $quarter;
353ffa53
TO
1337 $quarter = $quarter - $difference;
1338 $subtractYear = 0;
6a488035
TO
1339 if ($quarter <= 0) {
1340 $subtractYear = 1;
1341 $quarter += 4;
1342 }
1343 $from['d'] = 1;
1344 $from['M'] = (3 * $quarter) - 2;
1345 switch ($current_quarter) {
1346 case 1:
1347 $to['M'] = (4 * $quarter);
1348 break;
1349
1350 case 2:
1351 $to['M'] = (4 * $quarter) + 3;
1352 break;
1353
1354 case 3:
1355 $to['M'] = (4 * $quarter) + 2;
1356 break;
1357
1358 case 4:
1359 $to['M'] = (4 * $quarter) + 1;
1360 break;
1361 }
1362 $to['Y'] = $from['Y'] = $now['year'] - $subtractYear;
1363 if ($to['M'] > 12) {
1364 $to['M'] = 3 * ($quarter - 3);
1365 $to['Y'] = $now['year'];
1366 }
1367 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1368 break;
1369
1370 case 'earlier':
1371 $quarter = ceil($now['mon'] / 3) - 1;
d75f2f47 1372 $subtractYear = 0;
6a488035
TO
1373 if ($quarter <= 0) {
1374 $subtractYear = 1;
1375 $quarter += 4;
1376 }
1377 $to['M'] = 3 * $quarter;
1378 $to['Y'] = $from['Y'] = $now['year'] - $subtractYear;
1379 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1380 unset($from);
1381 break;
1382
1383 case 'greater':
353ffa53 1384 $quarter = ceil($now['mon'] / 3);
6a488035
TO
1385 $from['d'] = 1;
1386 $from['M'] = (3 * $quarter) - 2;
1387 $from['Y'] = $now['year'];
1388 unset($to);
1389 break;
d75f2f47 1390
52f15bd6 1391 case 'greater_previous':
1392 $quarter = ceil($now['mon'] / 3) - 1;
353ffa53 1393 $subtractYear = 0;
52f15bd6 1394 if ($quarter <= 0) {
1395 $subtractYear = 1;
1396 $quarter += 4;
1397 }
1398 $from['M'] = 3 * $quarter;
1399 $from['Y'] = $from['Y'] = $now['year'] - $subtractYear;
1400 $from['d'] = date('t', mktime(0, 0, 0, $from['M'], 1, $from['Y']));
1401 unset($to);
1402 break;
6a488035
TO
1403
1404 case 'ending':
1405 $to['d'] = $now['mday'];
1406 $to['M'] = $now['mon'];
1407 $to['Y'] = $now['year'];
1408 $to['H'] = 23;
1409 $to['i'] = $to['s'] = 59;
2de679ba 1410 $from = self::intervalAdd('day', -90, $to);
353ffa53 1411 $from = self::intervalAdd('second', 1, $from);
6a488035 1412 break;
e902edd1 1413
1414 case 'current':
353ffa53 1415 $quarter = ceil($now['mon'] / 3);
e902edd1 1416 $from['d'] = 1;
1417 $from['M'] = (3 * $quarter) - 2;
1418 $from['Y'] = $now['year'];
1419 $to['d'] = $now['mday'];
1420 $to['M'] = $now['mon'];
1421 $to['Y'] = $now['year'];
1422 $to['H'] = 23;
1423 $to['i'] = $to['s'] = 59;
1424 break;
c5670e9e 1425
1426 case 'less':
353ffa53
TO
1427 $quarter = ceil($now['mon'] / 3);
1428 $to['M'] = 3 * $quarter;
1429 $to['Y'] = $now['year'];
1430 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $now['year']));
c5670e9e 1431 unset($from);
1432 break;
1433
1434 case 'next':
1435 $difference = -1;
1436 $subtractYear = 0;
353ffa53
TO
1437 $quarter = ceil($now['mon'] / 3);
1438 $quarter = $quarter - $difference;
50bfb460 1439 // CRM-14550 QA Fix
22e263ad 1440 if ($quarter > 4) {
c5670e9e 1441 $now['year'] = $now['year'] + 1;
1442 $quarter = 1;
1443 }
1444 if ($quarter <= 0) {
1445 $subtractYear = 1;
1446 $quarter += 4;
1447 }
1448 $from['d'] = 1;
1449 $from['M'] = (3 * $quarter) - 2;
353ffa53
TO
1450 $to['M'] = 3 * $quarter;
1451 $to['Y'] = $from['Y'] = $now['year'] - $subtractYear;
1452 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
c5670e9e 1453 break;
2de679ba 1454
1455 case 'starting':
1456 $from['d'] = $now['mday'];
1457 $from['M'] = $now['mon'];
1458 $from['Y'] = $now['year'];
1459 $from['H'] = 00;
1460 $from['i'] = $to['s'] = 00;
1461 $to = self::intervalAdd('day', 90, $from);
1462 $to = self::intervalAdd('second', -1, $to);
1463 break;
ad336d61 1464
1465 default:
1466 if ($relativeTermPrefix === 'ending') {
1467 $to['d'] = $now['mday'];
1468 $to['M'] = $now['mon'];
1469 $to['Y'] = $now['year'];
1470 $to['H'] = 23;
1471 $to['i'] = $to['s'] = 59;
1472 $from = self::intervalAdd('month', -($relativeTermSuffix * 3), $to);
1473 $from = self::intervalAdd('second', 1, $from);
1474 }
6a488035
TO
1475 }
1476 break;
1477
1478 case 'month':
1479 switch ($relativeTerm) {
1480 case 'this':
1481 $from['d'] = 1;
353ffa53 1482 $to['d'] = date('t', mktime(0, 0, 0, $now['mon'], 1, $now['year']));
6a488035
TO
1483 $from['M'] = $to['M'] = $now['mon'];
1484 $from['Y'] = $to['Y'] = $now['year'];
1485 break;
1486
1487 case 'previous':
1488 $from['d'] = 1;
1489 if ($now['mon'] == 1) {
1490 $from['M'] = $to['M'] = 12;
1491 $from['Y'] = $to['Y'] = $now['year'] - 1;
1492 }
1493 else {
1494 $from['M'] = $to['M'] = $now['mon'] - 1;
1495 $from['Y'] = $to['Y'] = $now['year'];
1496 }
1497 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1498 break;
1499
1500 case 'previous_before':
1501 $from['d'] = 1;
1502 if ($now['mon'] < 3) {
1503 $from['M'] = $to['M'] = 10 + $now['mon'];
1504 $from['Y'] = $to['Y'] = $now['year'] - 1;
1505 }
1506 else {
1507 $from['M'] = $to['M'] = $now['mon'] - 2;
1508 $from['Y'] = $to['Y'] = $now['year'];
1509 }
1510 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1511 break;
1512
1513 case 'previous_2':
1514 $from['d'] = 1;
1515 if ($now['mon'] < 3) {
1516 $from['M'] = 10 + $now['mon'];
1517 $from['Y'] = $now['year'] - 1;
1518 }
1519 else {
1520 $from['M'] = $now['mon'] - 2;
1521 $from['Y'] = $now['year'];
1522 }
1523
1524 if ($now['mon'] == 1) {
1525 $to['M'] = 12;
1526 $to['Y'] = $now['year'] - 1;
1527 }
1528 else {
1529 $to['M'] = $now['mon'] - 1;
1530 $to['Y'] = $now['year'];
1531 }
1532
1533 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1534 break;
1535
1536 case 'earlier':
50bfb460 1537 // before end of past month
6a488035
TO
1538 if ($now['mon'] == 1) {
1539 $to['M'] = 12;
1540 $to['Y'] = $now['year'] - 1;
1541 }
1542 else {
1543 $to['M'] = $now['mon'] - 1;
1544 $to['Y'] = $now['year'];
1545 }
1546
1547 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1548 unset($from);
1549 break;
1550
1551 case 'greater':
1552 $from['d'] = 1;
1553 $from['M'] = $now['mon'];;
1554 $from['Y'] = $now['year'];
1555 unset($to);
1556 break;
1557
52f15bd6 1558 case 'greater_previous':
50bfb460 1559 // from end of past month
52f15bd6 1560 if ($now['mon'] == 1) {
1561 $from['M'] = 12;
1562 $from['Y'] = $now['year'] - 1;
1563 }
1564 else {
1565 $from['M'] = $now['mon'] - 1;
1566 $from['Y'] = $now['year'];
1567 }
1568
1569 $from['d'] = date('t', mktime(0, 0, 0, $from['M'], 1, $from['Y']));
1570 unset($to);
1571 break;
1572
0db07823 1573 case 'ending_2':
1574 $to['d'] = $now['mday'];
1575 $to['M'] = $now['mon'];
1576 $to['Y'] = $now['year'];
1577 $to['H'] = 23;
1578 $to['i'] = $to['s'] = 59;
1579 $from = self::intervalAdd('day', -60, $to);
1580 $from = self::intervalAdd('second', 1, $from);
1581 break;
1582
6a488035
TO
1583 case 'ending':
1584 $to['d'] = $now['mday'];
1585 $to['M'] = $now['mon'];
1586 $to['Y'] = $now['year'];
1587 $to['H'] = 23;
1588 $to['i'] = $to['s'] = 59;
315eef7b 1589 $from = self::intervalAdd('day', -30, $to);
353ffa53 1590 $from = self::intervalAdd('second', 1, $from);
6a488035 1591 break;
e902edd1 1592
1593 case 'current':
1594 $from['d'] = 1;
1595 $from['M'] = $now['mon'];;
1596 $from['Y'] = $now['year'];
1597 $to['d'] = $now['mday'];
1598 $to['M'] = $now['mon'];
1599 $to['Y'] = $now['year'];
1600 $to['H'] = 23;
1601 $to['i'] = $to['s'] = 59;
1602 break;
c5670e9e 1603
1604 case 'less':
50bfb460 1605 // CRM-14550 QA Fix
c5670e9e 1606 $to['Y'] = $now['year'];
1607 $to['M'] = $now['mon'];
1608 $to['d'] = date('t', mktime(0, 0, 0, $now['mon'], 1, $now['year']));
1609 unset($from);
1610 break;
1611
1612 case 'next':
1613 $from['d'] = 1;
1614 if ($now['mon'] == 12) {
1615 $from['M'] = $to['M'] = 1;
1616 $from['Y'] = $to['Y'] = $now['year'] + 1;
1617 }
1618 else {
1619 $from['M'] = $to['M'] = $now['mon'] + 1;
1620 $from['Y'] = $to['Y'] = $now['year'];
1621 }
1622 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1623 break;
1624
1625 case 'starting':
2db7c428 1626 $from['d'] = $now['mday'];
1627 $from['M'] = $now['mon'];
1628 $from['Y'] = $now['year'];
1629 $from['H'] = 00;
1630 $from['i'] = $to['s'] = 00;
1631 $to = self::intervalAdd('day', 30, $from);
0db07823 1632 $to = self::intervalAdd('second', -1, $to);
1633 break;
1634
1635 case 'starting_2':
1636 $from['d'] = $now['mday'];
1637 $from['M'] = $now['mon'];
1638 $from['Y'] = $now['year'];
1639 $from['H'] = 00;
1640 $from['i'] = $to['s'] = 00;
1641 $to = self::intervalAdd('day', 60, $from);
2db7c428 1642 $to = self::intervalAdd('second', -1, $to);
c5670e9e 1643 break;
ad336d61 1644
1645 default:
1646 if ($relativeTermPrefix === 'ending') {
1647 $to['d'] = $now['mday'];
1648 $to['M'] = $now['mon'];
1649 $to['Y'] = $now['year'];
1650 $to['H'] = 23;
1651 $to['i'] = $to['s'] = 59;
1652 $from = self::intervalAdd($unit, -$relativeTermSuffix, $to);
1653 $from = self::intervalAdd('second', 1, $from);
1654 }
6a488035
TO
1655 }
1656 break;
1657
1658 case 'week':
aaffa79f 1659 $weekFirst = Civi::settings()->get('weekBegins');
a3d92acb 1660 $thisDay = $now['wday'];
38d131e3 1661 if ($weekFirst > $thisDay) {
a3d92acb 1662 $diffDay = $thisDay - $weekFirst + 7;
1663 }
1664 else {
1665 $diffDay = $thisDay - $weekFirst;
1666 }
6a488035
TO
1667 switch ($relativeTerm) {
1668 case 'this':
1669 $from['d'] = $now['mday'];
1670 $from['M'] = $now['mon'];
1671 $from['Y'] = $now['year'];
a3d92acb 1672 $from = self::intervalAdd('day', -1 * ($diffDay), $from);
353ffa53 1673 $to = self::intervalAdd('day', 6, $from);
6a488035
TO
1674 break;
1675
1676 case 'previous':
1677 $from['d'] = $now['mday'];
1678 $from['M'] = $now['mon'];
1679 $from['Y'] = $now['year'];
a3d92acb 1680 $from = self::intervalAdd('day', -1 * ($diffDay) - 7, $from);
353ffa53 1681 $to = self::intervalAdd('day', 6, $from);
6a488035
TO
1682 break;
1683
1684 case 'previous_before':
1685 $from['d'] = $now['mday'];
1686 $from['M'] = $now['mon'];
1687 $from['Y'] = $now['year'];
a3d92acb 1688 $from = self::intervalAdd('day', -1 * ($diffDay) - 14, $from);
353ffa53 1689 $to = self::intervalAdd('day', 6, $from);
6a488035
TO
1690 break;
1691
1692 case 'previous_2':
1693 $from['d'] = $now['mday'];
1694 $from['M'] = $now['mon'];
1695 $from['Y'] = $now['year'];
a3d92acb 1696 $from = self::intervalAdd('day', -1 * ($diffDay) - 14, $from);
353ffa53 1697 $to = self::intervalAdd('day', 13, $from);
6a488035
TO
1698 break;
1699
1700 case 'earlier':
1701 $to['d'] = $now['mday'];
1702 $to['M'] = $now['mon'];
1703 $to['Y'] = $now['year'];
a3d92acb 1704 $to = self::intervalAdd('day', -1 * ($diffDay) - 1, $to);
6a488035
TO
1705 unset($from);
1706 break;
1707
1708 case 'greater':
1709 $from['d'] = $now['mday'];
1710 $from['M'] = $now['mon'];
1711 $from['Y'] = $now['year'];
a3d92acb 1712 $from = self::intervalAdd('day', -1 * ($diffDay), $from);
6a488035
TO
1713 unset($to);
1714 break;
1715
52f15bd6 1716 case 'greater_previous':
1717 $from['d'] = $now['mday'];
1718 $from['M'] = $now['mon'];
1719 $from['Y'] = $now['year'];
a3d92acb 1720 $from = self::intervalAdd('day', -1 * ($diffDay) - 1, $from);
52f15bd6 1721 unset($to);
1722 break;
1723
6a488035
TO
1724 case 'ending':
1725 $to['d'] = $now['mday'];
1726 $to['M'] = $now['mon'];
1727 $to['Y'] = $now['year'];
1728 $to['H'] = 23;
1729 $to['i'] = $to['s'] = 59;
353ffa53
TO
1730 $from = self::intervalAdd('day', -7, $to);
1731 $from = self::intervalAdd('second', 1, $from);
6a488035 1732 break;
e902edd1 1733
1734 case 'current':
1735 $from['d'] = $now['mday'];
1736 $from['M'] = $now['mon'];
1737 $from['Y'] = $now['year'];
a3d92acb 1738 $from = self::intervalAdd('day', -1 * ($diffDay), $from);
e902edd1 1739 $to['d'] = $now['mday'];
1740 $to['M'] = $now['mon'];
1741 $to['Y'] = $now['year'];
1742 $to['H'] = 23;
1743 $to['i'] = $to['s'] = 59;
1744 break;
c5670e9e 1745
1746 case 'less':
1747 $to['d'] = $now['mday'];
1748 $to['M'] = $now['mon'];
1749 $to['Y'] = $now['year'];
50bfb460 1750 // CRM-14550 QA Fix
a3d92acb 1751 $to = self::intervalAdd('day', -1 * ($diffDay) + 6, $to);
c5670e9e 1752 unset($from);
1753 break;
1754
1755 case 'next':
1756 $from['d'] = $now['mday'];
1757 $from['M'] = $now['mon'];
1758 $from['Y'] = $now['year'];
a3d92acb 1759 $from = self::intervalAdd('day', -1 * ($diffDay) + 7, $from);
d5cc0fc2 1760 $to = self::intervalAdd('day', 6, $from);
c5670e9e 1761 break;
1762
1763 case 'starting':
1764 $from['d'] = $now['mday'];
1765 $from['M'] = $now['mon'];
1766 $from['Y'] = $now['year'];
1767 $from['H'] = 00;
1768 $from['i'] = $to['s'] = 00;
d5cc0fc2 1769 $to = self::intervalAdd('day', 7, $from);
353ffa53 1770 $to = self::intervalAdd('second', -1, $to);
c5670e9e 1771 break;
ad336d61 1772
1773 default:
1774 if ($relativeTermPrefix === 'ending') {
1775 $to['d'] = $now['mday'];
1776 $to['M'] = $now['mon'];
1777 $to['Y'] = $now['year'];
1778 $to['H'] = 23;
1779 $to['i'] = $to['s'] = 59;
1780 $from = self::intervalAdd($unit, -$relativeTermSuffix, $to);
1781 $from = self::intervalAdd('second', 1, $from);
1782 }
6a488035
TO
1783 }
1784 break;
1785
1786 case 'day':
1787 switch ($relativeTerm) {
1788 case 'this':
1789 $from['d'] = $to['d'] = $now['mday'];
1790 $from['M'] = $to['M'] = $now['mon'];
1791 $from['Y'] = $to['Y'] = $now['year'];
1792 break;
1793
1794 case 'previous':
1795 $from['d'] = $now['mday'];
1796 $from['M'] = $now['mon'];
1797 $from['Y'] = $now['year'];
353ffa53
TO
1798 $from = self::intervalAdd('day', -1, $from);
1799 $to['d'] = $from['d'];
1800 $to['M'] = $from['M'];
1801 $to['Y'] = $from['Y'];
6a488035
TO
1802 break;
1803
1804 case 'previous_before':
1805 $from['d'] = $now['mday'];
1806 $from['M'] = $now['mon'];
1807 $from['Y'] = $now['year'];
353ffa53
TO
1808 $from = self::intervalAdd('day', -2, $from);
1809 $to['d'] = $from['d'];
1810 $to['M'] = $from['M'];
1811 $to['Y'] = $from['Y'];
6a488035
TO
1812 break;
1813
1814 case 'previous_2':
1815 $from['d'] = $to['d'] = $now['mday'];
1816 $from['M'] = $to['M'] = $now['mon'];
1817 $from['Y'] = $to['Y'] = $now['year'];
353ffa53
TO
1818 $from = self::intervalAdd('day', -2, $from);
1819 $to = self::intervalAdd('day', -1, $to);
6a488035
TO
1820 break;
1821
1822 case 'earlier':
1823 $to['d'] = $now['mday'];
1824 $to['M'] = $now['mon'];
1825 $to['Y'] = $now['year'];
1826 unset($from);
1827 break;
1828
1829 case 'greater':
1830 $from['d'] = $now['mday'];
1831 $from['M'] = $now['mon'];;
1832 $from['Y'] = $now['year'];
1833 unset($to);
1834 break;
c5670e9e 1835
1836 case 'starting':
353ffa53
TO
1837 $to['d'] = $now['mday'];
1838 $to['M'] = $now['mon'];
1839 $to['Y'] = $now['year'];
d5cc0fc2 1840 $to = self::intervalAdd('day', 1, $to);
c5670e9e 1841 $from['d'] = $to['d'];
1842 $from['M'] = $to['M'];
1843 $from['Y'] = $to['Y'];
1844 break;
1845
ad336d61 1846 default:
1847 if ($relativeTermPrefix === 'ending') {
1848 $to['d'] = $now['mday'];
1849 $to['M'] = $now['mon'];
1850 $to['Y'] = $now['year'];
1851 $to['H'] = 23;
1852 $to['i'] = $to['s'] = 59;
1853 $from = self::intervalAdd($unit, -$relativeTermSuffix, $to);
1854 $from = self::intervalAdd('second', 1, $from);
1855 }
6a488035
TO
1856 }
1857 break;
1858 }
1859
1860 foreach (array(
353ffa53 1861 'from',
d5cc0fc2 1862 'to',
353ffa53 1863 ) as $item) {
6a488035
TO
1864 if (!empty($$item)) {
1865 $dateRange[$item] = self::format($$item);
1866 }
1867 else {
1868 $dateRange[$item] = NULL;
1869 }
1870 }
1871 return $dateRange;
1872 }
1873
1874 /**
fe482240 1875 * Calculate current fiscal year based on the fiscal month and day.
6a488035 1876 *
77855840
TO
1877 * @param int $fyDate
1878 * Fiscal start date.
6a488035 1879 *
77855840
TO
1880 * @param int $fyMonth
1881 * Fiscal Start Month.
6a488035 1882 *
a6c01b45 1883 * @return int
1e60a380 1884 * $fy Current Fiscal Year
6a488035 1885 */
00be9182 1886 public static function calculateFiscalYear($fyDate, $fyMonth) {
6a488035
TO
1887 $date = date("Y-m-d");
1888 $currentYear = date("Y");
1889
50bfb460 1890 // recalculate the date because month 4::04 make the difference
353ffa53
TO
1891 $fiscalYear = explode('-', date("Y-m-d", mktime(0, 0, 0, $fyMonth, $fyDate, $currentYear)));
1892 $fyDate = $fiscalYear[2];
1893 $fyMonth = $fiscalYear[1];
6a488035
TO
1894 $fyStartDate = date("Y-m-d", mktime(0, 0, 0, $fyMonth, $fyDate, $currentYear));
1895
1896 if ($fyStartDate > $date) {
1897 $fy = intval(intval($currentYear) - 1);
1898 }
1899 else {
1900 $fy = intval($currentYear);
1901 }
1902 return $fy;
1903 }
1904
1905 /**
50bfb460 1906 * Function to process date, convert to mysql format
6a488035 1907 *
77855840
TO
1908 * @param string $date
1909 * Date string.
1910 * @param string $time
1911 * Time string.
f4aaa82a 1912 * @param bool|string $returnNullString 'null' needs to be returned
6a488035 1913 * so that db oject will set null in db
77855840
TO
1914 * @param string $format
1915 * Expected return date format.( default is mysql ).
6a488035 1916 *
a6c01b45
CW
1917 * @return string
1918 * date format that is excepted by mysql
6a488035 1919 */
00be9182 1920 public static function processDate($date, $time = NULL, $returnNullString = FALSE, $format = 'YmdHis') {
6a488035
TO
1921 $mysqlDate = NULL;
1922
1923 if ($returnNullString) {
1924 $mysqlDate = 'null';
1925 }
1926
1927 if (trim($date)) {
1928 $mysqlDate = date($format, strtotime($date . ' ' . $time));
1929 }
1930
1931 return $mysqlDate;
1932 }
1933
d86e674f 1934 /**
1935 * Add the metadata about a date field to the field.
1936 *
1937 * This metadata will work with the call $form->add('datepicker', ...
1938 *
1939 * @param array $fieldMetaData
1940 * @param array $field
1941 *
1942 * @return array
1943 */
1944 public static function addDateMetadataToField($fieldMetaData, $field) {
1945 if (isset($fieldMetaData['html'])) {
1946 $field['html_type'] = $fieldMetaData['html']['type'];
e9f229db 1947 if ($field['html_type'] === 'Select Date') {
1948 if (!isset($field['date_format'])) {
1949 $dateAttributes = CRM_Core_SelectValues::date($fieldMetaData['html']['formatType'], NULL, NULL, NULL, 'Input');
1950 $field['start_date_years'] = $dateAttributes['minYear'];
1951 $field['end_date_years'] = $dateAttributes['maxYear'];
1952 $field['date_format'] = $dateAttributes['format'];
1953 $field['is_datetime_field'] = TRUE;
1954 $field['time_format'] = $dateAttributes['time'];
ed0ca248 1955 $field['smarty_view_format'] = $dateAttributes['smarty_view_format'];
d86e674f 1956 }
e9f229db 1957 $field['datepicker']['extra'] = self::getDatePickerExtra($field);
1958 $field['datepicker']['attributes'] = self::getDatePickerAttributes($field);
d86e674f 1959 }
d86e674f 1960 }
1961 return $field;
1962 }
1963
1964
1965 /**
1966 * Get the fields required for the 'extra' parameter when adding a datepicker.
1967 *
1968 * @param array $field
1969 *
1970 * @return array
1971 */
1972 public static function getDatePickerExtra($field) {
1973 $extra = array();
1974 if (isset($field['date_format'])) {
1975 $extra['date'] = $field['date_format'];
1976 $extra['time'] = $field['time_format'];
1977 }
1978 $thisYear = date('Y');
1979 if (isset($field['start_date_years'])) {
1980 $extra['minDate'] = date('Y-m-d', strtotime('-' . ($thisYear - $field['start_date_years']) . ' years'));
1981 }
1982 if (isset($field['end_date_years'])) {
1983 $extra['maxDate'] = date('Y-m-d', strtotime('-' . ($thisYear - $field['end_date_years']) . ' years'));
1984 }
1985 return $extra;
1986 }
1987
1988 /**
1989 * Get the attributes parameters required for datepicker.
1990 *
1991 * @param array $field
1992 * Field metadata
1993 *
1994 * @return array
1995 * Array ready to pass to $this->addForm('datepicker' as attributes.
1996 */
1997 public static function getDatePickerAttributes(&$field) {
1998 $attributes = array();
1999 $dateAttributes = array(
2000 'start_date_years' => 'minYear',
2001 'end_date_years' => 'maxYear',
2002 'date_format' => 'format',
2003 );
2004 foreach ($dateAttributes as $dateAttribute => $mapTo) {
2005 if (isset($field[$dateAttribute])) {
2006 $attributes[$mapTo] = $field[$dateAttribute];
2007 }
2008 }
2009 return $attributes;
2010 }
2011
6a488035 2012 /**
50bfb460 2013 * Function to convert mysql to date plugin format.
6a488035 2014 *
77855840
TO
2015 * @param string $mysqlDate
2016 * Date string.
f4aaa82a
EM
2017 *
2018 * @param null $formatType
2019 * @param null $format
2020 * @param null $timeFormat
6a488035 2021 *
a6c01b45
CW
2022 * @return array
2023 * and time
6a488035 2024 */
00be9182 2025 public static function setDateDefaults($mysqlDate = NULL, $formatType = NULL, $format = NULL, $timeFormat = NULL) {
6a488035
TO
2026 // if date is not passed assume it as today
2027 if (!$mysqlDate) {
2028 $mysqlDate = date('Y-m-d G:i:s');
2029 }
2030
2031 $config = CRM_Core_Config::singleton();
2032 if ($formatType) {
2033 // get actual format
2034 $params = array('name' => $formatType);
2035 $values = array();
2036 CRM_Core_DAO::commonRetrieve('CRM_Core_DAO_PreferencesDate', $params, $values);
2037
2038 if ($values['date_format']) {
2039 $format = $values['date_format'];
2040 }
2041
2042 if (isset($values['time_format'])) {
2043 $timeFormat = $values['time_format'];
2044 }
2045 }
2046
2047 // now we set display date using js, hence we should always setdefault
2048 // 'm/d/Y' format. So that submitted value is alwats mm/dd/YY format
2049 // note that for date display we dynamically create text field
2050 /*
e70a7fc0
TO
2051 if ( !$format ) {
2052 $format = $config->dateInputFormat;
2053 }
6a488035 2054
e70a7fc0
TO
2055 // get actual format
2056 $actualPHPFormats = CRM_Core_SelectValues::datePluginToPHPFormats( );
2057 $dateFormat = CRM_Utils_Array::value( $format, $actualPHPFormats );
2058 */
6a488035 2059
6a488035
TO
2060 $dateFormat = 'm/d/Y';
2061 $date = date($dateFormat, strtotime($mysqlDate));
2062
2063 if (!$timeFormat) {
2064 $timeFormat = $config->timeInputFormat;
2065 }
2066
2067 $actualTimeFormat = "g:iA";
2068 $appendZeroLength = 7;
2069 if ($timeFormat > 1) {
2070 $actualTimeFormat = "G:i";
2071 $appendZeroLength = 5;
2072 }
2073
2074 $time = date($actualTimeFormat, strtotime($mysqlDate));
2075
2076 // need to append zero for hours < 10
2077 if (strlen($time) < $appendZeroLength) {
2078 $time = '0' . $time;
2079 }
2080
2081 return array($date, $time);
2082 }
2083
2084 /**
fe482240 2085 * Function get date format.
6a488035 2086 *
77855840
TO
2087 * @param string $formatType
2088 * Date name e.g. birth.
6a488035 2089 *
a6c01b45 2090 * @return string
6a488035 2091 */
00be9182 2092 public static function getDateFormat($formatType = NULL) {
6a488035
TO
2093 $format = NULL;
2094 if ($formatType) {
395d8dc6 2095 $format = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_PreferencesDate',
353ffa53 2096 $formatType, 'date_format', 'name'
6a488035
TO
2097 );
2098 }
2099
2100 if (!$format) {
2101 $config = CRM_Core_Config::singleton();
2102 $format = $config->dateInputFormat;
2103 }
2104 return $format;
2105 }
2106
5bc392e6
EM
2107 /**
2108 * @param $date
2109 * @param $dateType
2110 *
2111 * @return null|string
2112 */
00be9182 2113 public static function formatDate($date, $dateType) {
6a488035
TO
2114 $formattedDate = NULL;
2115 if (empty($date)) {
2116 return $formattedDate;
2117 }
2118
50bfb460
SB
2119 // 1. first convert date to default format.
2120 // 2. append time to default formatted date (might be removed during format)
2121 // 3. validate date / date time.
2122 // 4. If date and time then convert to default date time format.
6a488035
TO
2123
2124 $dateKey = 'date';
2125 $dateParams = array($dateKey => $date);
2126
2127 if (CRM_Utils_Date::convertToDefaultDate($dateParams, $dateType, $dateKey)) {
2128 $dateVal = $dateParams[$dateKey];
2129 $ruleName = 'date';
2130 if ($dateType == 1) {
2131 $matches = array();
2132 if (preg_match("/(\s(([01]\d)|[2][0-3]):([0-5]\d))$/", $date, $matches)) {
2133 $ruleName = 'dateTime';
2134 if (strpos($date, '-') !== FALSE) {
2135 $dateVal .= array_shift($matches);
2136 }
2137 }
2138 }
2139
2140 // validate date.
0e6e8724 2141 $valid = CRM_Utils_Rule::$ruleName($dateVal);
6a488035
TO
2142
2143 if ($valid) {
50bfb460 2144 // format date and time to default.
6a488035
TO
2145 if ($ruleName == 'dateTime') {
2146 $dateVal = CRM_Utils_Date::customFormat(preg_replace("/(:|\s)?/", "", $dateVal), '%Y%m%d%H%i');
50bfb460 2147 // hack to add seconds
6a488035
TO
2148 $dateVal .= '00';
2149 }
2150 $formattedDate = $dateVal;
2151 }
2152 }
2153
2154 return $formattedDate;
2155 }
2156
dccd9f4f
ERL
2157 /**
2158 * Function to return days of the month.
2159 *
2160 * @return array
2161 */
2162 public static function getCalendarDayOfMonth() {
2163 $month = array();
2164 for ($i = 1; $i <= 31; $i++) {
2165 $month[$i] = $i;
2166 if ($i == 31) {
2167 $month[$i] = $i . ' / Last day of month';
2168 }
2169 }
2170 return $month;
2171 }
2172
6a488035 2173}