dolibarr 21.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 MDW <mdeweerd@users.noreply.github.com>
8 * Copyright (C) 2024 Frédéric France <frederic.france@free.fr>
9 *
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 3 of the License, or
13 * (at your option) any later version.
14 *
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
19 *
20 * You should have received a copy of the GNU General Public License
21 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 * or see https://www.gnu.org/
23 */
24
36function get_tz_array()
37{
38 $tzarray = array(
39 -11 => "Pacific/Pago_Pago",
40 -10 => "Pacific/Honolulu",
41 -9 => "America/Anchorage",
42 -8 => "America/Los_Angeles",
43 -7 => "America/Dawson_Creek",
44 -6 => "America/Chicago",
45 -5 => "America/Bogota",
46 -4 => "America/Asuncion",
47 -3 => "America/Araguaina",
48 -2 => "America/Noronha",
49 -1 => "Atlantic/Azores",
50 0 => "Europe/London",
51 1 => "Europe/Paris",
52 2 => "Europe/Helsinki",
53 3 => "Europe/Moscow",
54 4 => "Asia/Dubai",
55 5 => "Asia/Karachi",
56 6 => "Indian/Chagos",
57 7 => "Asia/Jakarta",
58 8 => "Asia/Hong_Kong",
59 9 => "Asia/Tokyo",
60 10 => "Australia/Sydney",
61 11 => "Pacific/Noumea",
62 12 => "Pacific/Auckland",
63 13 => "Pacific/Fakaofo",
64 14 => "Pacific/Kiritimati"
65 );
66 return $tzarray;
67}
68
69
76{
77 return @date_default_timezone_get();
78}
79
86function getServerTimeZoneInt($refgmtdate = 'now')
87{
88 if (method_exists('DateTimeZone', 'getOffset')) {
89 // Method 1 (include daylight)
90 $gmtnow = dol_now('gmt');
91 $yearref = dol_print_date($gmtnow, '%Y');
92 $monthref = dol_print_date($gmtnow, '%m');
93 $dayref = dol_print_date($gmtnow, '%d');
94 if ($refgmtdate == 'now') {
95 $newrefgmtdate = $yearref.'-'.$monthref.'-'.$dayref;
96 } elseif ($refgmtdate == 'summer') {
97 $newrefgmtdate = $yearref.'-08-01';
98 } else {
99 $newrefgmtdate = $yearref.'-01-01';
100 }
101 $newrefgmtdate .= 'T00:00:00+00:00';
102 $localtz = new DateTimeZone(getServerTimeZoneString());
103 $localdt = new DateTime($newrefgmtdate, $localtz);
104 $tmp = -1 * $localtz->getOffset($localdt);
105 //print $refgmtdate.'='.$tmp;
106 } else {
107 $tmp = 0;
108 dol_print_error(null, 'PHP version must be 5.3+');
109 }
110 $tz = round(($tmp < 0 ? 1 : -1) * abs($tmp / 3600));
111 return $tz;
112}
113
114
125function dol_time_plus_duree($time, $duration_value, $duration_unit, $ruleforendofmonth = 0)
126{
127 if (empty($duration_value)) {
128 return $time;
129 }
130 if ($duration_unit == 's') {
131 return $time + (int) ($duration_value);
132 }
133 if ($duration_unit == 'i') {
134 return $time + (int) (60 * $duration_value);
135 }
136 if ($duration_unit == 'h') {
137 return $time + (int) (3600 * $duration_value);
138 }
139 if ($duration_unit == 'w') {
140 return $time + (int) (3600 * 24 * 7 * $duration_value);
141 }
142
143 $deltastring = 'P';
144
145 if ($duration_value > 0) {
146 $deltastring .= abs($duration_value);
147 $sub = false;
148 }
149 if ($duration_value < 0) {
150 $deltastring .= abs($duration_value);
151 $sub = true;
152 }
153 if ($duration_unit == 'd') {
154 $deltastring .= "D";
155 }
156 if ($duration_unit == 'm') {
157 $deltastring .= "M";
158 }
159 if ($duration_unit == 'y') {
160 $deltastring .= "Y";
161 }
162
163 $date = new DateTime();
164 if (getDolGlobalString('MAIN_DATE_IN_MEMORY_ARE_GMT')) {
165 $date->setTimezone(new DateTimeZone('UTC'));
166 }
167 $date->setTimestamp($time);
168 $interval = new DateInterval($deltastring);
169
170 if ($sub) {
171 $date->sub($interval);
172 } else {
173 $date->add($interval);
174 }
175 //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)
176 if ($ruleforendofmonth == 1 && $duration_unit == 'm') {
177 $timeyear = (int) dol_print_date($time, '%Y');
178 $timemonth = (int) dol_print_date($time, '%m');
179 $timetotalmonths = (($timeyear * 12) + $timemonth);
180
181 $monthsexpected = ($timetotalmonths + $duration_value);
182
183 $newtime = $date->getTimestamp();
184
185 $newtimeyear = (int) dol_print_date($newtime, '%Y');
186 $newtimemonth = (int) dol_print_date($newtime, '%m');
187 $newtimetotalmonths = (($newtimeyear * 12) + $newtimemonth);
188
189 if ($monthsexpected < $newtimetotalmonths) {
190 $newtimehours = (int) dol_print_date($newtime, '%H');
191 $newtimemins = (int) dol_print_date($newtime, '%M');
192 $newtimesecs = (int) dol_print_date($newtime, '%S');
193
194 $datelim = dol_mktime($newtimehours, $newtimemins, $newtimesecs, $newtimemonth, 1, $newtimeyear);
195 $datelim -= (3600 * 24);
196
197 $date->setTimestamp($datelim);
198 }
199 }
200 return $date->getTimestamp();
201}
202
203
213function convertTime2Seconds($iHours = 0, $iMinutes = 0, $iSeconds = 0)
214{
215 $iResult = ((int) $iHours * 3600) + ((int) $iMinutes * 60) + (int) $iSeconds;
216 return $iResult;
217}
218
219
242function convertSecondToTime($iSecond, $format = 'all', $lengthOfDay = 86400, $lengthOfWeek = 7)
243{
244 global $langs;
245
246 if (empty($lengthOfDay)) {
247 $lengthOfDay = 86400; // 1 day = 24 hours
248 }
249 if (empty($lengthOfWeek)) {
250 $lengthOfWeek = 7; // 1 week = 7 days
251 }
252 $nbHbyDay = $lengthOfDay / 3600;
253
254 if ($format == 'all' || $format == 'allwithouthour' || $format == 'allhour' || $format == 'allhourmin' || $format == 'allhourminsec') {
255 if ((int) $iSecond === 0) {
256 return '0'; // This is to avoid having 0 return a 12:00 AM for en_US
257 }
258
259 $sTime = '';
260 $sDay = 0;
261 $sWeek = 0;
262
263 if ($iSecond >= $lengthOfDay) {
264 for ($i = $iSecond; $i >= $lengthOfDay; $i -= $lengthOfDay) {
265 $sDay++;
266 $iSecond -= $lengthOfDay;
267 }
268 $dayTranslate = $langs->trans("Day");
269 if ($iSecond >= ($lengthOfDay * 2)) {
270 $dayTranslate = $langs->trans("Days");
271 }
272 }
273
274 if ($lengthOfWeek < 7) {
275 if ($sDay) {
276 if ($sDay >= $lengthOfWeek) {
277 $sWeek = (int) (($sDay - $sDay % $lengthOfWeek) / $lengthOfWeek);
278 $sDay %= $lengthOfWeek;
279 $weekTranslate = $langs->trans("DurationWeek");
280 if ($sWeek >= 2) {
281 $weekTranslate = $langs->trans("DurationWeeks");
282 }
283 $sTime .= $sWeek.' '.$weekTranslate.' ';
284 }
285 }
286 }
287 if ($sDay > 0) {
288 $dayTranslate = $langs->trans("Day");
289 if ($sDay > 1) {
290 $dayTranslate = $langs->trans("Days");
291 }
292 $sTime .= $sDay.' '.$langs->trans("d").' ';
293 }
294
295 if ($format == 'all') {
296 if ($iSecond || empty($sDay)) {
297 $sTime .= dol_print_date($iSecond, 'hourduration', true);
298 }
299 } elseif ($format == 'allhourminsec') {
300 return sprintf("%02d", ($sWeek * $lengthOfWeek * $nbHbyDay + $sDay * $nbHbyDay + (int) floor($iSecond / 3600))).':'.sprintf("%02d", ((int) floor(($iSecond % 3600) / 60))).':'.sprintf("%02d", ((int) ($iSecond % 60)));
301 } elseif ($format == 'allhourmin') {
302 return sprintf("%02d", ($sWeek * $lengthOfWeek * $nbHbyDay + $sDay * $nbHbyDay + (int) floor($iSecond / 3600))).':'.sprintf("%02d", ((int) floor(($iSecond % 3600) / 60)));
303 } elseif ($format == 'allhour') {
304 return sprintf("%02d", ($sWeek * $lengthOfWeek * $nbHbyDay + $sDay * $nbHbyDay + (int) floor($iSecond / 3600)));
305 }
306 } elseif ($format == 'hour') { // only hour part
307 $sTime = dol_print_date($iSecond, '%H', true);
308 } elseif ($format == 'fullhour') {
309 if (!empty($iSecond)) {
310 $iSecond /= 3600;
311 } else {
312 $iSecond = 0;
313 }
314 $sTime = $iSecond;
315 } elseif ($format == 'min') { // only min part
316 $sTime = dol_print_date($iSecond, '%M', true);
317 } elseif ($format == 'sec') { // only sec part
318 $sTime = dol_print_date($iSecond, '%S', true);
319 } elseif ($format == 'month') { // only month part
320 $sTime = dol_print_date($iSecond, '%m', true);
321 } elseif ($format == 'year') { // only year part
322 $sTime = dol_print_date($iSecond, '%Y', true);
323 }
324 return trim($sTime);
325}
326
327
334function convertDurationtoHour($duration_value, $duration_unit)
335{
336 $result = 0;
337
338 if ($duration_unit == 's') {
339 $result = $duration_value / 3600;
340 }
341 if ($duration_unit == 'i') {
342 $result = $duration_value / 60;
343 }
344 if ($duration_unit == 'h') {
345 $result = $duration_value;
346 }
347 if ($duration_unit == 'd') {
348 $result = $duration_value * 24;
349 }
350 if ($duration_unit == 'w') {
351 $result = $duration_value * 24 * 7;
352 }
353 if ($duration_unit == 'm') {
354 $result = $duration_value * 730.484;
355 }
356 if ($duration_unit == 'y') {
357 $result = $duration_value * 365 * 24;
358 }
359
360 return $result;
361}
362
378function dolSqlDateFilter($datefield, $day_date, $month_date, $year_date, $excludefirstand = 0, $gm = false)
379{
380 global $db;
381 $sqldate = '';
382
383 $day_date = intval($day_date);
384 $month_date = intval($month_date);
385 $year_date = intval($year_date);
386
387 if ($month_date > 0) {
388 if ($month_date > 12) { // protection for bad value of month
389 return " AND 1 = 2";
390 }
391 if ($year_date > 0 && empty($day_date)) {
392 $sqldate .= ($excludefirstand ? "" : " AND ").$datefield." BETWEEN '".$db->idate(dol_get_first_day($year_date, $month_date, $gm));
393 $sqldate .= "' AND '".$db->idate(dol_get_last_day($year_date, $month_date, $gm))."'";
394 } elseif ($year_date > 0 && !empty($day_date)) {
395 $sqldate .= ($excludefirstand ? "" : " AND ").$datefield." BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $month_date, $day_date, $year_date, $gm));
396 $sqldate .= "' AND '".$db->idate(dol_mktime(23, 59, 59, $month_date, $day_date, $year_date, $gm))."'";
397 } else {
398 // This case is not reliable on TZ, but we should not need it.
399 $sqldate .= ($excludefirstand ? "" : " AND ")." date_format( ".$datefield.", '%c') = '".$db->escape($month_date)."'";
400 }
401 } elseif ($year_date > 0) {
402 $sqldate .= ($excludefirstand ? "" : " AND ").$datefield." BETWEEN '".$db->idate(dol_get_first_day($year_date, 1, $gm));
403 $sqldate .= "' AND '".$db->idate(dol_get_last_day($year_date, 12, $gm))."'";
404 }
405 return $sqldate;
406}
407
427function dol_stringtotime($string, $gm = 1)
428{
429 $reg = array();
430 // Convert date with format DD/MM/YYY HH:MM:SS. This part of code should not be used.
431 if (preg_match('/^([0-9]+)\/([0-9]+)\/([0-9]+)\s?([0-9]+)?:?([0-9]+)?:?([0-9]+)?/i', $string, $reg)) {
432 dol_syslog("dol_stringtotime call to function with deprecated parameter format", LOG_WARNING);
433 // Date est au format 'DD/MM/YY' ou 'DD/MM/YY HH:MM:SS'
434 // Date est au format 'DD/MM/YYYY' ou 'DD/MM/YYYY HH:MM:SS'
435 $sday = (int) $reg[1];
436 $smonth = (int) $reg[2];
437 $syear = (int) $reg[3];
438 $shour = (int) $reg[4];
439 $smin = (int) $reg[5];
440 $ssec = (int) $reg[6];
441 if ($syear < 50) {
442 $syear += 1900;
443 }
444 if ($syear >= 50 && $syear < 100) {
445 $syear += 2000;
446 }
447 $string = sprintf("%04d%02d%02d%02d%02d%02d", $syear, $smonth, $sday, $shour, $smin, $ssec);
448 } 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)
449 || 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
450 || 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
451 ) {
452 $syear = (int) $reg[1];
453 $smonth = (int) $reg[2];
454 $sday = (int) $reg[3];
455 $shour = (int) $reg[4];
456 $smin = (int) $reg[5];
457 $ssec = (int) $reg[6];
458 $string = sprintf("%04d%02d%02d%02d%02d%02d", $syear, $smonth, $sday, $shour, $smin, $ssec);
459 }
460
461 $string = preg_replace('/([^0-9])/i', '', $string);
462 $tmp = $string.'000000';
463 // Clean $gm
464 if ($gm === 1) {
465 $gm = 'gmt';
466 } elseif (empty($gm) || $gm === 'tzserver') {
467 $gm = 'tzserver';
468 }
469
470 $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);
471
472 return $date;
473}
474
475
484function dol_get_prev_day($day, $month, $year)
485{
486 $time = dol_mktime(12, 0, 0, $month, $day, $year, 1, 0);
487 $time -= 24 * 60 * 60;
488 $tmparray = dol_getdate($time, true);
489 return array('year' => $tmparray['year'], 'month' => $tmparray['mon'], 'day' => $tmparray['mday']);
490}
491
500function dol_get_next_day($day, $month, $year)
501{
502 $time = dol_mktime(12, 0, 0, $month, $day, $year, 1, 0);
503 $time += 24 * 60 * 60;
504 $tmparray = dol_getdate($time, true);
505 return array('year' => $tmparray['year'], 'month' => $tmparray['mon'], 'day' => $tmparray['mday']);
506}
507
515function dol_get_prev_month($month, $year)
516{
517 if ($month == 1) {
518 $prev_month = 12;
519 $prev_year = $year - 1;
520 } else {
521 $prev_month = $month - 1;
522 $prev_year = $year;
523 }
524 return array('year' => $prev_year, 'month' => $prev_month);
525}
526
534function dol_get_next_month($month, $year)
535{
536 if ($month == 12) {
537 $next_month = 1;
538 $next_year = $year + 1;
539 } else {
540 $next_month = $month + 1;
541 $next_year = $year;
542 }
543 return array('year' => $next_year, 'month' => $next_month);
544}
545
555function dol_get_prev_week($day, $week, $month, $year)
556{
557 $tmparray = dol_get_first_day_week($day, $month, $year);
558
559 $time = dol_mktime(12, 0, 0, $month, $tmparray['first_day'], $year, 1, 0);
560 $time -= 24 * 60 * 60 * 7;
561 $tmparray = dol_getdate($time, true);
562 return array('year' => $tmparray['year'], 'month' => $tmparray['mon'], 'day' => $tmparray['mday']);
563}
564
574function dol_get_next_week($day, $week, $month, $year)
575{
576 $tmparray = dol_get_first_day_week($day, $month, $year);
577
578 $time = dol_mktime(12, 0, 0, $tmparray['first_month'], $tmparray['first_day'], $tmparray['first_year'], 1, 0);
579 $time += 24 * 60 * 60 * 7;
580 $tmparray = dol_getdate($time, true);
581
582 return array('year' => $tmparray['year'], 'month' => $tmparray['mon'], 'day' => $tmparray['mday']);
583}
584
596function dol_get_first_day($year, $month = 1, $gm = false)
597{
598 if ($year > 9999) {
599 return '';
600 }
601 return dol_mktime(0, 0, 0, $month, 1, $year, $gm);
602}
603
604
615function dol_get_last_day($year, $month = 12, $gm = false)
616{
617 if ($year > 9999) {
618 return '';
619 }
620 if ($month == 12) {
621 $month = 1;
622 $year += 1;
623 } else {
624 $month += 1;
625 }
626
627 // On se deplace au debut du mois suivant, et on retire un jour
628 $datelim = dol_mktime(23, 59, 59, $month, 1, $year, $gm);
629 $datelim -= (3600 * 24);
630
631 return $datelim;
632}
633
642function dol_get_last_hour($date, $gm = 'tzserver')
643{
644 $tmparray = dol_getdate($date, false, ($gm == 'gmt' ? 'gmt' : ''));
645 return dol_mktime(23, 59, 59, $tmparray['mon'], $tmparray['mday'], $tmparray['year'], $gm);
646}
647
656function dol_get_first_hour($date, $gm = 'tzserver')
657{
658 $tmparray = dol_getdate($date, false, ($gm == 'gmt' ? 'gmt' : ''));
659 return dol_mktime(0, 0, 0, $tmparray['mon'], $tmparray['mday'], $tmparray['year'], $gm);
660}
661
671function dol_get_first_day_week($day, $month, $year, $gm = false)
672{
673 global $conf;
674
675 //$day=2; $month=2; $year=2015;
676 $date = dol_mktime(0, 0, 0, $month, $day, $year, $gm);
677
678 //Checking conf of start week
679 $start_week = (isset($conf->global->MAIN_START_WEEK) ? $conf->global->MAIN_START_WEEK : 1);
680
681 $tmparray = dol_getdate($date, true); // detail of current day
682
683 //Calculate days = offset from current day
684 $days = $start_week - $tmparray['wday'];
685 if ($days >= 1) {
686 $days = 7 - $days;
687 }
688 $days = abs($days);
689 $seconds = $days * 24 * 60 * 60;
690 //print 'start_week='.$start_week.' tmparray[wday]='.$tmparray['wday'].' day offset='.$days.' seconds offset='.$seconds.'<br>';
691
692 //Get first day of week
693 $tmpdaytms = (int) date((string) $tmparray['0']) - $seconds; // $tmparray[0] is day of parameters
694 $tmpday = idate("d", $tmpdaytms);
695
696 //Check first day of week is in same month than current day or not
697 if ($tmpday > $day) {
698 $prev_month = $month - 1;
699 $prev_year = $year;
700
701 if ($prev_month == 0) {
702 $prev_month = 12;
703 $prev_year = $year - 1;
704 }
705 } else {
706 $prev_month = $month;
707 $prev_year = $year;
708 }
709 $tmpmonth = $prev_month;
710 $tmpyear = $prev_year;
711
712 //Get first day of next week
713 $tmptime = dol_mktime(12, 0, 0, $month, $tmpday, $year, 1, 0);
714 $tmptime -= 24 * 60 * 60 * 7;
715 $tmparray = dol_getdate($tmptime, true);
716 $prev_day = $tmparray['mday'];
717
718 //Check prev day of week is in same month than first day or not
719 if ($prev_day > $tmpday) {
720 $prev_month = $month - 1;
721 $prev_year = $year;
722
723 if ($prev_month == 0) {
724 $prev_month = 12;
725 $prev_year = $year - 1;
726 }
727 }
728
729 $week = date("W", dol_mktime(0, 0, 0, $tmpmonth, $tmpday, $tmpyear, $gm));
730
731 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);
732}
733
741function getGMTEasterDatetime($year)
742{
743 $base = new DateTime("$year-03-21", new DateTimeZone("UTC"));
744 $days = easter_days($year); // Return number of days between 21 march and easter day.
745 $tmp = $base->add(new DateInterval("P{$days}D"));
746 return $tmp->getTimestamp();
747}
748
765function num_public_holiday($timestampStart, $timestampEnd, $country_code = '', $lastday = 0, $includesaturday = -1, $includesunday = -1, $includefriday = -1, $includemonday = -1)
766{
767 global $conf, $db, $mysoc;
768
769 $nbFerie = 0;
770
771 // Check to ensure we use correct parameters
772 if (($timestampEnd - $timestampStart) % 86400 != 0) {
773 return 'Error Dates must use same hours and must be GMT dates';
774 }
775
776 if (empty($country_code)) {
777 $country_code = $mysoc->country_code;
778 }
779 if ($includemonday < 0) {
780 $includemonday = getDolGlobalInt('MAIN_NON_WORKING_DAYS_INCLUDE_MONDAY', 0);
781 }
782 if ($includefriday < 0) {
783 $includefriday = getDolGlobalInt('MAIN_NON_WORKING_DAYS_INCLUDE_FRIDAY', 0);
784 }
785 if ($includesaturday < 0) {
786 $includesaturday = getDolGlobalInt('MAIN_NON_WORKING_DAYS_INCLUDE_SATURDAY', 1);
787 }
788 if ($includesunday < 0) {
789 $includesunday = getDolGlobalInt('MAIN_NON_WORKING_DAYS_INCLUDE_SUNDAY', 1);
790 }
791
792 $country_id = dol_getIdFromCode($db, $country_code, 'c_country', 'code', 'rowid');
793
794 if (empty($conf->cache['arrayOfActivePublicHolidays_'.$country_id])) {
795 // Loop on public holiday defined into hrm_public_holiday for the day, month and year analyzed
796 $tmpArrayOfPublicHolidays = array();
797 $sql = "SELECT id, code, entity, fk_country, dayrule, year, month, day, active";
798 $sql .= " FROM ".MAIN_DB_PREFIX."c_hrm_public_holiday";
799 $sql .= " WHERE active = 1 and fk_country IN (0".($country_id > 0 ? ", ".$country_id : 0).")";
800 $sql .= " AND entity IN (0," .getEntity('holiday') .")";
801
802 $resql = $db->query($sql);
803 if ($resql) {
804 $num_rows = $db->num_rows($resql);
805 $i = 0;
806 while ($i < $num_rows) {
807 $obj = $db->fetch_object($resql);
808 $tmpArrayOfPublicHolidays[$obj->id] = array('dayrule' => $obj->dayrule, 'year' => $obj->year, 'month' => $obj->month, 'day' => $obj->day);
809 $i++;
810 }
811 } else {
812 dol_syslog($db->lasterror(), LOG_ERR);
813 return 'Error sql '.$db->lasterror();
814 }
815
816 //var_dump($tmpArrayOfPublicHolidays);
817 $conf->cache['arrayOfActivePublicHolidays_'.$country_id] = $tmpArrayOfPublicHolidays;
818 }
819
820 $arrayOfPublicHolidays = $conf->cache['arrayOfActivePublicHolidays_'.$country_id];
821
822 $i = 0;
823 while ((($lastday == 0 && $timestampStart < $timestampEnd) || ($lastday && $timestampStart <= $timestampEnd))
824 && ($i < 50000)) { // Loop end when equals (Test on i is a security loop to avoid infinite loop)
825 $ferie = false;
826 $specialdayrule = array();
827
828 $jour = (int) gmdate("d", $timestampStart);
829 $mois = (int) gmdate("m", $timestampStart);
830 $annee = (int) gmdate("Y", $timestampStart);
831
832 //print "jour=".$jour." month=".$mois." year=".$annee." includesaturday=".$includesaturday." includesunday=".$includesunday."\n";
833 foreach ($arrayOfPublicHolidays as $entrypublicholiday) {
834 if (!empty($entrypublicholiday['dayrule']) && $entrypublicholiday['dayrule'] != 'date') { // For example 'easter', '...'
835 $specialdayrule[$entrypublicholiday['dayrule']] = $entrypublicholiday['dayrule'];
836 } else {
837 $match = 1;
838 if (!empty($entrypublicholiday['year']) && $entrypublicholiday['year'] != $annee) {
839 $match = 0;
840 }
841 if ($entrypublicholiday['month'] != $mois) {
842 $match = 0;
843 }
844 if ($entrypublicholiday['day'] != $jour) {
845 $match = 0;
846 }
847
848 if ($match) {
849 $ferie = true;
850 }
851 }
852
853 $i++;
854 }
855 //var_dump($specialdayrule)."\n";
856 //print "ferie=".$ferie."\n";
857
858 if (!$ferie) {
859 // Special dayrules
860 if (in_array('easter', $specialdayrule)) {
861 // Calculation for easter date
862 $date_paques = getGMTEasterDatetime($annee);
863 $jour_paques = gmdate("d", $date_paques);
864 $mois_paques = gmdate("m", $date_paques);
865 if ($jour_paques == $jour && $mois_paques == $mois) {
866 $ferie = true;
867 }
868 // Easter (sunday)
869 }
870
871 if (in_array('eastermonday', $specialdayrule)) {
872 // Calculation for the monday of easter date
873 $date_paques = getGMTEasterDatetime($annee);
874 //print 'PPP'.$date_paques.' '.dol_print_date($date_paques, 'dayhour', 'gmt')." ";
875 $date_lundi_paques = $date_paques + (3600 * 24);
876 $jour_lundi_paques = gmdate("d", $date_lundi_paques);
877 $mois_lundi_paques = gmdate("m", $date_lundi_paques);
878 if ($jour_lundi_paques == $jour && $mois_lundi_paques == $mois) {
879 $ferie = true;
880 }
881 // Easter (monday)
882 //print 'annee='.$annee.' $jour='.$jour.' $mois='.$mois.' $jour_lundi_paques='.$jour_lundi_paques.' $mois_lundi_paques='.$mois_lundi_paques."\n";
883 }
884
885 //Good Friday
886 if (in_array('goodfriday', $specialdayrule)) {
887 // Pulls the date of Easter
888 $easter = getGMTEasterDatetime($annee);
889
890 // Calculates the date of Good Friday based on Easter
891 $date_good_friday = $easter - (2 * 3600 * 24);
892 $dom_good_friday = gmdate("d", $date_good_friday);
893 $month_good_friday = gmdate("m", $date_good_friday);
894
895 if ($dom_good_friday == $jour && $month_good_friday == $mois) {
896 $ferie = true;
897 }
898 }
899
900 if (in_array('ascension', $specialdayrule)) {
901 // Calcul du jour de l'ascension (39 days after easter day)
902 $date_paques = getGMTEasterDatetime($annee);
903 $date_ascension = $date_paques + (3600 * 24 * 39);
904 $jour_ascension = gmdate("d", $date_ascension);
905 $mois_ascension = gmdate("m", $date_ascension);
906 if ($jour_ascension == $jour && $mois_ascension == $mois) {
907 $ferie = true;
908 }
909 // Ascension (thursday)
910 }
911
912 if (in_array('pentecost', $specialdayrule)) {
913 // Calculation of "Pentecote" (49 days after easter day)
914 $date_paques = getGMTEasterDatetime($annee);
915 $date_pentecote = $date_paques + (3600 * 24 * 49);
916 $jour_pentecote = gmdate("d", $date_pentecote);
917 $mois_pentecote = gmdate("m", $date_pentecote);
918 if ($jour_pentecote == $jour && $mois_pentecote == $mois) {
919 $ferie = true;
920 }
921 // "Pentecote" (sunday)
922 }
923 if (in_array('pentecotemonday', $specialdayrule)) {
924 // Calculation of "Pentecote" (49 days after easter day)
925 $date_paques = getGMTEasterDatetime($annee);
926 $date_pentecote = $date_paques + (3600 * 24 * 50);
927 $jour_pentecote = gmdate("d", $date_pentecote);
928 $mois_pentecote = gmdate("m", $date_pentecote);
929 if ($jour_pentecote == $jour && $mois_pentecote == $mois) {
930 $ferie = true;
931 }
932 // "Pentecote" (monday)
933 }
934
935 if (in_array('viernessanto', $specialdayrule)) {
936 // Viernes Santo
937 $date_paques = getGMTEasterDatetime($annee);
938 $date_viernes = $date_paques - (3600 * 24 * 2);
939 $jour_viernes = gmdate("d", $date_viernes);
940 $mois_viernes = gmdate("m", $date_viernes);
941 if ($jour_viernes == $jour && $mois_viernes == $mois) {
942 $ferie = true;
943 }
944 //Viernes Santo
945 }
946
947 if (in_array('fronleichnam', $specialdayrule)) {
948 // Fronleichnam (60 days after easter sunday)
949 $date_paques = getGMTEasterDatetime($annee);
950 $date_fronleichnam = $date_paques + (3600 * 24 * 60);
951 $jour_fronleichnam = gmdate("d", $date_fronleichnam);
952 $mois_fronleichnam = gmdate("m", $date_fronleichnam);
953 if ($jour_fronleichnam == $jour && $mois_fronleichnam == $mois) {
954 $ferie = true;
955 }
956 // Fronleichnam
957 }
958
959 if (in_array('genevafast', $specialdayrule)) {
960 // Geneva fast in Switzerland (Thursday after the first sunday in September)
961 $date_1sunsept = strtotime('next thursday', strtotime('next sunday', mktime(0, 0, 0, 9, 1, $annee)));
962 $jour_1sunsept = date("d", $date_1sunsept);
963 $mois_1sunsept = date("m", $date_1sunsept);
964 if ($jour_1sunsept == $jour && $mois_1sunsept == $mois) {
965 $ferie = true;
966 }
967 // Geneva fast in Switzerland
968 }
969 }
970 //print "ferie=".$ferie."\n";
971
972 // If we have to include Friday, Saturday and Sunday
973 if (!$ferie) {
974 if ($includefriday || $includesaturday || $includesunday) {
975 $jour_julien = unixtojd($timestampStart);
976 $jour_semaine = jddayofweek($jour_julien, 0);
977 if ($includefriday) { //Friday (5), Saturday (6) and Sunday (0)
978 if ($jour_semaine == 5) {
979 $ferie = true;
980 }
981 }
982 if ($includesaturday) { //Friday (5), Saturday (6) and Sunday (0)
983 if ($jour_semaine == 6) {
984 $ferie = true;
985 }
986 }
987 if ($includesunday) { //Friday (5), Saturday (6) and Sunday (0)
988 if ($jour_semaine == 0) {
989 $ferie = true;
990 }
991 }
992 }
993 }
994 //print "ferie=".$ferie."\n";
995
996 // We increase the counter of non working day
997 if ($ferie) {
998 $nbFerie++;
999 }
1000
1001 // Increase number of days (on go up into loop)
1002 $timestampStart = dol_time_plus_duree($timestampStart, 1, 'd');
1003 //var_dump($jour.' '.$mois.' '.$annee.' '.$timestampStart);
1004
1005 $i++;
1006 }
1007
1008 //print "nbFerie=".$nbFerie."\n";
1009 return $nbFerie;
1010}
1011
1022function num_between_day($timestampStart, $timestampEnd, $lastday = 0)
1023{
1024 if ($timestampStart < $timestampEnd) {
1025 if ($lastday == 1) {
1026 $bit = 0;
1027 } else {
1028 $bit = 1;
1029 }
1030 $nbjours = (int) floor(($timestampEnd - $timestampStart) / (60 * 60 * 24)) + 1 - $bit;
1031 } else {
1032 $nbjours = 0;
1033 }
1034 //print ($timestampEnd - $timestampStart) - $lastday;
1035 return $nbjours;
1036}
1037
1050function num_open_day($timestampStart, $timestampEnd, $inhour = 0, $lastday = 0, $halfday = 0, $country_code = '')
1051{
1052 global $langs, $mysoc;
1053
1054 if (empty($country_code)) {
1055 $country_code = $mysoc->country_code;
1056 }
1057
1058 dol_syslog('num_open_day timestampStart='.$timestampStart.' timestampEnd='.$timestampEnd.' bit='.$lastday.' country_code='.$country_code);
1059
1060 // Check parameters
1061 if (!is_int($timestampStart) && !is_float($timestampStart)) {
1062 return 'ErrorBadParameter_num_open_day';
1063 }
1064 if (!is_int($timestampEnd) && !is_float($timestampEnd)) {
1065 return 'ErrorBadParameter_num_open_day';
1066 }
1067
1068 //print 'num_open_day timestampStart='.$timestampStart.' timestampEnd='.$timestampEnd.' bit='.$lastday;
1069 if ($timestampStart < $timestampEnd) {
1070 $numdays = num_between_day($timestampStart, $timestampEnd, $lastday);
1071
1072 $numholidays = num_public_holiday($timestampStart, $timestampEnd, $country_code, $lastday);
1073 $nbOpenDay = ($numdays - $numholidays);
1074 if ($inhour == 1 && $nbOpenDay <= 3) {
1075 $nbOpenDay *= 24;
1076 }
1077 return $nbOpenDay - (($inhour == 1 ? 12 : 0.5) * abs($halfday));
1078 } elseif ($timestampStart == $timestampEnd) {
1079 $numholidays = 0;
1080 if ($lastday) {
1081 $numholidays = num_public_holiday($timestampStart, $timestampEnd, $country_code, $lastday);
1082 if ($numholidays == 1) {
1083 return 0;
1084 }
1085 }
1086
1087 $nbOpenDay = $lastday;
1088
1089 if ($inhour == 1) {
1090 $nbOpenDay *= 24;
1091 }
1092 return $nbOpenDay - (($inhour == 1 ? 12 : 0.5) * abs($halfday));
1093 } else {
1094 return $langs->trans("Error");
1095 }
1096}
1097
1098
1099
1108function monthArray($outputlangs, $short = 0)
1109{
1110 $montharray = array(
1111 1 => $outputlangs->trans("Month01"),
1112 2 => $outputlangs->trans("Month02"),
1113 3 => $outputlangs->trans("Month03"),
1114 4 => $outputlangs->trans("Month04"),
1115 5 => $outputlangs->trans("Month05"),
1116 6 => $outputlangs->trans("Month06"),
1117 7 => $outputlangs->trans("Month07"),
1118 8 => $outputlangs->trans("Month08"),
1119 9 => $outputlangs->trans("Month09"),
1120 10 => $outputlangs->trans("Month10"),
1121 11 => $outputlangs->trans("Month11"),
1122 12 => $outputlangs->trans("Month12")
1123 );
1124
1125 if (!empty($short)) {
1126 $montharray = array(
1127 1 => $outputlangs->trans("MonthShort01"),
1128 2 => $outputlangs->trans("MonthShort02"),
1129 3 => $outputlangs->trans("MonthShort03"),
1130 4 => $outputlangs->trans("MonthShort04"),
1131 5 => $outputlangs->trans("MonthShort05"),
1132 6 => $outputlangs->trans("MonthShort06"),
1133 7 => $outputlangs->trans("MonthShort07"),
1134 8 => $outputlangs->trans("MonthShort08"),
1135 9 => $outputlangs->trans("MonthShort09"),
1136 10 => $outputlangs->trans("MonthShort10"),
1137 11 => $outputlangs->trans("MonthShort11"),
1138 12 => $outputlangs->trans("MonthShort12")
1139 );
1140 }
1141
1142 return $montharray;
1143}
1144
1152function getWeekNumbersOfMonth($month, $year)
1153{
1154 $nb_days = cal_days_in_month(CAL_GREGORIAN, $month, $year);
1155 $TWeek = array();
1156 for ($day = 1; $day < $nb_days; $day++) {
1157 $week_number = getWeekNumber($day, $month, $year);
1158 $TWeek[$week_number] = $week_number;
1159 }
1160 return $TWeek;
1161}
1162
1170function getFirstDayOfEachWeek($TWeek, $year)
1171{
1172 $TFirstDayOfWeek = array();
1173 foreach ($TWeek as $weekNb) {
1174 if (in_array('01', $TWeek) && in_array('52', $TWeek) && $weekNb == '01') {
1175 $year++; //Si on a la 1re semaine et la semaine 52 c'est qu'on change d'année
1176 }
1177 $TFirstDayOfWeek[$weekNb] = date('d', strtotime($year.'W'.$weekNb));
1178 }
1179 return $TFirstDayOfWeek;
1180}
1181
1189function getLastDayOfEachWeek($TWeek, $year)
1190{
1191 $TLastDayOfWeek = array();
1192 foreach ($TWeek as $weekNb) {
1193 $TLastDayOfWeek[$weekNb] = date('d', strtotime($year.'W'.$weekNb.'+6 days'));
1194 }
1195 return $TLastDayOfWeek;
1196}
1197
1206function getWeekNumber($day, $month, $year)
1207{
1208 $date = new DateTime($year.'-'.$month.'-'.$day);
1209 $week = $date->format("W");
1210 return $week;
1211}
dol_get_prev_month($month, $year)
Return previous month.
Definition date.lib.php:515
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:656
dol_get_next_day($day, $month, $year)
Return next day.
Definition date.lib.php:500
dol_get_next_week($day, $week, $month, $year)
Return next week.
Definition date.lib.php:574
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:378
getServerTimeZoneString()
Return server timezone string.
Definition date.lib.php:75
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:642
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:86
dol_get_first_day_week($day, $month, $year, $gm=false)
Return first day of week for a date.
Definition date.lib.php:671
getGMTEasterDatetime($year)
Return the easter day in GMT time.
Definition date.lib.php:741
convertDurationtoHour($duration_value, $duration_unit)
Convert duration to hour.
Definition date.lib.php:334
get_tz_array()
Return an array with timezone values.
Definition date.lib.php:36
dol_get_prev_day($day, $month, $year)
Return previous day.
Definition date.lib.php:484
dol_get_first_day($year, $month=1, $gm=false)
Return GMT time for first day of a month or year.
Definition date.lib.php:596
getFirstDayOfEachWeek($TWeek, $year)
Return array of first day of weeks.
dol_get_next_month($month, $year)
Return next month.
Definition date.lib.php:534
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...
convertTime2Seconds($iHours=0, $iMinutes=0, $iSeconds=0)
Convert hours and minutes into seconds.
Definition date.lib.php:213
num_open_day($timestampStart, $timestampEnd, $inhour=0, $lastday=0, $halfday=0, $country_code='')
Function to return number of working days (and text of units) between two dates (working days)
dol_time_plus_duree($time, $duration_value, $duration_unit, $ruleforendofmonth=0)
Add a delay to a date.
Definition date.lib.php:125
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:242
dol_get_prev_week($day, $week, $month, $year)
Return previous week.
Definition date.lib.php:555
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:427
dol_get_last_day($year, $month=12, $gm=false)
Return GMT time for last day of a month or year.
Definition date.lib.php:615
monthArray($outputlangs, $short=0)
Return array of translated months or selected month.
num_public_holiday($timestampStart, $timestampEnd, $country_code='', $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:765
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_now($mode='auto')
Return date for now.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
dol_getIdFromCode($db, $key, $tablename, $fieldkey='code', $fieldid='id', $entityfilter=0, $filters='')
Return an id or code from a code or id.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false)
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.
dol_getdate($timestamp, $fast=false, $forcetimezone='')
Return an array with locale date info.