dolibarr 24.0.3
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-2024 Charlene Benke <charlene@patas-monkey.com>
7 * Copyright (C) 2024-2026 MDW <mdeweerd@users.noreply.github.com>
8 * Copyright (C) 2024-2026 Frédéric France <frederic.france@free.fr>
9 * Copyright (C) 2026 Joachim Küter <git-jk@bloxera.com>
10 *
11 * This program is free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation; either version 3 of the License, or
14 * (at your option) any later version.
15 *
16 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU General Public License for more details.
20 *
21 * You should have received a copy of the GNU General Public License
22 * along with this program. If not, see <https://www.gnu.org/licenses/>.
23 * or see https://www.gnu.org/
24 */
25
37function get_tz_array()
38{
39 $tzarray = array(
40 -11 => "Pacific/Pago_Pago",
41 -10 => "Pacific/Honolulu",
42 -9 => "America/Anchorage",
43 -8 => "America/Los_Angeles",
44 -7 => "America/Dawson_Creek",
45 -6 => "America/Chicago",
46 -5 => "America/Bogota",
47 -4 => "America/Asuncion",
48 -3 => "America/Araguaina",
49 -2 => "America/Noronha",
50 -1 => "Atlantic/Azores",
51 0 => "Europe/London",
52 1 => "Europe/Paris",
53 2 => "Europe/Helsinki",
54 3 => "Europe/Moscow",
55 4 => "Asia/Dubai",
56 5 => "Asia/Karachi",
57 6 => "Indian/Chagos",
58 7 => "Asia/Jakarta",
59 8 => "Asia/Hong_Kong",
60 9 => "Asia/Tokyo",
61 10 => "Australia/Sydney",
62 11 => "Pacific/Noumea",
63 12 => "Pacific/Auckland",
64 13 => "Pacific/Fakaofo",
65 14 => "Pacific/Kiritimati"
66 );
67 return $tzarray;
68}
69
70
77{
78 return @date_default_timezone_get();
79}
80
87function getServerTimeZoneInt($refgmtdate = 'now')
88{
89 if (method_exists('DateTimeZone', 'getOffset')) {
90 // Method 1 (include daylight)
91 $gmtnow = dol_now('gmt');
92 $yearref = dol_print_date($gmtnow, '%Y');
93 $monthref = dol_print_date($gmtnow, '%m');
94 $dayref = dol_print_date($gmtnow, '%d');
95 if ($refgmtdate == 'now') {
96 $newrefgmtdate = $yearref.'-'.$monthref.'-'.$dayref;
97 } elseif ($refgmtdate == 'summer') {
98 $newrefgmtdate = $yearref.'-08-01';
99 } else {
100 $newrefgmtdate = $yearref.'-01-01';
101 }
102 $newrefgmtdate .= 'T00:00:00+00:00';
103 $localtz = new DateTimeZone(getServerTimeZoneString());
104 $localdt = new DateTime($newrefgmtdate, $localtz);
105 $tmp = -1 * $localtz->getOffset($localdt);
106 //print $refgmtdate.'='.$tmp;
107 } else {
108 $tmp = 0;
109 dol_print_error(null, 'PHP version must be 5.3+');
110 }
111 $tz = round(($tmp < 0 ? 1 : -1) * abs($tmp / 3600));
112 return $tz;
113}
114
115
129function dol_time_plus_duree($time, $duration_value, $duration_unit, $ruleforendofmonth = 0, $tz = '')
130{
131 if (empty($duration_value)) {
132 return $time;
133 }
134 if ($duration_unit == 's') {
135 return $time + (int) ($duration_value);
136 }
137 if ($duration_unit == 'i' || $duration_unit == 'mn' || $duration_unit == 'min') {
138 return $time + (int) (60 * $duration_value);
139 }
140 if ($duration_unit == 'h') {
141 return $time + (int) (3600 * $duration_value);
142 }
143 if ($duration_unit == 'w') {
144 return $time + (int) (3600 * 24 * 7 * $duration_value);
145 }
146
147 $deltastring = 'P';
148
149 $sub = false;
150
151 if ($duration_value > 0) {
152 $deltastring .= abs($duration_value);
153 $sub = false;
154 }
155 if ($duration_value < 0) {
156 $deltastring .= abs($duration_value);
157 $sub = true;
158 }
159 if ($duration_unit == 'd') {
160 $deltastring .= "D";
161 }
162 if ($duration_unit == 'm') {
163 $deltastring .= "M";
164 }
165 if ($duration_unit == 'y') {
166 $deltastring .= "Y";
167 }
168
169 $date = new DateTime();
170 if ($tz == 'gmt') {
171 $date->setTimezone(new DateTimeZone('UTC'));
172 } elseif ($tz !== '') {
173 $date->setTimezone(new DateTimeZone($tz == 'tzserver' ? date_default_timezone_get() : $tz));
174 } elseif (!function_exists('getDolGlobalString') || !getDolGlobalString('MAIN_DATE_IN_MEMORY_ARE_NOT_GMT')) { // Add function_exists to allow usage of this function with minimal context
175 $date->setTimezone(new DateTimeZone('UTC'));
176 }
177
178
179 $date->setTimestamp((int) $time);
180 $interval = new DateInterval($deltastring);
181
182 if ($sub) {
183 $date->sub($interval);
184 } else {
185 $date->add($interval);
186 }
187
188 // 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)
189 if ($ruleforendofmonth == 1 && $duration_unit == 'm' && $tz !== '') {
190 // Months are compared in the same timezone than the one used to add the delay
191 $origin = new DateTime('@'.((int) $time));
192 $origin->setTimezone($date->getTimezone());
193 $monthsexpected = ((int) $origin->format('Y') * 12) + (int) $origin->format('n') + (int) $duration_value;
194 if (((int) $date->format('Y') * 12) + (int) $date->format('n') != $monthsexpected) {
195 $date->modify('last day of previous month'); // Keep the time of the day
196 }
197 } elseif ($ruleforendofmonth == 1 && $duration_unit == 'm') {
198 $timeyear = (int) dol_print_date($time, '%Y');
199 $timemonth = (int) dol_print_date($time, '%m');
200 $timetotalmonths = (($timeyear * 12) + $timemonth);
201
202 $monthsexpected = ($timetotalmonths + $duration_value);
203
204 $newtime = $date->getTimestamp();
205
206 $newtimeyear = (int) dol_print_date($newtime, '%Y');
207 $newtimemonth = (int) dol_print_date($newtime, '%m');
208 $newtimetotalmonths = (($newtimeyear * 12) + $newtimemonth);
209
210 if ($monthsexpected < $newtimetotalmonths || $monthsexpected > $newtimetotalmonths) { // If months differs
211 $newtimehours = (int) dol_print_date($newtime, '%H');
212 $newtimemins = (int) dol_print_date($newtime, '%M');
213 $newtimesecs = (int) dol_print_date($newtime, '%S');
214
215 $datelim = dol_mktime($newtimehours, $newtimemins, $newtimesecs, $newtimemonth, 1, $newtimeyear); // Take first day
216 $datelim -= (3600 * 24); // Remove 1 day to get the last day of month
217
218 $date->setTimestamp($datelim); // Set new date
219 }
220 }
221 return $date->getTimestamp();
222}
223
224
234function convertTime2Seconds($iHours = 0, $iMinutes = 0, $iSeconds = 0)
235{
236 $iResult = ((int) $iHours * 3600) + ((int) $iMinutes * 60) + (int) $iSeconds;
237 return $iResult;
238}
239
240
263function convertSecondToTime($iSecond, $format = 'all', $lengthOfDay = 86400, $lengthOfWeek = 7)
264{
265 global $langs;
266
267 if (empty($lengthOfDay)) {
268 $lengthOfDay = 86400; // 1 day = 24 hours
269 }
270 if (empty($lengthOfWeek)) {
271 $lengthOfWeek = 7; // 1 week = 7 days
272 }
273 $nbHbyDay = $lengthOfDay / 3600;
274
275 $sTime = '';
276
277 if ($format == 'all' || $format == 'allwithouthour' || $format == 'allhour' || $format == 'allhourmin' || $format == 'allhourminsec') {
278 if ((int) $iSecond === 0) {
279 return '0'; // This is to avoid having 0 return a 12:00 AM for en_US
280 }
281
282 $sDay = 0;
283 $sWeek = 0;
284
285 if ($iSecond >= $lengthOfDay) {
286 for ($i = $iSecond; $i >= $lengthOfDay; $i -= $lengthOfDay) {
287 $sDay++;
288 $iSecond -= $lengthOfDay;
289 }
290 $dayTranslate = $langs->trans("Day");
291 if ($iSecond >= ($lengthOfDay * 2)) {
292 $dayTranslate = $langs->trans("Days");
293 }
294 }
295
296 if ($lengthOfWeek < 7) {
297 if ($sDay) {
298 if ($sDay >= $lengthOfWeek) {
299 $sWeek = (int) (($sDay - $sDay % $lengthOfWeek) / $lengthOfWeek);
300 $sDay %= $lengthOfWeek;
301 $weekTranslate = $langs->trans("DurationWeek");
302 if ($sWeek >= 2) {
303 $weekTranslate = $langs->trans("DurationWeeks");
304 }
305 $sTime .= $sWeek.' '.$weekTranslate.' ';
306 }
307 }
308 }
309 if ($sDay > 0) {
310 $dayTranslate = $langs->trans("Day");
311 if ($sDay > 1) {
312 $dayTranslate = $langs->trans("Days");
313 }
314 $sTime .= $sDay.' '.$langs->trans("d").' ';
315 }
316
317 if ($format == 'all') {
318 if ($iSecond || empty($sDay)) {
319 $sTime .= dol_print_date($iSecond, 'hourduration', true);
320 }
321 } elseif ($format == 'allhourminsec') {
322 return sprintf("%02d", ($sWeek * $lengthOfWeek * $nbHbyDay + $sDay * $nbHbyDay + (int) floor($iSecond / 3600))).':'.sprintf("%02d", ((int) floor(($iSecond % 3600) / 60))).':'.sprintf("%02d", ((int) ($iSecond % 60)));
323 } elseif ($format == 'allhourmin') {
324 return sprintf("%02d", ($sWeek * $lengthOfWeek * $nbHbyDay + $sDay * $nbHbyDay + (int) floor($iSecond / 3600))).':'.sprintf("%02d", ((int) floor(($iSecond % 3600) / 60)));
325 } elseif ($format == 'allhour') {
326 return sprintf("%02d", ($sWeek * $lengthOfWeek * $nbHbyDay + $sDay * $nbHbyDay + (int) floor($iSecond / 3600)));
327 }
328 } elseif ($format == 'hour') { // only hour part
329 $sTime = dol_print_date($iSecond, '%H', true);
330 } elseif ($format == 'fullhour') {
331 if (!empty($iSecond)) {
332 $iSecond /= 3600;
333 } else {
334 $iSecond = 0;
335 }
336 $sTime = $iSecond;
337 } elseif ($format == 'min') { // only min part
338 $sTime = dol_print_date($iSecond, '%M', true);
339 } elseif ($format == 'sec') { // only sec part
340 $sTime = dol_print_date($iSecond, '%S', true);
341 } elseif ($format == 'month') { // only month part
342 $sTime = dol_print_date($iSecond, '%m', true);
343 } elseif ($format == 'year') { // only year part
344 $sTime = dol_print_date($iSecond, '%Y', true);
345 }
346 return trim((string) $sTime);
347}
348
349
357function convertDurationtoHour($duration_value, $duration_unit)
358{
359 $result = 0;
360
361 if ($duration_unit == 's') {
362 $result = $duration_value / 3600;
363 }
364 if ($duration_unit == 'i' || $duration_unit == 'mn' || $duration_unit == 'min') {
365 $result = $duration_value / 60;
366 }
367 if ($duration_unit == 'h') {
368 $result = $duration_value;
369 }
370 if ($duration_unit == 'd') {
371 $result = $duration_value * 24;
372 }
373 if ($duration_unit == 'w') {
374 $result = $duration_value * 24 * 7;
375 }
376 if ($duration_unit == 'm') {
377 $result = $duration_value * 730.484;
378 }
379 if ($duration_unit == 'y') {
380 $result = $duration_value * 365 * 24;
381 }
382
383 return $result;
384}
385
401function dolSqlDateFilter($datefield, $day_date, $month_date, $year_date, $excludefirstand = 0, $gm = false)
402{
403 global $db;
404 $sqldate = '';
405
406 $day_date = intval($day_date);
407 $month_date = intval($month_date);
408 $year_date = intval($year_date);
409 $sql_datefield = $db->sanitize($datefield);
410
411 if ($month_date > 0) {
412 if ($month_date > 12) { // protection for bad value of month
413 return " AND 1 = 2";
414 }
415 if ($year_date > 0 && empty($day_date)) {
416 $sqldate .= ($excludefirstand ? "" : " AND ").$sql_datefield." BETWEEN '".$db->idate(dol_get_first_day($year_date, $month_date, $gm))."'";
417 $sqldate .= " AND '".$db->idate(dol_get_last_day($year_date, $month_date, $gm))."'";
418 } elseif ($year_date > 0 && !empty($day_date)) {
419 $sqldate .= ($excludefirstand ? "" : " AND ").$sql_datefield." BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $month_date, $day_date, $year_date, $gm))."'";
420 $sqldate .= " AND '".$db->idate(dol_mktime(23, 59, 59, $month_date, $day_date, $year_date, $gm))."'";
421 } else {
422 // This case is not reliable on TZ, but we should not need it.
423 $sqldate .= ($excludefirstand ? "" : " AND ")." date_format( ".$sql_datefield.", '%c') = '".$db->escape((string) $month_date)."'";
424 }
425 } elseif ($year_date > 0) {
426 $sqldate .= ($excludefirstand ? "" : " AND ").$sql_datefield." BETWEEN '".$db->idate(dol_get_first_day($year_date, 1, $gm))."'";
427 $sqldate .= " AND '".$db->idate(dol_get_last_day($year_date, 12, $gm))."'";
428 }
429 return $sqldate;
430}
431
451function dol_stringtotime($string, $gm = 1)
452{
453 $reg = array();
454 // Convert date with format DD/MM/YYY HH:MM:SS. This part of code should not be used.
455 if (preg_match('/^([0-9]+)\/([0-9]+)\/([0-9]+)\s?([0-9]+)?:?([0-9]+)?:?([0-9]+)?/i', $string, $reg)) {
456 dol_syslog("dol_stringtotime call to function with deprecated parameter format", LOG_WARNING);
457 // Date is in format 'DD/MM/YY' or 'DD/MM/YY HH:MM:SS'
458 // Date is in format 'DD/MM/YYYY' or 'DD/MM/YYYY HH:MM:SS'
459 $sday = (int) $reg[1];
460 $smonth = (int) $reg[2];
461 $syear = (int) $reg[3];
462 $shour = (int) $reg[4];
463 $smin = (int) $reg[5];
464 $ssec = (int) $reg[6];
465 if ($syear < 50) {
466 $syear += 1900;
467 }
468 if ($syear >= 50 && $syear < 100) {
469 $syear += 2000;
470 }
471 $string = sprintf("%04d%02d%02d%02d%02d%02d", $syear, $smonth, $sday, $shour, $smin, $ssec);
472 } 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)
473 || 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
474 || 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
475 ) {
476 $syear = (int) $reg[1];
477 $smonth = (int) $reg[2];
478 $sday = (int) $reg[3];
479 $shour = (int) $reg[4];
480 $smin = (int) $reg[5];
481 $ssec = (int) $reg[6];
482 $string = sprintf("%04d%02d%02d%02d%02d%02d", $syear, $smonth, $sday, $shour, $smin, $ssec);
483 }
484
485 $string = preg_replace('/([^0-9])/i', '', $string);
486 $tmp = $string.'000000';
487 // Clean $gm
488 if ($gm === 1) {
489 $gm = 'gmt';
490 } elseif (empty($gm) || $gm === 'tzserver') {
491 $gm = 'tzserver';
492 }
493
494 $date = dol_mktime((int) substr($tmp, 8, 2), (int) substr($tmp, 10, 2), (int) substr($tmp, 12, 2), (int) substr($tmp, 4, 2), (int) substr($tmp, 6, 2), (int) substr($tmp, 0, 4), $gm);
495
496 return $date;
497}
498
499
508function dol_get_prev_day($day, $month, $year)
509{
510 $time = dol_mktime(12, 0, 0, $month, $day, $year, 1, 0);
511 $time -= 24 * 60 * 60;
512 $tmparray = dol_getdate($time, true);
513 return array('year' => $tmparray['year'], 'month' => $tmparray['mon'], 'day' => $tmparray['mday']);
514}
515
524function dol_get_next_day($day, $month, $year)
525{
526 $time = dol_mktime(12, 0, 0, $month, $day, $year, 1, 0);
527 $time += 24 * 60 * 60;
528 $tmparray = dol_getdate($time, true);
529 return array('year' => $tmparray['year'], 'month' => $tmparray['mon'], 'day' => $tmparray['mday']);
530}
531
539function dol_get_prev_month($month, $year)
540{
541 if ($month == 1) {
542 $prev_month = 12;
543 $prev_year = $year - 1;
544 } else {
545 $prev_month = $month - 1;
546 $prev_year = $year;
547 }
548 return array('year' => $prev_year, 'month' => $prev_month);
549}
550
558function dol_get_next_month($month, $year)
559{
560 if ($month == 12) {
561 $next_month = 1;
562 $next_year = $year + 1;
563 } else {
564 $next_month = $month + 1;
565 $next_year = $year;
566 }
567 return array('year' => $next_year, 'month' => $next_month);
568}
569
579function dol_get_prev_week($day, $week, $month, $year)
580{
581 $tmparray = dol_get_first_day_week($day, $month, $year);
582
583 $time = dol_mktime(12, 0, 0, $tmparray['first_month'], $tmparray['first_day'], $tmparray['first_year'], 1, 0);
584 $time -= 24 * 60 * 60 * 7;
585 $tmparray = dol_getdate($time, true);
586 return array('year' => $tmparray['year'], 'month' => $tmparray['mon'], 'day' => $tmparray['mday']);
587}
588
598function dol_get_next_week($day, $week, $month, $year)
599{
600 $tmparray = dol_get_first_day_week($day, $month, $year);
601
602 $time = dol_mktime(12, 0, 0, $tmparray['first_month'], $tmparray['first_day'], $tmparray['first_year'], 1, 0);
603 $time += 24 * 60 * 60 * 7;
604 $tmparray = dol_getdate($time, true);
605
606 return array('year' => $tmparray['year'], 'month' => $tmparray['mon'], 'day' => $tmparray['mday']);
607}
608
620function dol_get_first_day($year, $month = 1, $gm = false)
621{
622 if ($year > 9999) {
623 return '';
624 }
625 return dol_mktime(0, 0, 0, $month, 1, $year, $gm);
626}
627
628
639function dol_get_last_day($year, $month = 12, $gm = false)
640{
641 if ($year > 9999) {
642 return '';
643 }
644 if ($month == 12) {
645 $month = 1;
646 $year += 1;
647 } else {
648 $month += 1;
649 }
650
651 // Move to the start of the next month, then subtract one day
652 $datelim = dol_mktime(23, 59, 59, $month, 1, $year, $gm);
653 $datelim -= (3600 * 24);
654
655 return $datelim;
656}
657
666function dol_get_last_hour($date, $gm = 'tzserver')
667{
668 $tmparray = dol_getdate($date, false, ($gm == 'gmt' ? 'gmt' : ''));
669 return dol_mktime(23, 59, 59, $tmparray['mon'], $tmparray['mday'], $tmparray['year'], $gm);
670}
671
680function dol_get_first_hour($date, $gm = 'tzserver')
681{
682 $tmparray = dol_getdate($date, false, ($gm == 'gmt' ? 'gmt' : ''));
683 return dol_mktime(0, 0, 0, $tmparray['mon'], $tmparray['mday'], $tmparray['year'], $gm);
684}
685
695function dol_get_first_day_week($day, $month, $year, $gm = false)
696{
697 //$day=2; $month=2; $year=2015;
698 $date = dol_mktime(0, 0, 0, $month, $day, $year, $gm);
699
700 //Checking conf of start week
701 $start_week = getDolGlobalInt('MAIN_START_WEEK', 1);
702
703 $tmparray = dol_getdate($date, true); // detail of current day
704
705 //Calculate days = offset from current day
706 $days = $start_week - $tmparray['wday'];
707 if ($days >= 1) {
708 $days = 7 - $days;
709 }
710 $days = abs($days);
711 $seconds = $days * 24 * 60 * 60;
712 //print 'start_week='.$start_week.' tmparray[wday]='.$tmparray['wday'].' day offset='.$days.' seconds offset='.$seconds.'<br>';
713
714 //Get first day of week
715 $tmpdaytms = (int) date((string) $tmparray['0']) - $seconds; // $tmparray[0] is day of parameters
716 $tmpday = idate("d", $tmpdaytms);
717
718 //Check first day of week is in same month than current day or not
719 if ($tmpday > $day) {
720 $prev_month = $month - 1;
721 $prev_year = $year;
722
723 if ($prev_month == 0) {
724 $prev_month = 12;
725 $prev_year = $year - 1;
726 }
727 } else {
728 $prev_month = $month;
729 $prev_year = $year;
730 }
731 $tmpmonth = $prev_month;
732 $tmpyear = $prev_year;
733
734 //Get first day of next week
735 $tmptime = dol_mktime(12, 0, 0, $month, $tmpday, $year, 1, 0);
736 $tmptime -= 24 * 60 * 60 * 7;
737 $tmparray = dol_getdate($tmptime, true);
738 $prev_day = $tmparray['mday'];
739
740 //Check prev day of week is in same month than first day or not
741 if ($prev_day > $tmpday) {
742 $prev_month = $month - 1;
743 $prev_year = $year;
744
745 if ($prev_month == 0) {
746 $prev_month = 12;
747 $prev_year = $year - 1;
748 }
749 }
750
751 $week = date("W", dol_mktime(0, 0, 0, $tmpmonth, $tmpday, $tmpyear, $gm));
752
753 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);
754}
755
763function getGMTEasterDatetime($year)
764{
765 $base = new DateTime("$year-03-21", new DateTimeZone("UTC"));
766 $days = easter_days($year); // Return number of days between 21 march and easter day.
767 $tmp = $base->add(new DateInterval("P{$days}D"));
768 return $tmp->getTimestamp();
769}
770
787function num_public_holiday($timestampStart, $timestampEnd, $countryCodeOrId = '', $lastday = 0, $includesaturday = -1, $includesunday = -1, $includefriday = -1, $includemonday = -1)
788{
789 global $conf, $db, $mysoc;
790
791 $nbFerie = 0;
792
793 // Check to ensure we use correct parameters
794 if (($timestampEnd - $timestampStart) % 86400 != 0) {
795 return 'Error Dates must use same hours and must be GMT dates';
796 }
797
798 if (empty($countryCodeOrId)) {
799 $countryCodeOrId = $mysoc->country_code;
800 }
801 if ($includemonday < 0) {
802 $includemonday = getDolGlobalInt('MAIN_NON_WORKING_DAYS_INCLUDE_MONDAY', 0);
803 }
804 if ($includefriday < 0) {
805 $includefriday = getDolGlobalInt('MAIN_NON_WORKING_DAYS_INCLUDE_FRIDAY', 0);
806 }
807 if ($includesaturday < 0) {
808 $includesaturday = getDolGlobalInt('MAIN_NON_WORKING_DAYS_INCLUDE_SATURDAY', 1);
809 }
810 if ($includesunday < 0) {
811 $includesunday = getDolGlobalInt('MAIN_NON_WORKING_DAYS_INCLUDE_SUNDAY', 1);
812 }
813
814 if (is_numeric($countryCodeOrId)) {
815 $country_id = $countryCodeOrId;
816 } else {
817 $country_id = dol_getIdFromCode($db, $countryCodeOrId, 'c_country', 'code', 'rowid');
818 }
819
820 if (empty($conf->cache['arrayOfActivePublicHolidays_'.$country_id])) {
821 // Loop on public holiday defined into hrm_public_holiday for the day, month and year analyzed
822 $tmpArrayOfPublicHolidays = array();
823 $sql = "SELECT id, code, entity, fk_country, dayrule, year, month, day, active";
824 $sql .= " FROM ".MAIN_DB_PREFIX."c_hrm_public_holiday";
825 // A public holiday created without a country has fk_country NULL, and NULL never matches an IN list,
826 // so such a holiday was ignored and the day was counted as a working day.
827 $sql .= " WHERE active = 1 and (fk_country IS NULL OR fk_country IN (0".($country_id > 0 ? ", ".((int) $country_id) : 0)."))";
828 $sql .= " AND entity IN (0," .getEntity('holiday') .")";
829
830 $resql = $db->query($sql);
831 if ($resql) {
832 $num_rows = $db->num_rows($resql);
833 $i = 0;
834 while ($i < $num_rows) {
835 $obj = $db->fetch_object($resql);
836 $tmpArrayOfPublicHolidays[$obj->id] = array('dayrule' => $obj->dayrule, 'year' => $obj->year, 'month' => $obj->month, 'day' => $obj->day);
837 $i++;
838 }
839 } else {
840 dol_syslog($db->lasterror(), LOG_ERR);
841 return 'Error sql '.$db->lasterror();
842 }
843
844 //var_dump($tmpArrayOfPublicHolidays);
845 $conf->cache['arrayOfActivePublicHolidays_'.$country_id] = $tmpArrayOfPublicHolidays;
846 }
847
848 $arrayOfPublicHolidays = $conf->cache['arrayOfActivePublicHolidays_'.$country_id];
849
850 $i = 0;
851 while ((($lastday == 0 && $timestampStart < $timestampEnd) || ($lastday && $timestampStart <= $timestampEnd))
852 && ($i < 50000)) { // Loop end when equals (Test on i is a security loop to avoid infinite loop)
853 $ferie = false;
854 $specialdayrule = array();
855
856 $jour = (int) gmdate("d", $timestampStart);
857 $mois = (int) gmdate("m", $timestampStart);
858 $annee = (int) gmdate("Y", $timestampStart);
859 $jour_semaine = (int) gmdate("w", $timestampStart); // sunday = 0, monday = 1, ...
860
861 //print "jour=".$jour." month=".$mois." year=".$annee." includesaturday=".$includesaturday." includesunday=".$includesunday."\n";
862 foreach ($arrayOfPublicHolidays as $entrypublicholiday) {
863 if (!empty($entrypublicholiday['dayrule']) && $entrypublicholiday['dayrule'] != 'date') { // For example 'easter', '...'
864 $specialdayrule[$entrypublicholiday['dayrule']] = $entrypublicholiday['dayrule'];
865 } else {
866 $match = 1;
867 if (!empty($entrypublicholiday['year']) && $entrypublicholiday['year'] != $annee) {
868 $match = 0;
869 }
870 if ($entrypublicholiday['month'] != $mois) {
871 $match = 0;
872 }
873 if ($entrypublicholiday['day'] != $jour) {
874 $match = 0;
875 }
876
877 if ($match) {
878 $ferie = true;
879 }
880 }
881
882 $i++;
883 }
884 //var_dump($specialdayrule)."\n";
885 //print "ferie=".$ferie."\n";
886
887 if (!$ferie) {
888 // Special dayrules
889 if (in_array('easter', $specialdayrule)) {
890 // Calculation for easter date
891 $date_paques = getGMTEasterDatetime($annee);
892 $jour_paques = gmdate("d", $date_paques);
893 $mois_paques = gmdate("m", $date_paques);
894 if ($jour_paques == $jour && $mois_paques == $mois) {
895 $ferie = true;
896 }
897 // Easter (sunday)
898 }
899
900 if (in_array('eastermonday', $specialdayrule)) {
901 // Calculation for the monday of easter date
902 $date_paques = getGMTEasterDatetime($annee);
903 //print 'PPP'.$date_paques.' '.dol_print_date($date_paques, 'dayhour', 'gmt')." ";
904 $date_lundi_paques = $date_paques + (3600 * 24);
905 $jour_lundi_paques = gmdate("d", $date_lundi_paques);
906 $mois_lundi_paques = gmdate("m", $date_lundi_paques);
907 if ($jour_lundi_paques == $jour && $mois_lundi_paques == $mois) {
908 $ferie = true;
909 }
910 // Easter (monday)
911 //print 'annee='.$annee.' $jour='.$jour.' $mois='.$mois.' $jour_lundi_paques='.$jour_lundi_paques.' $mois_lundi_paques='.$mois_lundi_paques."\n";
912 }
913
914 //Good Friday
915 if (in_array('goodfriday', $specialdayrule)) {
916 // Pulls the date of Easter
917 $easter = getGMTEasterDatetime($annee);
918
919 // Calculates the date of Good Friday based on Easter
920 $date_good_friday = $easter - (2 * 3600 * 24);
921 $dom_good_friday = gmdate("d", $date_good_friday);
922 $month_good_friday = gmdate("m", $date_good_friday);
923
924 if ($dom_good_friday == $jour && $month_good_friday == $mois) {
925 $ferie = true;
926 }
927 }
928
929 if (in_array('ascension', $specialdayrule)) {
930 // Calculation of Ascension day (39 days after easter day)
931 $date_paques = getGMTEasterDatetime($annee);
932 $date_ascension = $date_paques + (3600 * 24 * 39);
933 $jour_ascension = gmdate("d", $date_ascension);
934 $mois_ascension = gmdate("m", $date_ascension);
935 if ($jour_ascension == $jour && $mois_ascension == $mois) {
936 $ferie = true;
937 }
938 // Ascension (thursday)
939 }
940
941 if (in_array('pentecost', $specialdayrule)) {
942 // Calculation of "Pentecote" (49 days after easter day)
943 $date_paques = getGMTEasterDatetime($annee);
944 $date_pentecote = $date_paques + (3600 * 24 * 49);
945 $jour_pentecote = gmdate("d", $date_pentecote);
946 $mois_pentecote = gmdate("m", $date_pentecote);
947 if ($jour_pentecote == $jour && $mois_pentecote == $mois) {
948 $ferie = true;
949 }
950 // "Pentecote" (sunday)
951 }
952 if (in_array('pentecotemonday', $specialdayrule)) {
953 // Calculation of "Pentecote" (49 days after easter day)
954 $date_paques = getGMTEasterDatetime($annee);
955 $date_pentecote = $date_paques + (3600 * 24 * 50);
956 $jour_pentecote = gmdate("d", $date_pentecote);
957 $mois_pentecote = gmdate("m", $date_pentecote);
958 if ($jour_pentecote == $jour && $mois_pentecote == $mois) {
959 $ferie = true;
960 }
961 // "Pentecote" (monday)
962 }
963
964 if (in_array('viernessanto', $specialdayrule)) {
965 // Viernes Santo
966 $date_paques = getGMTEasterDatetime($annee);
967 $date_viernes = $date_paques - (3600 * 24 * 2);
968 $jour_viernes = gmdate("d", $date_viernes);
969 $mois_viernes = gmdate("m", $date_viernes);
970 if ($jour_viernes == $jour && $mois_viernes == $mois) {
971 $ferie = true;
972 }
973 //Viernes Santo
974 }
975
976 if (in_array('fronleichnam', $specialdayrule)) {
977 // Fronleichnam (60 days after easter sunday)
978 $date_paques = getGMTEasterDatetime($annee);
979 $date_fronleichnam = $date_paques + (3600 * 24 * 60);
980 $jour_fronleichnam = gmdate("d", $date_fronleichnam);
981 $mois_fronleichnam = gmdate("m", $date_fronleichnam);
982 if ($jour_fronleichnam == $jour && $mois_fronleichnam == $mois) {
983 $ferie = true;
984 }
985 // Fronleichnam
986 }
987
988 if (in_array('genevafast', $specialdayrule)) {
989 // Geneva fast in Switzerland (Thursday after the first sunday in September)
990 $date_1sunsept = strtotime('next thursday', strtotime('next sunday', mktime(0, 0, 0, 9, 1, $annee)));
991 $jour_1sunsept = date("d", $date_1sunsept);
992 $mois_1sunsept = date("m", $date_1sunsept);
993 if ($jour_1sunsept == $jour && $mois_1sunsept == $mois) {
994 $ferie = true;
995 }
996 // Geneva fast in Switzerland
997 }
998 }
999 //print "ferie afterspe=".$ferie."\n";
1000
1001 // If we have to include Friday, Saturday and Sunday
1002 if (!$ferie) {
1003 if ($includefriday || $includesaturday || $includesunday || $includemonday) {
1004 //Monday (1), Friday (5), Saturday (6) and Sunday (0)
1005 if ($includefriday && $jour_semaine == 5) {
1006 $ferie = true;
1007 }
1008 if ($includesaturday && $jour_semaine == 6) {
1009 $ferie = true;
1010 }
1011 if ($includesunday && $jour_semaine == 0) {
1012 $ferie = true;
1013 }
1014 if ($includemonday && $jour_semaine == 1) {
1015 $ferie = true;
1016 }
1017 }
1018 }
1019 //print "ferie afterincludexxxday=".$ferie."\n";
1020
1021 // We increase the counter of non working day
1022 if ($ferie) {
1023 $nbFerie++;
1024 }
1025
1026 // Increase number of days (on go up into loop)
1027 // Advance by exactly one GMT day. We can use += instead of dol_time_plus_duree() here because
1028 // inputs of this function are GMT dates (checked above), so a day
1029 // is always exactly 86400 seconds.
1030 //var_dump("before ".$jour.' '.$mois.' '.$annee.' '.$timestampStart);
1031 $timestampStart += 86400;
1032 //var_dump("after ".$jour.' '.$mois.' '.$annee.' '.$timestampStart);
1033
1034 $i++;
1035 }
1036
1037 //print "nbFerie=".$nbFerie."\n";
1038 return $nbFerie;
1039}
1040
1057function listPublicHoliday($timestampStart, $timestampEnd, $countryCodeOrId = '', $lastday = 0, $excludesaturday = -1, $excludesunday = -1, $excludefriday = -1, $excludemonday = -1)
1058{
1059 global $conf, $db, $mysoc;
1060
1061 // Check to ensure we use correct parameters
1062 if (($timestampEnd - $timestampStart) % 86400 != 0) {
1063 return 'Error Dates must use same hours and must be GMT dates';
1064 }
1065
1066 if (empty($countryCodeOrId)) {
1067 $countryCodeOrId = $mysoc->country_code;
1068 }
1069 if ($excludemonday < 0) {
1070 $excludemonday = getDolGlobalInt('MAIN_NON_WORKING_DAYS_INCLUDE_MONDAY', 0);
1071 }
1072 if ($excludefriday < 0) {
1073 $excludefriday = getDolGlobalInt('MAIN_NON_WORKING_DAYS_INCLUDE_FRIDAY', 0);
1074 }
1075 if ($excludesaturday < 0) {
1076 $excludesaturday = getDolGlobalInt('MAIN_NON_WORKING_DAYS_INCLUDE_SATURDAY', 1);
1077 }
1078 if ($excludesunday < 0) {
1079 $excludesunday = getDolGlobalInt('MAIN_NON_WORKING_DAYS_INCLUDE_SUNDAY', 1);
1080 }
1081
1082 if (is_numeric($countryCodeOrId)) {
1083 $country_id = $countryCodeOrId;
1084 } else {
1085 $country_id = dol_getIdFromCode($db, $countryCodeOrId, 'c_country', 'code', 'rowid');
1086 }
1087
1088 if (empty($conf->cache['arrayOfActivePublicHolidays_' . $country_id])) {
1089 // Loop on public holiday defined into hrm_public_holiday for the day, month and year analyzed
1090 $tmpArrayOfPublicHolidays = array();
1091 $sql = "SELECT id, code, entity, fk_country, dayrule, year, month, day, active";
1092 $sql .= " FROM " . MAIN_DB_PREFIX . "c_hrm_public_holiday";
1093 // A public holiday created without a country has fk_country NULL, and NULL never matches an IN list,
1094 // so such a holiday was missing from the list.
1095 $sql .= " WHERE active = 1 and (fk_country IS NULL OR fk_country IN (0" . ($country_id > 0 ? ", " . ((int) $country_id) : 0) . "))";
1096 $sql .= " AND entity IN (0," . getEntity('holiday') . ")";
1097
1098 $resql = $db->query($sql);
1099 if ($resql) {
1100 $num_rows = $db->num_rows($resql);
1101 $i = 0;
1102 while ($i < $num_rows) {
1103 $obj = $db->fetch_object($resql);
1104 $tmpArrayOfPublicHolidays[$obj->id] = array('dayrule' => $obj->dayrule, 'year' => $obj->year, 'month' => $obj->month, 'day' => $obj->day);
1105 $i++;
1106 }
1107 } else {
1108 dol_syslog($db->lasterror(), LOG_ERR);
1109 return 'Error sql ' . $db->lasterror();
1110 }
1111
1112 //var_dump($tmpArrayOfPublicHolidays);
1113 $conf->cache['arrayOfActivePublicHolidays_' . $country_id] = $tmpArrayOfPublicHolidays;
1114 }
1115
1116 $arrayOfPublicHolidays = $conf->cache['arrayOfActivePublicHolidays_' . $country_id];
1117 $listFeries = [];
1118 $i = 0;
1119 while ((($lastday == 0 && $timestampStart < $timestampEnd) || ($lastday && $timestampStart <= $timestampEnd))
1120 && ($i < 50000)) { // Loop end when equals (Test on i is a security loop to avoid infinite loop)
1121 $nonWorkingDay = false;
1122 $ferie = false;
1123 $specialdayrule = array();
1124
1125 $jour = (int) gmdate("d", $timestampStart);
1126 $mois = (int) gmdate("m", $timestampStart);
1127 $annee = (int) gmdate("Y", $timestampStart);
1128
1129 // If we have to exclude Friday, Saturday and Sunday
1130 if ($excludefriday || $excludesaturday || $excludesunday) {
1131 $jour_julien = unixtojd($timestampStart);
1132 $jour_semaine = jddayofweek($jour_julien, 0);
1133 if ($excludefriday) { //Friday (5), Saturday (6) and Sunday (0)
1134 if ($jour_semaine == 5) {
1135 $nonWorkingDay = true;
1136 }
1137 }
1138 if ($excludesaturday) { //Friday (5), Saturday (6) and Sunday (0)
1139 if ($jour_semaine == 6) {
1140 $nonWorkingDay = true;
1141 }
1142 }
1143 if ($excludesunday) { //Friday (5), Saturday (6) and Sunday (0)
1144 if ($jour_semaine == 0) {
1145 $nonWorkingDay = true;
1146 }
1147 }
1148 }
1149 //print "ferie=".$nonWorkingDay."\n";
1150
1151 if (!$nonWorkingDay) {
1152 //print "jour=".$jour." month=".$mois." year=".$annee." includesaturday=".$excludesaturday." includesunday=".$excludesunday."\n";
1153 foreach ($arrayOfPublicHolidays as $entrypublicholiday) {
1154 if (!empty($entrypublicholiday['dayrule']) && $entrypublicholiday['dayrule'] != 'date') { // For example 'easter', '...'
1155 $specialdayrule[$entrypublicholiday['dayrule']] = $entrypublicholiday['dayrule'];
1156 } else {
1157 $match = 1;
1158 if (!empty($entrypublicholiday['year']) && $entrypublicholiday['year'] != $annee) {
1159 $match = 0;
1160 }
1161 if ($entrypublicholiday['month'] != $mois) {
1162 $match = 0;
1163 }
1164 if ($entrypublicholiday['day'] != $jour) {
1165 $match = 0;
1166 }
1167
1168 if ($match) {
1169 $ferie = true;
1170 $listFeries[] = $timestampStart;
1171 }
1172 }
1173
1174 $i++;
1175 }
1176 //var_dump($specialdayrule)."\n";
1177 //print "ferie=".$nonWorkingDay."\n";
1178 }
1179
1180 if (!$nonWorkingDay && !$ferie) {
1181 // Special dayrules
1182 if (in_array('easter', $specialdayrule)) {
1183 // Calculation for easter date
1184 $date_paques = getGMTEasterDatetime($annee);
1185 $jour_paques = gmdate("d", $date_paques);
1186 $mois_paques = gmdate("m", $date_paques);
1187 if ($jour_paques == $jour && $mois_paques == $mois) {
1188 $ferie = true;
1189 $listFeries[] = $timestampStart;
1190 }
1191 // Easter (sunday)
1192 }
1193
1194 if (in_array('eastermonday', $specialdayrule)) {
1195 // Calculation for the monday of easter date
1196 $date_paques = getGMTEasterDatetime($annee);
1197 //print 'PPP'.$date_paques.' '.dol_print_date($date_paques, 'dayhour', 'gmt')." ";
1198 $date_lundi_paques = $date_paques + (3600 * 24);
1199 $jour_lundi_paques = gmdate("d", $date_lundi_paques);
1200 $mois_lundi_paques = gmdate("m", $date_lundi_paques);
1201 if ($jour_lundi_paques == $jour && $mois_lundi_paques == $mois) {
1202 $ferie = true;
1203 $listFeries[] = $timestampStart;
1204 }
1205 // Easter (monday)
1206 //print 'annee='.$annee.' $jour='.$jour.' $mois='.$mois.' $jour_lundi_paques='.$jour_lundi_paques.' $mois_lundi_paques='.$mois_lundi_paques."\n";
1207 }
1208
1209 //Good Friday
1210 if (in_array('goodfriday', $specialdayrule)) {
1211 // Pulls the date of Easter
1212 $easter = getGMTEasterDatetime($annee);
1213
1214 // Calculates the date of Good Friday based on Easter
1215 $date_good_friday = $easter - (2 * 3600 * 24);
1216 $dom_good_friday = gmdate("d", $date_good_friday);
1217 $month_good_friday = gmdate("m", $date_good_friday);
1218
1219 if ($dom_good_friday == $jour && $month_good_friday == $mois) {
1220 $ferie = true;
1221 $listFeries[] = $timestampStart;
1222 }
1223 }
1224
1225 if (in_array('ascension', $specialdayrule)) {
1226 // Calculation of Ascension day (39 days after easter day)
1227 $date_paques = getGMTEasterDatetime($annee);
1228 $date_ascension = $date_paques + (3600 * 24 * 39);
1229 $jour_ascension = gmdate("d", $date_ascension);
1230 $mois_ascension = gmdate("m", $date_ascension);
1231 if ($jour_ascension == $jour && $mois_ascension == $mois) {
1232 $ferie = true;
1233 $listFeries[] = $timestampStart;
1234 }
1235 // Ascension (thursday)
1236 }
1237
1238 if (in_array('pentecost', $specialdayrule)) {
1239 // Calculation of "Pentecote" (49 days after easter day)
1240 $date_paques = getGMTEasterDatetime($annee);
1241 $date_pentecote = $date_paques + (3600 * 24 * 49);
1242 $jour_pentecote = gmdate("d", $date_pentecote);
1243 $mois_pentecote = gmdate("m", $date_pentecote);
1244 if ($jour_pentecote == $jour && $mois_pentecote == $mois) {
1245 $ferie = true;
1246 $listFeries[] = $timestampStart;
1247 }
1248 // "Pentecote" (sunday)
1249 }
1250
1251 if (in_array('pentecotemonday', $specialdayrule)) {
1252 // Calculation of "Pentecote" (49 days after easter day)
1253 $date_paques = getGMTEasterDatetime($annee);
1254 $date_pentecote = $date_paques + (3600 * 24 * 50);
1255 $jour_pentecote = gmdate("d", $date_pentecote);
1256 $mois_pentecote = gmdate("m", $date_pentecote);
1257 if ($jour_pentecote == $jour && $mois_pentecote == $mois) {
1258 $ferie = true;
1259 $listFeries[] = $timestampStart;
1260 }
1261 // "Pentecote" (monday)
1262 }
1263
1264 if (in_array('viernessanto', $specialdayrule)) {
1265 // Viernes Santo
1266 $date_paques = getGMTEasterDatetime($annee);
1267 $date_viernes = $date_paques - (3600 * 24 * 2);
1268 $jour_viernes = gmdate("d", $date_viernes);
1269 $mois_viernes = gmdate("m", $date_viernes);
1270 if ($jour_viernes == $jour && $mois_viernes == $mois) {
1271 $ferie = true;
1272 $listFeries[] = $timestampStart;
1273 }
1274 //Viernes Santo
1275 }
1276
1277 if (in_array('fronleichnam', $specialdayrule)) {
1278 // Fronleichnam (60 days after easter sunday)
1279 $date_paques = getGMTEasterDatetime($annee);
1280 $date_fronleichnam = $date_paques + (3600 * 24 * 60);
1281 $jour_fronleichnam = gmdate("d", $date_fronleichnam);
1282 $mois_fronleichnam = gmdate("m", $date_fronleichnam);
1283 if ($jour_fronleichnam == $jour && $mois_fronleichnam == $mois) {
1284 $ferie = true;
1285 $listFeries[] = $timestampStart;
1286 }
1287 // Fronleichnam
1288 }
1289
1290 if (in_array('genevafast', $specialdayrule)) {
1291 // Geneva fast in Switzerland (Thursday after the first sunday in September)
1292 $date_1sunsept = strtotime('next thursday', strtotime('next sunday', mktime(0, 0, 0, 9, 1, $annee)));
1293 $jour_1sunsept = date("d", $date_1sunsept);
1294 $mois_1sunsept = date("m", $date_1sunsept);
1295 if ($jour_1sunsept == $jour && $mois_1sunsept == $mois) {
1296 $ferie = true;
1297 $listFeries[] = $timestampStart;
1298 }
1299 // Geneva fast in Switzerland
1300 }
1301 }
1302 //print "ferie=".$nonWorkingDay."\n";
1303
1304 // Increase number of days (on go up into loop)
1305 $timestampStart = dol_time_plus_duree($timestampStart, 1, 'd');
1306 //var_dump($jour.' '.$mois.' '.$annee.' '.$timestampStart);
1307
1308 $i++;
1309 }
1310
1311 //print "nbFerie=".$nbFerie."\n";
1312 return $listFeries;
1313}
1314
1325function num_between_day($timestampStart, $timestampEnd, $lastday = 0)
1326{
1327 if ($timestampStart <= $timestampEnd) {
1328 if ($lastday == 1) {
1329 $bit = 0;
1330 } else {
1331 $bit = 1;
1332 }
1333 $nbjours = (int) floor(($timestampEnd - $timestampStart) / (60 * 60 * 24)) + 1 - $bit;
1334 } else {
1335 $nbjours = 0;
1336 }
1337 //print ($timestampEnd - $timestampStart) - $lastday;
1338 return $nbjours;
1339}
1340
1357function num_open_day($timestampStart, $timestampEnd, $inhour = 0, $lastday = 0, $halfday = 0, $countryCodeOrId = '', $user_id = 0)
1358{
1359 global $langs, $mysoc, $hookmanager;
1360
1361 if (empty($countryCodeOrId) || $countryCodeOrId < 0) {
1362 $countryCodeOrId = $mysoc->country_code;
1363 }
1364
1365 dol_syslog('num_open_day timestampStart='.$timestampStart.' timestampEnd='.$timestampEnd.' bit='.$lastday.' countryCodeOrId='.$countryCodeOrId);
1366
1367 // Check parameters
1368 if (!is_int($timestampStart) && !is_float($timestampStart)) {
1369 return 'ErrorBadParameter_num_open_day';
1370 }
1371 if (!is_int($timestampEnd) && !is_float($timestampEnd)) {
1372 return 'ErrorBadParameter_num_open_day';
1373 }
1374
1375 $nbOpenDay = 0; // expressed in days; inhour conversion happens at the end
1376
1377 if ($timestampStart < $timestampEnd) {
1378 // --- 1. Calculate Gross Working Days ---
1379 // Gross working days = total days in range - non-working days (weekends & public holidays).
1380 $a = num_between_day($timestampStart, $timestampEnd, $lastday);
1381 $b = num_public_holiday($timestampStart, $timestampEnd, $countryCodeOrId, $lastday);
1382 $nbOpenDay = $a - $b;
1383
1384 // --- 2. Apply Contextual Half-Day Deductions ---
1385 $halfday = (int) $halfday; // Ensure $halfday is an integer for reliable comparisons.
1386
1387 // Check if start/end days are working days just ONCE to optimize performance
1388 // by avoiding redundant calls to the potentially slow num_public_holiday() function.
1389 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
1390 $isStartDayWorking = (num_public_holiday($timestampStart, $timestampStart, $countryCodeOrId, 1) == 0);
1391 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
1392 $isEndDayWorking = (num_public_holiday($timestampEnd, $timestampEnd, $countryCodeOrId, 1) == 0);
1393
1394 // Deduct 0.5 if the leave starts in the afternoon of a working day.
1395 if (($halfday == -1 || $halfday == 2) && $isStartDayWorking) {
1396 $nbOpenDay -= 0.5;
1397 }
1398
1399 // Deduct 0.5 if the leave ends in the morning of a different, working day.
1400 if (($halfday == 1 || $halfday == 2) && date('Y-m-d', $timestampStart) != date('Y-m-d', $timestampEnd) && $isEndDayWorking) {
1401 $nbOpenDay -= 0.5;
1402 }
1403 } elseif ($timestampStart == $timestampEnd) {
1404 $isSingleDayHoliday = false;
1405 if ($lastday) {
1406 $numholidays = num_public_holiday($timestampStart, $timestampEnd, $countryCodeOrId, $lastday);
1407 if ($numholidays == 1) {
1408 $isSingleDayHoliday = true;
1409 }
1410 }
1411 if (!$isSingleDayHoliday) {
1412 $nbOpenDay = $lastday - 0.5 * abs((int) $halfday);
1413 }
1414 } else {
1415 return $langs->trans("Error");
1416 }
1417
1418 // --- 3. Allow modules to adjust the result based on the user (e.g. per-employee
1419 // individual workdays, bridge days, fixed half-days). Only fires when caller
1420 // opts in by passing a non-zero $user_id, so existing call sites are unaffected.
1421 if ($user_id > 0 && is_object($hookmanager)) {
1422 $parameters = array(
1423 'timestampStart' => $timestampStart,
1424 'timestampEnd' => $timestampEnd,
1425 'inhour' => $inhour,
1426 'lastday' => $lastday,
1427 'halfday' => $halfday,
1428 'countryCodeOrId' => $countryCodeOrId,
1429 'user_id' => $user_id,
1430 'nbOpenDay' => $nbOpenDay,
1431 );
1432 $action = '';
1433 $reshook = $hookmanager->executeHooks('numOpenDay', $parameters, $hookmanager, $action);
1434 if ($reshook > 0 && isset($hookmanager->resArray['nbOpenDay'])) {
1435 $nbOpenDay = $hookmanager->resArray['nbOpenDay'];
1436 }
1437 }
1438
1439 if ($inhour == 1) {
1440 return (int) ($nbOpenDay * 24);
1441 }
1442 return $nbOpenDay;
1443}
1444
1445
1446
1455function monthArray($outputlangs, $short = 0)
1456{
1457 $montharray = array(
1458 1 => $outputlangs->trans("Month01"),
1459 2 => $outputlangs->trans("Month02"),
1460 3 => $outputlangs->trans("Month03"),
1461 4 => $outputlangs->trans("Month04"),
1462 5 => $outputlangs->trans("Month05"),
1463 6 => $outputlangs->trans("Month06"),
1464 7 => $outputlangs->trans("Month07"),
1465 8 => $outputlangs->trans("Month08"),
1466 9 => $outputlangs->trans("Month09"),
1467 10 => $outputlangs->trans("Month10"),
1468 11 => $outputlangs->trans("Month11"),
1469 12 => $outputlangs->trans("Month12")
1470 );
1471
1472 if (!empty($short)) {
1473 $montharray = array(
1474 1 => $outputlangs->trans("MonthShort01"),
1475 2 => $outputlangs->trans("MonthShort02"),
1476 3 => $outputlangs->trans("MonthShort03"),
1477 4 => $outputlangs->trans("MonthShort04"),
1478 5 => $outputlangs->trans("MonthShort05"),
1479 6 => $outputlangs->trans("MonthShort06"),
1480 7 => $outputlangs->trans("MonthShort07"),
1481 8 => $outputlangs->trans("MonthShort08"),
1482 9 => $outputlangs->trans("MonthShort09"),
1483 10 => $outputlangs->trans("MonthShort10"),
1484 11 => $outputlangs->trans("MonthShort11"),
1485 12 => $outputlangs->trans("MonthShort12")
1486 );
1487 }
1488
1489 return $montharray;
1490}
1491
1499function getWeekNumbersOfMonth($month, $year)
1500{
1501 $nb_days = cal_days_in_month(CAL_GREGORIAN, $month, $year);
1502 $TWeek = array();
1503 for ($day = 1; $day <= $nb_days; $day++) {
1504 $week_number = getWeekNumber($day, $month, $year);
1505 $TWeek[$week_number] = $week_number;
1506 }
1507 return $TWeek;
1508}
1509
1517function getFirstDayOfEachWeek($TWeek, $year)
1518{
1519 $TFirstDayOfWeek = array();
1520 // When a month overlaps 2 years, the weeks 52/53 of previous year and the week 01 of next year are present together in $TWeek.
1521 // If $TWeek starts with week 52 or 53 (a January), these first weeks belong to previous year.
1522 // If $TWeek ends with week 01 (a December), this last week belongs to next year.
1523 $startwithweeksofpreviousyear = ((int) reset($TWeek) >= 52 && in_array('01', $TWeek));
1524 foreach ($TWeek as $weekNb) {
1525 $yeartouse = $year;
1526 if ($startwithweeksofpreviousyear) {
1527 if ((int) $weekNb >= 52) {
1528 $yeartouse = $year - 1;
1529 }
1530 } elseif ($weekNb == '01' && in_array('52', $TWeek)) {
1531 $yeartouse = $year + 1;
1532 }
1533 $TFirstDayOfWeek[$weekNb] = date('d', strtotime($yeartouse.'W'.$weekNb));
1534 }
1535 return $TFirstDayOfWeek;
1536}
1537
1545function getLastDayOfEachWeek($TWeek, $year)
1546{
1547 $TLastDayOfWeek = array();
1548 // Same rule as in getFirstDayOfEachWeek() to find the year each week belongs to
1549 $startwithweeksofpreviousyear = ((int) reset($TWeek) >= 52 && in_array('01', $TWeek));
1550 foreach ($TWeek as $weekNb) {
1551 $yeartouse = $year;
1552 if ($startwithweeksofpreviousyear) {
1553 if ((int) $weekNb >= 52) {
1554 $yeartouse = $year - 1;
1555 }
1556 } elseif ($weekNb == '01' && in_array('52', $TWeek)) {
1557 $yeartouse = $year + 1;
1558 }
1559 $TLastDayOfWeek[$weekNb] = date('d', strtotime($yeartouse.'W'.$weekNb.'+6 days'));
1560 }
1561 return $TLastDayOfWeek;
1562}
1563
1572function getWeekNumber($day, $month, $year)
1573{
1574 $date = new DateTime($year.'-'.$month.'-'.$day);
1575 $week = $date->format("W");
1576 return $week;
1577}
global $mysoc
dol_get_prev_month($month, $year)
Return previous month.
Definition date.lib.php:539
listPublicHoliday($timestampStart, $timestampEnd, $countryCodeOrId='', $lastday=0, $excludesaturday=-1, $excludesunday=-1, $excludefriday=-1, $excludemonday=-1)
Return the list of public holidays including Friday, Saturday and Sunday (or not) between 2 dates in ...
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:680
dol_get_next_day($day, $month, $year)
Return next day.
Definition date.lib.php:524
dol_get_next_week($day, $week, $month, $year)
Return next week.
Definition date.lib.php:598
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:401
getServerTimeZoneString()
Return server timezone string.
Definition date.lib.php:76
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:666
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:87
dol_get_first_day_week($day, $month, $year, $gm=false)
Return first day of week for a date.
Definition date.lib.php:695
getGMTEasterDatetime($year)
Return the easter day in GMT time.
Definition date.lib.php:763
num_open_day($timestampStart, $timestampEnd, $inhour=0, $lastday=0, $halfday=0, $countryCodeOrId='', $user_id=0)
Function to return number of working days (and text of units) between two dates (working days)
convertDurationtoHour($duration_value, $duration_unit)
Convert duration to hour.
Definition date.lib.php:357
get_tz_array()
Return an array with timezone values.
Definition date.lib.php:37
dol_get_prev_day($day, $month, $year)
Return previous day.
Definition date.lib.php:508
dol_get_first_day($year, $month=1, $gm=false)
Return GMT time for first day of a month or year.
Definition date.lib.php:620
getFirstDayOfEachWeek($TWeek, $year)
Return array of first day of weeks.
dol_get_next_month($month, $year)
Return next month.
Definition date.lib.php:558
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...
num_public_holiday($timestampStart, $timestampEnd, $countryCodeOrId='', $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:787
convertTime2Seconds($iHours=0, $iMinutes=0, $iSeconds=0)
Convert hours and minutes into seconds.
Definition date.lib.php:234
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:263
dol_get_prev_week($day, $week, $month, $year)
Return previous week.
Definition date.lib.php:579
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:451
dol_get_last_day($year, $month=12, $gm=false)
Return GMT time for last day of a month or year.
Definition date.lib.php:639
monthArray($outputlangs, $short=0)
Return array of translated months or selected month.
dol_time_plus_duree($time, $duration_value, $duration_unit, $ruleforendofmonth=0, $tz='')
Add a delay to a date.
Definition date.lib.php:129
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $db
API class for accounts.
dol_now($mode='gmt')
Return date for now.
dol_mktime($hour, $minute, $second, $month, $day, $year, $gm='auto', $check=1)
Return a timestamp date built from detailed information (by default a local PHP server timestamp) Rep...
dol_getIdFromCode($db, $key, $tablename, $fieldkey='code', $fieldid='id', $entityfilter=0, $filters='', $useCache=true)
Return an id or code from a code or id.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false, $decorate=0)
Output date in a string format according to outputlangs (or langs if not defined).
dol_print_error($db=null, $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
getEntity($element, $shared=1, $currentobject=null)
Get list of entity id to use.
dol_getdate($timestamp, $fast=false, $forcetimezone='')
Return an array with locale date info.
print $langs trans('Date')." left Ref Label right Qty right Price right TotalHT right TotalTTC right right right right right right right right right centpercent right TotalHT right n right VAT right n right TotalVAT right n No sujeto a RE IRPF right TotalLT1 right n right TotalLT2 right n right TotalTTC right n takeposcustomercurrency takeposcustomercurrency takeposcustomercurrency takeposcustomercurrency right TotalTTC takeposcustomercurrency right takeposcustomercurrency n right Paid right PaymentTypeShortLIQ right SELECT p pos_change as p datep as date
Definition receipt.php:492