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 ($duration_unit == 's') {
132 return $time + (int) ($duration_value);
133 }
134 if ($duration_unit == 'i' || $duration_unit == 'mn' || $duration_unit == 'min') {
135 return $time + (int) (60 * $duration_value);
136 }
137 if ($duration_unit == 'h') {
138 return $time + (int) (3600 * $duration_value);
139 }
140 if ($duration_unit == 'w') {
141 return $time + (int) (3600 * 24 * 7 * $duration_value);
142 }
143
144 $deltastring = 'P';
145
146 $sub = false;
147
148 if ($duration_value > 0) {
149 $deltastring .= abs($duration_value);
150 $sub = false;
151 }
152 if ($duration_value < 0) {
153 $deltastring .= abs($duration_value);
154 $sub = true;
155 }
156 if ($duration_unit == 'd') {
157 $deltastring .= "D";
158 }
159 if ($duration_unit == 'm') {
160 $deltastring .= "M";
161 }
162 if ($duration_unit == 'y') {
163 $deltastring .= "Y";
164 }
165
166 $date = new DateTime();
167 if (!function_exists('getDolGlobalString') || !getDolGlobalString('MAIN_DATE_IN_MEMORY_ARE_NOT_GMT')) { // Add function_exists to allow usage of this function with minimal context
168 $date->setTimezone(new DateTimeZone('UTC'));
169 }
170
171
172 $date->setTimestamp((int) $time);
173 $interval = new DateInterval($deltastring);
174
175 if ($sub) {
176 $date->sub($interval);
177 } else {
178 $date->add($interval);
179 }
180
181 // 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)
182 if ($ruleforendofmonth == 1 && $duration_unit == 'm') {
183 $timeyear = (int) dol_print_date($time, '%Y');
184 $timemonth = (int) dol_print_date($time, '%m');
185 $timetotalmonths = (($timeyear * 12) + $timemonth);
186
187 $monthsexpected = ($timetotalmonths + $duration_value);
188
189 $newtime = $date->getTimestamp();
190
191 $newtimeyear = (int) dol_print_date($newtime, '%Y');
192 $newtimemonth = (int) dol_print_date($newtime, '%m');
193 $newtimetotalmonths = (($newtimeyear * 12) + $newtimemonth);
194
195 if ($monthsexpected < $newtimetotalmonths || $monthsexpected > $newtimetotalmonths) { // If months differs
196 $newtimehours = (int) dol_print_date($newtime, '%H');
197 $newtimemins = (int) dol_print_date($newtime, '%M');
198 $newtimesecs = (int) dol_print_date($newtime, '%S');
199
200 $datelim = dol_mktime($newtimehours, $newtimemins, $newtimesecs, $newtimemonth, 1, $newtimeyear); // Take first day
201 $datelim -= (3600 * 24); // Remove 1 day to get the last day of month
202
203 $date->setTimestamp($datelim); // Set new date
204 }
205 }
206 return $date->getTimestamp();
207}
208
209
219function convertTime2Seconds($iHours = 0, $iMinutes = 0, $iSeconds = 0)
220{
221 $iResult = ((int) $iHours * 3600) + ((int) $iMinutes * 60) + (int) $iSeconds;
222 return $iResult;
223}
224
225
248function convertSecondToTime($iSecond, $format = 'all', $lengthOfDay = 86400, $lengthOfWeek = 7)
249{
250 global $langs;
251
252 if (empty($lengthOfDay)) {
253 $lengthOfDay = 86400; // 1 day = 24 hours
254 }
255 if (empty($lengthOfWeek)) {
256 $lengthOfWeek = 7; // 1 week = 7 days
257 }
258 $nbHbyDay = $lengthOfDay / 3600;
259
260 $sTime = '';
261
262 if ($format == 'all' || $format == 'allwithouthour' || $format == 'allhour' || $format == 'allhourmin' || $format == 'allhourminsec') {
263 if ((int) $iSecond === 0) {
264 return '0'; // This is to avoid having 0 return a 12:00 AM for en_US
265 }
266
267 $sDay = 0;
268 $sWeek = 0;
269
270 if ($iSecond >= $lengthOfDay) {
271 for ($i = $iSecond; $i >= $lengthOfDay; $i -= $lengthOfDay) {
272 $sDay++;
273 $iSecond -= $lengthOfDay;
274 }
275 $dayTranslate = $langs->trans("Day");
276 if ($iSecond >= ($lengthOfDay * 2)) {
277 $dayTranslate = $langs->trans("Days");
278 }
279 }
280
281 if ($lengthOfWeek < 7) {
282 if ($sDay) {
283 if ($sDay >= $lengthOfWeek) {
284 $sWeek = (int) (($sDay - $sDay % $lengthOfWeek) / $lengthOfWeek);
285 $sDay %= $lengthOfWeek;
286 $weekTranslate = $langs->trans("DurationWeek");
287 if ($sWeek >= 2) {
288 $weekTranslate = $langs->trans("DurationWeeks");
289 }
290 $sTime .= $sWeek.' '.$weekTranslate.' ';
291 }
292 }
293 }
294 if ($sDay > 0) {
295 $dayTranslate = $langs->trans("Day");
296 if ($sDay > 1) {
297 $dayTranslate = $langs->trans("Days");
298 }
299 $sTime .= $sDay.' '.$langs->trans("d").' ';
300 }
301
302 if ($format == 'all') {
303 if ($iSecond || empty($sDay)) {
304 $sTime .= dol_print_date($iSecond, 'hourduration', true);
305 }
306 } elseif ($format == 'allhourminsec') {
307 return sprintf("%02d", ($sWeek * $lengthOfWeek * $nbHbyDay + $sDay * $nbHbyDay + (int) floor($iSecond / 3600))).':'.sprintf("%02d", ((int) floor(($iSecond % 3600) / 60))).':'.sprintf("%02d", ((int) ($iSecond % 60)));
308 } elseif ($format == 'allhourmin') {
309 return sprintf("%02d", ($sWeek * $lengthOfWeek * $nbHbyDay + $sDay * $nbHbyDay + (int) floor($iSecond / 3600))).':'.sprintf("%02d", ((int) floor(($iSecond % 3600) / 60)));
310 } elseif ($format == 'allhour') {
311 return sprintf("%02d", ($sWeek * $lengthOfWeek * $nbHbyDay + $sDay * $nbHbyDay + (int) floor($iSecond / 3600)));
312 }
313 } elseif ($format == 'hour') { // only hour part
314 $sTime = dol_print_date($iSecond, '%H', true);
315 } elseif ($format == 'fullhour') {
316 if (!empty($iSecond)) {
317 $iSecond /= 3600;
318 } else {
319 $iSecond = 0;
320 }
321 $sTime = $iSecond;
322 } elseif ($format == 'min') { // only min part
323 $sTime = dol_print_date($iSecond, '%M', true);
324 } elseif ($format == 'sec') { // only sec part
325 $sTime = dol_print_date($iSecond, '%S', true);
326 } elseif ($format == 'month') { // only month part
327 $sTime = dol_print_date($iSecond, '%m', true);
328 } elseif ($format == 'year') { // only year part
329 $sTime = dol_print_date($iSecond, '%Y', true);
330 }
331 return trim((string) $sTime);
332}
333
334
342function convertDurationtoHour($duration_value, $duration_unit)
343{
344 $result = 0;
345
346 if ($duration_unit == 's') {
347 $result = $duration_value / 3600;
348 }
349 if ($duration_unit == 'i' || $duration_unit == 'mn' || $duration_unit == 'min') {
350 $result = $duration_value / 60;
351 }
352 if ($duration_unit == 'h') {
353 $result = $duration_value;
354 }
355 if ($duration_unit == 'd') {
356 $result = $duration_value * 24;
357 }
358 if ($duration_unit == 'w') {
359 $result = $duration_value * 24 * 7;
360 }
361 if ($duration_unit == 'm') {
362 $result = $duration_value * 730.484;
363 }
364 if ($duration_unit == 'y') {
365 $result = $duration_value * 365 * 24;
366 }
367
368 return $result;
369}
370
386function dolSqlDateFilter($datefield, $day_date, $month_date, $year_date, $excludefirstand = 0, $gm = false)
387{
388 global $db;
389 $sqldate = '';
390
391 $day_date = intval($day_date);
392 $month_date = intval($month_date);
393 $year_date = intval($year_date);
394 $sql_datefield = $db->sanitize($datefield);
395
396 if ($month_date > 0) {
397 if ($month_date > 12) { // protection for bad value of month
398 return " AND 1 = 2";
399 }
400 if ($year_date > 0 && empty($day_date)) {
401 $sqldate .= ($excludefirstand ? "" : " AND ").$sql_datefield." BETWEEN '".$db->idate(dol_get_first_day($year_date, $month_date, $gm))."'";
402 $sqldate .= " AND '".$db->idate(dol_get_last_day($year_date, $month_date, $gm))."'";
403 } elseif ($year_date > 0 && !empty($day_date)) {
404 $sqldate .= ($excludefirstand ? "" : " AND ").$sql_datefield." BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $month_date, $day_date, $year_date, $gm))."'";
405 $sqldate .= " AND '".$db->idate(dol_mktime(23, 59, 59, $month_date, $day_date, $year_date, $gm))."'";
406 } else {
407 // This case is not reliable on TZ, but we should not need it.
408 $sqldate .= ($excludefirstand ? "" : " AND ")." date_format( ".$sql_datefield.", '%c') = '".$db->escape((string) $month_date)."'";
409 }
410 } elseif ($year_date > 0) {
411 $sqldate .= ($excludefirstand ? "" : " AND ").$sql_datefield." BETWEEN '".$db->idate(dol_get_first_day($year_date, 1, $gm))."'";
412 $sqldate .= " AND '".$db->idate(dol_get_last_day($year_date, 12, $gm))."'";
413 }
414 return $sqldate;
415}
416
436function dol_stringtotime($string, $gm = 1)
437{
438 $reg = array();
439 // Convert date with format DD/MM/YYY HH:MM:SS. This part of code should not be used.
440 if (preg_match('/^([0-9]+)\/([0-9]+)\/([0-9]+)\s?([0-9]+)?:?([0-9]+)?:?([0-9]+)?/i', $string, $reg)) {
441 dol_syslog("dol_stringtotime call to function with deprecated parameter format", LOG_WARNING);
442 // Date is in format 'DD/MM/YY' or 'DD/MM/YY HH:MM:SS'
443 // Date is in format 'DD/MM/YYYY' or 'DD/MM/YYYY HH:MM:SS'
444 $sday = (int) $reg[1];
445 $smonth = (int) $reg[2];
446 $syear = (int) $reg[3];
447 $shour = (int) $reg[4];
448 $smin = (int) $reg[5];
449 $ssec = (int) $reg[6];
450 if ($syear < 50) {
451 $syear += 1900;
452 }
453 if ($syear >= 50 && $syear < 100) {
454 $syear += 2000;
455 }
456 $string = sprintf("%04d%02d%02d%02d%02d%02d", $syear, $smonth, $sday, $shour, $smin, $ssec);
457 } 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)
458 || 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
459 || 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
460 ) {
461 $syear = (int) $reg[1];
462 $smonth = (int) $reg[2];
463 $sday = (int) $reg[3];
464 $shour = (int) $reg[4];
465 $smin = (int) $reg[5];
466 $ssec = (int) $reg[6];
467 $string = sprintf("%04d%02d%02d%02d%02d%02d", $syear, $smonth, $sday, $shour, $smin, $ssec);
468 }
469
470 $string = preg_replace('/([^0-9])/i', '', $string);
471 $tmp = $string.'000000';
472 // Clean $gm
473 if ($gm === 1) {
474 $gm = 'gmt';
475 } elseif (empty($gm) || $gm === 'tzserver') {
476 $gm = 'tzserver';
477 }
478
479 $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);
480
481 return $date;
482}
483
484
493function dol_get_prev_day($day, $month, $year)
494{
495 $time = dol_mktime(12, 0, 0, $month, $day, $year, 1, 0);
496 $time -= 24 * 60 * 60;
497 $tmparray = dol_getdate($time, true);
498 return array('year' => $tmparray['year'], 'month' => $tmparray['mon'], 'day' => $tmparray['mday']);
499}
500
509function dol_get_next_day($day, $month, $year)
510{
511 $time = dol_mktime(12, 0, 0, $month, $day, $year, 1, 0);
512 $time += 24 * 60 * 60;
513 $tmparray = dol_getdate($time, true);
514 return array('year' => $tmparray['year'], 'month' => $tmparray['mon'], 'day' => $tmparray['mday']);
515}
516
524function dol_get_prev_month($month, $year)
525{
526 if ($month == 1) {
527 $prev_month = 12;
528 $prev_year = $year - 1;
529 } else {
530 $prev_month = $month - 1;
531 $prev_year = $year;
532 }
533 return array('year' => $prev_year, 'month' => $prev_month);
534}
535
543function dol_get_next_month($month, $year)
544{
545 if ($month == 12) {
546 $next_month = 1;
547 $next_year = $year + 1;
548 } else {
549 $next_month = $month + 1;
550 $next_year = $year;
551 }
552 return array('year' => $next_year, 'month' => $next_month);
553}
554
564function dol_get_prev_week($day, $week, $month, $year)
565{
566 $tmparray = dol_get_first_day_week($day, $month, $year);
567
568 $time = dol_mktime(12, 0, 0, $month, $tmparray['first_day'], $year, 1, 0);
569 $time -= 24 * 60 * 60 * 7;
570 $tmparray = dol_getdate($time, true);
571 return array('year' => $tmparray['year'], 'month' => $tmparray['mon'], 'day' => $tmparray['mday']);
572}
573
583function dol_get_next_week($day, $week, $month, $year)
584{
585 $tmparray = dol_get_first_day_week($day, $month, $year);
586
587 $time = dol_mktime(12, 0, 0, $tmparray['first_month'], $tmparray['first_day'], $tmparray['first_year'], 1, 0);
588 $time += 24 * 60 * 60 * 7;
589 $tmparray = dol_getdate($time, true);
590
591 return array('year' => $tmparray['year'], 'month' => $tmparray['mon'], 'day' => $tmparray['mday']);
592}
593
605function dol_get_first_day($year, $month = 1, $gm = false)
606{
607 if ($year > 9999) {
608 return '';
609 }
610 return dol_mktime(0, 0, 0, $month, 1, $year, $gm);
611}
612
613
624function dol_get_last_day($year, $month = 12, $gm = false)
625{
626 if ($year > 9999) {
627 return '';
628 }
629 if ($month == 12) {
630 $month = 1;
631 $year += 1;
632 } else {
633 $month += 1;
634 }
635
636 // Move to the start of the next month, then subtract one day
637 $datelim = dol_mktime(23, 59, 59, $month, 1, $year, $gm);
638 $datelim -= (3600 * 24);
639
640 return $datelim;
641}
642
651function dol_get_last_hour($date, $gm = 'tzserver')
652{
653 $tmparray = dol_getdate($date, false, ($gm == 'gmt' ? 'gmt' : ''));
654 return dol_mktime(23, 59, 59, $tmparray['mon'], $tmparray['mday'], $tmparray['year'], $gm);
655}
656
665function dol_get_first_hour($date, $gm = 'tzserver')
666{
667 $tmparray = dol_getdate($date, false, ($gm == 'gmt' ? 'gmt' : ''));
668 return dol_mktime(0, 0, 0, $tmparray['mon'], $tmparray['mday'], $tmparray['year'], $gm);
669}
670
680function dol_get_first_day_week($day, $month, $year, $gm = false)
681{
682 //$day=2; $month=2; $year=2015;
683 $date = dol_mktime(0, 0, 0, $month, $day, $year, $gm);
684
685 //Checking conf of start week
686 $start_week = getDolGlobalInt('MAIN_START_WEEK', 1);
687
688 $tmparray = dol_getdate($date, true); // detail of current day
689
690 //Calculate days = offset from current day
691 $days = $start_week - $tmparray['wday'];
692 if ($days >= 1) {
693 $days = 7 - $days;
694 }
695 $days = abs($days);
696 $seconds = $days * 24 * 60 * 60;
697 //print 'start_week='.$start_week.' tmparray[wday]='.$tmparray['wday'].' day offset='.$days.' seconds offset='.$seconds.'<br>';
698
699 //Get first day of week
700 $tmpdaytms = (int) date((string) $tmparray['0']) - $seconds; // $tmparray[0] is day of parameters
701 $tmpday = idate("d", $tmpdaytms);
702
703 //Check first day of week is in same month than current day or not
704 if ($tmpday > $day) {
705 $prev_month = $month - 1;
706 $prev_year = $year;
707
708 if ($prev_month == 0) {
709 $prev_month = 12;
710 $prev_year = $year - 1;
711 }
712 } else {
713 $prev_month = $month;
714 $prev_year = $year;
715 }
716 $tmpmonth = $prev_month;
717 $tmpyear = $prev_year;
718
719 //Get first day of next week
720 $tmptime = dol_mktime(12, 0, 0, $month, $tmpday, $year, 1, 0);
721 $tmptime -= 24 * 60 * 60 * 7;
722 $tmparray = dol_getdate($tmptime, true);
723 $prev_day = $tmparray['mday'];
724
725 //Check prev day of week is in same month than first day or not
726 if ($prev_day > $tmpday) {
727 $prev_month = $month - 1;
728 $prev_year = $year;
729
730 if ($prev_month == 0) {
731 $prev_month = 12;
732 $prev_year = $year - 1;
733 }
734 }
735
736 $week = date("W", dol_mktime(0, 0, 0, $tmpmonth, $tmpday, $tmpyear, $gm));
737
738 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);
739}
740
748function getGMTEasterDatetime($year)
749{
750 $base = new DateTime("$year-03-21", new DateTimeZone("UTC"));
751 $days = easter_days($year); // Return number of days between 21 march and easter day.
752 $tmp = $base->add(new DateInterval("P{$days}D"));
753 return $tmp->getTimestamp();
754}
755
772function num_public_holiday($timestampStart, $timestampEnd, $countryCodeOrId = '', $lastday = 0, $includesaturday = -1, $includesunday = -1, $includefriday = -1, $includemonday = -1)
773{
774 global $conf, $db, $mysoc;
775
776 $nbFerie = 0;
777
778 // Check to ensure we use correct parameters
779 if (($timestampEnd - $timestampStart) % 86400 != 0) {
780 return 'Error Dates must use same hours and must be GMT dates';
781 }
782
783 if (empty($countryCodeOrId)) {
784 $countryCodeOrId = $mysoc->country_code;
785 }
786 if ($includemonday < 0) {
787 $includemonday = getDolGlobalInt('MAIN_NON_WORKING_DAYS_INCLUDE_MONDAY', 0);
788 }
789 if ($includefriday < 0) {
790 $includefriday = getDolGlobalInt('MAIN_NON_WORKING_DAYS_INCLUDE_FRIDAY', 0);
791 }
792 if ($includesaturday < 0) {
793 $includesaturday = getDolGlobalInt('MAIN_NON_WORKING_DAYS_INCLUDE_SATURDAY', 1);
794 }
795 if ($includesunday < 0) {
796 $includesunday = getDolGlobalInt('MAIN_NON_WORKING_DAYS_INCLUDE_SUNDAY', 1);
797 }
798
799 if (is_numeric($countryCodeOrId)) {
800 $country_id = $countryCodeOrId;
801 } else {
802 $country_id = dol_getIdFromCode($db, $countryCodeOrId, 'c_country', 'code', 'rowid');
803 }
804
805 if (empty($conf->cache['arrayOfActivePublicHolidays_'.$country_id])) {
806 // Loop on public holiday defined into hrm_public_holiday for the day, month and year analyzed
807 $tmpArrayOfPublicHolidays = array();
808 $sql = "SELECT id, code, entity, fk_country, dayrule, year, month, day, active";
809 $sql .= " FROM ".MAIN_DB_PREFIX."c_hrm_public_holiday";
810 $sql .= " WHERE active = 1 and fk_country IN (0".($country_id > 0 ? ", ".((int) $country_id) : 0).")";
811 $sql .= " AND entity IN (0," .getEntity('holiday') .")";
812
813 $resql = $db->query($sql);
814 if ($resql) {
815 $num_rows = $db->num_rows($resql);
816 $i = 0;
817 while ($i < $num_rows) {
818 $obj = $db->fetch_object($resql);
819 $tmpArrayOfPublicHolidays[$obj->id] = array('dayrule' => $obj->dayrule, 'year' => $obj->year, 'month' => $obj->month, 'day' => $obj->day);
820 $i++;
821 }
822 } else {
823 dol_syslog($db->lasterror(), LOG_ERR);
824 return 'Error sql '.$db->lasterror();
825 }
826
827 //var_dump($tmpArrayOfPublicHolidays);
828 $conf->cache['arrayOfActivePublicHolidays_'.$country_id] = $tmpArrayOfPublicHolidays;
829 }
830
831 $arrayOfPublicHolidays = $conf->cache['arrayOfActivePublicHolidays_'.$country_id];
832
833 $i = 0;
834 while ((($lastday == 0 && $timestampStart < $timestampEnd) || ($lastday && $timestampStart <= $timestampEnd))
835 && ($i < 50000)) { // Loop end when equals (Test on i is a security loop to avoid infinite loop)
836 $ferie = false;
837 $specialdayrule = array();
838
839 $jour = (int) gmdate("d", $timestampStart);
840 $mois = (int) gmdate("m", $timestampStart);
841 $annee = (int) gmdate("Y", $timestampStart);
842 $jour_semaine = (int) gmdate("w", $timestampStart); // sunday = 0, monday = 1, ...
843
844 //print "jour=".$jour." month=".$mois." year=".$annee." includesaturday=".$includesaturday." includesunday=".$includesunday."\n";
845 foreach ($arrayOfPublicHolidays as $entrypublicholiday) {
846 if (!empty($entrypublicholiday['dayrule']) && $entrypublicholiday['dayrule'] != 'date') { // For example 'easter', '...'
847 $specialdayrule[$entrypublicholiday['dayrule']] = $entrypublicholiday['dayrule'];
848 } else {
849 $match = 1;
850 if (!empty($entrypublicholiday['year']) && $entrypublicholiday['year'] != $annee) {
851 $match = 0;
852 }
853 if ($entrypublicholiday['month'] != $mois) {
854 $match = 0;
855 }
856 if ($entrypublicholiday['day'] != $jour) {
857 $match = 0;
858 }
859
860 if ($match) {
861 $ferie = true;
862 }
863 }
864
865 $i++;
866 }
867 //var_dump($specialdayrule)."\n";
868 //print "ferie=".$ferie."\n";
869
870 if (!$ferie) {
871 // Special dayrules
872 if (in_array('easter', $specialdayrule)) {
873 // Calculation for easter date
874 $date_paques = getGMTEasterDatetime($annee);
875 $jour_paques = gmdate("d", $date_paques);
876 $mois_paques = gmdate("m", $date_paques);
877 if ($jour_paques == $jour && $mois_paques == $mois) {
878 $ferie = true;
879 }
880 // Easter (sunday)
881 }
882
883 if (in_array('eastermonday', $specialdayrule)) {
884 // Calculation for the monday of easter date
885 $date_paques = getGMTEasterDatetime($annee);
886 //print 'PPP'.$date_paques.' '.dol_print_date($date_paques, 'dayhour', 'gmt')." ";
887 $date_lundi_paques = $date_paques + (3600 * 24);
888 $jour_lundi_paques = gmdate("d", $date_lundi_paques);
889 $mois_lundi_paques = gmdate("m", $date_lundi_paques);
890 if ($jour_lundi_paques == $jour && $mois_lundi_paques == $mois) {
891 $ferie = true;
892 }
893 // Easter (monday)
894 //print 'annee='.$annee.' $jour='.$jour.' $mois='.$mois.' $jour_lundi_paques='.$jour_lundi_paques.' $mois_lundi_paques='.$mois_lundi_paques."\n";
895 }
896
897 //Good Friday
898 if (in_array('goodfriday', $specialdayrule)) {
899 // Pulls the date of Easter
900 $easter = getGMTEasterDatetime($annee);
901
902 // Calculates the date of Good Friday based on Easter
903 $date_good_friday = $easter - (2 * 3600 * 24);
904 $dom_good_friday = gmdate("d", $date_good_friday);
905 $month_good_friday = gmdate("m", $date_good_friday);
906
907 if ($dom_good_friday == $jour && $month_good_friday == $mois) {
908 $ferie = true;
909 }
910 }
911
912 if (in_array('ascension', $specialdayrule)) {
913 // Calculation of Ascension day (39 days after easter day)
914 $date_paques = getGMTEasterDatetime($annee);
915 $date_ascension = $date_paques + (3600 * 24 * 39);
916 $jour_ascension = gmdate("d", $date_ascension);
917 $mois_ascension = gmdate("m", $date_ascension);
918 if ($jour_ascension == $jour && $mois_ascension == $mois) {
919 $ferie = true;
920 }
921 // Ascension (thursday)
922 }
923
924 if (in_array('pentecost', $specialdayrule)) {
925 // Calculation of "Pentecote" (49 days after easter day)
926 $date_paques = getGMTEasterDatetime($annee);
927 $date_pentecote = $date_paques + (3600 * 24 * 49);
928 $jour_pentecote = gmdate("d", $date_pentecote);
929 $mois_pentecote = gmdate("m", $date_pentecote);
930 if ($jour_pentecote == $jour && $mois_pentecote == $mois) {
931 $ferie = true;
932 }
933 // "Pentecote" (sunday)
934 }
935 if (in_array('pentecotemonday', $specialdayrule)) {
936 // Calculation of "Pentecote" (49 days after easter day)
937 $date_paques = getGMTEasterDatetime($annee);
938 $date_pentecote = $date_paques + (3600 * 24 * 50);
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" (monday)
945 }
946
947 if (in_array('viernessanto', $specialdayrule)) {
948 // Viernes Santo
949 $date_paques = getGMTEasterDatetime($annee);
950 $date_viernes = $date_paques - (3600 * 24 * 2);
951 $jour_viernes = gmdate("d", $date_viernes);
952 $mois_viernes = gmdate("m", $date_viernes);
953 if ($jour_viernes == $jour && $mois_viernes == $mois) {
954 $ferie = true;
955 }
956 //Viernes Santo
957 }
958
959 if (in_array('fronleichnam', $specialdayrule)) {
960 // Fronleichnam (60 days after easter sunday)
961 $date_paques = getGMTEasterDatetime($annee);
962 $date_fronleichnam = $date_paques + (3600 * 24 * 60);
963 $jour_fronleichnam = gmdate("d", $date_fronleichnam);
964 $mois_fronleichnam = gmdate("m", $date_fronleichnam);
965 if ($jour_fronleichnam == $jour && $mois_fronleichnam == $mois) {
966 $ferie = true;
967 }
968 // Fronleichnam
969 }
970
971 if (in_array('genevafast', $specialdayrule)) {
972 // Geneva fast in Switzerland (Thursday after the first sunday in September)
973 $date_1sunsept = strtotime('next thursday', strtotime('next sunday', mktime(0, 0, 0, 9, 1, $annee)));
974 $jour_1sunsept = date("d", $date_1sunsept);
975 $mois_1sunsept = date("m", $date_1sunsept);
976 if ($jour_1sunsept == $jour && $mois_1sunsept == $mois) {
977 $ferie = true;
978 }
979 // Geneva fast in Switzerland
980 }
981 }
982 //print "ferie afterspe=".$ferie."\n";
983
984 // If we have to include Friday, Saturday and Sunday
985 if (!$ferie) {
986 if ($includefriday || $includesaturday || $includesunday || $includemonday) {
987 //Monday (1), Friday (5), Saturday (6) and Sunday (0)
988 if ($includefriday && $jour_semaine == 5) {
989 $ferie = true;
990 }
991 if ($includesaturday && $jour_semaine == 6) {
992 $ferie = true;
993 }
994 if ($includesunday && $jour_semaine == 0) {
995 $ferie = true;
996 }
997 if ($includemonday && $jour_semaine == 1) {
998 $ferie = true;
999 }
1000 }
1001 }
1002 //print "ferie afterincludexxxday=".$ferie."\n";
1003
1004 // We increase the counter of non working day
1005 if ($ferie) {
1006 $nbFerie++;
1007 }
1008
1009 // Increase number of days (on go up into loop)
1010 // Advance by exactly one GMT day. We can use += instead of dol_time_plus_duree() here because
1011 // inputs of this function are GMT dates (checked above), so a day
1012 // is always exactly 86400 seconds.
1013 //var_dump("before ".$jour.' '.$mois.' '.$annee.' '.$timestampStart);
1014 $timestampStart += 86400;
1015 //var_dump("after ".$jour.' '.$mois.' '.$annee.' '.$timestampStart);
1016
1017 $i++;
1018 }
1019
1020 //print "nbFerie=".$nbFerie."\n";
1021 return $nbFerie;
1022}
1023
1040function listPublicHoliday($timestampStart, $timestampEnd, $countryCodeOrId = '', $lastday = 0, $excludesaturday = -1, $excludesunday = -1, $excludefriday = -1, $excludemonday = -1)
1041{
1042 global $conf, $db, $mysoc;
1043
1044 // Check to ensure we use correct parameters
1045 if (($timestampEnd - $timestampStart) % 86400 != 0) {
1046 return 'Error Dates must use same hours and must be GMT dates';
1047 }
1048
1049 if (empty($countryCodeOrId)) {
1050 $countryCodeOrId = $mysoc->country_code;
1051 }
1052 if ($excludemonday < 0) {
1053 $excludemonday = getDolGlobalInt('MAIN_NON_WORKING_DAYS_INCLUDE_MONDAY', 0);
1054 }
1055 if ($excludefriday < 0) {
1056 $excludefriday = getDolGlobalInt('MAIN_NON_WORKING_DAYS_INCLUDE_FRIDAY', 0);
1057 }
1058 if ($excludesaturday < 0) {
1059 $excludesaturday = getDolGlobalInt('MAIN_NON_WORKING_DAYS_INCLUDE_SATURDAY', 1);
1060 }
1061 if ($excludesunday < 0) {
1062 $excludesunday = getDolGlobalInt('MAIN_NON_WORKING_DAYS_INCLUDE_SUNDAY', 1);
1063 }
1064
1065 if (is_numeric($countryCodeOrId)) {
1066 $country_id = $countryCodeOrId;
1067 } else {
1068 $country_id = dol_getIdFromCode($db, $countryCodeOrId, 'c_country', 'code', 'rowid');
1069 }
1070
1071 if (empty($conf->cache['arrayOfActivePublicHolidays_' . $country_id])) {
1072 // Loop on public holiday defined into hrm_public_holiday for the day, month and year analyzed
1073 $tmpArrayOfPublicHolidays = array();
1074 $sql = "SELECT id, code, entity, fk_country, dayrule, year, month, day, active";
1075 $sql .= " FROM " . MAIN_DB_PREFIX . "c_hrm_public_holiday";
1076 $sql .= " WHERE active = 1 and fk_country IN (0" . ($country_id > 0 ? ", " . ((int) $country_id) : 0) . ")";
1077 $sql .= " AND entity IN (0," . getEntity('holiday') . ")";
1078
1079 $resql = $db->query($sql);
1080 if ($resql) {
1081 $num_rows = $db->num_rows($resql);
1082 $i = 0;
1083 while ($i < $num_rows) {
1084 $obj = $db->fetch_object($resql);
1085 $tmpArrayOfPublicHolidays[$obj->id] = array('dayrule' => $obj->dayrule, 'year' => $obj->year, 'month' => $obj->month, 'day' => $obj->day);
1086 $i++;
1087 }
1088 } else {
1089 dol_syslog($db->lasterror(), LOG_ERR);
1090 return 'Error sql ' . $db->lasterror();
1091 }
1092
1093 //var_dump($tmpArrayOfPublicHolidays);
1094 $conf->cache['arrayOfActivePublicHolidays_' . $country_id] = $tmpArrayOfPublicHolidays;
1095 }
1096
1097 $arrayOfPublicHolidays = $conf->cache['arrayOfActivePublicHolidays_' . $country_id];
1098 $listFeries = [];
1099 $i = 0;
1100 while ((($lastday == 0 && $timestampStart < $timestampEnd) || ($lastday && $timestampStart <= $timestampEnd))
1101 && ($i < 50000)) { // Loop end when equals (Test on i is a security loop to avoid infinite loop)
1102 $nonWorkingDay = false;
1103 $ferie = false;
1104 $specialdayrule = array();
1105
1106 $jour = (int) gmdate("d", $timestampStart);
1107 $mois = (int) gmdate("m", $timestampStart);
1108 $annee = (int) gmdate("Y", $timestampStart);
1109
1110 // If we have to exclude Friday, Saturday and Sunday
1111 if ($excludefriday || $excludesaturday || $excludesunday) {
1112 $jour_julien = unixtojd($timestampStart);
1113 $jour_semaine = jddayofweek($jour_julien, 0);
1114 if ($excludefriday) { //Friday (5), Saturday (6) and Sunday (0)
1115 if ($jour_semaine == 5) {
1116 $nonWorkingDay = true;
1117 }
1118 }
1119 if ($excludesaturday) { //Friday (5), Saturday (6) and Sunday (0)
1120 if ($jour_semaine == 6) {
1121 $nonWorkingDay = true;
1122 }
1123 }
1124 if ($excludesunday) { //Friday (5), Saturday (6) and Sunday (0)
1125 if ($jour_semaine == 0) {
1126 $nonWorkingDay = true;
1127 }
1128 }
1129 }
1130 //print "ferie=".$nonWorkingDay."\n";
1131
1132 if (!$nonWorkingDay) {
1133 //print "jour=".$jour." month=".$mois." year=".$annee." includesaturday=".$excludesaturday." includesunday=".$excludesunday."\n";
1134 foreach ($arrayOfPublicHolidays as $entrypublicholiday) {
1135 if (!empty($entrypublicholiday['dayrule']) && $entrypublicholiday['dayrule'] != 'date') { // For example 'easter', '...'
1136 $specialdayrule[$entrypublicholiday['dayrule']] = $entrypublicholiday['dayrule'];
1137 } else {
1138 $match = 1;
1139 if (!empty($entrypublicholiday['year']) && $entrypublicholiday['year'] != $annee) {
1140 $match = 0;
1141 }
1142 if ($entrypublicholiday['month'] != $mois) {
1143 $match = 0;
1144 }
1145 if ($entrypublicholiday['day'] != $jour) {
1146 $match = 0;
1147 }
1148
1149 if ($match) {
1150 $ferie = true;
1151 $listFeries[] = $timestampStart;
1152 }
1153 }
1154
1155 $i++;
1156 }
1157 //var_dump($specialdayrule)."\n";
1158 //print "ferie=".$nonWorkingDay."\n";
1159 }
1160
1161 if (!$nonWorkingDay && !$ferie) {
1162 // Special dayrules
1163 if (in_array('easter', $specialdayrule)) {
1164 // Calculation for easter date
1165 $date_paques = getGMTEasterDatetime($annee);
1166 $jour_paques = gmdate("d", $date_paques);
1167 $mois_paques = gmdate("m", $date_paques);
1168 if ($jour_paques == $jour && $mois_paques == $mois) {
1169 $ferie = true;
1170 $listFeries[] = $timestampStart;
1171 }
1172 // Easter (sunday)
1173 }
1174
1175 if (in_array('eastermonday', $specialdayrule)) {
1176 // Calculation for the monday of easter date
1177 $date_paques = getGMTEasterDatetime($annee);
1178 //print 'PPP'.$date_paques.' '.dol_print_date($date_paques, 'dayhour', 'gmt')." ";
1179 $date_lundi_paques = $date_paques + (3600 * 24);
1180 $jour_lundi_paques = gmdate("d", $date_lundi_paques);
1181 $mois_lundi_paques = gmdate("m", $date_lundi_paques);
1182 if ($jour_lundi_paques == $jour && $mois_lundi_paques == $mois) {
1183 $ferie = true;
1184 $listFeries[] = $timestampStart;
1185 }
1186 // Easter (monday)
1187 //print 'annee='.$annee.' $jour='.$jour.' $mois='.$mois.' $jour_lundi_paques='.$jour_lundi_paques.' $mois_lundi_paques='.$mois_lundi_paques."\n";
1188 }
1189
1190 //Good Friday
1191 if (in_array('goodfriday', $specialdayrule)) {
1192 // Pulls the date of Easter
1193 $easter = getGMTEasterDatetime($annee);
1194
1195 // Calculates the date of Good Friday based on Easter
1196 $date_good_friday = $easter - (2 * 3600 * 24);
1197 $dom_good_friday = gmdate("d", $date_good_friday);
1198 $month_good_friday = gmdate("m", $date_good_friday);
1199
1200 if ($dom_good_friday == $jour && $month_good_friday == $mois) {
1201 $ferie = true;
1202 $listFeries[] = $timestampStart;
1203 }
1204 }
1205
1206 if (in_array('ascension', $specialdayrule)) {
1207 // Calculation of Ascension day (39 days after easter day)
1208 $date_paques = getGMTEasterDatetime($annee);
1209 $date_ascension = $date_paques + (3600 * 24 * 39);
1210 $jour_ascension = gmdate("d", $date_ascension);
1211 $mois_ascension = gmdate("m", $date_ascension);
1212 if ($jour_ascension == $jour && $mois_ascension == $mois) {
1213 $ferie = true;
1214 $listFeries[] = $timestampStart;
1215 }
1216 // Ascension (thursday)
1217 }
1218
1219 if (in_array('pentecost', $specialdayrule)) {
1220 // Calculation of "Pentecote" (49 days after easter day)
1221 $date_paques = getGMTEasterDatetime($annee);
1222 $date_pentecote = $date_paques + (3600 * 24 * 49);
1223 $jour_pentecote = gmdate("d", $date_pentecote);
1224 $mois_pentecote = gmdate("m", $date_pentecote);
1225 if ($jour_pentecote == $jour && $mois_pentecote == $mois) {
1226 $ferie = true;
1227 $listFeries[] = $timestampStart;
1228 }
1229 // "Pentecote" (sunday)
1230 }
1231
1232 if (in_array('pentecotemonday', $specialdayrule)) {
1233 // Calculation of "Pentecote" (49 days after easter day)
1234 $date_paques = getGMTEasterDatetime($annee);
1235 $date_pentecote = $date_paques + (3600 * 24 * 50);
1236 $jour_pentecote = gmdate("d", $date_pentecote);
1237 $mois_pentecote = gmdate("m", $date_pentecote);
1238 if ($jour_pentecote == $jour && $mois_pentecote == $mois) {
1239 $ferie = true;
1240 $listFeries[] = $timestampStart;
1241 }
1242 // "Pentecote" (monday)
1243 }
1244
1245 if (in_array('viernessanto', $specialdayrule)) {
1246 // Viernes Santo
1247 $date_paques = getGMTEasterDatetime($annee);
1248 $date_viernes = $date_paques - (3600 * 24 * 2);
1249 $jour_viernes = gmdate("d", $date_viernes);
1250 $mois_viernes = gmdate("m", $date_viernes);
1251 if ($jour_viernes == $jour && $mois_viernes == $mois) {
1252 $ferie = true;
1253 $listFeries[] = $timestampStart;
1254 }
1255 //Viernes Santo
1256 }
1257
1258 if (in_array('fronleichnam', $specialdayrule)) {
1259 // Fronleichnam (60 days after easter sunday)
1260 $date_paques = getGMTEasterDatetime($annee);
1261 $date_fronleichnam = $date_paques + (3600 * 24 * 60);
1262 $jour_fronleichnam = gmdate("d", $date_fronleichnam);
1263 $mois_fronleichnam = gmdate("m", $date_fronleichnam);
1264 if ($jour_fronleichnam == $jour && $mois_fronleichnam == $mois) {
1265 $ferie = true;
1266 $listFeries[] = $timestampStart;
1267 }
1268 // Fronleichnam
1269 }
1270
1271 if (in_array('genevafast', $specialdayrule)) {
1272 // Geneva fast in Switzerland (Thursday after the first sunday in September)
1273 $date_1sunsept = strtotime('next thursday', strtotime('next sunday', mktime(0, 0, 0, 9, 1, $annee)));
1274 $jour_1sunsept = date("d", $date_1sunsept);
1275 $mois_1sunsept = date("m", $date_1sunsept);
1276 if ($jour_1sunsept == $jour && $mois_1sunsept == $mois) {
1277 $ferie = true;
1278 $listFeries[] = $timestampStart;
1279 }
1280 // Geneva fast in Switzerland
1281 }
1282 }
1283 //print "ferie=".$nonWorkingDay."\n";
1284
1285 // Increase number of days (on go up into loop)
1286 $timestampStart = dol_time_plus_duree($timestampStart, 1, 'd');
1287 //var_dump($jour.' '.$mois.' '.$annee.' '.$timestampStart);
1288
1289 $i++;
1290 }
1291
1292 //print "nbFerie=".$nbFerie."\n";
1293 return $listFeries;
1294}
1295
1306function num_between_day($timestampStart, $timestampEnd, $lastday = 0)
1307{
1308 if ($timestampStart <= $timestampEnd) {
1309 if ($lastday == 1) {
1310 $bit = 0;
1311 } else {
1312 $bit = 1;
1313 }
1314 $nbjours = (int) floor(($timestampEnd - $timestampStart) / (60 * 60 * 24)) + 1 - $bit;
1315 } else {
1316 $nbjours = 0;
1317 }
1318 //print ($timestampEnd - $timestampStart) - $lastday;
1319 return $nbjours;
1320}
1321
1338function num_open_day($timestampStart, $timestampEnd, $inhour = 0, $lastday = 0, $halfday = 0, $countryCodeOrId = '', $user_id = 0)
1339{
1340 global $langs, $mysoc, $hookmanager;
1341
1342 if (empty($countryCodeOrId) || $countryCodeOrId < 0) {
1343 $countryCodeOrId = $mysoc->country_code;
1344 }
1345
1346 dol_syslog('num_open_day timestampStart='.$timestampStart.' timestampEnd='.$timestampEnd.' bit='.$lastday.' countryCodeOrId='.$countryCodeOrId);
1347
1348 // Check parameters
1349 if (!is_int($timestampStart) && !is_float($timestampStart)) {
1350 return 'ErrorBadParameter_num_open_day';
1351 }
1352 if (!is_int($timestampEnd) && !is_float($timestampEnd)) {
1353 return 'ErrorBadParameter_num_open_day';
1354 }
1355
1356 $nbOpenDay = 0; // expressed in days; inhour conversion happens at the end
1357
1358 if ($timestampStart < $timestampEnd) {
1359 // --- 1. Calculate Gross Working Days ---
1360 // Gross working days = total days in range - non-working days (weekends & public holidays).
1361 $a = num_between_day($timestampStart, $timestampEnd, $lastday);
1362 $b = num_public_holiday($timestampStart, $timestampEnd, $countryCodeOrId, $lastday);
1363 $nbOpenDay = $a - $b;
1364
1365 // --- 2. Apply Contextual Half-Day Deductions ---
1366 $halfday = (int) $halfday; // Ensure $halfday is an integer for reliable comparisons.
1367
1368 // Check if start/end days are working days just ONCE to optimize performance
1369 // by avoiding redundant calls to the potentially slow num_public_holiday() function.
1370 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
1371 $isStartDayWorking = (num_public_holiday($timestampStart, $timestampStart, $countryCodeOrId, 1) == 0);
1372 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
1373 $isEndDayWorking = (num_public_holiday($timestampEnd, $timestampEnd, $countryCodeOrId, 1) == 0);
1374
1375 // Deduct 0.5 if the leave starts in the afternoon of a working day.
1376 if (($halfday == -1 || $halfday == 2) && $isStartDayWorking) {
1377 $nbOpenDay -= 0.5;
1378 }
1379
1380 // Deduct 0.5 if the leave ends in the morning of a different, working day.
1381 if (($halfday == 1 || $halfday == 2) && date('Y-m-d', $timestampStart) != date('Y-m-d', $timestampEnd) && $isEndDayWorking) {
1382 $nbOpenDay -= 0.5;
1383 }
1384 } elseif ($timestampStart == $timestampEnd) {
1385 $isSingleDayHoliday = false;
1386 if ($lastday) {
1387 $numholidays = num_public_holiday($timestampStart, $timestampEnd, $countryCodeOrId, $lastday);
1388 if ($numholidays == 1) {
1389 $isSingleDayHoliday = true;
1390 }
1391 }
1392 if (!$isSingleDayHoliday) {
1393 $nbOpenDay = $lastday - 0.5 * abs((int) $halfday);
1394 }
1395 } else {
1396 return $langs->trans("Error");
1397 }
1398
1399 // --- 3. Allow modules to adjust the result based on the user (e.g. per-employee
1400 // individual workdays, bridge days, fixed half-days). Only fires when caller
1401 // opts in by passing a non-zero $user_id, so existing call sites are unaffected.
1402 if ($user_id > 0 && is_object($hookmanager)) {
1403 $parameters = array(
1404 'timestampStart' => $timestampStart,
1405 'timestampEnd' => $timestampEnd,
1406 'inhour' => $inhour,
1407 'lastday' => $lastday,
1408 'halfday' => $halfday,
1409 'countryCodeOrId' => $countryCodeOrId,
1410 'user_id' => $user_id,
1411 'nbOpenDay' => $nbOpenDay,
1412 );
1413 $action = '';
1414 $reshook = $hookmanager->executeHooks('numOpenDay', $parameters, $hookmanager, $action);
1415 if ($reshook > 0 && isset($hookmanager->resArray['nbOpenDay'])) {
1416 $nbOpenDay = $hookmanager->resArray['nbOpenDay'];
1417 }
1418 }
1419
1420 if ($inhour == 1) {
1421 return (int) ($nbOpenDay * 24);
1422 }
1423 return $nbOpenDay;
1424}
1425
1426
1427
1436function monthArray($outputlangs, $short = 0)
1437{
1438 $montharray = array(
1439 1 => $outputlangs->trans("Month01"),
1440 2 => $outputlangs->trans("Month02"),
1441 3 => $outputlangs->trans("Month03"),
1442 4 => $outputlangs->trans("Month04"),
1443 5 => $outputlangs->trans("Month05"),
1444 6 => $outputlangs->trans("Month06"),
1445 7 => $outputlangs->trans("Month07"),
1446 8 => $outputlangs->trans("Month08"),
1447 9 => $outputlangs->trans("Month09"),
1448 10 => $outputlangs->trans("Month10"),
1449 11 => $outputlangs->trans("Month11"),
1450 12 => $outputlangs->trans("Month12")
1451 );
1452
1453 if (!empty($short)) {
1454 $montharray = array(
1455 1 => $outputlangs->trans("MonthShort01"),
1456 2 => $outputlangs->trans("MonthShort02"),
1457 3 => $outputlangs->trans("MonthShort03"),
1458 4 => $outputlangs->trans("MonthShort04"),
1459 5 => $outputlangs->trans("MonthShort05"),
1460 6 => $outputlangs->trans("MonthShort06"),
1461 7 => $outputlangs->trans("MonthShort07"),
1462 8 => $outputlangs->trans("MonthShort08"),
1463 9 => $outputlangs->trans("MonthShort09"),
1464 10 => $outputlangs->trans("MonthShort10"),
1465 11 => $outputlangs->trans("MonthShort11"),
1466 12 => $outputlangs->trans("MonthShort12")
1467 );
1468 }
1469
1470 return $montharray;
1471}
1472
1480function getWeekNumbersOfMonth($month, $year)
1481{
1482 $nb_days = cal_days_in_month(CAL_GREGORIAN, $month, $year);
1483 $TWeek = array();
1484 for ($day = 1; $day <= $nb_days; $day++) {
1485 $week_number = getWeekNumber($day, $month, $year);
1486 $TWeek[$week_number] = $week_number;
1487 }
1488 return $TWeek;
1489}
1490
1498function getFirstDayOfEachWeek($TWeek, $year)
1499{
1500 $TFirstDayOfWeek = array();
1501 // 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.
1502 // If $TWeek starts with week 52 or 53 (a January), these first weeks belong to previous year.
1503 // If $TWeek ends with week 01 (a December), this last week belongs to next year.
1504 $startwithweeksofpreviousyear = ((int) reset($TWeek) >= 52 && in_array('01', $TWeek));
1505 foreach ($TWeek as $weekNb) {
1506 $yeartouse = $year;
1507 if ($startwithweeksofpreviousyear) {
1508 if ((int) $weekNb >= 52) {
1509 $yeartouse = $year - 1;
1510 }
1511 } elseif ($weekNb == '01' && in_array('52', $TWeek)) {
1512 $yeartouse = $year + 1;
1513 }
1514 $TFirstDayOfWeek[$weekNb] = date('d', strtotime($yeartouse.'W'.$weekNb));
1515 }
1516 return $TFirstDayOfWeek;
1517}
1518
1526function getLastDayOfEachWeek($TWeek, $year)
1527{
1528 $TLastDayOfWeek = array();
1529 // Same rule as in getFirstDayOfEachWeek() to find the year each week belongs to
1530 $startwithweeksofpreviousyear = ((int) reset($TWeek) >= 52 && in_array('01', $TWeek));
1531 foreach ($TWeek as $weekNb) {
1532 $yeartouse = $year;
1533 if ($startwithweeksofpreviousyear) {
1534 if ((int) $weekNb >= 52) {
1535 $yeartouse = $year - 1;
1536 }
1537 } elseif ($weekNb == '01' && in_array('52', $TWeek)) {
1538 $yeartouse = $year + 1;
1539 }
1540 $TLastDayOfWeek[$weekNb] = date('d', strtotime($yeartouse.'W'.$weekNb.'+6 days'));
1541 }
1542 return $TLastDayOfWeek;
1543}
1544
1553function getWeekNumber($day, $month, $year)
1554{
1555 $date = new DateTime($year.'-'.$month.'-'.$day);
1556 $week = $date->format("W");
1557 return $week;
1558}
global $mysoc
dol_get_prev_month($month, $year)
Return previous month.
Definition date.lib.php:524
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:665
dol_get_next_day($day, $month, $year)
Return next day.
Definition date.lib.php:509
dol_get_next_week($day, $week, $month, $year)
Return next week.
Definition date.lib.php:583
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:386
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:651
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:680
getGMTEasterDatetime($year)
Return the easter day in GMT time.
Definition date.lib.php:748
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:342
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:493
dol_get_first_day($year, $month=1, $gm=false)
Return GMT time for first day of a month or year.
Definition date.lib.php:605
getFirstDayOfEachWeek($TWeek, $year)
Return array of first day of weeks.
dol_get_next_month($month, $year)
Return next month.
Definition date.lib.php:543
getWeekNumber($day, $month, $year)
Return week number.
num_between_day($timestampStart, $timestampEnd, $lastday=0)
Function to return number of days between two dates (date must be UTC date !) Example: 2012-01-01 201...
num_public_holiday($timestampStart, $timestampEnd, $countryCodeOrId='', $lastday=0, $includesaturday=-1, $includesunday=-1, $includefriday=-1, $includemonday=-1)
Return the number of non working days including Friday, Saturday and Sunday (or not) between 2 dates ...
Definition date.lib.php:772
convertTime2Seconds($iHours=0, $iMinutes=0, $iSeconds=0)
Convert hours and minutes into seconds.
Definition date.lib.php:219
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:248
dol_get_prev_week($day, $week, $month, $year)
Return previous week.
Definition date.lib.php:564
dol_stringtotime($string, $gm=1)
Convert a string date into a GM Timestamps date Warning: YYYY-MM-DDTHH:MM:SS+02:00 (RFC3339) is not s...
Definition date.lib.php:436
dol_get_last_day($year, $month=12, $gm=false)
Return GMT time for last day of a month or year.
Definition date.lib.php:624
monthArray($outputlangs, $short=0)
Return array of translated months or selected month.
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $db
API class for accounts.
dol_now($mode='gmt')
Return date for now.
dol_mktime($hour, $minute, $second, $month, $day, $year, $gm='auto', $check=1)
Return a timestamp date built from detailed information (by default a local PHP server timestamp) Rep...
dol_getIdFromCode($db, $key, $tablename, $fieldkey='code', $fieldid='id', $entityfilter=0, $filters='', $useCache=true)
Return an id or code from a code or id.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false, $decorate=0)
Output date in a string format according to outputlangs (or langs if not defined).
dol_print_error($db=null, $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
getEntity($element, $shared=1, $currentobject=null)
Get list of entity id to use.
dol_getdate($timestamp, $fast=false, $forcetimezone='')
Return an array with locale date info.
print $langs trans('Date')." left Ref Label right Qty right Price right TotalHT right TotalTTC right right right right right right right right right centpercent right TotalHT right n right VAT right n right TotalVAT right n No sujeto a RE IRPF right TotalLT1 right n right TotalLT2 right n right TotalTTC right n takeposcustomercurrency takeposcustomercurrency takeposcustomercurrency takeposcustomercurrency right TotalTTC takeposcustomercurrency right takeposcustomercurrency n right Paid right PaymentTypeShortLIQ right SELECT p pos_change as p datep as date
Definition receipt.php:487