dolibarr 24.0.2
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, $month, $tmparray['first_day'], $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 $sql .= " WHERE active = 1 and fk_country IN (0".($country_id > 0 ? ", ".((int) $country_id) : 0).")";
826 $sql .= " AND entity IN (0," .getEntity('holiday') .")";
827
828 $resql = $db->query($sql);
829 if ($resql) {
830 $num_rows = $db->num_rows($resql);
831 $i = 0;
832 while ($i < $num_rows) {
833 $obj = $db->fetch_object($resql);
834 $tmpArrayOfPublicHolidays[$obj->id] = array('dayrule' => $obj->dayrule, 'year' => $obj->year, 'month' => $obj->month, 'day' => $obj->day);
835 $i++;
836 }
837 } else {
838 dol_syslog($db->lasterror(), LOG_ERR);
839 return 'Error sql '.$db->lasterror();
840 }
841
842 //var_dump($tmpArrayOfPublicHolidays);
843 $conf->cache['arrayOfActivePublicHolidays_'.$country_id] = $tmpArrayOfPublicHolidays;
844 }
845
846 $arrayOfPublicHolidays = $conf->cache['arrayOfActivePublicHolidays_'.$country_id];
847
848 $i = 0;
849 while ((($lastday == 0 && $timestampStart < $timestampEnd) || ($lastday && $timestampStart <= $timestampEnd))
850 && ($i < 50000)) { // Loop end when equals (Test on i is a security loop to avoid infinite loop)
851 $ferie = false;
852 $specialdayrule = array();
853
854 $jour = (int) gmdate("d", $timestampStart);
855 $mois = (int) gmdate("m", $timestampStart);
856 $annee = (int) gmdate("Y", $timestampStart);
857 $jour_semaine = (int) gmdate("w", $timestampStart); // sunday = 0, monday = 1, ...
858
859 //print "jour=".$jour." month=".$mois." year=".$annee." includesaturday=".$includesaturday." includesunday=".$includesunday."\n";
860 foreach ($arrayOfPublicHolidays as $entrypublicholiday) {
861 if (!empty($entrypublicholiday['dayrule']) && $entrypublicholiday['dayrule'] != 'date') { // For example 'easter', '...'
862 $specialdayrule[$entrypublicholiday['dayrule']] = $entrypublicholiday['dayrule'];
863 } else {
864 $match = 1;
865 if (!empty($entrypublicholiday['year']) && $entrypublicholiday['year'] != $annee) {
866 $match = 0;
867 }
868 if ($entrypublicholiday['month'] != $mois) {
869 $match = 0;
870 }
871 if ($entrypublicholiday['day'] != $jour) {
872 $match = 0;
873 }
874
875 if ($match) {
876 $ferie = true;
877 }
878 }
879
880 $i++;
881 }
882 //var_dump($specialdayrule)."\n";
883 //print "ferie=".$ferie."\n";
884
885 if (!$ferie) {
886 // Special dayrules
887 if (in_array('easter', $specialdayrule)) {
888 // Calculation for easter date
889 $date_paques = getGMTEasterDatetime($annee);
890 $jour_paques = gmdate("d", $date_paques);
891 $mois_paques = gmdate("m", $date_paques);
892 if ($jour_paques == $jour && $mois_paques == $mois) {
893 $ferie = true;
894 }
895 // Easter (sunday)
896 }
897
898 if (in_array('eastermonday', $specialdayrule)) {
899 // Calculation for the monday of easter date
900 $date_paques = getGMTEasterDatetime($annee);
901 //print 'PPP'.$date_paques.' '.dol_print_date($date_paques, 'dayhour', 'gmt')." ";
902 $date_lundi_paques = $date_paques + (3600 * 24);
903 $jour_lundi_paques = gmdate("d", $date_lundi_paques);
904 $mois_lundi_paques = gmdate("m", $date_lundi_paques);
905 if ($jour_lundi_paques == $jour && $mois_lundi_paques == $mois) {
906 $ferie = true;
907 }
908 // Easter (monday)
909 //print 'annee='.$annee.' $jour='.$jour.' $mois='.$mois.' $jour_lundi_paques='.$jour_lundi_paques.' $mois_lundi_paques='.$mois_lundi_paques."\n";
910 }
911
912 //Good Friday
913 if (in_array('goodfriday', $specialdayrule)) {
914 // Pulls the date of Easter
915 $easter = getGMTEasterDatetime($annee);
916
917 // Calculates the date of Good Friday based on Easter
918 $date_good_friday = $easter - (2 * 3600 * 24);
919 $dom_good_friday = gmdate("d", $date_good_friday);
920 $month_good_friday = gmdate("m", $date_good_friday);
921
922 if ($dom_good_friday == $jour && $month_good_friday == $mois) {
923 $ferie = true;
924 }
925 }
926
927 if (in_array('ascension', $specialdayrule)) {
928 // Calculation of Ascension day (39 days after easter day)
929 $date_paques = getGMTEasterDatetime($annee);
930 $date_ascension = $date_paques + (3600 * 24 * 39);
931 $jour_ascension = gmdate("d", $date_ascension);
932 $mois_ascension = gmdate("m", $date_ascension);
933 if ($jour_ascension == $jour && $mois_ascension == $mois) {
934 $ferie = true;
935 }
936 // Ascension (thursday)
937 }
938
939 if (in_array('pentecost', $specialdayrule)) {
940 // Calculation of "Pentecote" (49 days after easter day)
941 $date_paques = getGMTEasterDatetime($annee);
942 $date_pentecote = $date_paques + (3600 * 24 * 49);
943 $jour_pentecote = gmdate("d", $date_pentecote);
944 $mois_pentecote = gmdate("m", $date_pentecote);
945 if ($jour_pentecote == $jour && $mois_pentecote == $mois) {
946 $ferie = true;
947 }
948 // "Pentecote" (sunday)
949 }
950 if (in_array('pentecotemonday', $specialdayrule)) {
951 // Calculation of "Pentecote" (49 days after easter day)
952 $date_paques = getGMTEasterDatetime($annee);
953 $date_pentecote = $date_paques + (3600 * 24 * 50);
954 $jour_pentecote = gmdate("d", $date_pentecote);
955 $mois_pentecote = gmdate("m", $date_pentecote);
956 if ($jour_pentecote == $jour && $mois_pentecote == $mois) {
957 $ferie = true;
958 }
959 // "Pentecote" (monday)
960 }
961
962 if (in_array('viernessanto', $specialdayrule)) {
963 // Viernes Santo
964 $date_paques = getGMTEasterDatetime($annee);
965 $date_viernes = $date_paques - (3600 * 24 * 2);
966 $jour_viernes = gmdate("d", $date_viernes);
967 $mois_viernes = gmdate("m", $date_viernes);
968 if ($jour_viernes == $jour && $mois_viernes == $mois) {
969 $ferie = true;
970 }
971 //Viernes Santo
972 }
973
974 if (in_array('fronleichnam', $specialdayrule)) {
975 // Fronleichnam (60 days after easter sunday)
976 $date_paques = getGMTEasterDatetime($annee);
977 $date_fronleichnam = $date_paques + (3600 * 24 * 60);
978 $jour_fronleichnam = gmdate("d", $date_fronleichnam);
979 $mois_fronleichnam = gmdate("m", $date_fronleichnam);
980 if ($jour_fronleichnam == $jour && $mois_fronleichnam == $mois) {
981 $ferie = true;
982 }
983 // Fronleichnam
984 }
985
986 if (in_array('genevafast', $specialdayrule)) {
987 // Geneva fast in Switzerland (Thursday after the first sunday in September)
988 $date_1sunsept = strtotime('next thursday', strtotime('next sunday', mktime(0, 0, 0, 9, 1, $annee)));
989 $jour_1sunsept = date("d", $date_1sunsept);
990 $mois_1sunsept = date("m", $date_1sunsept);
991 if ($jour_1sunsept == $jour && $mois_1sunsept == $mois) {
992 $ferie = true;
993 }
994 // Geneva fast in Switzerland
995 }
996 }
997 //print "ferie afterspe=".$ferie."\n";
998
999 // If we have to include Friday, Saturday and Sunday
1000 if (!$ferie) {
1001 if ($includefriday || $includesaturday || $includesunday || $includemonday) {
1002 //Monday (1), Friday (5), Saturday (6) and Sunday (0)
1003 if ($includefriday && $jour_semaine == 5) {
1004 $ferie = true;
1005 }
1006 if ($includesaturday && $jour_semaine == 6) {
1007 $ferie = true;
1008 }
1009 if ($includesunday && $jour_semaine == 0) {
1010 $ferie = true;
1011 }
1012 if ($includemonday && $jour_semaine == 1) {
1013 $ferie = true;
1014 }
1015 }
1016 }
1017 //print "ferie afterincludexxxday=".$ferie."\n";
1018
1019 // We increase the counter of non working day
1020 if ($ferie) {
1021 $nbFerie++;
1022 }
1023
1024 // Increase number of days (on go up into loop)
1025 // Advance by exactly one GMT day. We can use += instead of dol_time_plus_duree() here because
1026 // inputs of this function are GMT dates (checked above), so a day
1027 // is always exactly 86400 seconds.
1028 //var_dump("before ".$jour.' '.$mois.' '.$annee.' '.$timestampStart);
1029 $timestampStart += 86400;
1030 //var_dump("after ".$jour.' '.$mois.' '.$annee.' '.$timestampStart);
1031
1032 $i++;
1033 }
1034
1035 //print "nbFerie=".$nbFerie."\n";
1036 return $nbFerie;
1037}
1038
1055function listPublicHoliday($timestampStart, $timestampEnd, $countryCodeOrId = '', $lastday = 0, $excludesaturday = -1, $excludesunday = -1, $excludefriday = -1, $excludemonday = -1)
1056{
1057 global $conf, $db, $mysoc;
1058
1059 // Check to ensure we use correct parameters
1060 if (($timestampEnd - $timestampStart) % 86400 != 0) {
1061 return 'Error Dates must use same hours and must be GMT dates';
1062 }
1063
1064 if (empty($countryCodeOrId)) {
1065 $countryCodeOrId = $mysoc->country_code;
1066 }
1067 if ($excludemonday < 0) {
1068 $excludemonday = getDolGlobalInt('MAIN_NON_WORKING_DAYS_INCLUDE_MONDAY', 0);
1069 }
1070 if ($excludefriday < 0) {
1071 $excludefriday = getDolGlobalInt('MAIN_NON_WORKING_DAYS_INCLUDE_FRIDAY', 0);
1072 }
1073 if ($excludesaturday < 0) {
1074 $excludesaturday = getDolGlobalInt('MAIN_NON_WORKING_DAYS_INCLUDE_SATURDAY', 1);
1075 }
1076 if ($excludesunday < 0) {
1077 $excludesunday = getDolGlobalInt('MAIN_NON_WORKING_DAYS_INCLUDE_SUNDAY', 1);
1078 }
1079
1080 if (is_numeric($countryCodeOrId)) {
1081 $country_id = $countryCodeOrId;
1082 } else {
1083 $country_id = dol_getIdFromCode($db, $countryCodeOrId, 'c_country', 'code', 'rowid');
1084 }
1085
1086 if (empty($conf->cache['arrayOfActivePublicHolidays_' . $country_id])) {
1087 // Loop on public holiday defined into hrm_public_holiday for the day, month and year analyzed
1088 $tmpArrayOfPublicHolidays = array();
1089 $sql = "SELECT id, code, entity, fk_country, dayrule, year, month, day, active";
1090 $sql .= " FROM " . MAIN_DB_PREFIX . "c_hrm_public_holiday";
1091 $sql .= " WHERE active = 1 and fk_country IN (0" . ($country_id > 0 ? ", " . ((int) $country_id) : 0) . ")";
1092 $sql .= " AND entity IN (0," . getEntity('holiday') . ")";
1093
1094 $resql = $db->query($sql);
1095 if ($resql) {
1096 $num_rows = $db->num_rows($resql);
1097 $i = 0;
1098 while ($i < $num_rows) {
1099 $obj = $db->fetch_object($resql);
1100 $tmpArrayOfPublicHolidays[$obj->id] = array('dayrule' => $obj->dayrule, 'year' => $obj->year, 'month' => $obj->month, 'day' => $obj->day);
1101 $i++;
1102 }
1103 } else {
1104 dol_syslog($db->lasterror(), LOG_ERR);
1105 return 'Error sql ' . $db->lasterror();
1106 }
1107
1108 //var_dump($tmpArrayOfPublicHolidays);
1109 $conf->cache['arrayOfActivePublicHolidays_' . $country_id] = $tmpArrayOfPublicHolidays;
1110 }
1111
1112 $arrayOfPublicHolidays = $conf->cache['arrayOfActivePublicHolidays_' . $country_id];
1113 $listFeries = [];
1114 $i = 0;
1115 while ((($lastday == 0 && $timestampStart < $timestampEnd) || ($lastday && $timestampStart <= $timestampEnd))
1116 && ($i < 50000)) { // Loop end when equals (Test on i is a security loop to avoid infinite loop)
1117 $nonWorkingDay = false;
1118 $ferie = false;
1119 $specialdayrule = array();
1120
1121 $jour = (int) gmdate("d", $timestampStart);
1122 $mois = (int) gmdate("m", $timestampStart);
1123 $annee = (int) gmdate("Y", $timestampStart);
1124
1125 // If we have to exclude Friday, Saturday and Sunday
1126 if ($excludefriday || $excludesaturday || $excludesunday) {
1127 $jour_julien = unixtojd($timestampStart);
1128 $jour_semaine = jddayofweek($jour_julien, 0);
1129 if ($excludefriday) { //Friday (5), Saturday (6) and Sunday (0)
1130 if ($jour_semaine == 5) {
1131 $nonWorkingDay = true;
1132 }
1133 }
1134 if ($excludesaturday) { //Friday (5), Saturday (6) and Sunday (0)
1135 if ($jour_semaine == 6) {
1136 $nonWorkingDay = true;
1137 }
1138 }
1139 if ($excludesunday) { //Friday (5), Saturday (6) and Sunday (0)
1140 if ($jour_semaine == 0) {
1141 $nonWorkingDay = true;
1142 }
1143 }
1144 }
1145 //print "ferie=".$nonWorkingDay."\n";
1146
1147 if (!$nonWorkingDay) {
1148 //print "jour=".$jour." month=".$mois." year=".$annee." includesaturday=".$excludesaturday." includesunday=".$excludesunday."\n";
1149 foreach ($arrayOfPublicHolidays as $entrypublicholiday) {
1150 if (!empty($entrypublicholiday['dayrule']) && $entrypublicholiday['dayrule'] != 'date') { // For example 'easter', '...'
1151 $specialdayrule[$entrypublicholiday['dayrule']] = $entrypublicholiday['dayrule'];
1152 } else {
1153 $match = 1;
1154 if (!empty($entrypublicholiday['year']) && $entrypublicholiday['year'] != $annee) {
1155 $match = 0;
1156 }
1157 if ($entrypublicholiday['month'] != $mois) {
1158 $match = 0;
1159 }
1160 if ($entrypublicholiday['day'] != $jour) {
1161 $match = 0;
1162 }
1163
1164 if ($match) {
1165 $ferie = true;
1166 $listFeries[] = $timestampStart;
1167 }
1168 }
1169
1170 $i++;
1171 }
1172 //var_dump($specialdayrule)."\n";
1173 //print "ferie=".$nonWorkingDay."\n";
1174 }
1175
1176 if (!$nonWorkingDay && !$ferie) {
1177 // Special dayrules
1178 if (in_array('easter', $specialdayrule)) {
1179 // Calculation for easter date
1180 $date_paques = getGMTEasterDatetime($annee);
1181 $jour_paques = gmdate("d", $date_paques);
1182 $mois_paques = gmdate("m", $date_paques);
1183 if ($jour_paques == $jour && $mois_paques == $mois) {
1184 $ferie = true;
1185 $listFeries[] = $timestampStart;
1186 }
1187 // Easter (sunday)
1188 }
1189
1190 if (in_array('eastermonday', $specialdayrule)) {
1191 // Calculation for the monday of easter date
1192 $date_paques = getGMTEasterDatetime($annee);
1193 //print 'PPP'.$date_paques.' '.dol_print_date($date_paques, 'dayhour', 'gmt')." ";
1194 $date_lundi_paques = $date_paques + (3600 * 24);
1195 $jour_lundi_paques = gmdate("d", $date_lundi_paques);
1196 $mois_lundi_paques = gmdate("m", $date_lundi_paques);
1197 if ($jour_lundi_paques == $jour && $mois_lundi_paques == $mois) {
1198 $ferie = true;
1199 $listFeries[] = $timestampStart;
1200 }
1201 // Easter (monday)
1202 //print 'annee='.$annee.' $jour='.$jour.' $mois='.$mois.' $jour_lundi_paques='.$jour_lundi_paques.' $mois_lundi_paques='.$mois_lundi_paques."\n";
1203 }
1204
1205 //Good Friday
1206 if (in_array('goodfriday', $specialdayrule)) {
1207 // Pulls the date of Easter
1208 $easter = getGMTEasterDatetime($annee);
1209
1210 // Calculates the date of Good Friday based on Easter
1211 $date_good_friday = $easter - (2 * 3600 * 24);
1212 $dom_good_friday = gmdate("d", $date_good_friday);
1213 $month_good_friday = gmdate("m", $date_good_friday);
1214
1215 if ($dom_good_friday == $jour && $month_good_friday == $mois) {
1216 $ferie = true;
1217 $listFeries[] = $timestampStart;
1218 }
1219 }
1220
1221 if (in_array('ascension', $specialdayrule)) {
1222 // Calculation of Ascension day (39 days after easter day)
1223 $date_paques = getGMTEasterDatetime($annee);
1224 $date_ascension = $date_paques + (3600 * 24 * 39);
1225 $jour_ascension = gmdate("d", $date_ascension);
1226 $mois_ascension = gmdate("m", $date_ascension);
1227 if ($jour_ascension == $jour && $mois_ascension == $mois) {
1228 $ferie = true;
1229 $listFeries[] = $timestampStart;
1230 }
1231 // Ascension (thursday)
1232 }
1233
1234 if (in_array('pentecost', $specialdayrule)) {
1235 // Calculation of "Pentecote" (49 days after easter day)
1236 $date_paques = getGMTEasterDatetime($annee);
1237 $date_pentecote = $date_paques + (3600 * 24 * 49);
1238 $jour_pentecote = gmdate("d", $date_pentecote);
1239 $mois_pentecote = gmdate("m", $date_pentecote);
1240 if ($jour_pentecote == $jour && $mois_pentecote == $mois) {
1241 $ferie = true;
1242 $listFeries[] = $timestampStart;
1243 }
1244 // "Pentecote" (sunday)
1245 }
1246
1247 if (in_array('pentecotemonday', $specialdayrule)) {
1248 // Calculation of "Pentecote" (49 days after easter day)
1249 $date_paques = getGMTEasterDatetime($annee);
1250 $date_pentecote = $date_paques + (3600 * 24 * 50);
1251 $jour_pentecote = gmdate("d", $date_pentecote);
1252 $mois_pentecote = gmdate("m", $date_pentecote);
1253 if ($jour_pentecote == $jour && $mois_pentecote == $mois) {
1254 $ferie = true;
1255 $listFeries[] = $timestampStart;
1256 }
1257 // "Pentecote" (monday)
1258 }
1259
1260 if (in_array('viernessanto', $specialdayrule)) {
1261 // Viernes Santo
1262 $date_paques = getGMTEasterDatetime($annee);
1263 $date_viernes = $date_paques - (3600 * 24 * 2);
1264 $jour_viernes = gmdate("d", $date_viernes);
1265 $mois_viernes = gmdate("m", $date_viernes);
1266 if ($jour_viernes == $jour && $mois_viernes == $mois) {
1267 $ferie = true;
1268 $listFeries[] = $timestampStart;
1269 }
1270 //Viernes Santo
1271 }
1272
1273 if (in_array('fronleichnam', $specialdayrule)) {
1274 // Fronleichnam (60 days after easter sunday)
1275 $date_paques = getGMTEasterDatetime($annee);
1276 $date_fronleichnam = $date_paques + (3600 * 24 * 60);
1277 $jour_fronleichnam = gmdate("d", $date_fronleichnam);
1278 $mois_fronleichnam = gmdate("m", $date_fronleichnam);
1279 if ($jour_fronleichnam == $jour && $mois_fronleichnam == $mois) {
1280 $ferie = true;
1281 $listFeries[] = $timestampStart;
1282 }
1283 // Fronleichnam
1284 }
1285
1286 if (in_array('genevafast', $specialdayrule)) {
1287 // Geneva fast in Switzerland (Thursday after the first sunday in September)
1288 $date_1sunsept = strtotime('next thursday', strtotime('next sunday', mktime(0, 0, 0, 9, 1, $annee)));
1289 $jour_1sunsept = date("d", $date_1sunsept);
1290 $mois_1sunsept = date("m", $date_1sunsept);
1291 if ($jour_1sunsept == $jour && $mois_1sunsept == $mois) {
1292 $ferie = true;
1293 $listFeries[] = $timestampStart;
1294 }
1295 // Geneva fast in Switzerland
1296 }
1297 }
1298 //print "ferie=".$nonWorkingDay."\n";
1299
1300 // Increase number of days (on go up into loop)
1301 $timestampStart = dol_time_plus_duree($timestampStart, 1, 'd');
1302 //var_dump($jour.' '.$mois.' '.$annee.' '.$timestampStart);
1303
1304 $i++;
1305 }
1306
1307 //print "nbFerie=".$nbFerie."\n";
1308 return $listFeries;
1309}
1310
1321function num_between_day($timestampStart, $timestampEnd, $lastday = 0)
1322{
1323 if ($timestampStart <= $timestampEnd) {
1324 if ($lastday == 1) {
1325 $bit = 0;
1326 } else {
1327 $bit = 1;
1328 }
1329 $nbjours = (int) floor(($timestampEnd - $timestampStart) / (60 * 60 * 24)) + 1 - $bit;
1330 } else {
1331 $nbjours = 0;
1332 }
1333 //print ($timestampEnd - $timestampStart) - $lastday;
1334 return $nbjours;
1335}
1336
1353function num_open_day($timestampStart, $timestampEnd, $inhour = 0, $lastday = 0, $halfday = 0, $countryCodeOrId = '', $user_id = 0)
1354{
1355 global $langs, $mysoc, $hookmanager;
1356
1357 if (empty($countryCodeOrId) || $countryCodeOrId < 0) {
1358 $countryCodeOrId = $mysoc->country_code;
1359 }
1360
1361 dol_syslog('num_open_day timestampStart='.$timestampStart.' timestampEnd='.$timestampEnd.' bit='.$lastday.' countryCodeOrId='.$countryCodeOrId);
1362
1363 // Check parameters
1364 if (!is_int($timestampStart) && !is_float($timestampStart)) {
1365 return 'ErrorBadParameter_num_open_day';
1366 }
1367 if (!is_int($timestampEnd) && !is_float($timestampEnd)) {
1368 return 'ErrorBadParameter_num_open_day';
1369 }
1370
1371 $nbOpenDay = 0; // expressed in days; inhour conversion happens at the end
1372
1373 if ($timestampStart < $timestampEnd) {
1374 // --- 1. Calculate Gross Working Days ---
1375 // Gross working days = total days in range - non-working days (weekends & public holidays).
1376 $a = num_between_day($timestampStart, $timestampEnd, $lastday);
1377 $b = num_public_holiday($timestampStart, $timestampEnd, $countryCodeOrId, $lastday);
1378 $nbOpenDay = $a - $b;
1379
1380 // --- 2. Apply Contextual Half-Day Deductions ---
1381 $halfday = (int) $halfday; // Ensure $halfday is an integer for reliable comparisons.
1382
1383 // Check if start/end days are working days just ONCE to optimize performance
1384 // by avoiding redundant calls to the potentially slow num_public_holiday() function.
1385 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
1386 $isStartDayWorking = (num_public_holiday($timestampStart, $timestampStart, $countryCodeOrId, 1) == 0);
1387 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
1388 $isEndDayWorking = (num_public_holiday($timestampEnd, $timestampEnd, $countryCodeOrId, 1) == 0);
1389
1390 // Deduct 0.5 if the leave starts in the afternoon of a working day.
1391 if (($halfday == -1 || $halfday == 2) && $isStartDayWorking) {
1392 $nbOpenDay -= 0.5;
1393 }
1394
1395 // Deduct 0.5 if the leave ends in the morning of a different, working day.
1396 if (($halfday == 1 || $halfday == 2) && date('Y-m-d', $timestampStart) != date('Y-m-d', $timestampEnd) && $isEndDayWorking) {
1397 $nbOpenDay -= 0.5;
1398 }
1399 } elseif ($timestampStart == $timestampEnd) {
1400 $isSingleDayHoliday = false;
1401 if ($lastday) {
1402 $numholidays = num_public_holiday($timestampStart, $timestampEnd, $countryCodeOrId, $lastday);
1403 if ($numholidays == 1) {
1404 $isSingleDayHoliday = true;
1405 }
1406 }
1407 if (!$isSingleDayHoliday) {
1408 $nbOpenDay = $lastday - 0.5 * abs((int) $halfday);
1409 }
1410 } else {
1411 return $langs->trans("Error");
1412 }
1413
1414 // --- 3. Allow modules to adjust the result based on the user (e.g. per-employee
1415 // individual workdays, bridge days, fixed half-days). Only fires when caller
1416 // opts in by passing a non-zero $user_id, so existing call sites are unaffected.
1417 if ($user_id > 0 && is_object($hookmanager)) {
1418 $parameters = array(
1419 'timestampStart' => $timestampStart,
1420 'timestampEnd' => $timestampEnd,
1421 'inhour' => $inhour,
1422 'lastday' => $lastday,
1423 'halfday' => $halfday,
1424 'countryCodeOrId' => $countryCodeOrId,
1425 'user_id' => $user_id,
1426 'nbOpenDay' => $nbOpenDay,
1427 );
1428 $action = '';
1429 $reshook = $hookmanager->executeHooks('numOpenDay', $parameters, $hookmanager, $action);
1430 if ($reshook > 0 && isset($hookmanager->resArray['nbOpenDay'])) {
1431 $nbOpenDay = $hookmanager->resArray['nbOpenDay'];
1432 }
1433 }
1434
1435 if ($inhour == 1) {
1436 return (int) ($nbOpenDay * 24);
1437 }
1438 return $nbOpenDay;
1439}
1440
1441
1442
1451function monthArray($outputlangs, $short = 0)
1452{
1453 $montharray = array(
1454 1 => $outputlangs->trans("Month01"),
1455 2 => $outputlangs->trans("Month02"),
1456 3 => $outputlangs->trans("Month03"),
1457 4 => $outputlangs->trans("Month04"),
1458 5 => $outputlangs->trans("Month05"),
1459 6 => $outputlangs->trans("Month06"),
1460 7 => $outputlangs->trans("Month07"),
1461 8 => $outputlangs->trans("Month08"),
1462 9 => $outputlangs->trans("Month09"),
1463 10 => $outputlangs->trans("Month10"),
1464 11 => $outputlangs->trans("Month11"),
1465 12 => $outputlangs->trans("Month12")
1466 );
1467
1468 if (!empty($short)) {
1469 $montharray = array(
1470 1 => $outputlangs->trans("MonthShort01"),
1471 2 => $outputlangs->trans("MonthShort02"),
1472 3 => $outputlangs->trans("MonthShort03"),
1473 4 => $outputlangs->trans("MonthShort04"),
1474 5 => $outputlangs->trans("MonthShort05"),
1475 6 => $outputlangs->trans("MonthShort06"),
1476 7 => $outputlangs->trans("MonthShort07"),
1477 8 => $outputlangs->trans("MonthShort08"),
1478 9 => $outputlangs->trans("MonthShort09"),
1479 10 => $outputlangs->trans("MonthShort10"),
1480 11 => $outputlangs->trans("MonthShort11"),
1481 12 => $outputlangs->trans("MonthShort12")
1482 );
1483 }
1484
1485 return $montharray;
1486}
1487
1495function getWeekNumbersOfMonth($month, $year)
1496{
1497 $nb_days = cal_days_in_month(CAL_GREGORIAN, $month, $year);
1498 $TWeek = array();
1499 for ($day = 1; $day <= $nb_days; $day++) {
1500 $week_number = getWeekNumber($day, $month, $year);
1501 $TWeek[$week_number] = $week_number;
1502 }
1503 return $TWeek;
1504}
1505
1513function getFirstDayOfEachWeek($TWeek, $year)
1514{
1515 $TFirstDayOfWeek = array();
1516 // 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.
1517 // If $TWeek starts with week 52 or 53 (a January), these first weeks belong to previous year.
1518 // If $TWeek ends with week 01 (a December), this last week belongs to next year.
1519 $startwithweeksofpreviousyear = ((int) reset($TWeek) >= 52 && in_array('01', $TWeek));
1520 foreach ($TWeek as $weekNb) {
1521 $yeartouse = $year;
1522 if ($startwithweeksofpreviousyear) {
1523 if ((int) $weekNb >= 52) {
1524 $yeartouse = $year - 1;
1525 }
1526 } elseif ($weekNb == '01' && in_array('52', $TWeek)) {
1527 $yeartouse = $year + 1;
1528 }
1529 $TFirstDayOfWeek[$weekNb] = date('d', strtotime($yeartouse.'W'.$weekNb));
1530 }
1531 return $TFirstDayOfWeek;
1532}
1533
1541function getLastDayOfEachWeek($TWeek, $year)
1542{
1543 $TLastDayOfWeek = array();
1544 // Same rule as in getFirstDayOfEachWeek() to find the year each week belongs to
1545 $startwithweeksofpreviousyear = ((int) reset($TWeek) >= 52 && in_array('01', $TWeek));
1546 foreach ($TWeek as $weekNb) {
1547 $yeartouse = $year;
1548 if ($startwithweeksofpreviousyear) {
1549 if ((int) $weekNb >= 52) {
1550 $yeartouse = $year - 1;
1551 }
1552 } elseif ($weekNb == '01' && in_array('52', $TWeek)) {
1553 $yeartouse = $year + 1;
1554 }
1555 $TLastDayOfWeek[$weekNb] = date('d', strtotime($yeartouse.'W'.$weekNb.'+6 days'));
1556 }
1557 return $TLastDayOfWeek;
1558}
1559
1568function getWeekNumber($day, $month, $year)
1569{
1570 $date = new DateTime($year.'-'.$month.'-'.$day);
1571 $week = $date->format("W");
1572 return $week;
1573}
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