dolibarr 25.0.0-alpha
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
126function dol_time_plus_duree($time, $duration_value, $duration_unit, $ruleforendofmonth = 0)
127{
128 if (empty($duration_value)) {
129 return $time;
130 }
131 if (!in_array($duration_unit, array('s', 'i', 'mn', 'min', 'h', 'd', 'w', 'm', 'y'))) {
132 $errormsg = 'dol_time_plus_duree call to function with undefined or bad duration_unit : ' . $duration_unit;
133 dol_syslog($errormsg, LOG_ERR);
134 return $time;
135 }
136 if ($duration_unit == 's') {
137 return $time + (int) ($duration_value);
138 }
139 if ($duration_unit == 'i' || $duration_unit == 'mn' || $duration_unit == 'min') {
140 return $time + (int) (60 * $duration_value);
141 }
142 if ($duration_unit == 'h') {
143 return $time + (int) (3600 * $duration_value);
144 }
145 if ($duration_unit == 'w') {
146 return $time + (int) (3600 * 24 * 7 * $duration_value);
147 }
148
149 $deltastring = 'P';
150
151 $sub = false;
152
153 if ($duration_value > 0) {
154 $deltastring .= abs($duration_value);
155 $sub = false;
156 }
157 if ($duration_value < 0) {
158 $deltastring .= abs($duration_value);
159 $sub = true;
160 }
161 if ($duration_unit == 'd') {
162 $deltastring .= "D";
163 }
164 if ($duration_unit == 'm') {
165 $deltastring .= "M";
166 }
167 if ($duration_unit == 'y') {
168 $deltastring .= "Y";
169 }
170
171 $date = new DateTime();
172 if (!function_exists('getDolGlobalString') || !getDolGlobalString('MAIN_DATE_IN_MEMORY_ARE_NOT_GMT')) { // Add function_exists to allow usage of this function with minimal context
173 $date->setTimezone(new DateTimeZone('UTC'));
174 }
175
176
177 $date->setTimestamp((int) $time);
178 $interval = new DateInterval($deltastring);
179
180 if ($sub) {
181 $date->sub($interval);
182 } else {
183 $date->add($interval);
184 }
185
186 // 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)
187 if ($ruleforendofmonth == 1 && $duration_unit == 'm') {
188 $timeyear = (int) dol_print_date($time, '%Y');
189 $timemonth = (int) dol_print_date($time, '%m');
190 $timetotalmonths = (($timeyear * 12) + $timemonth);
191
192 $monthsexpected = ($timetotalmonths + $duration_value);
193
194 $newtime = $date->getTimestamp();
195
196 $newtimeyear = (int) dol_print_date($newtime, '%Y');
197 $newtimemonth = (int) dol_print_date($newtime, '%m');
198 $newtimetotalmonths = (($newtimeyear * 12) + $newtimemonth);
199
200 if ($monthsexpected < $newtimetotalmonths || $monthsexpected > $newtimetotalmonths) { // If months differs
201 $newtimehours = (int) dol_print_date($newtime, '%H');
202 $newtimemins = (int) dol_print_date($newtime, '%M');
203 $newtimesecs = (int) dol_print_date($newtime, '%S');
204
205 $datelim = dol_mktime($newtimehours, $newtimemins, $newtimesecs, $newtimemonth, 1, $newtimeyear); // Take first day
206 $datelim -= (3600 * 24); // Remove 1 day to get the last day of month
207
208 $date->setTimestamp($datelim); // Set new date
209 }
210 }
211 return $date->getTimestamp();
212}
213
214
224function convertTime2Seconds($iHours = 0, $iMinutes = 0, $iSeconds = 0)
225{
226 $iResult = ((int) $iHours * 3600) + ((int) $iMinutes * 60) + (int) $iSeconds;
227 return $iResult;
228}
229
230
253function convertSecondToTime($iSecond, $format = 'all', $lengthOfDay = 86400, $lengthOfWeek = 7)
254{
255 global $langs;
256
257 if (empty($lengthOfDay)) {
258 $lengthOfDay = 86400; // 1 day = 24 hours
259 }
260 if (empty($lengthOfWeek)) {
261 $lengthOfWeek = 7; // 1 week = 7 days
262 }
263 $nbHbyDay = $lengthOfDay / 3600;
264
265 $sTime = '';
266
267 if ($format == 'all' || $format == 'allwithouthour' || $format == 'allhour' || $format == 'allhourmin' || $format == 'allhourminsec') {
268 if ((int) $iSecond === 0) {
269 return '0'; // This is to avoid having 0 return a 12:00 AM for en_US
270 }
271
272 $sDay = 0;
273 $sWeek = 0;
274
275 if ($iSecond >= $lengthOfDay) {
276 for ($i = $iSecond; $i >= $lengthOfDay; $i -= $lengthOfDay) {
277 $sDay++;
278 $iSecond -= $lengthOfDay;
279 }
280 $dayTranslate = $langs->trans("Day");
281 if ($iSecond >= ($lengthOfDay * 2)) {
282 $dayTranslate = $langs->trans("Days");
283 }
284 }
285
286 if ($lengthOfWeek < 7) {
287 if ($sDay) {
288 if ($sDay >= $lengthOfWeek) {
289 $sWeek = (int) (($sDay - $sDay % $lengthOfWeek) / $lengthOfWeek);
290 $sDay %= $lengthOfWeek;
291 $weekTranslate = $langs->trans("DurationWeek");
292 if ($sWeek >= 2) {
293 $weekTranslate = $langs->trans("DurationWeeks");
294 }
295 $sTime .= $sWeek.' '.$weekTranslate.' ';
296 }
297 }
298 }
299 if ($sDay > 0) {
300 $dayTranslate = $langs->trans("Day");
301 if ($sDay > 1) {
302 $dayTranslate = $langs->trans("Days");
303 }
304 $sTime .= $sDay.' '.$langs->trans("d").' ';
305 }
306
307 if ($format == 'all') {
308 if ($iSecond || empty($sDay)) {
309 $sTime .= dol_print_date($iSecond, 'hourduration', true);
310 }
311 } elseif ($format == 'allhourminsec') {
312 return sprintf("%02d", ($sWeek * $lengthOfWeek * $nbHbyDay + $sDay * $nbHbyDay + (int) floor($iSecond / 3600))).':'.sprintf("%02d", ((int) floor(($iSecond % 3600) / 60))).':'.sprintf("%02d", ((int) ($iSecond % 60)));
313 } elseif ($format == 'allhourmin') {
314 return sprintf("%02d", ($sWeek * $lengthOfWeek * $nbHbyDay + $sDay * $nbHbyDay + (int) floor($iSecond / 3600))).':'.sprintf("%02d", ((int) floor(($iSecond % 3600) / 60)));
315 } elseif ($format == 'allhour') {
316 return sprintf("%02d", ($sWeek * $lengthOfWeek * $nbHbyDay + $sDay * $nbHbyDay + (int) floor($iSecond / 3600)));
317 }
318 } elseif ($format == 'hour') { // only hour part
319 $sTime = dol_print_date($iSecond, '%H', true);
320 } elseif ($format == 'fullhour') {
321 if (!empty($iSecond)) {
322 $iSecond /= 3600;
323 } else {
324 $iSecond = 0;
325 }
326 $sTime = $iSecond;
327 } elseif ($format == 'min') { // only min part
328 $sTime = dol_print_date($iSecond, '%M', true);
329 } elseif ($format == 'sec') { // only sec part
330 $sTime = dol_print_date($iSecond, '%S', true);
331 } elseif ($format == 'month') { // only month part
332 $sTime = dol_print_date($iSecond, '%m', true);
333 } elseif ($format == 'year') { // only year part
334 $sTime = dol_print_date($iSecond, '%Y', true);
335 }
336 return trim((string) $sTime);
337}
338
339
347function convertDurationtoHour($duration_value, $duration_unit)
348{
349 $result = 0;
350
351 if ($duration_unit == 's') {
352 $result = $duration_value / 3600;
353 }
354 if ($duration_unit == 'i' || $duration_unit == 'mn' || $duration_unit == 'min') {
355 $result = $duration_value / 60;
356 }
357 if ($duration_unit == 'h') {
358 $result = $duration_value;
359 }
360 if ($duration_unit == 'd') {
361 $result = $duration_value * 24;
362 }
363 if ($duration_unit == 'w') {
364 $result = $duration_value * 24 * 7;
365 }
366 if ($duration_unit == 'm') {
367 $result = $duration_value * 730.484;
368 }
369 if ($duration_unit == 'y') {
370 $result = $duration_value * 365 * 24;
371 }
372
373 return $result;
374}
375
391function dolSqlDateFilter($datefield, $day_date, $month_date, $year_date, $excludefirstand = 0, $gm = false)
392{
393 global $db;
394 $sqldate = '';
395
396 $day_date = intval($day_date);
397 $month_date = intval($month_date);
398 $year_date = intval($year_date);
399 $sql_datefield = $db->sanitize($datefield);
400
401 if ($month_date > 0) {
402 if ($month_date > 12) { // protection for bad value of month
403 return " AND 1 = 2";
404 }
405 if ($year_date > 0 && empty($day_date)) {
406 $sqldate .= ($excludefirstand ? "" : " AND ").$sql_datefield." BETWEEN '".$db->idate(dol_get_first_day($year_date, $month_date, $gm))."'";
407 $sqldate .= " AND '".$db->idate(dol_get_last_day($year_date, $month_date, $gm))."'";
408 } elseif ($year_date > 0 && !empty($day_date)) {
409 $sqldate .= ($excludefirstand ? "" : " AND ").$sql_datefield." BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $month_date, $day_date, $year_date, $gm))."'";
410 $sqldate .= " AND '".$db->idate(dol_mktime(23, 59, 59, $month_date, $day_date, $year_date, $gm))."'";
411 } else {
412 // This case is not reliable on TZ, but we should not need it.
413 $sqldate .= ($excludefirstand ? "" : " AND ")." date_format( ".$sql_datefield.", '%c') = '".$db->escape((string) $month_date)."'";
414 }
415 } elseif ($year_date > 0) {
416 $sqldate .= ($excludefirstand ? "" : " AND ").$sql_datefield." BETWEEN '".$db->idate(dol_get_first_day($year_date, 1, $gm))."'";
417 $sqldate .= " AND '".$db->idate(dol_get_last_day($year_date, 12, $gm))."'";
418 }
419 return $sqldate;
420}
421
442function dol_stringtotime($string, $gm = 1, $processnotimeasnoon = 0)
443{
444 $reg = array();
445 // Convert date with format DD/MM/YYY HH:MM:SS. This part of code should not be used as receiving a non standard format should not happen.
446 if (preg_match('/^([0-9]+)\/([0-9]+)\/([0-9]+)\s?([0-9]+)?:?([0-9]+)?:?([0-9]+)?/i', $string, $reg)) {
447 dol_syslog("dol_stringtotime call to function with deprecated parameter format", LOG_WARNING);
448 // Date is in format 'DD/MM/YY' or 'DD/MM/YY HH:MM:SS'
449 // Date is in format 'DD/MM/YYYY' or 'DD/MM/YYYY HH:MM:SS'
450 $sday = (int) $reg[1];
451 $smonth = (int) $reg[2];
452 $syear = (int) $reg[3];
453 $shour = (int) $reg[4];
454 $smin = (int) $reg[5];
455 $ssec = (int) $reg[6];
456 if ($syear < 50) {
457 $syear += 1900;
458 }
459 if ($syear >= 50 && $syear < 100) {
460 $syear += 2000;
461 }
462 $string = sprintf("%04d%02d%02d%02d%02d%02d", $syear, $smonth, $sday, $shour, $smin, $ssec);
463 } 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)
464 || 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
465 || 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
466 ) {
467 $syear = (int) $reg[1];
468 $smonth = (int) $reg[2];
469 $sday = (int) $reg[3];
470 $shour = (int) $reg[4];
471 $smin = (int) $reg[5];
472 $ssec = (int) $reg[6];
473 $string = sprintf("%04d%02d%02d%02d%02d%02d", $syear, $smonth, $sday, $shour, $smin, $ssec);
474 }
475
476 $string = preg_replace('/([^0-9])/i', '', $string);
477 // If not time was provided, we add it (if it was, it won't be seen)
478 if ($processnotimeasnoon) {
479 $tmp = $string.'120000';
480 } else {
481 $tmp = $string.'000000';
482 }
483 // Clean $gm
484 if ($gm === 1) {
485 $gm = 'gmt';
486 } elseif (empty($gm) || $gm === 'tzserver') {
487 $gm = 'tzserver';
488 }
489
490 $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);
491
492 return $date;
493}
494
495
504function dol_get_prev_day($day, $month, $year)
505{
506 $time = dol_mktime(12, 0, 0, $month, $day, $year, 1, 0);
507 $time -= 24 * 60 * 60;
508 $tmparray = dol_getdate($time, true);
509 return array('year' => $tmparray['year'], 'month' => $tmparray['mon'], 'day' => $tmparray['mday']);
510}
511
520function dol_get_next_day($day, $month, $year)
521{
522 $time = dol_mktime(12, 0, 0, $month, $day, $year, 1, 0);
523 $time += 24 * 60 * 60;
524 $tmparray = dol_getdate($time, true);
525 return array('year' => $tmparray['year'], 'month' => $tmparray['mon'], 'day' => $tmparray['mday']);
526}
527
535function dol_get_prev_month($month, $year)
536{
537 if ($month == 1) {
538 $prev_month = 12;
539 $prev_year = $year - 1;
540 } else {
541 $prev_month = $month - 1;
542 $prev_year = $year;
543 }
544 return array('year' => $prev_year, 'month' => $prev_month);
545}
546
554function dol_get_next_month($month, $year)
555{
556 if ($month == 12) {
557 $next_month = 1;
558 $next_year = $year + 1;
559 } else {
560 $next_month = $month + 1;
561 $next_year = $year;
562 }
563 return array('year' => $next_year, 'month' => $next_month);
564}
565
575function dol_get_prev_week($day, $week, $month, $year)
576{
577 $tmparray = dol_get_first_day_week($day, $month, $year);
578
579 $time = dol_mktime(12, 0, 0, $month, $tmparray['first_day'], $year, 1, 0);
580 $time -= 24 * 60 * 60 * 7;
581 $tmparray = dol_getdate($time, true);
582 return array('year' => $tmparray['year'], 'month' => $tmparray['mon'], 'day' => $tmparray['mday']);
583}
584
594function dol_get_next_week($day, $week, $month, $year)
595{
596 $tmparray = dol_get_first_day_week($day, $month, $year);
597
598 $time = dol_mktime(12, 0, 0, $tmparray['first_month'], $tmparray['first_day'], $tmparray['first_year'], 1, 0);
599 $time += 24 * 60 * 60 * 7;
600 $tmparray = dol_getdate($time, true);
601
602 return array('year' => $tmparray['year'], 'month' => $tmparray['mon'], 'day' => $tmparray['mday']);
603}
604
616function dol_get_first_day($year, $month = 1, $gm = false)
617{
618 if ($year > 9999) {
619 return '';
620 }
621 return dol_mktime(0, 0, 0, $month, 1, $year, $gm);
622}
623
624
635function dol_get_last_day($year, $month = 12, $gm = false)
636{
637 if ($year > 9999) {
638 return '';
639 }
640 if ($month == 12) {
641 $month = 1;
642 $year += 1;
643 } else {
644 $month += 1;
645 }
646
647 // Move to the start of the next month, then subtract one day
648 $datelim = dol_mktime(23, 59, 59, $month, 1, $year, $gm);
649 $datelim -= (3600 * 24);
650
651 return $datelim;
652}
653
662function dol_get_last_hour($date, $gm = 'tzserver')
663{
664 $tmparray = dol_getdate($date, false, ($gm == 'gmt' ? 'gmt' : ''));
665 return dol_mktime(23, 59, 59, $tmparray['mon'], $tmparray['mday'], $tmparray['year'], $gm);
666}
667
676function dol_get_first_hour($date, $gm = 'tzserver')
677{
678 $tmparray = dol_getdate($date, false, ($gm == 'gmt' ? 'gmt' : ''));
679 return dol_mktime(0, 0, 0, $tmparray['mon'], $tmparray['mday'], $tmparray['year'], $gm);
680}
681
691function dol_get_first_day_week($day, $month, $year, $gm = false)
692{
693 //$day=2; $month=2; $year=2015;
694 $date = dol_mktime(0, 0, 0, $month, $day, $year, $gm);
695
696 //Checking conf of start week
697 $start_week = getDolGlobalInt('MAIN_START_WEEK', 1);
698
699 $tmparray = dol_getdate($date, true); // detail of current day
700
701 //Calculate days = offset from current day
702 $days = $start_week - $tmparray['wday'];
703 if ($days >= 1) {
704 $days = 7 - $days;
705 }
706 $days = abs($days);
707 $seconds = $days * 24 * 60 * 60;
708 //print 'start_week='.$start_week.' tmparray[wday]='.$tmparray['wday'].' day offset='.$days.' seconds offset='.$seconds.'<br>';
709
710 //Get first day of week
711 $tmpdaytms = (int) date((string) $tmparray['0']) - $seconds; // $tmparray[0] is day of parameters
712 $tmpday = idate("d", $tmpdaytms);
713
714 //Check first day of week is in same month than current day or not
715 if ($tmpday > $day) {
716 $prev_month = $month - 1;
717 $prev_year = $year;
718
719 if ($prev_month == 0) {
720 $prev_month = 12;
721 $prev_year = $year - 1;
722 }
723 } else {
724 $prev_month = $month;
725 $prev_year = $year;
726 }
727 $tmpmonth = $prev_month;
728 $tmpyear = $prev_year;
729
730 //Get first day of next week
731 $tmptime = dol_mktime(12, 0, 0, $month, $tmpday, $year, 1, 0);
732 $tmptime -= 24 * 60 * 60 * 7;
733 $tmparray = dol_getdate($tmptime, true);
734 $prev_day = $tmparray['mday'];
735
736 //Check prev day of week is in same month than first day or not
737 if ($prev_day > $tmpday) {
738 $prev_month = $month - 1;
739 $prev_year = $year;
740
741 if ($prev_month == 0) {
742 $prev_month = 12;
743 $prev_year = $year - 1;
744 }
745 }
746
747 $week = date("W", dol_mktime(0, 0, 0, $tmpmonth, $tmpday, $tmpyear, $gm));
748
749 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);
750}
751
759function getGMTEasterDatetime($year)
760{
761 $base = new DateTime("$year-03-21", new DateTimeZone("UTC"));
762 $days = easter_days($year); // Return number of days between 21 march and easter day.
763 $tmp = $base->add(new DateInterval("P{$days}D"));
764 return $tmp->getTimestamp();
765}
766
783function num_public_holiday($timestampStart, $timestampEnd, $countryCodeOrId = '', $lastday = 0, $includesaturday = -1, $includesunday = -1, $includefriday = -1, $includemonday = -1)
784{
785 global $conf, $db, $mysoc;
786
787 $nbFerie = 0;
788
789 // Check to ensure we use correct parameters
790 if (($timestampEnd - $timestampStart) % 86400 != 0) {
791 return 'Error Dates must use same hours and must be GMT dates';
792 }
793
794 if (empty($countryCodeOrId)) {
795 $countryCodeOrId = $mysoc->country_code;
796 }
797 if ($includemonday < 0) {
798 $includemonday = getDolGlobalInt('MAIN_NON_WORKING_DAYS_INCLUDE_MONDAY', 0);
799 }
800 if ($includefriday < 0) {
801 $includefriday = getDolGlobalInt('MAIN_NON_WORKING_DAYS_INCLUDE_FRIDAY', 0);
802 }
803 if ($includesaturday < 0) {
804 $includesaturday = getDolGlobalInt('MAIN_NON_WORKING_DAYS_INCLUDE_SATURDAY', 1);
805 }
806 if ($includesunday < 0) {
807 $includesunday = getDolGlobalInt('MAIN_NON_WORKING_DAYS_INCLUDE_SUNDAY', 1);
808 }
809
810 if (is_numeric($countryCodeOrId)) {
811 $country_id = $countryCodeOrId;
812 } else {
813 $country_id = dol_getIdFromCode($db, $countryCodeOrId, 'c_country', 'code', 'rowid');
814 }
815
816 if (empty($conf->cache['arrayOfActivePublicHolidays_'.$country_id])) {
817 // Loop on public holiday defined into hrm_public_holiday for the day, month and year analyzed
818 $tmpArrayOfPublicHolidays = array();
819 $sql = "SELECT id, code, entity, fk_country, dayrule, year, month, day, active";
820 $sql .= " FROM ".MAIN_DB_PREFIX."c_hrm_public_holiday";
821 $sql .= " WHERE active = 1 and fk_country IN (0".($country_id > 0 ? ", ".((int) $country_id) : 0).")";
822 $sql .= " AND entity IN (0," .getEntity('holiday') .")";
823
824 $resql = $db->query($sql);
825 if ($resql) {
826 $num_rows = $db->num_rows($resql);
827 $i = 0;
828 while ($i < $num_rows) {
829 $obj = $db->fetch_object($resql);
830 $tmpArrayOfPublicHolidays[$obj->id] = array('dayrule' => $obj->dayrule, 'year' => $obj->year, 'month' => $obj->month, 'day' => $obj->day);
831 $i++;
832 }
833 } else {
834 dol_syslog($db->lasterror(), LOG_ERR);
835 return 'Error sql '.$db->lasterror();
836 }
837
838 //var_dump($tmpArrayOfPublicHolidays);
839 $conf->cache['arrayOfActivePublicHolidays_'.$country_id] = $tmpArrayOfPublicHolidays;
840 }
841
842 $arrayOfPublicHolidays = $conf->cache['arrayOfActivePublicHolidays_'.$country_id];
843
844 $i = 0;
845 while ((($lastday == 0 && $timestampStart < $timestampEnd) || ($lastday && $timestampStart <= $timestampEnd))
846 && ($i < 50000)) { // Loop end when equals (Test on i is a security loop to avoid infinite loop)
847 $ferie = false;
848 $specialdayrule = array();
849
850 $jour = (int) gmdate("d", $timestampStart);
851 $mois = (int) gmdate("m", $timestampStart);
852 $annee = (int) gmdate("Y", $timestampStart);
853 $jour_semaine = (int) gmdate("w", $timestampStart); // sunday = 0, monday = 1, ...
854
855 //print "jour=".$jour." month=".$mois." year=".$annee." includesaturday=".$includesaturday." includesunday=".$includesunday."\n";
856 foreach ($arrayOfPublicHolidays as $entrypublicholiday) {
857 if (!empty($entrypublicholiday['dayrule']) && $entrypublicholiday['dayrule'] != 'date') { // For example 'easter', '...'
858 $specialdayrule[$entrypublicholiday['dayrule']] = $entrypublicholiday['dayrule'];
859 } else {
860 $match = 1;
861 if (!empty($entrypublicholiday['year']) && $entrypublicholiday['year'] != $annee) {
862 $match = 0;
863 }
864 if ($entrypublicholiday['month'] != $mois) {
865 $match = 0;
866 }
867 if ($entrypublicholiday['day'] != $jour) {
868 $match = 0;
869 }
870
871 if ($match) {
872 $ferie = true;
873 }
874 }
875
876 $i++;
877 }
878 //var_dump($specialdayrule)."\n";
879 //print "ferie=".$ferie."\n";
880
881 if (!$ferie) {
882 // Special dayrules
883 if (in_array('easter', $specialdayrule)) {
884 // Calculation for easter date
885 $date_paques = getGMTEasterDatetime($annee);
886 $jour_paques = gmdate("d", $date_paques);
887 $mois_paques = gmdate("m", $date_paques);
888 if ($jour_paques == $jour && $mois_paques == $mois) {
889 $ferie = true;
890 }
891 // Easter (sunday)
892 }
893
894 if (in_array('eastermonday', $specialdayrule)) {
895 // Calculation for the monday of easter date
896 $date_paques = getGMTEasterDatetime($annee);
897 //print 'PPP'.$date_paques.' '.dol_print_date($date_paques, 'dayhour', 'gmt')." ";
898 $date_lundi_paques = $date_paques + (3600 * 24);
899 $jour_lundi_paques = gmdate("d", $date_lundi_paques);
900 $mois_lundi_paques = gmdate("m", $date_lundi_paques);
901 if ($jour_lundi_paques == $jour && $mois_lundi_paques == $mois) {
902 $ferie = true;
903 }
904 // Easter (monday)
905 //print 'annee='.$annee.' $jour='.$jour.' $mois='.$mois.' $jour_lundi_paques='.$jour_lundi_paques.' $mois_lundi_paques='.$mois_lundi_paques."\n";
906 }
907
908 //Good Friday
909 if (in_array('goodfriday', $specialdayrule)) {
910 // Pulls the date of Easter
911 $easter = getGMTEasterDatetime($annee);
912
913 // Calculates the date of Good Friday based on Easter
914 $date_good_friday = $easter - (2 * 3600 * 24);
915 $dom_good_friday = gmdate("d", $date_good_friday);
916 $month_good_friday = gmdate("m", $date_good_friday);
917
918 if ($dom_good_friday == $jour && $month_good_friday == $mois) {
919 $ferie = true;
920 }
921 }
922
923 if (in_array('ascension', $specialdayrule)) {
924 // Calculation of Ascension day (39 days after easter day)
925 $date_paques = getGMTEasterDatetime($annee);
926 $date_ascension = $date_paques + (3600 * 24 * 39);
927 $jour_ascension = gmdate("d", $date_ascension);
928 $mois_ascension = gmdate("m", $date_ascension);
929 if ($jour_ascension == $jour && $mois_ascension == $mois) {
930 $ferie = true;
931 }
932 // Ascension (thursday)
933 }
934
935 if (in_array('pentecost', $specialdayrule)) {
936 // Calculation of "Pentecote" (49 days after easter day)
937 $date_paques = getGMTEasterDatetime($annee);
938 $date_pentecote = $date_paques + (3600 * 24 * 49);
939 $jour_pentecote = gmdate("d", $date_pentecote);
940 $mois_pentecote = gmdate("m", $date_pentecote);
941 if ($jour_pentecote == $jour && $mois_pentecote == $mois) {
942 $ferie = true;
943 }
944 // "Pentecote" (sunday)
945 }
946 if (in_array('pentecotemonday', $specialdayrule)) {
947 // Calculation of "Pentecote" (49 days after easter day)
948 $date_paques = getGMTEasterDatetime($annee);
949 $date_pentecote = $date_paques + (3600 * 24 * 50);
950 $jour_pentecote = gmdate("d", $date_pentecote);
951 $mois_pentecote = gmdate("m", $date_pentecote);
952 if ($jour_pentecote == $jour && $mois_pentecote == $mois) {
953 $ferie = true;
954 }
955 // "Pentecote" (monday)
956 }
957
958 if (in_array('viernessanto', $specialdayrule)) {
959 // Viernes Santo
960 $date_paques = getGMTEasterDatetime($annee);
961 $date_viernes = $date_paques - (3600 * 24 * 2);
962 $jour_viernes = gmdate("d", $date_viernes);
963 $mois_viernes = gmdate("m", $date_viernes);
964 if ($jour_viernes == $jour && $mois_viernes == $mois) {
965 $ferie = true;
966 }
967 //Viernes Santo
968 }
969
970 if (in_array('fronleichnam', $specialdayrule)) {
971 // Fronleichnam (60 days after easter sunday)
972 $date_paques = getGMTEasterDatetime($annee);
973 $date_fronleichnam = $date_paques + (3600 * 24 * 60);
974 $jour_fronleichnam = gmdate("d", $date_fronleichnam);
975 $mois_fronleichnam = gmdate("m", $date_fronleichnam);
976 if ($jour_fronleichnam == $jour && $mois_fronleichnam == $mois) {
977 $ferie = true;
978 }
979 // Fronleichnam
980 }
981
982 if (in_array('genevafast', $specialdayrule)) {
983 // Geneva fast in Switzerland (Thursday after the first sunday in September)
984 $date_1sunsept = strtotime('next thursday', strtotime('next sunday', mktime(0, 0, 0, 9, 1, $annee)));
985 $jour_1sunsept = date("d", $date_1sunsept);
986 $mois_1sunsept = date("m", $date_1sunsept);
987 if ($jour_1sunsept == $jour && $mois_1sunsept == $mois) {
988 $ferie = true;
989 }
990 // Geneva fast in Switzerland
991 }
992 }
993 //print "ferie afterspe=".$ferie."\n";
994
995 // If we have to include Friday, Saturday and Sunday
996 if (!$ferie) {
997 if ($includefriday || $includesaturday || $includesunday || $includemonday) {
998 //Monday (1), Friday (5), Saturday (6) and Sunday (0)
999 if ($includefriday && $jour_semaine == 5) {
1000 $ferie = true;
1001 }
1002 if ($includesaturday && $jour_semaine == 6) {
1003 $ferie = true;
1004 }
1005 if ($includesunday && $jour_semaine == 0) {
1006 $ferie = true;
1007 }
1008 if ($includemonday && $jour_semaine == 1) {
1009 $ferie = true;
1010 }
1011 }
1012 }
1013 //print "ferie afterincludexxxday=".$ferie."\n";
1014
1015 // We increase the counter of non working day
1016 if ($ferie) {
1017 $nbFerie++;
1018 }
1019
1020 // Increase number of days (on go up into loop)
1021 // Advance by exactly one GMT day. We can use += instead of dol_time_plus_duree() here because
1022 // inputs of this function are GMT dates (checked above), so a day
1023 // is always exactly 86400 seconds.
1024 //var_dump("before ".$jour.' '.$mois.' '.$annee.' '.$timestampStart);
1025 $timestampStart += 86400;
1026 //var_dump("after ".$jour.' '.$mois.' '.$annee.' '.$timestampStart);
1027
1028 $i++;
1029 }
1030
1031 //print "nbFerie=".$nbFerie."\n";
1032 return $nbFerie;
1033}
1034
1051function listPublicHoliday($timestampStart, $timestampEnd, $countryCodeOrId = '', $lastday = 0, $excludesaturday = -1, $excludesunday = -1, $excludefriday = -1, $excludemonday = -1)
1052{
1053 global $conf, $db, $mysoc;
1054
1055 // Check to ensure we use correct parameters
1056 if (($timestampEnd - $timestampStart) % 86400 != 0) {
1057 return 'Error Dates must use same hours and must be GMT dates';
1058 }
1059
1060 if (empty($countryCodeOrId)) {
1061 $countryCodeOrId = $mysoc->country_code;
1062 }
1063 if ($excludemonday < 0) {
1064 $excludemonday = getDolGlobalInt('MAIN_NON_WORKING_DAYS_INCLUDE_MONDAY', 0);
1065 }
1066 if ($excludefriday < 0) {
1067 $excludefriday = getDolGlobalInt('MAIN_NON_WORKING_DAYS_INCLUDE_FRIDAY', 0);
1068 }
1069 if ($excludesaturday < 0) {
1070 $excludesaturday = getDolGlobalInt('MAIN_NON_WORKING_DAYS_INCLUDE_SATURDAY', 1);
1071 }
1072 if ($excludesunday < 0) {
1073 $excludesunday = getDolGlobalInt('MAIN_NON_WORKING_DAYS_INCLUDE_SUNDAY', 1);
1074 }
1075
1076 if (is_numeric($countryCodeOrId)) {
1077 $country_id = $countryCodeOrId;
1078 } else {
1079 $country_id = dol_getIdFromCode($db, $countryCodeOrId, 'c_country', 'code', 'rowid');
1080 }
1081
1082 if (empty($conf->cache['arrayOfActivePublicHolidays_' . $country_id])) {
1083 // Loop on public holiday defined into hrm_public_holiday for the day, month and year analyzed
1084 $tmpArrayOfPublicHolidays = array();
1085 $sql = "SELECT id, code, entity, fk_country, dayrule, year, month, day, active";
1086 $sql .= " FROM " . MAIN_DB_PREFIX . "c_hrm_public_holiday";
1087 $sql .= " WHERE active = 1 and fk_country IN (0" . ($country_id > 0 ? ", " . ((int) $country_id) : 0) . ")";
1088 $sql .= " AND entity IN (0," . getEntity('holiday') . ")";
1089
1090 $resql = $db->query($sql);
1091 if ($resql) {
1092 $num_rows = $db->num_rows($resql);
1093 $i = 0;
1094 while ($i < $num_rows) {
1095 $obj = $db->fetch_object($resql);
1096 $tmpArrayOfPublicHolidays[$obj->id] = array('dayrule' => $obj->dayrule, 'year' => $obj->year, 'month' => $obj->month, 'day' => $obj->day);
1097 $i++;
1098 }
1099 } else {
1100 dol_syslog($db->lasterror(), LOG_ERR);
1101 return 'Error sql ' . $db->lasterror();
1102 }
1103
1104 //var_dump($tmpArrayOfPublicHolidays);
1105 $conf->cache['arrayOfActivePublicHolidays_' . $country_id] = $tmpArrayOfPublicHolidays;
1106 }
1107
1108 $arrayOfPublicHolidays = $conf->cache['arrayOfActivePublicHolidays_' . $country_id];
1109 $listFeries = [];
1110 $i = 0;
1111 while ((($lastday == 0 && $timestampStart < $timestampEnd) || ($lastday && $timestampStart <= $timestampEnd))
1112 && ($i < 50000)) { // Loop end when equals (Test on i is a security loop to avoid infinite loop)
1113 $nonWorkingDay = false;
1114 $ferie = false;
1115 $specialdayrule = array();
1116
1117 $jour = (int) gmdate("d", $timestampStart);
1118 $mois = (int) gmdate("m", $timestampStart);
1119 $annee = (int) gmdate("Y", $timestampStart);
1120
1121 // If we have to exclude Friday, Saturday and Sunday
1122 if ($excludefriday || $excludesaturday || $excludesunday) {
1123 $jour_julien = unixtojd($timestampStart);
1124 $jour_semaine = jddayofweek($jour_julien, 0);
1125 if ($excludefriday) { //Friday (5), Saturday (6) and Sunday (0)
1126 if ($jour_semaine == 5) {
1127 $nonWorkingDay = true;
1128 }
1129 }
1130 if ($excludesaturday) { //Friday (5), Saturday (6) and Sunday (0)
1131 if ($jour_semaine == 6) {
1132 $nonWorkingDay = true;
1133 }
1134 }
1135 if ($excludesunday) { //Friday (5), Saturday (6) and Sunday (0)
1136 if ($jour_semaine == 0) {
1137 $nonWorkingDay = true;
1138 }
1139 }
1140 }
1141 //print "ferie=".$nonWorkingDay."\n";
1142
1143 if (!$nonWorkingDay) {
1144 //print "jour=".$jour." month=".$mois." year=".$annee." includesaturday=".$excludesaturday." includesunday=".$excludesunday."\n";
1145 foreach ($arrayOfPublicHolidays as $entrypublicholiday) {
1146 if (!empty($entrypublicholiday['dayrule']) && $entrypublicholiday['dayrule'] != 'date') { // For example 'easter', '...'
1147 $specialdayrule[$entrypublicholiday['dayrule']] = $entrypublicholiday['dayrule'];
1148 } else {
1149 $match = 1;
1150 if (!empty($entrypublicholiday['year']) && $entrypublicholiday['year'] != $annee) {
1151 $match = 0;
1152 }
1153 if ($entrypublicholiday['month'] != $mois) {
1154 $match = 0;
1155 }
1156 if ($entrypublicholiday['day'] != $jour) {
1157 $match = 0;
1158 }
1159
1160 if ($match) {
1161 $ferie = true;
1162 $listFeries[] = $timestampStart;
1163 }
1164 }
1165
1166 $i++;
1167 }
1168 //var_dump($specialdayrule)."\n";
1169 //print "ferie=".$nonWorkingDay."\n";
1170 }
1171
1172 if (!$nonWorkingDay && !$ferie) {
1173 // Special dayrules
1174 if (in_array('easter', $specialdayrule)) {
1175 // Calculation for easter date
1176 $date_paques = getGMTEasterDatetime($annee);
1177 $jour_paques = gmdate("d", $date_paques);
1178 $mois_paques = gmdate("m", $date_paques);
1179 if ($jour_paques == $jour && $mois_paques == $mois) {
1180 $ferie = true;
1181 $listFeries[] = $timestampStart;
1182 }
1183 // Easter (sunday)
1184 }
1185
1186 if (in_array('eastermonday', $specialdayrule)) {
1187 // Calculation for the monday of easter date
1188 $date_paques = getGMTEasterDatetime($annee);
1189 //print 'PPP'.$date_paques.' '.dol_print_date($date_paques, 'dayhour', 'gmt')." ";
1190 $date_lundi_paques = $date_paques + (3600 * 24);
1191 $jour_lundi_paques = gmdate("d", $date_lundi_paques);
1192 $mois_lundi_paques = gmdate("m", $date_lundi_paques);
1193 if ($jour_lundi_paques == $jour && $mois_lundi_paques == $mois) {
1194 $ferie = true;
1195 $listFeries[] = $timestampStart;
1196 }
1197 // Easter (monday)
1198 //print 'annee='.$annee.' $jour='.$jour.' $mois='.$mois.' $jour_lundi_paques='.$jour_lundi_paques.' $mois_lundi_paques='.$mois_lundi_paques."\n";
1199 }
1200
1201 //Good Friday
1202 if (in_array('goodfriday', $specialdayrule)) {
1203 // Pulls the date of Easter
1204 $easter = getGMTEasterDatetime($annee);
1205
1206 // Calculates the date of Good Friday based on Easter
1207 $date_good_friday = $easter - (2 * 3600 * 24);
1208 $dom_good_friday = gmdate("d", $date_good_friday);
1209 $month_good_friday = gmdate("m", $date_good_friday);
1210
1211 if ($dom_good_friday == $jour && $month_good_friday == $mois) {
1212 $ferie = true;
1213 $listFeries[] = $timestampStart;
1214 }
1215 }
1216
1217 if (in_array('ascension', $specialdayrule)) {
1218 // Calculation of Ascension day (39 days after easter day)
1219 $date_paques = getGMTEasterDatetime($annee);
1220 $date_ascension = $date_paques + (3600 * 24 * 39);
1221 $jour_ascension = gmdate("d", $date_ascension);
1222 $mois_ascension = gmdate("m", $date_ascension);
1223 if ($jour_ascension == $jour && $mois_ascension == $mois) {
1224 $ferie = true;
1225 $listFeries[] = $timestampStart;
1226 }
1227 // Ascension (thursday)
1228 }
1229
1230 if (in_array('pentecost', $specialdayrule)) {
1231 // Calculation of "Pentecote" (49 days after easter day)
1232 $date_paques = getGMTEasterDatetime($annee);
1233 $date_pentecote = $date_paques + (3600 * 24 * 49);
1234 $jour_pentecote = gmdate("d", $date_pentecote);
1235 $mois_pentecote = gmdate("m", $date_pentecote);
1236 if ($jour_pentecote == $jour && $mois_pentecote == $mois) {
1237 $ferie = true;
1238 $listFeries[] = $timestampStart;
1239 }
1240 // "Pentecote" (sunday)
1241 }
1242
1243 if (in_array('pentecotemonday', $specialdayrule)) {
1244 // Calculation of "Pentecote" (49 days after easter day)
1245 $date_paques = getGMTEasterDatetime($annee);
1246 $date_pentecote = $date_paques + (3600 * 24 * 50);
1247 $jour_pentecote = gmdate("d", $date_pentecote);
1248 $mois_pentecote = gmdate("m", $date_pentecote);
1249 if ($jour_pentecote == $jour && $mois_pentecote == $mois) {
1250 $ferie = true;
1251 $listFeries[] = $timestampStart;
1252 }
1253 // "Pentecote" (monday)
1254 }
1255
1256 if (in_array('viernessanto', $specialdayrule)) {
1257 // Viernes Santo
1258 $date_paques = getGMTEasterDatetime($annee);
1259 $date_viernes = $date_paques - (3600 * 24 * 2);
1260 $jour_viernes = gmdate("d", $date_viernes);
1261 $mois_viernes = gmdate("m", $date_viernes);
1262 if ($jour_viernes == $jour && $mois_viernes == $mois) {
1263 $ferie = true;
1264 $listFeries[] = $timestampStart;
1265 }
1266 //Viernes Santo
1267 }
1268
1269 if (in_array('fronleichnam', $specialdayrule)) {
1270 // Fronleichnam (60 days after easter sunday)
1271 $date_paques = getGMTEasterDatetime($annee);
1272 $date_fronleichnam = $date_paques + (3600 * 24 * 60);
1273 $jour_fronleichnam = gmdate("d", $date_fronleichnam);
1274 $mois_fronleichnam = gmdate("m", $date_fronleichnam);
1275 if ($jour_fronleichnam == $jour && $mois_fronleichnam == $mois) {
1276 $ferie = true;
1277 $listFeries[] = $timestampStart;
1278 }
1279 // Fronleichnam
1280 }
1281
1282 if (in_array('genevafast', $specialdayrule)) {
1283 // Geneva fast in Switzerland (Thursday after the first sunday in September)
1284 $date_1sunsept = strtotime('next thursday', strtotime('next sunday', mktime(0, 0, 0, 9, 1, $annee)));
1285 $jour_1sunsept = date("d", $date_1sunsept);
1286 $mois_1sunsept = date("m", $date_1sunsept);
1287 if ($jour_1sunsept == $jour && $mois_1sunsept == $mois) {
1288 $ferie = true;
1289 $listFeries[] = $timestampStart;
1290 }
1291 // Geneva fast in Switzerland
1292 }
1293 }
1294 //print "ferie=".$nonWorkingDay."\n";
1295
1296 // Increase number of days (on go up into loop)
1297 $timestampStart = dol_time_plus_duree($timestampStart, 1, 'd');
1298 //var_dump($jour.' '.$mois.' '.$annee.' '.$timestampStart);
1299
1300 $i++;
1301 }
1302
1303 //print "nbFerie=".$nbFerie."\n";
1304 return $listFeries;
1305}
1306
1317function num_between_day($timestampStart, $timestampEnd, $lastday = 0)
1318{
1319 if ($timestampStart <= $timestampEnd) {
1320 if ($lastday == 1) {
1321 $bit = 0;
1322 } else {
1323 $bit = 1;
1324 }
1325 $nbjours = (int) floor(($timestampEnd - $timestampStart) / (60 * 60 * 24)) + 1 - $bit;
1326 } else {
1327 $nbjours = 0;
1328 }
1329 //print ($timestampEnd - $timestampStart) - $lastday;
1330 return $nbjours;
1331}
1332
1353function num_between_day_30_360($timestampStart, $timestampEnd, $lastday = 0, $forcetimezone = '')
1354{
1355 if ($timestampStart > $timestampEnd) {
1356 return 0;
1357 }
1358
1359 $start = dol_getdate((int) $timestampStart, false, $forcetimezone);
1360 $end = dol_getdate((int) $timestampEnd, false, $forcetimezone);
1361
1362 // The 31st of a month is brought back to the 30th, so that every month counts for 30 days
1363 $daystart = min($start['mday'], 30);
1364 $dayend = min($end['mday'], 30);
1365
1366 $nbdays = ($dayend - $daystart) + 30 * ($end['mon'] - $start['mon']) + 360 * ($end['year'] - $start['year']);
1367 if ($lastday == 1) {
1368 $nbdays++;
1369 }
1370
1371 return max(0, $nbdays);
1372}
1373
1381function num_days_in_year($year)
1382{
1383 $year = (int) $year;
1384 $isleapyear = (($year % 4 == 0 && $year % 100 != 0) || $year % 400 == 0);
1385
1386 return $isleapyear ? 366 : 365;
1387}
1388
1405function num_open_day($timestampStart, $timestampEnd, $inhour = 0, $lastday = 0, $halfday = 0, $countryCodeOrId = '', $user_id = 0)
1406{
1407 global $langs, $mysoc, $hookmanager;
1408
1409 if (empty($countryCodeOrId) || $countryCodeOrId < 0) {
1410 $countryCodeOrId = $mysoc->country_code;
1411 }
1412
1413 dol_syslog('num_open_day timestampStart='.$timestampStart.' timestampEnd='.$timestampEnd.' bit='.$lastday.' countryCodeOrId='.$countryCodeOrId);
1414
1415 // Check parameters
1416 if (!is_int($timestampStart) && !is_float($timestampStart)) {
1417 return 'ErrorBadParameter_num_open_day';
1418 }
1419 if (!is_int($timestampEnd) && !is_float($timestampEnd)) {
1420 return 'ErrorBadParameter_num_open_day';
1421 }
1422
1423 $nbOpenDay = 0; // expressed in days; inhour conversion happens at the end
1424
1425 if ($timestampStart < $timestampEnd) {
1426 // --- 1. Calculate Gross Working Days ---
1427 // Gross working days = total days in range - non-working days (weekends & public holidays).
1428 $a = num_between_day($timestampStart, $timestampEnd, $lastday);
1429 $b = num_public_holiday($timestampStart, $timestampEnd, $countryCodeOrId, $lastday);
1430 $nbOpenDay = $a - $b;
1431
1432 // --- 2. Apply Contextual Half-Day Deductions ---
1433 $halfday = (int) $halfday; // Ensure $halfday is an integer for reliable comparisons.
1434
1435 // Check if start/end days are working days just ONCE to optimize performance
1436 // by avoiding redundant calls to the potentially slow num_public_holiday() function.
1437 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
1438 $isStartDayWorking = (num_public_holiday($timestampStart, $timestampStart, $countryCodeOrId, 1) == 0);
1439 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
1440 $isEndDayWorking = (num_public_holiday($timestampEnd, $timestampEnd, $countryCodeOrId, 1) == 0);
1441
1442 // Deduct 0.5 if the leave starts in the afternoon of a working day.
1443 if (($halfday == -1 || $halfday == 2) && $isStartDayWorking) {
1444 $nbOpenDay -= 0.5;
1445 }
1446
1447 // Deduct 0.5 if the leave ends in the morning of a different, working day.
1448 if (($halfday == 1 || $halfday == 2) && date('Y-m-d', $timestampStart) != date('Y-m-d', $timestampEnd) && $isEndDayWorking) {
1449 $nbOpenDay -= 0.5;
1450 }
1451 } elseif ($timestampStart == $timestampEnd) {
1452 $isSingleDayHoliday = false;
1453 if ($lastday) {
1454 $numholidays = num_public_holiday($timestampStart, $timestampEnd, $countryCodeOrId, $lastday);
1455 if ($numholidays == 1) {
1456 $isSingleDayHoliday = true;
1457 }
1458 }
1459 if (!$isSingleDayHoliday) {
1460 $nbOpenDay = $lastday - 0.5 * abs((int) $halfday);
1461 }
1462 } else {
1463 return $langs->trans("Error");
1464 }
1465
1466 // --- 3. Allow modules to adjust the result based on the user (e.g. per-employee
1467 // individual workdays, bridge days, fixed half-days). Only fires when caller
1468 // opts in by passing a non-zero $user_id, so existing call sites are unaffected.
1469 if ($user_id > 0 && is_object($hookmanager)) {
1470 $parameters = array(
1471 'timestampStart' => $timestampStart,
1472 'timestampEnd' => $timestampEnd,
1473 'inhour' => $inhour,
1474 'lastday' => $lastday,
1475 'halfday' => $halfday,
1476 'countryCodeOrId' => $countryCodeOrId,
1477 'user_id' => $user_id,
1478 'nbOpenDay' => $nbOpenDay,
1479 );
1480 $action = '';
1481 $reshook = $hookmanager->executeHooks('numOpenDay', $parameters, $hookmanager, $action);
1482 if ($reshook > 0 && isset($hookmanager->resArray['nbOpenDay'])) {
1483 $nbOpenDay = $hookmanager->resArray['nbOpenDay'];
1484 }
1485 }
1486
1487 if ($inhour == 1) {
1488 return (int) ($nbOpenDay * 24);
1489 }
1490 return $nbOpenDay;
1491}
1492
1493
1494
1503function monthArray($outputlangs, $short = 0)
1504{
1505 $montharray = array(
1506 1 => $outputlangs->trans("Month01"),
1507 2 => $outputlangs->trans("Month02"),
1508 3 => $outputlangs->trans("Month03"),
1509 4 => $outputlangs->trans("Month04"),
1510 5 => $outputlangs->trans("Month05"),
1511 6 => $outputlangs->trans("Month06"),
1512 7 => $outputlangs->trans("Month07"),
1513 8 => $outputlangs->trans("Month08"),
1514 9 => $outputlangs->trans("Month09"),
1515 10 => $outputlangs->trans("Month10"),
1516 11 => $outputlangs->trans("Month11"),
1517 12 => $outputlangs->trans("Month12")
1518 );
1519
1520 if (!empty($short)) {
1521 $montharray = array(
1522 1 => $outputlangs->trans("MonthShort01"),
1523 2 => $outputlangs->trans("MonthShort02"),
1524 3 => $outputlangs->trans("MonthShort03"),
1525 4 => $outputlangs->trans("MonthShort04"),
1526 5 => $outputlangs->trans("MonthShort05"),
1527 6 => $outputlangs->trans("MonthShort06"),
1528 7 => $outputlangs->trans("MonthShort07"),
1529 8 => $outputlangs->trans("MonthShort08"),
1530 9 => $outputlangs->trans("MonthShort09"),
1531 10 => $outputlangs->trans("MonthShort10"),
1532 11 => $outputlangs->trans("MonthShort11"),
1533 12 => $outputlangs->trans("MonthShort12")
1534 );
1535 }
1536
1537 return $montharray;
1538}
1539
1547function getWeekNumbersOfMonth($month, $year)
1548{
1549 $nb_days = cal_days_in_month(CAL_GREGORIAN, $month, $year);
1550 $TWeek = array();
1551 for ($day = 1; $day <= $nb_days; $day++) {
1552 $week_number = getWeekNumber($day, $month, $year);
1553 $TWeek[$week_number] = $week_number;
1554 }
1555 return $TWeek;
1556}
1557
1565function getFirstDayOfEachWeek($TWeek, $year)
1566{
1567 $TFirstDayOfWeek = array();
1568 // 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.
1569 // If $TWeek starts with week 52 or 53 (a January), these first weeks belong to previous year.
1570 // If $TWeek ends with week 01 (a December), this last week belongs to next year.
1571 $startwithweeksofpreviousyear = ((int) reset($TWeek) >= 52 && in_array('01', $TWeek));
1572 foreach ($TWeek as $weekNb) {
1573 $yeartouse = $year;
1574 if ($startwithweeksofpreviousyear) {
1575 if ((int) $weekNb >= 52) {
1576 $yeartouse = $year - 1;
1577 }
1578 } elseif ($weekNb == '01' && in_array('52', $TWeek)) {
1579 $yeartouse = $year + 1;
1580 }
1581 $TFirstDayOfWeek[$weekNb] = date('d', strtotime($yeartouse.'W'.$weekNb));
1582 }
1583 return $TFirstDayOfWeek;
1584}
1585
1593function getLastDayOfEachWeek($TWeek, $year)
1594{
1595 $TLastDayOfWeek = array();
1596 // Same rule as in getFirstDayOfEachWeek() to find the year each week belongs to
1597 $startwithweeksofpreviousyear = ((int) reset($TWeek) >= 52 && in_array('01', $TWeek));
1598 foreach ($TWeek as $weekNb) {
1599 $yeartouse = $year;
1600 if ($startwithweeksofpreviousyear) {
1601 if ((int) $weekNb >= 52) {
1602 $yeartouse = $year - 1;
1603 }
1604 } elseif ($weekNb == '01' && in_array('52', $TWeek)) {
1605 $yeartouse = $year + 1;
1606 }
1607 $TLastDayOfWeek[$weekNb] = date('d', strtotime($yeartouse.'W'.$weekNb.'+6 days'));
1608 }
1609 return $TLastDayOfWeek;
1610}
1611
1620function getWeekNumber($day, $month, $year)
1621{
1622 $date = new DateTime($year.'-'.$month.'-'.$day);
1623 $week = $date->format("W");
1624 return $week;
1625}
global $mysoc
dol_get_prev_month($month, $year)
Return previous month.
Definition date.lib.php:535
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:676
num_days_in_year($year)
Function to return the real number of days of a year (365, or 366 for a leap year).
dol_get_next_day($day, $month, $year)
Return next day.
Definition date.lib.php:520
dol_get_next_week($day, $week, $month, $year)
Return next week.
Definition date.lib.php:594
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:391
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:662
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:691
getGMTEasterDatetime($year)
Return the easter day in GMT time.
Definition date.lib.php:759
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:347
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:504
dol_get_first_day($year, $month=1, $gm=false)
Return GMT time for first day of a month or year.
Definition date.lib.php:616
getFirstDayOfEachWeek($TWeek, $year)
Return array of first day of weeks.
dol_get_next_month($month, $year)
Return next month.
Definition date.lib.php:554
getWeekNumber($day, $month, $year)
Return week number.
num_between_day_30_360($timestampStart, $timestampEnd, $lastday=0, $forcetimezone='')
Function to return number of days between two dates using the 30/360 day count convention: every mont...
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:783
convertTime2Seconds($iHours=0, $iMinutes=0, $iSeconds=0)
Convert hours and minutes into seconds.
Definition date.lib.php:224
dol_time_plus_duree($time, $duration_value, $duration_unit, $ruleforendofmonth=0)
Add a delay to a date.
Definition date.lib.php:126
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:253
dol_get_prev_week($day, $week, $month, $year)
Return previous week.
Definition date.lib.php:575
dol_get_last_day($year, $month=12, $gm=false)
Return GMT time for last day of a month or year.
Definition date.lib.php:635
monthArray($outputlangs, $short=0)
Return array of translated months or selected month.
dol_stringtotime($string, $gm=1, $processnotimeasnoon=0)
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:442
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
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).
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