dolibarr 21.0.0-beta
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' || $duration_unit == 'mn' || $duration_unit == 'min') {
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 $sub = false;
146
147 if ($duration_value > 0) {
148 $deltastring .= abs($duration_value);
149 $sub = false;
150 }
151 if ($duration_value < 0) {
152 $deltastring .= abs($duration_value);
153 $sub = true;
154 }
155 if ($duration_unit == 'd') {
156 $deltastring .= "D";
157 }
158 if ($duration_unit == 'm') {
159 $deltastring .= "M";
160 }
161 if ($duration_unit == 'y') {
162 $deltastring .= "Y";
163 }
164
165 $date = new DateTime();
166 if (getDolGlobalString('MAIN_DATE_IN_MEMORY_ARE_GMT')) {
167 $date->setTimezone(new DateTimeZone('UTC'));
168 }
169 $date->setTimestamp($time);
170 $interval = new DateInterval($deltastring);
171
172 if ($sub) {
173 $date->sub($interval);
174 } else {
175 $date->add($interval);
176 }
177 //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)
178 if ($ruleforendofmonth == 1 && $duration_unit == 'm') {
179 $timeyear = (int) dol_print_date($time, '%Y');
180 $timemonth = (int) dol_print_date($time, '%m');
181 $timetotalmonths = (($timeyear * 12) + $timemonth);
182
183 $monthsexpected = ($timetotalmonths + $duration_value);
184
185 $newtime = $date->getTimestamp();
186
187 $newtimeyear = (int) dol_print_date($newtime, '%Y');
188 $newtimemonth = (int) dol_print_date($newtime, '%m');
189 $newtimetotalmonths = (($newtimeyear * 12) + $newtimemonth);
190
191 if ($monthsexpected < $newtimetotalmonths) {
192 $newtimehours = (int) dol_print_date($newtime, '%H');
193 $newtimemins = (int) dol_print_date($newtime, '%M');
194 $newtimesecs = (int) dol_print_date($newtime, '%S');
195
196 $datelim = dol_mktime($newtimehours, $newtimemins, $newtimesecs, $newtimemonth, 1, $newtimeyear);
197 $datelim -= (3600 * 24);
198
199 $date->setTimestamp($datelim);
200 }
201 }
202 return $date->getTimestamp();
203}
204
205
215function convertTime2Seconds($iHours = 0, $iMinutes = 0, $iSeconds = 0)
216{
217 $iResult = ((int) $iHours * 3600) + ((int) $iMinutes * 60) + (int) $iSeconds;
218 return $iResult;
219}
220
221
244function convertSecondToTime($iSecond, $format = 'all', $lengthOfDay = 86400, $lengthOfWeek = 7)
245{
246 global $langs;
247
248 if (empty($lengthOfDay)) {
249 $lengthOfDay = 86400; // 1 day = 24 hours
250 }
251 if (empty($lengthOfWeek)) {
252 $lengthOfWeek = 7; // 1 week = 7 days
253 }
254 $nbHbyDay = $lengthOfDay / 3600;
255
256 $sTime = '';
257
258 if ($format == 'all' || $format == 'allwithouthour' || $format == 'allhour' || $format == 'allhourmin' || $format == 'allhourminsec') {
259 if ((int) $iSecond === 0) {
260 return '0'; // This is to avoid having 0 return a 12:00 AM for en_US
261 }
262
263 $sDay = 0;
264 $sWeek = 0;
265
266 if ($iSecond >= $lengthOfDay) {
267 for ($i = $iSecond; $i >= $lengthOfDay; $i -= $lengthOfDay) {
268 $sDay++;
269 $iSecond -= $lengthOfDay;
270 }
271 $dayTranslate = $langs->trans("Day");
272 if ($iSecond >= ($lengthOfDay * 2)) {
273 $dayTranslate = $langs->trans("Days");
274 }
275 }
276
277 if ($lengthOfWeek < 7) {
278 if ($sDay) {
279 if ($sDay >= $lengthOfWeek) {
280 $sWeek = (int) (($sDay - $sDay % $lengthOfWeek) / $lengthOfWeek);
281 $sDay %= $lengthOfWeek;
282 $weekTranslate = $langs->trans("DurationWeek");
283 if ($sWeek >= 2) {
284 $weekTranslate = $langs->trans("DurationWeeks");
285 }
286 $sTime .= $sWeek.' '.$weekTranslate.' ';
287 }
288 }
289 }
290 if ($sDay > 0) {
291 $dayTranslate = $langs->trans("Day");
292 if ($sDay > 1) {
293 $dayTranslate = $langs->trans("Days");
294 }
295 $sTime .= $sDay.' '.$langs->trans("d").' ';
296 }
297
298 if ($format == 'all') {
299 if ($iSecond || empty($sDay)) {
300 $sTime .= dol_print_date($iSecond, 'hourduration', true);
301 }
302 } elseif ($format == 'allhourminsec') {
303 return sprintf("%02d", ($sWeek * $lengthOfWeek * $nbHbyDay + $sDay * $nbHbyDay + (int) floor($iSecond / 3600))).':'.sprintf("%02d", ((int) floor(($iSecond % 3600) / 60))).':'.sprintf("%02d", ((int) ($iSecond % 60)));
304 } elseif ($format == 'allhourmin') {
305 return sprintf("%02d", ($sWeek * $lengthOfWeek * $nbHbyDay + $sDay * $nbHbyDay + (int) floor($iSecond / 3600))).':'.sprintf("%02d", ((int) floor(($iSecond % 3600) / 60)));
306 } elseif ($format == 'allhour') {
307 return sprintf("%02d", ($sWeek * $lengthOfWeek * $nbHbyDay + $sDay * $nbHbyDay + (int) floor($iSecond / 3600)));
308 }
309 } elseif ($format == 'hour') { // only hour part
310 $sTime = dol_print_date($iSecond, '%H', true);
311 } elseif ($format == 'fullhour') {
312 if (!empty($iSecond)) {
313 $iSecond /= 3600;
314 } else {
315 $iSecond = 0;
316 }
317 $sTime = $iSecond;
318 } elseif ($format == 'min') { // only min part
319 $sTime = dol_print_date($iSecond, '%M', true);
320 } elseif ($format == 'sec') { // only sec part
321 $sTime = dol_print_date($iSecond, '%S', true);
322 } elseif ($format == 'month') { // only month part
323 $sTime = dol_print_date($iSecond, '%m', true);
324 } elseif ($format == 'year') { // only year part
325 $sTime = dol_print_date($iSecond, '%Y', true);
326 }
327 return trim((string) $sTime);
328}
329
330
338function convertDurationtoHour($duration_value, $duration_unit)
339{
340 $result = 0;
341
342 if ($duration_unit == 's') {
343 $result = $duration_value / 3600;
344 }
345 if ($duration_unit == 'i' || $duration_unit == 'mn' || $duration_unit == 'min') {
346 $result = $duration_value / 60;
347 }
348 if ($duration_unit == 'h') {
349 $result = $duration_value;
350 }
351 if ($duration_unit == 'd') {
352 $result = $duration_value * 24;
353 }
354 if ($duration_unit == 'w') {
355 $result = $duration_value * 24 * 7;
356 }
357 if ($duration_unit == 'm') {
358 $result = $duration_value * 730.484;
359 }
360 if ($duration_unit == 'y') {
361 $result = $duration_value * 365 * 24;
362 }
363
364 return $result;
365}
366
382function dolSqlDateFilter($datefield, $day_date, $month_date, $year_date, $excludefirstand = 0, $gm = false)
383{
384 global $db;
385 $sqldate = '';
386
387 $day_date = intval($day_date);
388 $month_date = intval($month_date);
389 $year_date = intval($year_date);
390
391 if ($month_date > 0) {
392 if ($month_date > 12) { // protection for bad value of month
393 return " AND 1 = 2";
394 }
395 if ($year_date > 0 && empty($day_date)) {
396 $sqldate .= ($excludefirstand ? "" : " AND ").$datefield." BETWEEN '".$db->idate(dol_get_first_day($year_date, $month_date, $gm));
397 $sqldate .= "' AND '".$db->idate(dol_get_last_day($year_date, $month_date, $gm))."'";
398 } elseif ($year_date > 0 && !empty($day_date)) {
399 $sqldate .= ($excludefirstand ? "" : " AND ").$datefield." BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $month_date, $day_date, $year_date, $gm));
400 $sqldate .= "' AND '".$db->idate(dol_mktime(23, 59, 59, $month_date, $day_date, $year_date, $gm))."'";
401 } else {
402 // This case is not reliable on TZ, but we should not need it.
403 $sqldate .= ($excludefirstand ? "" : " AND ")." date_format( ".$datefield.", '%c') = '".$db->escape($month_date)."'";
404 }
405 } elseif ($year_date > 0) {
406 $sqldate .= ($excludefirstand ? "" : " AND ").$datefield." BETWEEN '".$db->idate(dol_get_first_day($year_date, 1, $gm));
407 $sqldate .= "' AND '".$db->idate(dol_get_last_day($year_date, 12, $gm))."'";
408 }
409 return $sqldate;
410}
411
431function dol_stringtotime($string, $gm = 1)
432{
433 $reg = array();
434 // Convert date with format DD/MM/YYY HH:MM:SS. This part of code should not be used.
435 if (preg_match('/^([0-9]+)\/([0-9]+)\/([0-9]+)\s?([0-9]+)?:?([0-9]+)?:?([0-9]+)?/i', $string, $reg)) {
436 dol_syslog("dol_stringtotime call to function with deprecated parameter format", LOG_WARNING);
437 // Date est au format 'DD/MM/YY' ou 'DD/MM/YY HH:MM:SS'
438 // Date est au format 'DD/MM/YYYY' ou 'DD/MM/YYYY HH:MM:SS'
439 $sday = (int) $reg[1];
440 $smonth = (int) $reg[2];
441 $syear = (int) $reg[3];
442 $shour = (int) $reg[4];
443 $smin = (int) $reg[5];
444 $ssec = (int) $reg[6];
445 if ($syear < 50) {
446 $syear += 1900;
447 }
448 if ($syear >= 50 && $syear < 100) {
449 $syear += 2000;
450 }
451 $string = sprintf("%04d%02d%02d%02d%02d%02d", $syear, $smonth, $sday, $shour, $smin, $ssec);
452 } 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)
453 || 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
454 || 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
455 ) {
456 $syear = (int) $reg[1];
457 $smonth = (int) $reg[2];
458 $sday = (int) $reg[3];
459 $shour = (int) $reg[4];
460 $smin = (int) $reg[5];
461 $ssec = (int) $reg[6];
462 $string = sprintf("%04d%02d%02d%02d%02d%02d", $syear, $smonth, $sday, $shour, $smin, $ssec);
463 }
464
465 $string = preg_replace('/([^0-9])/i', '', $string);
466 $tmp = $string.'000000';
467 // Clean $gm
468 if ($gm === 1) {
469 $gm = 'gmt';
470 } elseif (empty($gm) || $gm === 'tzserver') {
471 $gm = 'tzserver';
472 }
473
474 $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);
475
476 return $date;
477}
478
479
488function dol_get_prev_day($day, $month, $year)
489{
490 $time = dol_mktime(12, 0, 0, $month, $day, $year, 1, 0);
491 $time -= 24 * 60 * 60;
492 $tmparray = dol_getdate($time, true);
493 return array('year' => $tmparray['year'], 'month' => $tmparray['mon'], 'day' => $tmparray['mday']);
494}
495
504function dol_get_next_day($day, $month, $year)
505{
506 $time = dol_mktime(12, 0, 0, $month, $day, $year, 1, 0);
507 $time += 24 * 60 * 60;
508 $tmparray = dol_getdate($time, true);
509 return array('year' => $tmparray['year'], 'month' => $tmparray['mon'], 'day' => $tmparray['mday']);
510}
511
519function dol_get_prev_month($month, $year)
520{
521 if ($month == 1) {
522 $prev_month = 12;
523 $prev_year = $year - 1;
524 } else {
525 $prev_month = $month - 1;
526 $prev_year = $year;
527 }
528 return array('year' => $prev_year, 'month' => $prev_month);
529}
530
538function dol_get_next_month($month, $year)
539{
540 if ($month == 12) {
541 $next_month = 1;
542 $next_year = $year + 1;
543 } else {
544 $next_month = $month + 1;
545 $next_year = $year;
546 }
547 return array('year' => $next_year, 'month' => $next_month);
548}
549
559function dol_get_prev_week($day, $week, $month, $year)
560{
561 $tmparray = dol_get_first_day_week($day, $month, $year);
562
563 $time = dol_mktime(12, 0, 0, $month, $tmparray['first_day'], $year, 1, 0);
564 $time -= 24 * 60 * 60 * 7;
565 $tmparray = dol_getdate($time, true);
566 return array('year' => $tmparray['year'], 'month' => $tmparray['mon'], 'day' => $tmparray['mday']);
567}
568
578function dol_get_next_week($day, $week, $month, $year)
579{
580 $tmparray = dol_get_first_day_week($day, $month, $year);
581
582 $time = dol_mktime(12, 0, 0, $tmparray['first_month'], $tmparray['first_day'], $tmparray['first_year'], 1, 0);
583 $time += 24 * 60 * 60 * 7;
584 $tmparray = dol_getdate($time, true);
585
586 return array('year' => $tmparray['year'], 'month' => $tmparray['mon'], 'day' => $tmparray['mday']);
587}
588
600function dol_get_first_day($year, $month = 1, $gm = false)
601{
602 if ($year > 9999) {
603 return '';
604 }
605 return dol_mktime(0, 0, 0, $month, 1, $year, $gm);
606}
607
608
619function dol_get_last_day($year, $month = 12, $gm = false)
620{
621 if ($year > 9999) {
622 return '';
623 }
624 if ($month == 12) {
625 $month = 1;
626 $year += 1;
627 } else {
628 $month += 1;
629 }
630
631 // On se deplace au debut du mois suivant, et on retire un jour
632 $datelim = dol_mktime(23, 59, 59, $month, 1, $year, $gm);
633 $datelim -= (3600 * 24);
634
635 return $datelim;
636}
637
646function dol_get_last_hour($date, $gm = 'tzserver')
647{
648 $tmparray = dol_getdate($date, false, ($gm == 'gmt' ? 'gmt' : ''));
649 return dol_mktime(23, 59, 59, $tmparray['mon'], $tmparray['mday'], $tmparray['year'], $gm);
650}
651
660function dol_get_first_hour($date, $gm = 'tzserver')
661{
662 $tmparray = dol_getdate($date, false, ($gm == 'gmt' ? 'gmt' : ''));
663 return dol_mktime(0, 0, 0, $tmparray['mon'], $tmparray['mday'], $tmparray['year'], $gm);
664}
665
675function dol_get_first_day_week($day, $month, $year, $gm = false)
676{
677 global $conf;
678
679 //$day=2; $month=2; $year=2015;
680 $date = dol_mktime(0, 0, 0, $month, $day, $year, $gm);
681
682 //Checking conf of start week
683 $start_week = (isset($conf->global->MAIN_START_WEEK) ? $conf->global->MAIN_START_WEEK : 1);
684
685 $tmparray = dol_getdate($date, true); // detail of current day
686
687 //Calculate days = offset from current day
688 $days = $start_week - $tmparray['wday'];
689 if ($days >= 1) {
690 $days = 7 - $days;
691 }
692 $days = abs($days);
693 $seconds = $days * 24 * 60 * 60;
694 //print 'start_week='.$start_week.' tmparray[wday]='.$tmparray['wday'].' day offset='.$days.' seconds offset='.$seconds.'<br>';
695
696 //Get first day of week
697 $tmpdaytms = (int) date((string) $tmparray['0']) - $seconds; // $tmparray[0] is day of parameters
698 $tmpday = idate("d", $tmpdaytms);
699
700 //Check first day of week is in same month than current day or not
701 if ($tmpday > $day) {
702 $prev_month = $month - 1;
703 $prev_year = $year;
704
705 if ($prev_month == 0) {
706 $prev_month = 12;
707 $prev_year = $year - 1;
708 }
709 } else {
710 $prev_month = $month;
711 $prev_year = $year;
712 }
713 $tmpmonth = $prev_month;
714 $tmpyear = $prev_year;
715
716 //Get first day of next week
717 $tmptime = dol_mktime(12, 0, 0, $month, $tmpday, $year, 1, 0);
718 $tmptime -= 24 * 60 * 60 * 7;
719 $tmparray = dol_getdate($tmptime, true);
720 $prev_day = $tmparray['mday'];
721
722 //Check prev day of week is in same month than first day or not
723 if ($prev_day > $tmpday) {
724 $prev_month = $month - 1;
725 $prev_year = $year;
726
727 if ($prev_month == 0) {
728 $prev_month = 12;
729 $prev_year = $year - 1;
730 }
731 }
732
733 $week = date("W", dol_mktime(0, 0, 0, $tmpmonth, $tmpday, $tmpyear, $gm));
734
735 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);
736}
737
745function getGMTEasterDatetime($year)
746{
747 $base = new DateTime("$year-03-21", new DateTimeZone("UTC"));
748 $days = easter_days($year); // Return number of days between 21 march and easter day.
749 $tmp = $base->add(new DateInterval("P{$days}D"));
750 return $tmp->getTimestamp();
751}
752
769function num_public_holiday($timestampStart, $timestampEnd, $country_code = '', $lastday = 0, $includesaturday = -1, $includesunday = -1, $includefriday = -1, $includemonday = -1)
770{
771 global $conf, $db, $mysoc;
772
773 $nbFerie = 0;
774
775 // Check to ensure we use correct parameters
776 if (($timestampEnd - $timestampStart) % 86400 != 0) {
777 return 'Error Dates must use same hours and must be GMT dates';
778 }
779
780 if (empty($country_code)) {
781 $country_code = $mysoc->country_code;
782 }
783 if ($includemonday < 0) {
784 $includemonday = getDolGlobalInt('MAIN_NON_WORKING_DAYS_INCLUDE_MONDAY', 0);
785 }
786 if ($includefriday < 0) {
787 $includefriday = getDolGlobalInt('MAIN_NON_WORKING_DAYS_INCLUDE_FRIDAY', 0);
788 }
789 if ($includesaturday < 0) {
790 $includesaturday = getDolGlobalInt('MAIN_NON_WORKING_DAYS_INCLUDE_SATURDAY', 1);
791 }
792 if ($includesunday < 0) {
793 $includesunday = getDolGlobalInt('MAIN_NON_WORKING_DAYS_INCLUDE_SUNDAY', 1);
794 }
795
796 $country_id = dol_getIdFromCode($db, $country_code, 'c_country', 'code', 'rowid');
797
798 if (empty($conf->cache['arrayOfActivePublicHolidays_'.$country_id])) {
799 // Loop on public holiday defined into hrm_public_holiday for the day, month and year analyzed
800 $tmpArrayOfPublicHolidays = array();
801 $sql = "SELECT id, code, entity, fk_country, dayrule, year, month, day, active";
802 $sql .= " FROM ".MAIN_DB_PREFIX."c_hrm_public_holiday";
803 $sql .= " WHERE active = 1 and fk_country IN (0".($country_id > 0 ? ", ".$country_id : 0).")";
804 $sql .= " AND entity IN (0," .getEntity('holiday') .")";
805
806 $resql = $db->query($sql);
807 if ($resql) {
808 $num_rows = $db->num_rows($resql);
809 $i = 0;
810 while ($i < $num_rows) {
811 $obj = $db->fetch_object($resql);
812 $tmpArrayOfPublicHolidays[$obj->id] = array('dayrule' => $obj->dayrule, 'year' => $obj->year, 'month' => $obj->month, 'day' => $obj->day);
813 $i++;
814 }
815 } else {
816 dol_syslog($db->lasterror(), LOG_ERR);
817 return 'Error sql '.$db->lasterror();
818 }
819
820 //var_dump($tmpArrayOfPublicHolidays);
821 $conf->cache['arrayOfActivePublicHolidays_'.$country_id] = $tmpArrayOfPublicHolidays;
822 }
823
824 $arrayOfPublicHolidays = $conf->cache['arrayOfActivePublicHolidays_'.$country_id];
825
826 $i = 0;
827 while ((($lastday == 0 && $timestampStart < $timestampEnd) || ($lastday && $timestampStart <= $timestampEnd))
828 && ($i < 50000)) { // Loop end when equals (Test on i is a security loop to avoid infinite loop)
829 $ferie = false;
830 $specialdayrule = array();
831
832 $jour = (int) gmdate("d", $timestampStart);
833 $mois = (int) gmdate("m", $timestampStart);
834 $annee = (int) gmdate("Y", $timestampStart);
835
836 //print "jour=".$jour." month=".$mois." year=".$annee." includesaturday=".$includesaturday." includesunday=".$includesunday."\n";
837 foreach ($arrayOfPublicHolidays as $entrypublicholiday) {
838 if (!empty($entrypublicholiday['dayrule']) && $entrypublicholiday['dayrule'] != 'date') { // For example 'easter', '...'
839 $specialdayrule[$entrypublicholiday['dayrule']] = $entrypublicholiday['dayrule'];
840 } else {
841 $match = 1;
842 if (!empty($entrypublicholiday['year']) && $entrypublicholiday['year'] != $annee) {
843 $match = 0;
844 }
845 if ($entrypublicholiday['month'] != $mois) {
846 $match = 0;
847 }
848 if ($entrypublicholiday['day'] != $jour) {
849 $match = 0;
850 }
851
852 if ($match) {
853 $ferie = true;
854 }
855 }
856
857 $i++;
858 }
859 //var_dump($specialdayrule)."\n";
860 //print "ferie=".$ferie."\n";
861
862 if (!$ferie) {
863 // Special dayrules
864 if (in_array('easter', $specialdayrule)) {
865 // Calculation for easter date
866 $date_paques = getGMTEasterDatetime($annee);
867 $jour_paques = gmdate("d", $date_paques);
868 $mois_paques = gmdate("m", $date_paques);
869 if ($jour_paques == $jour && $mois_paques == $mois) {
870 $ferie = true;
871 }
872 // Easter (sunday)
873 }
874
875 if (in_array('eastermonday', $specialdayrule)) {
876 // Calculation for the monday of easter date
877 $date_paques = getGMTEasterDatetime($annee);
878 //print 'PPP'.$date_paques.' '.dol_print_date($date_paques, 'dayhour', 'gmt')." ";
879 $date_lundi_paques = $date_paques + (3600 * 24);
880 $jour_lundi_paques = gmdate("d", $date_lundi_paques);
881 $mois_lundi_paques = gmdate("m", $date_lundi_paques);
882 if ($jour_lundi_paques == $jour && $mois_lundi_paques == $mois) {
883 $ferie = true;
884 }
885 // Easter (monday)
886 //print 'annee='.$annee.' $jour='.$jour.' $mois='.$mois.' $jour_lundi_paques='.$jour_lundi_paques.' $mois_lundi_paques='.$mois_lundi_paques."\n";
887 }
888
889 //Good Friday
890 if (in_array('goodfriday', $specialdayrule)) {
891 // Pulls the date of Easter
892 $easter = getGMTEasterDatetime($annee);
893
894 // Calculates the date of Good Friday based on Easter
895 $date_good_friday = $easter - (2 * 3600 * 24);
896 $dom_good_friday = gmdate("d", $date_good_friday);
897 $month_good_friday = gmdate("m", $date_good_friday);
898
899 if ($dom_good_friday == $jour && $month_good_friday == $mois) {
900 $ferie = true;
901 }
902 }
903
904 if (in_array('ascension', $specialdayrule)) {
905 // Calcul du jour de l'ascension (39 days after easter day)
906 $date_paques = getGMTEasterDatetime($annee);
907 $date_ascension = $date_paques + (3600 * 24 * 39);
908 $jour_ascension = gmdate("d", $date_ascension);
909 $mois_ascension = gmdate("m", $date_ascension);
910 if ($jour_ascension == $jour && $mois_ascension == $mois) {
911 $ferie = true;
912 }
913 // Ascension (thursday)
914 }
915
916 if (in_array('pentecost', $specialdayrule)) {
917 // Calculation of "Pentecote" (49 days after easter day)
918 $date_paques = getGMTEasterDatetime($annee);
919 $date_pentecote = $date_paques + (3600 * 24 * 49);
920 $jour_pentecote = gmdate("d", $date_pentecote);
921 $mois_pentecote = gmdate("m", $date_pentecote);
922 if ($jour_pentecote == $jour && $mois_pentecote == $mois) {
923 $ferie = true;
924 }
925 // "Pentecote" (sunday)
926 }
927 if (in_array('pentecotemonday', $specialdayrule)) {
928 // Calculation of "Pentecote" (49 days after easter day)
929 $date_paques = getGMTEasterDatetime($annee);
930 $date_pentecote = $date_paques + (3600 * 24 * 50);
931 $jour_pentecote = gmdate("d", $date_pentecote);
932 $mois_pentecote = gmdate("m", $date_pentecote);
933 if ($jour_pentecote == $jour && $mois_pentecote == $mois) {
934 $ferie = true;
935 }
936 // "Pentecote" (monday)
937 }
938
939 if (in_array('viernessanto', $specialdayrule)) {
940 // Viernes Santo
941 $date_paques = getGMTEasterDatetime($annee);
942 $date_viernes = $date_paques - (3600 * 24 * 2);
943 $jour_viernes = gmdate("d", $date_viernes);
944 $mois_viernes = gmdate("m", $date_viernes);
945 if ($jour_viernes == $jour && $mois_viernes == $mois) {
946 $ferie = true;
947 }
948 //Viernes Santo
949 }
950
951 if (in_array('fronleichnam', $specialdayrule)) {
952 // Fronleichnam (60 days after easter sunday)
953 $date_paques = getGMTEasterDatetime($annee);
954 $date_fronleichnam = $date_paques + (3600 * 24 * 60);
955 $jour_fronleichnam = gmdate("d", $date_fronleichnam);
956 $mois_fronleichnam = gmdate("m", $date_fronleichnam);
957 if ($jour_fronleichnam == $jour && $mois_fronleichnam == $mois) {
958 $ferie = true;
959 }
960 // Fronleichnam
961 }
962
963 if (in_array('genevafast', $specialdayrule)) {
964 // Geneva fast in Switzerland (Thursday after the first sunday in September)
965 $date_1sunsept = strtotime('next thursday', strtotime('next sunday', mktime(0, 0, 0, 9, 1, $annee)));
966 $jour_1sunsept = date("d", $date_1sunsept);
967 $mois_1sunsept = date("m", $date_1sunsept);
968 if ($jour_1sunsept == $jour && $mois_1sunsept == $mois) {
969 $ferie = true;
970 }
971 // Geneva fast in Switzerland
972 }
973 }
974 //print "ferie=".$ferie."\n";
975
976 // If we have to include Friday, Saturday and Sunday
977 if (!$ferie) {
978 if ($includefriday || $includesaturday || $includesunday) {
979 $jour_julien = unixtojd($timestampStart);
980 $jour_semaine = jddayofweek($jour_julien, 0);
981 if ($includefriday) { //Friday (5), Saturday (6) and Sunday (0)
982 if ($jour_semaine == 5) {
983 $ferie = true;
984 }
985 }
986 if ($includesaturday) { //Friday (5), Saturday (6) and Sunday (0)
987 if ($jour_semaine == 6) {
988 $ferie = true;
989 }
990 }
991 if ($includesunday) { //Friday (5), Saturday (6) and Sunday (0)
992 if ($jour_semaine == 0) {
993 $ferie = true;
994 }
995 }
996 }
997 }
998 //print "ferie=".$ferie."\n";
999
1000 // We increase the counter of non working day
1001 if ($ferie) {
1002 $nbFerie++;
1003 }
1004
1005 // Increase number of days (on go up into loop)
1006 $timestampStart = dol_time_plus_duree($timestampStart, 1, 'd');
1007 //var_dump($jour.' '.$mois.' '.$annee.' '.$timestampStart);
1008
1009 $i++;
1010 }
1011
1012 //print "nbFerie=".$nbFerie."\n";
1013 return $nbFerie;
1014}
1015
1026function num_between_day($timestampStart, $timestampEnd, $lastday = 0)
1027{
1028 if ($timestampStart <= $timestampEnd) {
1029 if ($lastday == 1) {
1030 $bit = 0;
1031 } else {
1032 $bit = 1;
1033 }
1034 $nbjours = (int) floor(($timestampEnd - $timestampStart) / (60 * 60 * 24)) + 1 - $bit;
1035 } else {
1036 $nbjours = 0;
1037 }
1038 //print ($timestampEnd - $timestampStart) - $lastday;
1039 return $nbjours;
1040}
1041
1054function num_open_day($timestampStart, $timestampEnd, $inhour = 0, $lastday = 0, $halfday = 0, $country_code = '')
1055{
1056 global $langs, $mysoc;
1057
1058 if (empty($country_code)) {
1059 $country_code = $mysoc->country_code;
1060 }
1061
1062 dol_syslog('num_open_day timestampStart='.$timestampStart.' timestampEnd='.$timestampEnd.' bit='.$lastday.' country_code='.$country_code);
1063
1064 // Check parameters
1065 if (!is_int($timestampStart) && !is_float($timestampStart)) {
1066 return 'ErrorBadParameter_num_open_day';
1067 }
1068 if (!is_int($timestampEnd) && !is_float($timestampEnd)) {
1069 return 'ErrorBadParameter_num_open_day';
1070 }
1071
1072 //print 'num_open_day timestampStart='.$timestampStart.' timestampEnd='.$timestampEnd.' bit='.$lastday;
1073 if ($timestampStart < $timestampEnd) {
1074 $numdays = num_between_day($timestampStart, $timestampEnd, $lastday);
1075
1076 $numholidays = num_public_holiday($timestampStart, $timestampEnd, $country_code, $lastday);
1077 $nbOpenDay = ($numdays - $numholidays);
1078 if ($inhour == 1 && $nbOpenDay <= 3) {
1079 $nbOpenDay *= 24;
1080 }
1081 return $nbOpenDay - (($inhour == 1 ? 12 : 0.5) * abs($halfday));
1082 } elseif ($timestampStart == $timestampEnd) {
1083 $numholidays = 0;
1084 if ($lastday) {
1085 $numholidays = num_public_holiday($timestampStart, $timestampEnd, $country_code, $lastday);
1086 if ($numholidays == 1) {
1087 return 0;
1088 }
1089 }
1090
1091 $nbOpenDay = $lastday;
1092
1093 if ($inhour == 1) {
1094 $nbOpenDay *= 24;
1095 }
1096 return $nbOpenDay - (($inhour == 1 ? 12 : 0.5) * abs($halfday));
1097 } else {
1098 return $langs->trans("Error");
1099 }
1100}
1101
1102
1103
1112function monthArray($outputlangs, $short = 0)
1113{
1114 $montharray = array(
1115 1 => $outputlangs->trans("Month01"),
1116 2 => $outputlangs->trans("Month02"),
1117 3 => $outputlangs->trans("Month03"),
1118 4 => $outputlangs->trans("Month04"),
1119 5 => $outputlangs->trans("Month05"),
1120 6 => $outputlangs->trans("Month06"),
1121 7 => $outputlangs->trans("Month07"),
1122 8 => $outputlangs->trans("Month08"),
1123 9 => $outputlangs->trans("Month09"),
1124 10 => $outputlangs->trans("Month10"),
1125 11 => $outputlangs->trans("Month11"),
1126 12 => $outputlangs->trans("Month12")
1127 );
1128
1129 if (!empty($short)) {
1130 $montharray = array(
1131 1 => $outputlangs->trans("MonthShort01"),
1132 2 => $outputlangs->trans("MonthShort02"),
1133 3 => $outputlangs->trans("MonthShort03"),
1134 4 => $outputlangs->trans("MonthShort04"),
1135 5 => $outputlangs->trans("MonthShort05"),
1136 6 => $outputlangs->trans("MonthShort06"),
1137 7 => $outputlangs->trans("MonthShort07"),
1138 8 => $outputlangs->trans("MonthShort08"),
1139 9 => $outputlangs->trans("MonthShort09"),
1140 10 => $outputlangs->trans("MonthShort10"),
1141 11 => $outputlangs->trans("MonthShort11"),
1142 12 => $outputlangs->trans("MonthShort12")
1143 );
1144 }
1145
1146 return $montharray;
1147}
1148
1156function getWeekNumbersOfMonth($month, $year)
1157{
1158 $nb_days = cal_days_in_month(CAL_GREGORIAN, $month, $year);
1159 $TWeek = array();
1160 for ($day = 1; $day < $nb_days; $day++) {
1161 $week_number = getWeekNumber($day, $month, $year);
1162 $TWeek[$week_number] = $week_number;
1163 }
1164 return $TWeek;
1165}
1166
1174function getFirstDayOfEachWeek($TWeek, $year)
1175{
1176 $TFirstDayOfWeek = array();
1177 foreach ($TWeek as $weekNb) {
1178 if (in_array('01', $TWeek) && in_array('52', $TWeek) && $weekNb == '01') {
1179 $year++; //Si on a la 1re semaine et la semaine 52 c'est qu'on change d'année
1180 }
1181 $TFirstDayOfWeek[$weekNb] = date('d', strtotime($year.'W'.$weekNb));
1182 }
1183 return $TFirstDayOfWeek;
1184}
1185
1193function getLastDayOfEachWeek($TWeek, $year)
1194{
1195 $TLastDayOfWeek = array();
1196 foreach ($TWeek as $weekNb) {
1197 $TLastDayOfWeek[$weekNb] = date('d', strtotime($year.'W'.$weekNb.'+6 days'));
1198 }
1199 return $TLastDayOfWeek;
1200}
1201
1210function getWeekNumber($day, $month, $year)
1211{
1212 $date = new DateTime($year.'-'.$month.'-'.$day);
1213 $week = $date->format("W");
1214 return $week;
1215}
dol_get_prev_month($month, $year)
Return previous month.
Definition date.lib.php:519
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:660
dol_get_next_day($day, $month, $year)
Return next day.
Definition date.lib.php:504
dol_get_next_week($day, $week, $month, $year)
Return next week.
Definition date.lib.php:578
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:382
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:646
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:675
getGMTEasterDatetime($year)
Return the easter day in GMT time.
Definition date.lib.php:745
convertDurationtoHour($duration_value, $duration_unit)
Convert duration to hour.
Definition date.lib.php:338
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:488
dol_get_first_day($year, $month=1, $gm=false)
Return GMT time for first day of a month or year.
Definition date.lib.php:600
getFirstDayOfEachWeek($TWeek, $year)
Return array of first day of weeks.
dol_get_next_month($month, $year)
Return next month.
Definition date.lib.php:538
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:215
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:244
dol_get_prev_week($day, $week, $month, $year)
Return previous week.
Definition date.lib.php:559
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:431
dol_get_last_day($year, $month=12, $gm=false)
Return GMT time for last day of a month or year.
Definition date.lib.php:619
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:769
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.
global $conf
The following vars must be defined: $type2label $form $conf, $lang, The following vars may also be de...
Definition member.php:79