dolibarr 18.0.6
date.lib.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2004-2011 Laurent Destailleur <eldy@users.sourceforge.net>
3 * Copyright (C) 2005-2011 Regis Houssin <regis.houssin@inodbox.com>
4 * Copyright (C) 2011-2015 Juanjo Menent <jmenent@2byte.es>
5 * Copyright (C) 2017 Ferran Marcet <fmarcet@2byte.es>
6 * Copyright (C) 2018 Charlene Benke <charlie@patas-monkey.com>
7*
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 3 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with this program. If not, see <https://www.gnu.org/licenses/>.
20 * or see https://www.gnu.org/
21 */
22
34function get_tz_array()
35{
36 $tzarray = array(
37 -11 => "Pacific/Pago_Pago",
38 -10 => "Pacific/Honolulu",
39 -9 => "America/Anchorage",
40 -8 => "America/Los_Angeles",
41 -7 => "America/Dawson_Creek",
42 -6 => "America/Chicago",
43 -5 => "America/Bogota",
44 -4 => "America/Asuncion",
45 -3 => "America/Araguaina",
46 -2 => "America/Noronha",
47 -1 => "Atlantic/Azores",
48 0 => "Europe/London",
49 1 => "Europe/Paris",
50 2 => "Europe/Helsinki",
51 3 => "Europe/Moscow",
52 4 => "Asia/Dubai",
53 5 => "Asia/Karachi",
54 6 => "Indian/Chagos",
55 7 => "Asia/Jakarta",
56 8 => "Asia/Hong_Kong",
57 9 => "Asia/Tokyo",
58 10 => "Australia/Sydney",
59 11 => "Pacific/Noumea",
60 12 => "Pacific/Auckland",
61 13 => "Pacific/Fakaofo",
62 14 => "Pacific/Kiritimati"
63 );
64 return $tzarray;
65}
66
67
74{
75 return @date_default_timezone_get();
76}
77
84function getServerTimeZoneInt($refgmtdate = 'now')
85{
86 if (method_exists('DateTimeZone', 'getOffset')) {
87 // Method 1 (include daylight)
88 $gmtnow = dol_now('gmt');
89 $yearref = dol_print_date($gmtnow, '%Y');
90 $monthref = dol_print_date($gmtnow, '%m');
91 $dayref = dol_print_date($gmtnow, '%d');
92 if ($refgmtdate == 'now') {
93 $newrefgmtdate = $yearref.'-'.$monthref.'-'.$dayref;
94 } elseif ($refgmtdate == 'summer') {
95 $newrefgmtdate = $yearref.'-08-01';
96 } else {
97 $newrefgmtdate = $yearref.'-01-01';
98 }
99 $newrefgmtdate .= 'T00:00:00+00:00';
100 $localtz = new DateTimeZone(getServerTimeZoneString());
101 $localdt = new DateTime($newrefgmtdate, $localtz);
102 $tmp = -1 * $localtz->getOffset($localdt);
103 //print $refgmtdate.'='.$tmp;
104 } else {
105 $tmp = 0;
106 dol_print_error('', 'PHP version must be 5.3+');
107 }
108 $tz = round(($tmp < 0 ? 1 : -1) * abs($tmp / 3600));
109 return $tz;
110}
111
112
123function dol_time_plus_duree($time, $duration_value, $duration_unit, $ruleforendofmonth = 0)
124{
125 global $conf;
126 if ($duration_unit == 's') {
127 return $time + ($duration_value);
128 }
129 if ($duration_value == 0) {
130 return $time;
131 }
132 if ($duration_unit == 'i') {
133 return $time + (60 * $duration_value);
134 }
135 if ($duration_unit == 'h') {
136 return $time + (3600 * $duration_value);
137 }
138 if ($duration_unit == 'w') {
139 return $time + (3600 * 24 * 7 * $duration_value);
140 }
141
142 $deltastring = 'P';
143
144 if ($duration_value > 0) {
145 $deltastring .= abs($duration_value);
146 $sub = false;
147 }
148 if ($duration_value < 0) {
149 $deltastring .= abs($duration_value);
150 $sub = true;
151 }
152 if ($duration_unit == 'd') {
153 $deltastring .= "D";
154 }
155 if ($duration_unit == 'm') {
156 $deltastring .= "M";
157 }
158 if ($duration_unit == 'y') {
159 $deltastring .= "Y";
160 }
161
162 $date = new DateTime();
163 if (!empty($conf->global->MAIN_DATE_IN_MEMORY_ARE_GMT)) {
164 $date->setTimezone(new DateTimeZone('UTC'));
165 }
166 $date->setTimestamp($time);
167 $interval = new DateInterval($deltastring);
168
169 if ($sub) {
170 $date->sub($interval);
171 } else {
172 $date->add($interval);
173 }
174 //Change the behavior of PHP over data-interval when the result of this function is Feb 29 (non-leap years), 30 or Feb 31 (so php returns March 1, 2 or 3 respectively)
175 if ($ruleforendofmonth == 1 && $duration_unit == 'm') {
176 $timeyear = dol_print_date($time, '%Y');
177 $timemonth = dol_print_date($time, '%m');
178 $timetotalmonths = (($timeyear * 12) + $timemonth);
179
180 $monthsexpected = ($timetotalmonths + $duration_value);
181
182 $newtime = $date->getTimestamp();
183
184 $newtimeyear = dol_print_date($newtime, '%Y');
185 $newtimemonth = dol_print_date($newtime, '%m');
186 $newtimetotalmonths = (($newtimeyear * 12) + $newtimemonth);
187
188 if ($monthsexpected < $newtimetotalmonths) {
189 $newtimehours = dol_print_date($newtime, '%H');
190 $newtimemins = dol_print_date($newtime, '%M');
191 $newtimesecs = dol_print_date($newtime, '%S');
192
193 $datelim = dol_mktime($newtimehours, $newtimemins, $newtimesecs, $newtimemonth, 1, $newtimeyear);
194 $datelim -= (3600 * 24);
195
196 $date->setTimestamp($datelim);
197 }
198 }
199 return $date->getTimestamp();
200}
201
202
212function convertTime2Seconds($iHours = 0, $iMinutes = 0, $iSeconds = 0)
213{
214 $iResult = ((int) $iHours * 3600) + ((int) $iMinutes * 60) + (int) $iSeconds;
215 return $iResult;
216}
217
218
241function convertSecondToTime($iSecond, $format = 'all', $lengthOfDay = 86400, $lengthOfWeek = 7)
242{
243 global $langs;
244
245 if (empty($lengthOfDay)) {
246 $lengthOfDay = 86400; // 1 day = 24 hours
247 }
248 if (empty($lengthOfWeek)) {
249 $lengthOfWeek = 7; // 1 week = 7 days
250 }
251 $nbHbyDay = $lengthOfDay / 3600;
252
253 if ($format == 'all' || $format == 'allwithouthour' || $format == 'allhour' || $format == 'allhourmin' || $format == 'allhourminsec') {
254 if ((int) $iSecond === 0) {
255 return '0'; // This is to avoid having 0 return a 12:00 AM for en_US
256 }
257
258 $sTime = '';
259 $sDay = 0;
260 $sWeek = 0;
261
262 if ($iSecond >= $lengthOfDay) {
263 for ($i = $iSecond; $i >= $lengthOfDay; $i -= $lengthOfDay) {
264 $sDay++;
265 $iSecond -= $lengthOfDay;
266 }
267 $dayTranslate = $langs->trans("Day");
268 if ($iSecond >= ($lengthOfDay * 2)) {
269 $dayTranslate = $langs->trans("Days");
270 }
271 }
272
273 if ($lengthOfWeek < 7) {
274 if ($sDay) {
275 if ($sDay >= $lengthOfWeek) {
276 $sWeek = (int) (($sDay - $sDay % $lengthOfWeek) / $lengthOfWeek);
277 $sDay = $sDay % $lengthOfWeek;
278 $weekTranslate = $langs->trans("DurationWeek");
279 if ($sWeek >= 2) {
280 $weekTranslate = $langs->trans("DurationWeeks");
281 }
282 $sTime .= $sWeek.' '.$weekTranslate.' ';
283 }
284 }
285 }
286 if ($sDay > 0) {
287 $dayTranslate = $langs->trans("Day");
288 if ($sDay > 1) {
289 $dayTranslate = $langs->trans("Days");
290 }
291 $sTime .= $sDay.' '.$langs->trans("d").' ';
292 }
293
294 if ($format == 'all') {
295 if ($iSecond || empty($sDay)) {
296 $sTime .= dol_print_date($iSecond, 'hourduration', true);
297 }
298 } elseif ($format == 'allhourminsec') {
299 return sprintf("%02d", ($sWeek * $lengthOfWeek * $nbHbyDay + $sDay * $nbHbyDay + (int) floor($iSecond/3600))).':'.sprintf("%02d", ((int) floor(($iSecond % 3600) / 60))).':'.sprintf("%02d", ((int) ($iSecond % 60)));
300 } elseif ($format == 'allhourmin') {
301 return sprintf("%02d", ($sWeek * $lengthOfWeek * $nbHbyDay + $sDay * $nbHbyDay + (int) floor($iSecond/3600))).':'.sprintf("%02d", ((int) floor(($iSecond % 3600)/60)));
302 } elseif ($format == 'allhour') {
303 return sprintf("%02d", ($sWeek * $lengthOfWeek * $nbHbyDay + $sDay * $nbHbyDay + (int) floor($iSecond/3600)));
304 }
305 } elseif ($format == 'hour') { // only hour part
306 $sTime = dol_print_date($iSecond, '%H', true);
307 } elseif ($format == 'fullhour') {
308 if (!empty($iSecond)) {
309 $iSecond = $iSecond / 3600;
310 } else {
311 $iSecond = 0;
312 }
313 $sTime = $iSecond;
314 } elseif ($format == 'min') { // only min part
315 $sTime = dol_print_date($iSecond, '%M', true);
316 } elseif ($format == 'sec') { // only sec part
317 $sTime = dol_print_date($iSecond, '%S', true);
318 } elseif ($format == 'month') { // only month part
319 $sTime = dol_print_date($iSecond, '%m', true);
320 } elseif ($format == 'year') { // only year part
321 $sTime = dol_print_date($iSecond, '%Y', true);
322 }
323 return trim($sTime);
324}
325
326
333function convertDurationtoHour($duration_value, $duration_unit)
334{
335 $result = 0;
336
337 if ($duration_unit == 's') $result = $duration_value / 3600;
338 if ($duration_unit == 'i') $result = $duration_value / 60;
339 if ($duration_unit == 'h') $result = $duration_value;
340 if ($duration_unit == 'd') $result = $duration_value * 24;
341 if ($duration_unit == 'w') $result = $duration_value * 24 * 7;
342 if ($duration_unit == 'm') $result = $duration_value * 730.484;
343 if ($duration_unit == 'y') $result = $duration_value * 365 * 24;
344
345 return $result;
346}
347
361function dolSqlDateFilter($datefield, $day_date, $month_date, $year_date, $excludefirstand = 0, $gm = false)
362{
363 global $db;
364 $sqldate = '';
365
366 $day_date = intval($day_date);
367 $month_date = intval($month_date);
368 $year_date = intval($year_date);
369
370 if ($month_date > 0) {
371 if ($month_date > 12) { // protection for bad value of month
372 return " AND 1 = 2";
373 }
374 if ($year_date > 0 && empty($day_date)) {
375 $sqldate .= ($excludefirstand ? "" : " AND ").$datefield." BETWEEN '".$db->idate(dol_get_first_day($year_date, $month_date, $gm));
376 $sqldate .= "' AND '".$db->idate(dol_get_last_day($year_date, $month_date, $gm))."'";
377 } elseif ($year_date > 0 && !empty($day_date)) {
378 $sqldate .= ($excludefirstand ? "" : " AND ").$datefield." BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $month_date, $day_date, $year_date, $gm));
379 $sqldate .= "' AND '".$db->idate(dol_mktime(23, 59, 59, $month_date, $day_date, $year_date, $gm))."'";
380 } else {
381 // This case is not reliable on TZ, but we should not need it.
382 $sqldate .= ($excludefirstand ? "" : " AND ")." date_format( ".$datefield.", '%c') = '".$db->escape($month_date)."'";
383 }
384 } elseif ($year_date > 0) {
385 $sqldate .= ($excludefirstand ? "" : " AND ").$datefield." BETWEEN '".$db->idate(dol_get_first_day($year_date, 1, $gm));
386 $sqldate .= "' AND '".$db->idate(dol_get_last_day($year_date, 12, $gm))."'";
387 }
388 return $sqldate;
389}
390
410function dol_stringtotime($string, $gm = 1)
411{
412 $reg = array();
413 // Convert date with format DD/MM/YYY HH:MM:SS. This part of code should not be used.
414 if (preg_match('/^([0-9]+)\/([0-9]+)\/([0-9]+)\s?([0-9]+)?:?([0-9]+)?:?([0-9]+)?/i', $string, $reg)) {
415 dol_syslog("dol_stringtotime call to function with deprecated parameter format", LOG_WARNING);
416 // Date est au format 'DD/MM/YY' ou 'DD/MM/YY HH:MM:SS'
417 // Date est au format 'DD/MM/YYYY' ou 'DD/MM/YYYY HH:MM:SS'
418 $sday = $reg[1];
419 $smonth = $reg[2];
420 $syear = $reg[3];
421 $shour = $reg[4];
422 $smin = $reg[5];
423 $ssec = $reg[6];
424 if ($syear < 50) {
425 $syear += 1900;
426 }
427 if ($syear >= 50 && $syear < 100) {
428 $syear += 2000;
429 }
430 $string = sprintf("%04d%02d%02d%02d%02d%02d", $syear, $smonth, $sday, $shour, $smin, $ssec);
431 } elseif (preg_match('/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})Z$/i', $string, $reg) // Convert date with format YYYY-MM-DDTHH:MM:SSZ (RFC3339)
432 || preg_match('/^([0-9]{4})-([0-9]{2})-([0-9]{2}) ([0-9]{2}):([0-9]{2}):([0-9]{2})$/i', $string, $reg) // Convert date with format YYYY-MM-DD HH:MM:SS
433 || preg_match('/^([0-9]{4})([0-9]{2})([0-9]{2})T([0-9]{2})([0-9]{2})([0-9]{2})Z$/i', $string, $reg) // Convert date with format YYYYMMDDTHHMMSSZ
434 ) {
435 $syear = $reg[1];
436 $smonth = $reg[2];
437 $sday = $reg[3];
438 $shour = $reg[4];
439 $smin = $reg[5];
440 $ssec = $reg[6];
441 $string = sprintf("%04d%02d%02d%02d%02d%02d", $syear, $smonth, $sday, $shour, $smin, $ssec);
442 }
443
444 $string = preg_replace('/([^0-9])/i', '', $string);
445 $tmp = $string.'000000';
446 // Clean $gm
447 if ($gm === 1) {
448 $gm = 'gmt';
449 } elseif (empty($gm) || $gm === 'tzserver') {
450 $gm = 'tzserver';
451 }
452
453 $date = dol_mktime(substr($tmp, 8, 2), substr($tmp, 10, 2), substr($tmp, 12, 2), substr($tmp, 4, 2), substr($tmp, 6, 2), substr($tmp, 0, 4), $gm);
454 return $date;
455}
456
457
466function dol_get_prev_day($day, $month, $year)
467{
468 $time = dol_mktime(12, 0, 0, $month, $day, $year, 1, 0);
469 $time -= 24 * 60 * 60;
470 $tmparray = dol_getdate($time, true);
471 return array('year' => $tmparray['year'], 'month' => $tmparray['mon'], 'day' => $tmparray['mday']);
472}
473
482function dol_get_next_day($day, $month, $year)
483{
484 $time = dol_mktime(12, 0, 0, $month, $day, $year, 1, 0);
485 $time += 24 * 60 * 60;
486 $tmparray = dol_getdate($time, true);
487 return array('year' => $tmparray['year'], 'month' => $tmparray['mon'], 'day' => $tmparray['mday']);
488}
489
497function dol_get_prev_month($month, $year)
498{
499 if ($month == 1) {
500 $prev_month = 12;
501 $prev_year = $year - 1;
502 } else {
503 $prev_month = $month - 1;
504 $prev_year = $year;
505 }
506 return array('year' => $prev_year, 'month' => $prev_month);
507}
508
516function dol_get_next_month($month, $year)
517{
518 if ($month == 12) {
519 $next_month = 1;
520 $next_year = $year + 1;
521 } else {
522 $next_month = $month + 1;
523 $next_year = $year;
524 }
525 return array('year' => $next_year, 'month' => $next_month);
526}
527
537function dol_get_prev_week($day, $week, $month, $year)
538{
539 $tmparray = dol_get_first_day_week($day, $month, $year);
540
541 $time = dol_mktime(12, 0, 0, $month, $tmparray['first_day'], $year, 1, 0);
542 $time -= 24 * 60 * 60 * 7;
543 $tmparray = dol_getdate($time, true);
544 return array('year' => $tmparray['year'], 'month' => $tmparray['mon'], 'day' => $tmparray['mday']);
545}
546
556function dol_get_next_week($day, $week, $month, $year)
557{
558 $tmparray = dol_get_first_day_week($day, $month, $year);
559
560 $time = dol_mktime(12, 0, 0, $tmparray['first_month'], $tmparray['first_day'], $tmparray['first_year'], 1, 0);
561 $time += 24 * 60 * 60 * 7;
562 $tmparray = dol_getdate($time, true);
563
564 return array('year' => $tmparray['year'], 'month' => $tmparray['mon'], 'day' => $tmparray['mday']);
565}
566
578function dol_get_first_day($year, $month = 1, $gm = false)
579{
580 if ($year > 9999) {
581 return '';
582 }
583 return dol_mktime(0, 0, 0, $month, 1, $year, $gm);
584}
585
586
597function dol_get_last_day($year, $month = 12, $gm = false)
598{
599 if ($year > 9999) {
600 return '';
601 }
602 if ($month == 12) {
603 $month = 1;
604 $year += 1;
605 } else {
606 $month += 1;
607 }
608
609 // On se deplace au debut du mois suivant, et on retire un jour
610 $datelim = dol_mktime(23, 59, 59, $month, 1, $year, $gm);
611 $datelim -= (3600 * 24);
612
613 return $datelim;
614}
615
624function dol_get_last_hour($date, $gm = 'tzserver')
625{
626 $tmparray = dol_getdate($date, false, ($gm == 'gmt' ? 'gmt' : ''));
627 return dol_mktime(23, 59, 59, $tmparray['mon'], $tmparray['mday'], $tmparray['year'], $gm);
628}
629
638function dol_get_first_hour($date, $gm = 'tzserver')
639{
640 $tmparray = dol_getdate($date, false, ($gm == 'gmt' ? 'gmt' : ''));
641 return dol_mktime(0, 0, 0, $tmparray['mon'], $tmparray['mday'], $tmparray['year'], $gm);
642}
643
653function dol_get_first_day_week($day, $month, $year, $gm = false)
654{
655 global $conf;
656
657 //$day=2; $month=2; $year=2015;
658 $date = dol_mktime(0, 0, 0, $month, $day, $year, $gm);
659
660 //Checking conf of start week
661 $start_week = (isset($conf->global->MAIN_START_WEEK) ? $conf->global->MAIN_START_WEEK : 1);
662
663 $tmparray = dol_getdate($date, true); // detail of current day
664
665 //Calculate days = offset from current day
666 $days = $start_week - $tmparray['wday'];
667 if ($days >= 1) {
668 $days = 7 - $days;
669 }
670 $days = abs($days);
671 $seconds = $days * 24 * 60 * 60;
672 //print 'start_week='.$start_week.' tmparray[wday]='.$tmparray['wday'].' day offset='.$days.' seconds offset='.$seconds.'<br>';
673
674 //Get first day of week
675 $tmpdaytms = date($tmparray[0]) - $seconds; // $tmparray[0] is day of parameters
676 $tmpday = date("d", $tmpdaytms);
677
678 //Check first day of week is in same month than current day or not
679 if ($tmpday > $day) {
680 $prev_month = $month - 1;
681 $prev_year = $year;
682
683 if ($prev_month == 0) {
684 $prev_month = 12;
685 $prev_year = $year - 1;
686 }
687 } else {
688 $prev_month = $month;
689 $prev_year = $year;
690 }
691 $tmpmonth = $prev_month;
692 $tmpyear = $prev_year;
693
694 //Get first day of next week
695 $tmptime = dol_mktime(12, 0, 0, $month, $tmpday, $year, 1, 0);
696 $tmptime -= 24 * 60 * 60 * 7;
697 $tmparray = dol_getdate($tmptime, true);
698 $prev_day = $tmparray['mday'];
699
700 //Check prev day of week is in same month than first day or not
701 if ($prev_day > $tmpday) {
702 $prev_month = $month - 1;
703 $prev_year = $year;
704
705 if ($prev_month == 0) {
706 $prev_month = 12;
707 $prev_year = $year - 1;
708 }
709 }
710
711 $week = date("W", dol_mktime(0, 0, 0, $tmpmonth, $tmpday, $tmpyear, $gm));
712
713 return array('year' => $year, 'month' => $month, 'week' => $week, 'first_day' => $tmpday, 'first_month' => $tmpmonth, 'first_year' => $tmpyear, 'prev_year' => $prev_year, 'prev_month' => $prev_month, 'prev_day' => $prev_day);
714}
715
723function getGMTEasterDatetime($year)
724{
725 $base = new DateTime("$year-03-21", new DateTimeZone("UTC"));
726 $days = easter_days($year); // Return number of days between 21 march and easter day.
727 $tmp = $base->add(new DateInterval("P{$days}D"));
728 return $tmp->getTimestamp();
729}
730
747function num_public_holiday($timestampStart, $timestampEnd, $country_code = '', $lastday = 0, $includesaturday = -1, $includesunday = -1, $includefriday = -1, $includemonday = -1)
748{
749 global $db, $conf, $mysoc;
750
751 $nbFerie = 0;
752
753 // Check to ensure we use correct parameters
754 if ((($timestampEnd - $timestampStart) % 86400) != 0) {
755 return 'Error Dates must use same hours and must be GMT dates';
756 }
757
758 if (empty($country_code)) {
759 $country_code = $mysoc->country_code;
760 }
761 if ($includemonday < 0) {
762 $includemonday = (isset($conf->global->MAIN_NON_WORKING_DAYS_INCLUDE_MONDAY) ? $conf->global->MAIN_NON_WORKING_DAYS_INCLUDE_MONDAY : 0);
763 }
764 if ($includefriday < 0) {
765 $includefriday = (isset($conf->global->MAIN_NON_WORKING_DAYS_INCLUDE_FRIDAY) ? $conf->global->MAIN_NON_WORKING_DAYS_INCLUDE_FRIDAY : 0);
766 }
767 if ($includesaturday < 0) {
768 $includesaturday = (isset($conf->global->MAIN_NON_WORKING_DAYS_INCLUDE_SATURDAY) ? $conf->global->MAIN_NON_WORKING_DAYS_INCLUDE_SATURDAY : 1);
769 }
770 if ($includesunday < 0) {
771 $includesunday = (isset($conf->global->MAIN_NON_WORKING_DAYS_INCLUDE_SUNDAY) ? $conf->global->MAIN_NON_WORKING_DAYS_INCLUDE_SUNDAY : 1);
772 }
773
774 $country_id = dol_getIdFromCode($db, $country_code, 'c_country', 'code', 'rowid');
775
776 $i = 0;
777 while ((($lastday == 0 && $timestampStart < $timestampEnd) || ($lastday && $timestampStart <= $timestampEnd))
778 && ($i < 50000)) { // Loop end when equals (Test on i is a security loop to avoid infinite loop)
779 $ferie = false;
780 $specialdayrule = array();
781
782 $jour = gmdate("d", $timestampStart);
783 $mois = gmdate("m", $timestampStart);
784 $annee = gmdate("Y", $timestampStart);
785
786 //print "jour=".$jour." month=".$mois." year=".$annee." includesaturday=".$includesaturday." includesunday=".$includesunday."\n";
787
788 // Loop on public holiday defined into hrm_public_holiday for the day, month and year analyzed
789 // TODO Execute this request first and store results into an array, then reuse this array.
790 $sql = "SELECT code, entity, fk_country, dayrule, year, month, day, active";
791 $sql .= " FROM ".MAIN_DB_PREFIX."c_hrm_public_holiday";
792 $sql .= " WHERE active = 1 and fk_country IN (0".($country_id > 0 ? ", ".$country_id : 0).")";
793 $sql .= " AND entity IN (0," .getEntity('holiday') .")";
794
795 $resql = $db->query($sql);
796 if ($resql) {
797 $num_rows = $db->num_rows($resql);
798 $i = 0;
799 while ($i < $num_rows) {
800 $obj = $db->fetch_object($resql);
801
802 if (!empty($obj->dayrule) && $obj->dayrule != 'date') { // For example 'easter', '...'
803 $specialdayrule[$obj->dayrule] = $obj->dayrule;
804 } else {
805 $match = 1;
806 if (!empty($obj->year) && $obj->year != $annee) {
807 $match = 0;
808 }
809 if ($obj->month != $mois) {
810 $match = 0;
811 }
812 if ($obj->day != $jour) {
813 $match = 0;
814 }
815
816 if ($match) {
817 $ferie = true;
818 }
819 }
820
821 $i++;
822 }
823 } else {
824 dol_syslog($db->lasterror(), LOG_ERR);
825 return 'Error sql '.$db->lasterror();
826 }
827 //var_dump($specialdayrule)."\n";
828 //print "ferie=".$ferie."\n";
829
830 if (!$ferie) {
831 // Special dayrules
832 if (in_array('easter', $specialdayrule)) {
833 // Calculation for easter date
834 $date_paques = getGMTEasterDatetime($annee);
835 $jour_paques = gmdate("d", $date_paques);
836 $mois_paques = gmdate("m", $date_paques);
837 if ($jour_paques == $jour && $mois_paques == $mois) {
838 $ferie = true;
839 }
840 // Easter (sunday)
841 }
842
843 if (in_array('eastermonday', $specialdayrule)) {
844 // Calculation for the monday of easter date
845 $date_paques = getGMTEasterDatetime($annee);
846 //print 'PPP'.$date_paques.' '.dol_print_date($date_paques, 'dayhour', 'gmt')." ";
847 $date_lundi_paques = $date_paques + (3600 * 24);
848 $jour_lundi_paques = gmdate("d", $date_lundi_paques);
849 $mois_lundi_paques = gmdate("m", $date_lundi_paques);
850 if ($jour_lundi_paques == $jour && $mois_lundi_paques == $mois) {
851 $ferie = true;
852 }
853 // Easter (monday)
854 //print 'annee='.$annee.' $jour='.$jour.' $mois='.$mois.' $jour_lundi_paques='.$jour_lundi_paques.' $mois_lundi_paques='.$mois_lundi_paques."\n";
855 }
856
857 //Good Friday
858 if (in_array('goodfriday', $specialdayrule)) {
859 // Pulls the date of Easter
860 $easter = getGMTEasterDatetime($annee);
861
862 // Calculates the date of Good Friday based on Easter
863 $date_good_friday = $easter - (2 * 3600 * 24);
864 $dom_good_friday = gmdate("d", $date_good_friday);
865 $month_good_friday = gmdate("m", $date_good_friday);
866
867 if ($dom_good_friday == $jour && $month_good_friday == $mois) {
868 $ferie = true;
869 }
870 }
871
872 if (in_array('ascension', $specialdayrule)) {
873 // Calcul du jour de l'ascension (39 days after easter day)
874 $date_paques = getGMTEasterDatetime($annee);
875 $date_ascension = $date_paques + (3600 * 24 * 39);
876 $jour_ascension = gmdate("d", $date_ascension);
877 $mois_ascension = gmdate("m", $date_ascension);
878 if ($jour_ascension == $jour && $mois_ascension == $mois) {
879 $ferie = true;
880 }
881 // Ascension (thursday)
882 }
883
884 if (in_array('pentecote', $specialdayrule)) {
885 // Calculation of "Pentecote" (49 days after easter day)
886 $date_paques = getGMTEasterDatetime($annee);
887 $date_pentecote = $date_paques + (3600 * 24 * 49);
888 $jour_pentecote = gmdate("d", $date_pentecote);
889 $mois_pentecote = gmdate("m", $date_pentecote);
890 if ($jour_pentecote == $jour && $mois_pentecote == $mois) {
891 $ferie = true;
892 }
893 // "Pentecote" (sunday)
894 }
895 if (in_array('pentecotemonday', $specialdayrule)) {
896 // Calculation of "Pentecote" (49 days after easter day)
897 $date_paques = getGMTEasterDatetime($annee);
898 $date_pentecote = $date_paques + (3600 * 24 * 50);
899 $jour_pentecote = gmdate("d", $date_pentecote);
900 $mois_pentecote = gmdate("m", $date_pentecote);
901 if ($jour_pentecote == $jour && $mois_pentecote == $mois) {
902 $ferie = true;
903 }
904 // "Pentecote" (monday)
905 }
906
907 if (in_array('viernessanto', $specialdayrule)) {
908 // Viernes Santo
909 $date_paques = getGMTEasterDatetime($annee);
910 $date_viernes = $date_paques - (3600 * 24 * 2);
911 $jour_viernes = gmdate("d", $date_viernes);
912 $mois_viernes = gmdate("m", $date_viernes);
913 if ($jour_viernes == $jour && $mois_viernes == $mois) {
914 $ferie = true;
915 }
916 //Viernes Santo
917 }
918
919 if (in_array('fronleichnam', $specialdayrule)) {
920 // Fronleichnam (60 days after easter sunday)
921 $date_paques = getGMTEasterDatetime($annee);
922 $date_fronleichnam = $date_paques + (3600 * 24 * 60);
923 $jour_fronleichnam = gmdate("d", $date_fronleichnam);
924 $mois_fronleichnam = gmdate("m", $date_fronleichnam);
925 if ($jour_fronleichnam == $jour && $mois_fronleichnam == $mois) {
926 $ferie = true;
927 }
928 // Fronleichnam
929 }
930
931 if (in_array('genevafast', $specialdayrule)) {
932 // Geneva fast in Switzerland (Thursday after the first sunday in September)
933 $date_1sunsept = strtotime('next thursday', strtotime('next sunday', mktime(0, 0, 0, 9, 1, $annee)));
934 $jour_1sunsept = date("d", $date_1sunsept);
935 $mois_1sunsept = date("m", $date_1sunsept);
936 if ($jour_1sunsept == $jour && $mois_1sunsept == $mois) $ferie=true;
937 // Geneva fast in Switzerland
938 }
939 }
940 //print "ferie=".$ferie."\n";
941
942 // If we have to include Friday, Saturday and Sunday
943 if (!$ferie) {
944 if ($includefriday || $includesaturday || $includesunday) {
945 $jour_julien = unixtojd($timestampStart);
946 $jour_semaine = jddayofweek($jour_julien, 0);
947 if ($includefriday) { //Friday (5), Saturday (6) and Sunday (0)
948 if ($jour_semaine == 5) {
949 $ferie = true;
950 }
951 }
952 if ($includesaturday) { //Friday (5), Saturday (6) and Sunday (0)
953 if ($jour_semaine == 6) {
954 $ferie = true;
955 }
956 }
957 if ($includesunday) { //Friday (5), Saturday (6) and Sunday (0)
958 if ($jour_semaine == 0) {
959 $ferie = true;
960 }
961 }
962 }
963 }
964 //print "ferie=".$ferie."\n";
965
966 // We increase the counter of non working day
967 if ($ferie) {
968 $nbFerie++;
969 }
970
971 // Increase number of days (on go up into loop)
972 $timestampStart = dol_time_plus_duree($timestampStart, 1, 'd');
973 //var_dump($jour.' '.$mois.' '.$annee.' '.$timestampStart);
974
975 $i++;
976 }
977
978 //print "nbFerie=".$nbFerie."\n";
979 return $nbFerie;
980}
981
992function num_between_day($timestampStart, $timestampEnd, $lastday = 0)
993{
994 if ($timestampStart < $timestampEnd) {
995 if ($lastday == 1) {
996 $bit = 0;
997 } else {
998 $bit = 1;
999 }
1000 $nbjours = (int) floor(($timestampEnd - $timestampStart) / (60 * 60 * 24)) + 1 - $bit;
1001 }
1002 //print ($timestampEnd - $timestampStart) - $lastday;
1003 return $nbjours;
1004}
1005
1018function num_open_day($timestampStart, $timestampEnd, $inhour = 0, $lastday = 0, $halfday = 0, $country_code = '')
1019{
1020 global $langs, $mysoc;
1021
1022 if (empty($country_code)) {
1023 $country_code = $mysoc->country_code;
1024 }
1025
1026 dol_syslog('num_open_day timestampStart='.$timestampStart.' timestampEnd='.$timestampEnd.' bit='.$lastday.' country_code='.$country_code);
1027
1028 // Check parameters
1029 if (!is_int($timestampStart) && !is_float($timestampStart)) {
1030 return 'ErrorBadParameter_num_open_day';
1031 }
1032 if (!is_int($timestampEnd) && !is_float($timestampEnd)) {
1033 return 'ErrorBadParameter_num_open_day';
1034 }
1035
1036 //print 'num_open_day timestampStart='.$timestampStart.' timestampEnd='.$timestampEnd.' bit='.$lastday;
1037 if ($timestampStart < $timestampEnd) {
1038 $numdays = num_between_day($timestampStart, $timestampEnd, $lastday);
1039
1040 $numholidays = num_public_holiday($timestampStart, $timestampEnd, $country_code, $lastday);
1041 $nbOpenDay = ($numdays - $numholidays);
1042 if ($inhour == 1 && $nbOpenDay <= 3) {
1043 $nbOpenDay = ($nbOpenDay * 24);
1044 }
1045 return $nbOpenDay - (($inhour == 1 ? 12 : 0.5) * abs($halfday));
1046 } elseif ($timestampStart == $timestampEnd) {
1047 $numholidays = 0;
1048 if ($lastday) {
1049 $numholidays = num_public_holiday($timestampStart, $timestampEnd, $country_code, $lastday);
1050 if ($numholidays == 1) {
1051 return 0;
1052 }
1053 }
1054
1055 $nbOpenDay = $lastday;
1056
1057 if ($inhour == 1) {
1058 $nbOpenDay = ($nbOpenDay * 24);
1059 }
1060 return $nbOpenDay - (($inhour == 1 ? 12 : 0.5) * abs($halfday));
1061 } else {
1062 return $langs->trans("Error");
1063 }
1064}
1065
1066
1067
1076function monthArray($outputlangs, $short = 0)
1077{
1078 $montharray = array(
1079 1 => $outputlangs->trans("Month01"),
1080 2 => $outputlangs->trans("Month02"),
1081 3 => $outputlangs->trans("Month03"),
1082 4 => $outputlangs->trans("Month04"),
1083 5 => $outputlangs->trans("Month05"),
1084 6 => $outputlangs->trans("Month06"),
1085 7 => $outputlangs->trans("Month07"),
1086 8 => $outputlangs->trans("Month08"),
1087 9 => $outputlangs->trans("Month09"),
1088 10 => $outputlangs->trans("Month10"),
1089 11 => $outputlangs->trans("Month11"),
1090 12 => $outputlangs->trans("Month12")
1091 );
1092
1093 if (!empty($short)) {
1094 $montharray = array(
1095 1 => $outputlangs->trans("MonthShort01"),
1096 2 => $outputlangs->trans("MonthShort02"),
1097 3 => $outputlangs->trans("MonthShort03"),
1098 4 => $outputlangs->trans("MonthShort04"),
1099 5 => $outputlangs->trans("MonthShort05"),
1100 6 => $outputlangs->trans("MonthShort06"),
1101 7 => $outputlangs->trans("MonthShort07"),
1102 8 => $outputlangs->trans("MonthShort08"),
1103 9 => $outputlangs->trans("MonthShort09"),
1104 10 => $outputlangs->trans("MonthShort10"),
1105 11 => $outputlangs->trans("MonthShort11"),
1106 12 => $outputlangs->trans("MonthShort12")
1107 );
1108 }
1109
1110 return $montharray;
1111}
1119function getWeekNumbersOfMonth($month, $year)
1120{
1121 $nb_days = cal_days_in_month(CAL_GREGORIAN, $month, $year);
1122 $TWeek = array();
1123 for ($day = 1; $day < $nb_days; $day++) {
1124 $week_number = getWeekNumber($day, $month, $year);
1125 $TWeek[$week_number] = $week_number;
1126 }
1127 return $TWeek;
1128}
1136function getFirstDayOfEachWeek($TWeek, $year)
1137{
1138 $TFirstDayOfWeek = array();
1139 foreach ($TWeek as $weekNb) {
1140 if (in_array('01', $TWeek) && in_array('52', $TWeek) && $weekNb == '01') {
1141 $year++; //Si on a la 1re semaine et la semaine 52 c'est qu'on change d'année
1142 }
1143 $TFirstDayOfWeek[$weekNb] = date('d', strtotime($year.'W'.$weekNb));
1144 }
1145 return $TFirstDayOfWeek;
1146}
1154function getLastDayOfEachWeek($TWeek, $year)
1155{
1156 $TLastDayOfWeek = array();
1157 foreach ($TWeek as $weekNb) {
1158 $TLastDayOfWeek[$weekNb] = date('d', strtotime($year.'W'.$weekNb.'+6 days'));
1159 }
1160 return $TLastDayOfWeek;
1161}
1170function getWeekNumber($day, $month, $year)
1171{
1172 $date = new DateTime($year.'-'.$month.'-'.$day);
1173 $week = $date->format("W");
1174 return $week;
1175}
dol_get_prev_month($month, $year)
Return previous month.
Definition date.lib.php:497
dol_get_first_hour($date, $gm='tzserver')
Return GMT time for first hour of a given GMT date (it removes hours, min and second part)
Definition date.lib.php:638
dol_get_next_day($day, $month, $year)
Return next day.
Definition date.lib.php:482
dol_get_next_week($day, $week, $month, $year)
Return next week.
Definition date.lib.php:556
dolSqlDateFilter($datefield, $day_date, $month_date, $year_date, $excludefirstand=0, $gm=false)
Generate a SQL string to make a filter into a range (for second of date until last second of date).
Definition date.lib.php:361
getServerTimeZoneString()
Return server timezone string.
Definition date.lib.php:73
dol_get_last_hour($date, $gm='tzserver')
Return GMT time for last hour of a given GMT date (it replaces hours, min and second part to 23:59:59...
Definition date.lib.php:624
getLastDayOfEachWeek($TWeek, $year)
Return array of last day of weeks.
getWeekNumbersOfMonth($month, $year)
Return array of week numbers.
getServerTimeZoneInt($refgmtdate='now')
Return server timezone int.
Definition date.lib.php:84
dol_get_first_day_week($day, $month, $year, $gm=false)
Return first day of week for a date.
Definition date.lib.php:653
getGMTEasterDatetime($year)
Return the easter day in GMT time.
Definition date.lib.php:723
convertDurationtoHour($duration_value, $duration_unit)
Convert duration to hour.
Definition date.lib.php:333
get_tz_array()
Return an array with timezone values.
Definition date.lib.php:34
dol_get_prev_day($day, $month, $year)
Return previous day.
Definition date.lib.php:466
dol_get_first_day($year, $month=1, $gm=false)
Return GMT time for first day of a month or year.
Definition date.lib.php:578
getFirstDayOfEachWeek($TWeek, $year)
Return array of first day of weeks.
dol_get_next_month($month, $year)
Return next month.
Definition date.lib.php:516
getWeekNumber($day, $month, $year)
Return week number.
num_between_day($timestampStart, $timestampEnd, $lastday=0)
Function to return number of days between two dates (date must be UTC date !) Example: 2012-01-01 201...
Definition date.lib.php:992
convertTime2Seconds($iHours=0, $iMinutes=0, $iSeconds=0)
Convert hours and minutes into seconds.
Definition date.lib.php:212
num_open_day($timestampStart, $timestampEnd, $inhour=0, $lastday=0, $halfday=0, $country_code='')
Function to return number of working days (and text of units) between two dates (working days)
dol_time_plus_duree($time, $duration_value, $duration_unit, $ruleforendofmonth=0)
Add a delay to a date.
Definition date.lib.php:123
convertSecondToTime($iSecond, $format='all', $lengthOfDay=86400, $lengthOfWeek=7)
Return, in clear text, value of a number of seconds in days, hours and minutes.
Definition date.lib.php:241
dol_get_prev_week($day, $week, $month, $year)
Return previous week.
Definition date.lib.php:537
dol_stringtotime($string, $gm=1)
Convert a string date into a GM Timestamps date Warning: YYYY-MM-DDTHH:MM:SS+02:00 (RFC3339) is not s...
Definition date.lib.php:410
dol_get_last_day($year, $month=12, $gm=false)
Return GMT time for last day of a month or year.
Definition date.lib.php:597
monthArray($outputlangs, $short=0)
Return array of translated months or selected month.
num_public_holiday($timestampStart, $timestampEnd, $country_code='', $lastday=0, $includesaturday=-1, $includesunday=-1, $includefriday=-1, $includemonday=-1)
Return the number of non working days including Friday, Saturday and Sunday (or not) between 2 dates ...
Definition date.lib.php:747
dol_mktime($hour, $minute, $second, $month, $day, $year, $gm='auto', $check=1)
Return a timestamp date built from detailed informations (by default a local PHP server timestamp) Re...
dol_print_error($db='', $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs='', $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
dol_now($mode='auto')
Return date for now.
dol_getIdFromCode($db, $key, $tablename, $fieldkey='code', $fieldid='id', $entityfilter=0, $filters='')
Return an id or code from a code or id.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
dol_getdate($timestamp, $fast=false, $forcetimezone='')
Return an array with locale date info.