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
127function dol_time_plus_duree($time, $duration_value, $duration_unit, $ruleforendofmonth = 0, $tz = '')
128{
129 if (empty($duration_value)) {
130 return $time;
131 }
132 if (!in_array($duration_unit, array('s', 'i', 'mn', 'min', 'h', 'd', 'w', 'm', 'y'))) {
133 $errormsg = 'dol_time_plus_duree call to function with undefined or bad duration_unit : ' . $duration_unit;
134 dol_syslog($errormsg, LOG_ERR);
135 return $time;
136 }
137 if ($duration_unit == 's') {
138 return $time + (int) ($duration_value);
139 }
140 if ($duration_unit == 'i' || $duration_unit == 'mn' || $duration_unit == 'min') {
141 return $time + (int) (60 * $duration_value);
142 }
143 if ($duration_unit == 'h') {
144 return $time + (int) (3600 * $duration_value);
145 }
146 if ($duration_unit == 'w') {
147 return $time + (int) (3600 * 24 * 7 * $duration_value);
148 }
149
150 $deltastring = 'P';
151
152 $sub = false;
153
154 if ($duration_value > 0) {
155 $deltastring .= abs($duration_value);
156 $sub = false;
157 }
158 if ($duration_value < 0) {
159 $deltastring .= abs($duration_value);
160 $sub = true;
161 }
162 if ($duration_unit == 'd') {
163 $deltastring .= "D";
164 }
165 if ($duration_unit == 'm') {
166 $deltastring .= "M";
167 }
168 if ($duration_unit == 'y') {
169 $deltastring .= "Y";
170 }
171
172 $date = new DateTime();
173 if (empty($tz) || $tz == 'gmt') {
174 $date->setTimezone(new DateTimeZone('UTC')); // The default, try to always use this case
175 } else {
176 $date->setTimezone(new DateTimeZone($tz == 'tzserver' ? date_default_timezone_get() : $tz));
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
452function dol_stringtotime($string, $gm = 1, $processnotimeasnoon = 0)
453{
454 $reg = array();
455 // 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.
456 if (preg_match('/^([0-9]+)\/([0-9]+)\/([0-9]+)\s?([0-9]+)?:?([0-9]+)?:?([0-9]+)?/i', $string, $reg)) {
457 dol_syslog("dol_stringtotime call to function with deprecated parameter format", LOG_WARNING);
458 // Date is in format 'DD/MM/YY' or 'DD/MM/YY HH:MM:SS'
459 // Date is in format 'DD/MM/YYYY' or 'DD/MM/YYYY HH:MM:SS'
460 $sday = (int) $reg[1];
461 $smonth = (int) $reg[2];
462 $syear = (int) $reg[3];
463 $shour = (int) $reg[4];
464 $smin = (int) $reg[5];
465 $ssec = (int) $reg[6];
466 if ($syear < 50) {
467 $syear += 1900;
468 }
469 if ($syear >= 50 && $syear < 100) {
470 $syear += 2000;
471 }
472 $string = sprintf("%04d%02d%02d%02d%02d%02d", $syear, $smonth, $sday, $shour, $smin, $ssec);
473 } 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)
474 || 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
475 || 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
476 ) {
477 $syear = (int) $reg[1];
478 $smonth = (int) $reg[2];
479 $sday = (int) $reg[3];
480 $shour = (int) $reg[4];
481 $smin = (int) $reg[5];
482 $ssec = (int) $reg[6];
483 $string = sprintf("%04d%02d%02d%02d%02d%02d", $syear, $smonth, $sday, $shour, $smin, $ssec);
484 }
485
486 $string = preg_replace('/([^0-9])/i', '', $string);
487 // If not time was provided, we add it (if it was, it won't be seen)
488 if ($processnotimeasnoon) {
489 $tmp = $string.'120000';
490 } else {
491 $tmp = $string.'000000';
492 }
493 // Clean $gm
494 if ($gm === 1) {
495 $gm = 'gmt';
496 } elseif (empty($gm) || $gm === 'tzserver') {
497 $gm = 'tzserver';
498 }
499
500 $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);
501
502 return $date;
503}
504
505
514function dol_get_prev_day($day, $month, $year)
515{
516 $time = dol_mktime(12, 0, 0, $month, $day, $year, 1, 0);
517 $time -= 24 * 60 * 60;
518 $tmparray = dol_getdate($time, true);
519 return array('year' => $tmparray['year'], 'month' => $tmparray['mon'], 'day' => $tmparray['mday']);
520}
521
530function dol_get_next_day($day, $month, $year)
531{
532 $time = dol_mktime(12, 0, 0, $month, $day, $year, 1, 0);
533 $time += 24 * 60 * 60;
534 $tmparray = dol_getdate($time, true);
535 return array('year' => $tmparray['year'], 'month' => $tmparray['mon'], 'day' => $tmparray['mday']);
536}
537
545function dol_get_prev_month($month, $year)
546{
547 if ($month == 1) {
548 $prev_month = 12;
549 $prev_year = $year - 1;
550 } else {
551 $prev_month = $month - 1;
552 $prev_year = $year;
553 }
554 return array('year' => $prev_year, 'month' => $prev_month);
555}
556
564function dol_get_next_month($month, $year)
565{
566 if ($month == 12) {
567 $next_month = 1;
568 $next_year = $year + 1;
569 } else {
570 $next_month = $month + 1;
571 $next_year = $year;
572 }
573 return array('year' => $next_year, 'month' => $next_month);
574}
575
585function dol_get_prev_week($day, $week, $month, $year)
586{
587 $tmparray = dol_get_first_day_week($day, $month, $year);
588
589 $time = dol_mktime(12, 0, 0, $tmparray['first_month'], $tmparray['first_day'], $tmparray['first_year'], 1, 0);
590 $time -= 24 * 60 * 60 * 7;
591 $tmparray = dol_getdate($time, true);
592 return array('year' => $tmparray['year'], 'month' => $tmparray['mon'], 'day' => $tmparray['mday']);
593}
594
604function dol_get_next_week($day, $week, $month, $year)
605{
606 $tmparray = dol_get_first_day_week($day, $month, $year);
607
608 $time = dol_mktime(12, 0, 0, $tmparray['first_month'], $tmparray['first_day'], $tmparray['first_year'], 1, 0);
609 $time += 24 * 60 * 60 * 7;
610 $tmparray = dol_getdate($time, true);
611
612 return array('year' => $tmparray['year'], 'month' => $tmparray['mon'], 'day' => $tmparray['mday']);
613}
614
626function dol_get_first_day($year, $month = 1, $gm = false)
627{
628 if ($year > 9999) {
629 return '';
630 }
631 return dol_mktime(0, 0, 0, $month, 1, $year, $gm);
632}
633
634
645function dol_get_last_day($year, $month = 12, $gm = false)
646{
647 if ($year > 9999) {
648 return '';
649 }
650 if ($month == 12) {
651 $month = 1;
652 $year += 1;
653 } else {
654 $month += 1;
655 }
656
657 // Move to the start of the next month, then subtract one day
658 $datelim = dol_mktime(23, 59, 59, $month, 1, $year, $gm);
659 $datelim -= (3600 * 24);
660
661 return $datelim;
662}
663
672function dol_get_last_hour($date, $gm = 'tzserver')
673{
674 $tmparray = dol_getdate($date, false, ($gm == 'gmt' ? 'gmt' : ''));
675 return dol_mktime(23, 59, 59, $tmparray['mon'], $tmparray['mday'], $tmparray['year'], $gm);
676}
677
686function dol_get_first_hour($date, $gm = 'tzserver')
687{
688 $tmparray = dol_getdate($date, false, ($gm == 'gmt' ? 'gmt' : ''));
689 return dol_mktime(0, 0, 0, $tmparray['mon'], $tmparray['mday'], $tmparray['year'], $gm);
690}
691
701function dol_get_first_day_week($day, $month, $year, $gm = false)
702{
703 //$day=2; $month=2; $year=2015;
704 $date = dol_mktime(0, 0, 0, $month, $day, $year, $gm);
705
706 //Checking conf of start week
707 $start_week = getDolGlobalInt('MAIN_START_WEEK', 1);
708
709 $tmparray = dol_getdate($date, true); // detail of current day
710
711 //Calculate days = offset from current day
712 $days = $start_week - $tmparray['wday'];
713 if ($days >= 1) {
714 $days = 7 - $days;
715 }
716 $days = abs($days);
717 $seconds = $days * 24 * 60 * 60;
718 //print 'start_week='.$start_week.' tmparray[wday]='.$tmparray['wday'].' day offset='.$days.' seconds offset='.$seconds.'<br>';
719
720 //Get first day of week
721 $tmpdaytms = (int) date((string) $tmparray['0']) - $seconds; // $tmparray[0] is day of parameters
722 $tmpday = idate("d", $tmpdaytms);
723
724 //Check first day of week is in same month than current day or not
725 if ($tmpday > $day) {
726 $prev_month = $month - 1;
727 $prev_year = $year;
728
729 if ($prev_month == 0) {
730 $prev_month = 12;
731 $prev_year = $year - 1;
732 }
733 } else {
734 $prev_month = $month;
735 $prev_year = $year;
736 }
737 $tmpmonth = $prev_month;
738 $tmpyear = $prev_year;
739
740 //Get first day of next week
741 $tmptime = dol_mktime(12, 0, 0, $month, $tmpday, $year, 1, 0);
742 $tmptime -= 24 * 60 * 60 * 7;
743 $tmparray = dol_getdate($tmptime, true);
744 $prev_day = $tmparray['mday'];
745
746 //Check prev day of week is in same month than first day or not
747 if ($prev_day > $tmpday) {
748 $prev_month = $month - 1;
749 $prev_year = $year;
750
751 if ($prev_month == 0) {
752 $prev_month = 12;
753 $prev_year = $year - 1;
754 }
755 }
756
757 $week = date("W", dol_mktime(0, 0, 0, $tmpmonth, $tmpday, $tmpyear, $gm));
758
759 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);
760}
761
769function getGMTEasterDatetime($year)
770{
771 $base = new DateTime("$year-03-21", new DateTimeZone("UTC"));
772 $days = easter_days($year); // Return number of days between 21 march and easter day.
773 $tmp = $base->add(new DateInterval("P{$days}D"));
774 return $tmp->getTimestamp();
775}
776
793function num_public_holiday($timestampStart, $timestampEnd, $countryCodeOrId = '', $lastday = 0, $includesaturday = -1, $includesunday = -1, $includefriday = -1, $includemonday = -1)
794{
795 global $conf, $db, $mysoc;
796
797 $nbFerie = 0;
798
799 // Check to ensure we use correct parameters
800 if (($timestampEnd - $timestampStart) % 86400 != 0) {
801 return 'Error Dates must use same hours and must be GMT dates';
802 }
803
804 if (empty($countryCodeOrId)) {
805 $countryCodeOrId = $mysoc->country_code;
806 }
807 if ($includemonday < 0) {
808 $includemonday = getDolGlobalInt('MAIN_NON_WORKING_DAYS_INCLUDE_MONDAY', 0);
809 }
810 if ($includefriday < 0) {
811 $includefriday = getDolGlobalInt('MAIN_NON_WORKING_DAYS_INCLUDE_FRIDAY', 0);
812 }
813 if ($includesaturday < 0) {
814 $includesaturday = getDolGlobalInt('MAIN_NON_WORKING_DAYS_INCLUDE_SATURDAY', 1);
815 }
816 if ($includesunday < 0) {
817 $includesunday = getDolGlobalInt('MAIN_NON_WORKING_DAYS_INCLUDE_SUNDAY', 1);
818 }
819
820 if (is_numeric($countryCodeOrId)) {
821 $country_id = $countryCodeOrId;
822 } else {
823 $country_id = dol_getIdFromCode($db, $countryCodeOrId, 'c_country', 'code', 'rowid');
824 }
825
826 if (empty($conf->cache['arrayOfActivePublicHolidays_'.$country_id])) {
827 // Loop on public holiday defined into hrm_public_holiday for the day, month and year analyzed
828 $tmpArrayOfPublicHolidays = array();
829 $sql = "SELECT id, code, entity, fk_country, dayrule, year, month, day, active";
830 $sql .= " FROM ".MAIN_DB_PREFIX."c_hrm_public_holiday";
831 $sql .= " WHERE active = 1 and fk_country IN (0".($country_id > 0 ? ", ".((int) $country_id) : 0).")";
832 $sql .= " AND entity IN (0," .getEntity('holiday') .")";
833
834 $resql = $db->query($sql);
835 if ($resql) {
836 $num_rows = $db->num_rows($resql);
837 $i = 0;
838 while ($i < $num_rows) {
839 $obj = $db->fetch_object($resql);
840 $tmpArrayOfPublicHolidays[$obj->id] = array('dayrule' => $obj->dayrule, 'year' => $obj->year, 'month' => $obj->month, 'day' => $obj->day);
841 $i++;
842 }
843 } else {
844 dol_syslog($db->lasterror(), LOG_ERR);
845 return 'Error sql '.$db->lasterror();
846 }
847
848 //var_dump($tmpArrayOfPublicHolidays);
849 $conf->cache['arrayOfActivePublicHolidays_'.$country_id] = $tmpArrayOfPublicHolidays;
850 }
851
852 $arrayOfPublicHolidays = $conf->cache['arrayOfActivePublicHolidays_'.$country_id];
853
854 $i = 0;
855 while ((($lastday == 0 && $timestampStart < $timestampEnd) || ($lastday && $timestampStart <= $timestampEnd))
856 && ($i < 50000)) { // Loop end when equals (Test on i is a security loop to avoid infinite loop)
857 $ferie = false;
858 $specialdayrule = array();
859
860 $jour = (int) gmdate("d", $timestampStart);
861 $mois = (int) gmdate("m", $timestampStart);
862 $annee = (int) gmdate("Y", $timestampStart);
863 $jour_semaine = (int) gmdate("w", $timestampStart); // sunday = 0, monday = 1, ...
864
865 //print "jour=".$jour." month=".$mois." year=".$annee." includesaturday=".$includesaturday." includesunday=".$includesunday."\n";
866 foreach ($arrayOfPublicHolidays as $entrypublicholiday) {
867 if (!empty($entrypublicholiday['dayrule']) && $entrypublicholiday['dayrule'] != 'date') { // For example 'easter', '...'
868 $specialdayrule[$entrypublicholiday['dayrule']] = $entrypublicholiday['dayrule'];
869 } else {
870 $match = 1;
871 if (!empty($entrypublicholiday['year']) && $entrypublicholiday['year'] != $annee) {
872 $match = 0;
873 }
874 if ($entrypublicholiday['month'] != $mois) {
875 $match = 0;
876 }
877 if ($entrypublicholiday['day'] != $jour) {
878 $match = 0;
879 }
880
881 if ($match) {
882 $ferie = true;
883 }
884 }
885
886 $i++;
887 }
888 //var_dump($specialdayrule)."\n";
889 //print "ferie=".$ferie."\n";
890
891 if (!$ferie) {
892 // Special dayrules
893 if (in_array('easter', $specialdayrule)) {
894 // Calculation for easter date
895 $date_paques = getGMTEasterDatetime($annee);
896 $jour_paques = gmdate("d", $date_paques);
897 $mois_paques = gmdate("m", $date_paques);
898 if ($jour_paques == $jour && $mois_paques == $mois) {
899 $ferie = true;
900 }
901 // Easter (sunday)
902 }
903
904 if (in_array('eastermonday', $specialdayrule)) {
905 // Calculation for the monday of easter date
906 $date_paques = getGMTEasterDatetime($annee);
907 //print 'PPP'.$date_paques.' '.dol_print_date($date_paques, 'dayhour', 'gmt')." ";
908 $date_lundi_paques = $date_paques + (3600 * 24);
909 $jour_lundi_paques = gmdate("d", $date_lundi_paques);
910 $mois_lundi_paques = gmdate("m", $date_lundi_paques);
911 if ($jour_lundi_paques == $jour && $mois_lundi_paques == $mois) {
912 $ferie = true;
913 }
914 // Easter (monday)
915 //print 'annee='.$annee.' $jour='.$jour.' $mois='.$mois.' $jour_lundi_paques='.$jour_lundi_paques.' $mois_lundi_paques='.$mois_lundi_paques."\n";
916 }
917
918 //Good Friday
919 if (in_array('goodfriday', $specialdayrule)) {
920 // Pulls the date of Easter
921 $easter = getGMTEasterDatetime($annee);
922
923 // Calculates the date of Good Friday based on Easter
924 $date_good_friday = $easter - (2 * 3600 * 24);
925 $dom_good_friday = gmdate("d", $date_good_friday);
926 $month_good_friday = gmdate("m", $date_good_friday);
927
928 if ($dom_good_friday == $jour && $month_good_friday == $mois) {
929 $ferie = true;
930 }
931 }
932
933 if (in_array('ascension', $specialdayrule)) {
934 // Calculation of Ascension day (39 days after easter day)
935 $date_paques = getGMTEasterDatetime($annee);
936 $date_ascension = $date_paques + (3600 * 24 * 39);
937 $jour_ascension = gmdate("d", $date_ascension);
938 $mois_ascension = gmdate("m", $date_ascension);
939 if ($jour_ascension == $jour && $mois_ascension == $mois) {
940 $ferie = true;
941 }
942 // Ascension (thursday)
943 }
944
945 if (in_array('pentecost', $specialdayrule)) {
946 // Calculation of "Pentecote" (49 days after easter day)
947 $date_paques = getGMTEasterDatetime($annee);
948 $date_pentecote = $date_paques + (3600 * 24 * 49);
949 $jour_pentecote = gmdate("d", $date_pentecote);
950 $mois_pentecote = gmdate("m", $date_pentecote);
951 if ($jour_pentecote == $jour && $mois_pentecote == $mois) {
952 $ferie = true;
953 }
954 // "Pentecote" (sunday)
955 }
956 if (in_array('pentecotemonday', $specialdayrule)) {
957 // Calculation of "Pentecote" (49 days after easter day)
958 $date_paques = getGMTEasterDatetime($annee);
959 $date_pentecote = $date_paques + (3600 * 24 * 50);
960 $jour_pentecote = gmdate("d", $date_pentecote);
961 $mois_pentecote = gmdate("m", $date_pentecote);
962 if ($jour_pentecote == $jour && $mois_pentecote == $mois) {
963 $ferie = true;
964 }
965 // "Pentecote" (monday)
966 }
967
968 if (in_array('viernessanto', $specialdayrule)) {
969 // Viernes Santo
970 $date_paques = getGMTEasterDatetime($annee);
971 $date_viernes = $date_paques - (3600 * 24 * 2);
972 $jour_viernes = gmdate("d", $date_viernes);
973 $mois_viernes = gmdate("m", $date_viernes);
974 if ($jour_viernes == $jour && $mois_viernes == $mois) {
975 $ferie = true;
976 }
977 //Viernes Santo
978 }
979
980 if (in_array('fronleichnam', $specialdayrule)) {
981 // Fronleichnam (60 days after easter sunday)
982 $date_paques = getGMTEasterDatetime($annee);
983 $date_fronleichnam = $date_paques + (3600 * 24 * 60);
984 $jour_fronleichnam = gmdate("d", $date_fronleichnam);
985 $mois_fronleichnam = gmdate("m", $date_fronleichnam);
986 if ($jour_fronleichnam == $jour && $mois_fronleichnam == $mois) {
987 $ferie = true;
988 }
989 // Fronleichnam
990 }
991
992 if (in_array('genevafast', $specialdayrule)) {
993 // Geneva fast in Switzerland (Thursday after the first sunday in September)
994 $date_1sunsept = strtotime('next thursday', strtotime('next sunday', mktime(0, 0, 0, 9, 1, $annee)));
995 $jour_1sunsept = date("d", $date_1sunsept);
996 $mois_1sunsept = date("m", $date_1sunsept);
997 if ($jour_1sunsept == $jour && $mois_1sunsept == $mois) {
998 $ferie = true;
999 }
1000 // Geneva fast in Switzerland
1001 }
1002 }
1003 //print "ferie afterspe=".$ferie."\n";
1004
1005 // If we have to include Friday, Saturday and Sunday
1006 if (!$ferie) {
1007 if ($includefriday || $includesaturday || $includesunday || $includemonday) {
1008 //Monday (1), Friday (5), Saturday (6) and Sunday (0)
1009 if ($includefriday && $jour_semaine == 5) {
1010 $ferie = true;
1011 }
1012 if ($includesaturday && $jour_semaine == 6) {
1013 $ferie = true;
1014 }
1015 if ($includesunday && $jour_semaine == 0) {
1016 $ferie = true;
1017 }
1018 if ($includemonday && $jour_semaine == 1) {
1019 $ferie = true;
1020 }
1021 }
1022 }
1023 //print "ferie afterincludexxxday=".$ferie."\n";
1024
1025 // We increase the counter of non working day
1026 if ($ferie) {
1027 $nbFerie++;
1028 }
1029
1030 // Increase number of days (on go up into loop)
1031 // Advance by exactly one GMT day. We can use += instead of dol_time_plus_duree() here because
1032 // inputs of this function are GMT dates (checked above), so a day
1033 // is always exactly 86400 seconds.
1034 //var_dump("before ".$jour.' '.$mois.' '.$annee.' '.$timestampStart);
1035 $timestampStart += 86400;
1036 //var_dump("after ".$jour.' '.$mois.' '.$annee.' '.$timestampStart);
1037
1038 $i++;
1039 }
1040
1041 //print "nbFerie=".$nbFerie."\n";
1042 return $nbFerie;
1043}
1044
1061function listPublicHoliday($timestampStart, $timestampEnd, $countryCodeOrId = '', $lastday = 0, $excludesaturday = -1, $excludesunday = -1, $excludefriday = -1, $excludemonday = -1)
1062{
1063 global $conf, $db, $mysoc;
1064
1065 // Check to ensure we use correct parameters
1066 if (($timestampEnd - $timestampStart) % 86400 != 0) {
1067 return 'Error Dates must use same hours and must be GMT dates';
1068 }
1069
1070 if (empty($countryCodeOrId)) {
1071 $countryCodeOrId = $mysoc->country_code;
1072 }
1073 if ($excludemonday < 0) {
1074 $excludemonday = getDolGlobalInt('MAIN_NON_WORKING_DAYS_INCLUDE_MONDAY', 0);
1075 }
1076 if ($excludefriday < 0) {
1077 $excludefriday = getDolGlobalInt('MAIN_NON_WORKING_DAYS_INCLUDE_FRIDAY', 0);
1078 }
1079 if ($excludesaturday < 0) {
1080 $excludesaturday = getDolGlobalInt('MAIN_NON_WORKING_DAYS_INCLUDE_SATURDAY', 1);
1081 }
1082 if ($excludesunday < 0) {
1083 $excludesunday = getDolGlobalInt('MAIN_NON_WORKING_DAYS_INCLUDE_SUNDAY', 1);
1084 }
1085
1086 if (is_numeric($countryCodeOrId)) {
1087 $country_id = $countryCodeOrId;
1088 } else {
1089 $country_id = dol_getIdFromCode($db, $countryCodeOrId, 'c_country', 'code', 'rowid');
1090 }
1091
1092 if (empty($conf->cache['arrayOfActivePublicHolidays_' . $country_id])) {
1093 // Loop on public holiday defined into hrm_public_holiday for the day, month and year analyzed
1094 $tmpArrayOfPublicHolidays = array();
1095 $sql = "SELECT id, code, entity, fk_country, dayrule, year, month, day, active";
1096 $sql .= " FROM " . MAIN_DB_PREFIX . "c_hrm_public_holiday";
1097 $sql .= " WHERE active = 1 and fk_country IN (0" . ($country_id > 0 ? ", " . ((int) $country_id) : 0) . ")";
1098 $sql .= " AND entity IN (0," . getEntity('holiday') . ")";
1099
1100 $resql = $db->query($sql);
1101 if ($resql) {
1102 $num_rows = $db->num_rows($resql);
1103 $i = 0;
1104 while ($i < $num_rows) {
1105 $obj = $db->fetch_object($resql);
1106 $tmpArrayOfPublicHolidays[$obj->id] = array('dayrule' => $obj->dayrule, 'year' => $obj->year, 'month' => $obj->month, 'day' => $obj->day);
1107 $i++;
1108 }
1109 } else {
1110 dol_syslog($db->lasterror(), LOG_ERR);
1111 return 'Error sql ' . $db->lasterror();
1112 }
1113
1114 //var_dump($tmpArrayOfPublicHolidays);
1115 $conf->cache['arrayOfActivePublicHolidays_' . $country_id] = $tmpArrayOfPublicHolidays;
1116 }
1117
1118 $arrayOfPublicHolidays = $conf->cache['arrayOfActivePublicHolidays_' . $country_id];
1119 $listFeries = [];
1120 $i = 0;
1121 while ((($lastday == 0 && $timestampStart < $timestampEnd) || ($lastday && $timestampStart <= $timestampEnd))
1122 && ($i < 50000)) { // Loop end when equals (Test on i is a security loop to avoid infinite loop)
1123 $nonWorkingDay = false;
1124 $ferie = false;
1125 $specialdayrule = array();
1126
1127 $jour = (int) gmdate("d", $timestampStart);
1128 $mois = (int) gmdate("m", $timestampStart);
1129 $annee = (int) gmdate("Y", $timestampStart);
1130
1131 // If we have to exclude Friday, Saturday and Sunday
1132 if ($excludefriday || $excludesaturday || $excludesunday) {
1133 $jour_julien = unixtojd($timestampStart);
1134 $jour_semaine = jddayofweek($jour_julien, 0);
1135 if ($excludefriday) { //Friday (5), Saturday (6) and Sunday (0)
1136 if ($jour_semaine == 5) {
1137 $nonWorkingDay = true;
1138 }
1139 }
1140 if ($excludesaturday) { //Friday (5), Saturday (6) and Sunday (0)
1141 if ($jour_semaine == 6) {
1142 $nonWorkingDay = true;
1143 }
1144 }
1145 if ($excludesunday) { //Friday (5), Saturday (6) and Sunday (0)
1146 if ($jour_semaine == 0) {
1147 $nonWorkingDay = true;
1148 }
1149 }
1150 }
1151 //print "ferie=".$nonWorkingDay."\n";
1152
1153 if (!$nonWorkingDay) {
1154 //print "jour=".$jour." month=".$mois." year=".$annee." includesaturday=".$excludesaturday." includesunday=".$excludesunday."\n";
1155 foreach ($arrayOfPublicHolidays as $entrypublicholiday) {
1156 if (!empty($entrypublicholiday['dayrule']) && $entrypublicholiday['dayrule'] != 'date') { // For example 'easter', '...'
1157 $specialdayrule[$entrypublicholiday['dayrule']] = $entrypublicholiday['dayrule'];
1158 } else {
1159 $match = 1;
1160 if (!empty($entrypublicholiday['year']) && $entrypublicholiday['year'] != $annee) {
1161 $match = 0;
1162 }
1163 if ($entrypublicholiday['month'] != $mois) {
1164 $match = 0;
1165 }
1166 if ($entrypublicholiday['day'] != $jour) {
1167 $match = 0;
1168 }
1169
1170 if ($match) {
1171 $ferie = true;
1172 $listFeries[] = $timestampStart;
1173 }
1174 }
1175
1176 $i++;
1177 }
1178 //var_dump($specialdayrule)."\n";
1179 //print "ferie=".$nonWorkingDay."\n";
1180 }
1181
1182 if (!$nonWorkingDay && !$ferie) {
1183 // Special dayrules
1184 if (in_array('easter', $specialdayrule)) {
1185 // Calculation for easter date
1186 $date_paques = getGMTEasterDatetime($annee);
1187 $jour_paques = gmdate("d", $date_paques);
1188 $mois_paques = gmdate("m", $date_paques);
1189 if ($jour_paques == $jour && $mois_paques == $mois) {
1190 $ferie = true;
1191 $listFeries[] = $timestampStart;
1192 }
1193 // Easter (sunday)
1194 }
1195
1196 if (in_array('eastermonday', $specialdayrule)) {
1197 // Calculation for the monday of easter date
1198 $date_paques = getGMTEasterDatetime($annee);
1199 //print 'PPP'.$date_paques.' '.dol_print_date($date_paques, 'dayhour', 'gmt')." ";
1200 $date_lundi_paques = $date_paques + (3600 * 24);
1201 $jour_lundi_paques = gmdate("d", $date_lundi_paques);
1202 $mois_lundi_paques = gmdate("m", $date_lundi_paques);
1203 if ($jour_lundi_paques == $jour && $mois_lundi_paques == $mois) {
1204 $ferie = true;
1205 $listFeries[] = $timestampStart;
1206 }
1207 // Easter (monday)
1208 //print 'annee='.$annee.' $jour='.$jour.' $mois='.$mois.' $jour_lundi_paques='.$jour_lundi_paques.' $mois_lundi_paques='.$mois_lundi_paques."\n";
1209 }
1210
1211 //Good Friday
1212 if (in_array('goodfriday', $specialdayrule)) {
1213 // Pulls the date of Easter
1214 $easter = getGMTEasterDatetime($annee);
1215
1216 // Calculates the date of Good Friday based on Easter
1217 $date_good_friday = $easter - (2 * 3600 * 24);
1218 $dom_good_friday = gmdate("d", $date_good_friday);
1219 $month_good_friday = gmdate("m", $date_good_friday);
1220
1221 if ($dom_good_friday == $jour && $month_good_friday == $mois) {
1222 $ferie = true;
1223 $listFeries[] = $timestampStart;
1224 }
1225 }
1226
1227 if (in_array('ascension', $specialdayrule)) {
1228 // Calculation of Ascension day (39 days after easter day)
1229 $date_paques = getGMTEasterDatetime($annee);
1230 $date_ascension = $date_paques + (3600 * 24 * 39);
1231 $jour_ascension = gmdate("d", $date_ascension);
1232 $mois_ascension = gmdate("m", $date_ascension);
1233 if ($jour_ascension == $jour && $mois_ascension == $mois) {
1234 $ferie = true;
1235 $listFeries[] = $timestampStart;
1236 }
1237 // Ascension (thursday)
1238 }
1239
1240 if (in_array('pentecost', $specialdayrule)) {
1241 // Calculation of "Pentecote" (49 days after easter day)
1242 $date_paques = getGMTEasterDatetime($annee);
1243 $date_pentecote = $date_paques + (3600 * 24 * 49);
1244 $jour_pentecote = gmdate("d", $date_pentecote);
1245 $mois_pentecote = gmdate("m", $date_pentecote);
1246 if ($jour_pentecote == $jour && $mois_pentecote == $mois) {
1247 $ferie = true;
1248 $listFeries[] = $timestampStart;
1249 }
1250 // "Pentecote" (sunday)
1251 }
1252
1253 if (in_array('pentecotemonday', $specialdayrule)) {
1254 // Calculation of "Pentecote" (49 days after easter day)
1255 $date_paques = getGMTEasterDatetime($annee);
1256 $date_pentecote = $date_paques + (3600 * 24 * 50);
1257 $jour_pentecote = gmdate("d", $date_pentecote);
1258 $mois_pentecote = gmdate("m", $date_pentecote);
1259 if ($jour_pentecote == $jour && $mois_pentecote == $mois) {
1260 $ferie = true;
1261 $listFeries[] = $timestampStart;
1262 }
1263 // "Pentecote" (monday)
1264 }
1265
1266 if (in_array('viernessanto', $specialdayrule)) {
1267 // Viernes Santo
1268 $date_paques = getGMTEasterDatetime($annee);
1269 $date_viernes = $date_paques - (3600 * 24 * 2);
1270 $jour_viernes = gmdate("d", $date_viernes);
1271 $mois_viernes = gmdate("m", $date_viernes);
1272 if ($jour_viernes == $jour && $mois_viernes == $mois) {
1273 $ferie = true;
1274 $listFeries[] = $timestampStart;
1275 }
1276 //Viernes Santo
1277 }
1278
1279 if (in_array('fronleichnam', $specialdayrule)) {
1280 // Fronleichnam (60 days after easter sunday)
1281 $date_paques = getGMTEasterDatetime($annee);
1282 $date_fronleichnam = $date_paques + (3600 * 24 * 60);
1283 $jour_fronleichnam = gmdate("d", $date_fronleichnam);
1284 $mois_fronleichnam = gmdate("m", $date_fronleichnam);
1285 if ($jour_fronleichnam == $jour && $mois_fronleichnam == $mois) {
1286 $ferie = true;
1287 $listFeries[] = $timestampStart;
1288 }
1289 // Fronleichnam
1290 }
1291
1292 if (in_array('genevafast', $specialdayrule)) {
1293 // Geneva fast in Switzerland (Thursday after the first sunday in September)
1294 $date_1sunsept = strtotime('next thursday', strtotime('next sunday', mktime(0, 0, 0, 9, 1, $annee)));
1295 $jour_1sunsept = date("d", $date_1sunsept);
1296 $mois_1sunsept = date("m", $date_1sunsept);
1297 if ($jour_1sunsept == $jour && $mois_1sunsept == $mois) {
1298 $ferie = true;
1299 $listFeries[] = $timestampStart;
1300 }
1301 // Geneva fast in Switzerland
1302 }
1303 }
1304 //print "ferie=".$nonWorkingDay."\n";
1305
1306 // Increase number of days (on go up into loop)
1307 $timestampStart = dol_time_plus_duree($timestampStart, 1, 'd');
1308 //var_dump($jour.' '.$mois.' '.$annee.' '.$timestampStart);
1309
1310 $i++;
1311 }
1312
1313 //print "nbFerie=".$nbFerie."\n";
1314 return $listFeries;
1315}
1316
1327function num_between_day($timestampStart, $timestampEnd, $lastday = 0)
1328{
1329 if ($timestampStart <= $timestampEnd) {
1330 if ($lastday == 1) {
1331 $bit = 0;
1332 } else {
1333 $bit = 1;
1334 }
1335 $nbjours = (int) floor(($timestampEnd - $timestampStart) / (60 * 60 * 24)) + 1 - $bit;
1336 } else {
1337 $nbjours = 0;
1338 }
1339 //print ($timestampEnd - $timestampStart) - $lastday;
1340 return $nbjours;
1341}
1342
1363function num_between_day_30_360($timestampStart, $timestampEnd, $lastday = 0, $forcetimezone = '')
1364{
1365 if ($timestampStart > $timestampEnd) {
1366 return 0;
1367 }
1368
1369 $start = dol_getdate((int) $timestampStart, false, $forcetimezone);
1370 $end = dol_getdate((int) $timestampEnd, false, $forcetimezone);
1371
1372 // The 31st of a month is brought back to the 30th, so that every month counts for 30 days
1373 $daystart = min($start['mday'], 30);
1374 $dayend = min($end['mday'], 30);
1375
1376 $nbdays = ($dayend - $daystart) + 30 * ($end['mon'] - $start['mon']) + 360 * ($end['year'] - $start['year']);
1377 if ($lastday == 1) {
1378 $nbdays++;
1379 }
1380
1381 return max(0, $nbdays);
1382}
1383
1391function num_days_in_year($year)
1392{
1393 $year = (int) $year;
1394 $isleapyear = (($year % 4 == 0 && $year % 100 != 0) || $year % 400 == 0);
1395
1396 return $isleapyear ? 366 : 365;
1397}
1398
1415function num_open_day($timestampStart, $timestampEnd, $inhour = 0, $lastday = 0, $halfday = 0, $countryCodeOrId = '', $user_id = 0)
1416{
1417 global $langs, $mysoc, $hookmanager;
1418
1419 if (empty($countryCodeOrId) || $countryCodeOrId < 0) {
1420 $countryCodeOrId = $mysoc->country_code;
1421 }
1422
1423 dol_syslog('num_open_day timestampStart='.$timestampStart.' timestampEnd='.$timestampEnd.' bit='.$lastday.' countryCodeOrId='.$countryCodeOrId);
1424
1425 // Check parameters
1426 if (!is_int($timestampStart) && !is_float($timestampStart)) {
1427 return 'ErrorBadParameter_num_open_day';
1428 }
1429 if (!is_int($timestampEnd) && !is_float($timestampEnd)) {
1430 return 'ErrorBadParameter_num_open_day';
1431 }
1432
1433 $nbOpenDay = 0; // expressed in days; inhour conversion happens at the end
1434
1435 if ($timestampStart < $timestampEnd) {
1436 // --- 1. Calculate Gross Working Days ---
1437 // Gross working days = total days in range - non-working days (weekends & public holidays).
1438 $a = num_between_day($timestampStart, $timestampEnd, $lastday);
1439 $b = num_public_holiday($timestampStart, $timestampEnd, $countryCodeOrId, $lastday);
1440 $nbOpenDay = $a - $b;
1441
1442 // --- 2. Apply Contextual Half-Day Deductions ---
1443 $halfday = (int) $halfday; // Ensure $halfday is an integer for reliable comparisons.
1444
1445 // Check if start/end days are working days just ONCE to optimize performance
1446 // by avoiding redundant calls to the potentially slow num_public_holiday() function.
1447 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
1448 $isStartDayWorking = (num_public_holiday($timestampStart, $timestampStart, $countryCodeOrId, 1) == 0);
1449 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
1450 $isEndDayWorking = (num_public_holiday($timestampEnd, $timestampEnd, $countryCodeOrId, 1) == 0);
1451
1452 // Deduct 0.5 if the leave starts in the afternoon of a working day.
1453 if (($halfday == -1 || $halfday == 2) && $isStartDayWorking) {
1454 $nbOpenDay -= 0.5;
1455 }
1456
1457 // Deduct 0.5 if the leave ends in the morning of a different, working day.
1458 if (($halfday == 1 || $halfday == 2) && date('Y-m-d', $timestampStart) != date('Y-m-d', $timestampEnd) && $isEndDayWorking) {
1459 $nbOpenDay -= 0.5;
1460 }
1461 } elseif ($timestampStart == $timestampEnd) {
1462 $isSingleDayHoliday = false;
1463 if ($lastday) {
1464 $numholidays = num_public_holiday($timestampStart, $timestampEnd, $countryCodeOrId, $lastday);
1465 if ($numholidays == 1) {
1466 $isSingleDayHoliday = true;
1467 }
1468 }
1469 if (!$isSingleDayHoliday) {
1470 $nbOpenDay = $lastday - 0.5 * abs((int) $halfday);
1471 }
1472 } else {
1473 return $langs->trans("Error");
1474 }
1475
1476 // --- 3. Allow modules to adjust the result based on the user (e.g. per-employee
1477 // individual workdays, bridge days, fixed half-days). Only fires when caller
1478 // opts in by passing a non-zero $user_id, so existing call sites are unaffected.
1479 if ($user_id > 0 && is_object($hookmanager)) {
1480 $parameters = array(
1481 'timestampStart' => $timestampStart,
1482 'timestampEnd' => $timestampEnd,
1483 'inhour' => $inhour,
1484 'lastday' => $lastday,
1485 'halfday' => $halfday,
1486 'countryCodeOrId' => $countryCodeOrId,
1487 'user_id' => $user_id,
1488 'nbOpenDay' => $nbOpenDay,
1489 );
1490 $action = '';
1491 $reshook = $hookmanager->executeHooks('numOpenDay', $parameters, $hookmanager, $action);
1492 if ($reshook > 0 && isset($hookmanager->resArray['nbOpenDay'])) {
1493 $nbOpenDay = $hookmanager->resArray['nbOpenDay'];
1494 }
1495 }
1496
1497 if ($inhour == 1) {
1498 return (int) ($nbOpenDay * 24);
1499 }
1500 return $nbOpenDay;
1501}
1502
1503
1504
1513function monthArray($outputlangs, $short = 0)
1514{
1515 $montharray = array(
1516 1 => $outputlangs->trans("Month01"),
1517 2 => $outputlangs->trans("Month02"),
1518 3 => $outputlangs->trans("Month03"),
1519 4 => $outputlangs->trans("Month04"),
1520 5 => $outputlangs->trans("Month05"),
1521 6 => $outputlangs->trans("Month06"),
1522 7 => $outputlangs->trans("Month07"),
1523 8 => $outputlangs->trans("Month08"),
1524 9 => $outputlangs->trans("Month09"),
1525 10 => $outputlangs->trans("Month10"),
1526 11 => $outputlangs->trans("Month11"),
1527 12 => $outputlangs->trans("Month12")
1528 );
1529
1530 if (!empty($short)) {
1531 $montharray = array(
1532 1 => $outputlangs->trans("MonthShort01"),
1533 2 => $outputlangs->trans("MonthShort02"),
1534 3 => $outputlangs->trans("MonthShort03"),
1535 4 => $outputlangs->trans("MonthShort04"),
1536 5 => $outputlangs->trans("MonthShort05"),
1537 6 => $outputlangs->trans("MonthShort06"),
1538 7 => $outputlangs->trans("MonthShort07"),
1539 8 => $outputlangs->trans("MonthShort08"),
1540 9 => $outputlangs->trans("MonthShort09"),
1541 10 => $outputlangs->trans("MonthShort10"),
1542 11 => $outputlangs->trans("MonthShort11"),
1543 12 => $outputlangs->trans("MonthShort12")
1544 );
1545 }
1546
1547 return $montharray;
1548}
1549
1557function getWeekNumbersOfMonth($month, $year)
1558{
1559 $nb_days = cal_days_in_month(CAL_GREGORIAN, $month, $year);
1560 $TWeek = array();
1561 for ($day = 1; $day <= $nb_days; $day++) {
1562 $week_number = getWeekNumber($day, $month, $year);
1563 $TWeek[$week_number] = $week_number;
1564 }
1565 return $TWeek;
1566}
1567
1575function getFirstDayOfEachWeek($TWeek, $year)
1576{
1577 $TFirstDayOfWeek = array();
1578 // 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.
1579 // If $TWeek starts with week 52 or 53 (a January), these first weeks belong to previous year.
1580 // If $TWeek ends with week 01 (a December), this last week belongs to next year.
1581 $startwithweeksofpreviousyear = ((int) reset($TWeek) >= 52 && in_array('01', $TWeek));
1582 foreach ($TWeek as $weekNb) {
1583 $yeartouse = $year;
1584 if ($startwithweeksofpreviousyear) {
1585 if ((int) $weekNb >= 52) {
1586 $yeartouse = $year - 1;
1587 }
1588 } elseif ($weekNb == '01' && in_array('52', $TWeek)) {
1589 $yeartouse = $year + 1;
1590 }
1591 $TFirstDayOfWeek[$weekNb] = date('d', strtotime($yeartouse.'W'.$weekNb));
1592 }
1593 return $TFirstDayOfWeek;
1594}
1595
1603function getLastDayOfEachWeek($TWeek, $year)
1604{
1605 $TLastDayOfWeek = array();
1606 // Same rule as in getFirstDayOfEachWeek() to find the year each week belongs to
1607 $startwithweeksofpreviousyear = ((int) reset($TWeek) >= 52 && in_array('01', $TWeek));
1608 foreach ($TWeek as $weekNb) {
1609 $yeartouse = $year;
1610 if ($startwithweeksofpreviousyear) {
1611 if ((int) $weekNb >= 52) {
1612 $yeartouse = $year - 1;
1613 }
1614 } elseif ($weekNb == '01' && in_array('52', $TWeek)) {
1615 $yeartouse = $year + 1;
1616 }
1617 $TLastDayOfWeek[$weekNb] = date('d', strtotime($yeartouse.'W'.$weekNb.'+6 days'));
1618 }
1619 return $TLastDayOfWeek;
1620}
1621
1630function getWeekNumber($day, $month, $year)
1631{
1632 $date = new DateTime($year.'-'.$month.'-'.$day);
1633 $week = $date->format("W");
1634 return $week;
1635}
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
global $mysoc
dol_get_prev_month($month, $year)
Return previous month.
Definition date.lib.php:545
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:686
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:530
dol_get_next_week($day, $week, $month, $year)
Return next week.
Definition date.lib.php:604
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:672
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:701
getGMTEasterDatetime($year)
Return the easter day in GMT time.
Definition date.lib.php:769
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:514
dol_get_first_day($year, $month=1, $gm=false)
Return GMT time for first day of a month or year.
Definition date.lib.php:626
getFirstDayOfEachWeek($TWeek, $year)
Return array of first day of weeks.
dol_get_next_month($month, $year)
Return next month.
Definition date.lib.php:564
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:793
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:585
dol_get_last_day($year, $month=12, $gm=false)
Return GMT time for last day of a month or year.
Definition date.lib.php:645
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:127
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:452
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_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