dolibarr  17.0.4
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 Charlene Benke <charlie@patas-monkey.com>
7 *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 3 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program. If not, see <https://www.gnu.org/licenses/>.
20  * or see https://www.gnu.org/
21  */
22 
34 function get_tz_array()
35 {
36  $tzarray = array(
37  -11=>"Pacific/Midway",
38  -10=>"Pacific/Fakaofo",
39  -9=>"America/Anchorage",
40  -8=>"America/Los_Angeles",
41  -7=>"America/Dawson_Creek",
42  -6=>"America/Chicago",
43  -5=>"America/Bogota",
44  -4=>"America/Anguilla",
45  -3=>"America/Araguaina",
46  -2=>"America/Noronha",
47  -1=>"Atlantic/Azores",
48  0=>"Africa/Abidjan",
49  1=>"Europe/Paris",
50  2=>"Europe/Helsinki",
51  3=>"Europe/Moscow",
52  4=>"Asia/Dubai",
53  5=>"Asia/Karachi",
54  6=>"Indian/Chagos",
55  7=>"Asia/Jakarta",
56  8=>"Asia/Hong_Kong",
57  9=>"Asia/Tokyo",
58  10=>"Australia/Sydney",
59  11=>"Pacific/Noumea",
60  12=>"Pacific/Auckland",
61  13=>"Pacific/Enderbury"
62  );
63  return $tzarray;
64 }
65 
66 
73 {
74  return @date_default_timezone_get();
75 }
76 
83 function getServerTimeZoneInt($refgmtdate = 'now')
84 {
85  if (method_exists('DateTimeZone', 'getOffset')) {
86  // Method 1 (include daylight)
87  $gmtnow = dol_now('gmt');
88  $yearref = dol_print_date($gmtnow, '%Y');
89  $monthref = dol_print_date($gmtnow, '%m');
90  $dayref = dol_print_date($gmtnow, '%d');
91  if ($refgmtdate == 'now') {
92  $newrefgmtdate = $yearref.'-'.$monthref.'-'.$dayref;
93  } elseif ($refgmtdate == 'summer') {
94  $newrefgmtdate = $yearref.'-08-01';
95  } else {
96  $newrefgmtdate = $yearref.'-01-01';
97  }
98  $newrefgmtdate .= 'T00:00:00+00:00';
99  $localtz = new DateTimeZone(getServerTimeZoneString());
100  $localdt = new DateTime($newrefgmtdate, $localtz);
101  $tmp = -1 * $localtz->getOffset($localdt);
102  //print $refgmtdate.'='.$tmp;
103  } else {
104  $tmp = 0;
105  dol_print_error('', 'PHP version must be 5.3+');
106  }
107  $tz = round(($tmp < 0 ? 1 : -1) * abs($tmp / 3600));
108  return $tz;
109 }
110 
111 
121 function dol_time_plus_duree($time, $duration_value, $duration_unit, $ruleforendofmonth = 0)
122 {
123  global $conf;
124  if ($duration_unit == 's') {
125  return $time + ($duration_value);
126  }
127  if ($duration_value == 0) {
128  return $time;
129  }
130  if ($duration_unit == 'i') {
131  return $time + (60 * $duration_value);
132  }
133  if ($duration_unit == 'h') {
134  return $time + (3600 * $duration_value);
135  }
136  if ($duration_unit == 'w') {
137  return $time + (3600 * 24 * 7 * $duration_value);
138  }
139 
140  $deltastring = 'P';
141 
142  if ($duration_value > 0) {
143  $deltastring .= abs($duration_value);
144  $sub = false;
145  }
146  if ($duration_value < 0) {
147  $deltastring .= abs($duration_value);
148  $sub = true;
149  }
150  if ($duration_unit == 'd') {
151  $deltastring .= "D";
152  }
153  if ($duration_unit == 'm') {
154  $deltastring .= "M";
155  }
156  if ($duration_unit == 'y') {
157  $deltastring .= "Y";
158  }
159 
160  $date = new DateTime();
161  if (!empty($conf->global->MAIN_DATE_IN_MEMORY_ARE_GMT)) {
162  $date->setTimezone(new DateTimeZone('UTC'));
163  }
164  $date->setTimestamp($time);
165  $interval = new DateInterval($deltastring);
166 
167  if ($sub) {
168  $date->sub($interval);
169  } else {
170  $date->add($interval);
171  }
172  //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)
173  if ($ruleforendofmonth == 1 && $duration_unit == 'm') {
174  $timeyear = dol_print_date($time, '%Y');
175  $timemonth = dol_print_date($time, '%m');
176  $timetotalmonths = (($timeyear * 12) + $timemonth);
177 
178  $monthsexpected = ($timetotalmonths + $duration_value);
179 
180  $newtime = $date->getTimestamp();
181 
182  $newtimeyear = dol_print_date($newtime, '%Y');
183  $newtimemonth = dol_print_date($newtime, '%m');
184  $newtimetotalmonths = (($newtimeyear * 12) + $newtimemonth);
185 
186  if ($monthsexpected < $newtimetotalmonths) {
187  $newtimehours = dol_print_date($newtime, '%H');
188  $newtimemins = dol_print_date($newtime, '%M');
189  $newtimesecs = dol_print_date($newtime, '%S');
190 
191  $datelim = dol_mktime($newtimehours, $newtimemins, $newtimesecs, $newtimemonth, 1, $newtimeyear);
192  $datelim -= (3600 * 24);
193 
194  $date->setTimestamp($datelim);
195  }
196  }
197  return $date->getTimestamp();
198 }
199 
200 
210 function convertTime2Seconds($iHours = 0, $iMinutes = 0, $iSeconds = 0)
211 {
212  $iResult = ((int) $iHours * 3600) + ((int) $iMinutes * 60) + (int) $iSeconds;
213  return $iResult;
214 }
215 
216 
238 function convertSecondToTime($iSecond, $format = 'all', $lengthOfDay = 86400, $lengthOfWeek = 7)
239 {
240  global $langs;
241 
242  if (empty($lengthOfDay)) {
243  $lengthOfDay = 86400; // 1 day = 24 hours
244  }
245  if (empty($lengthOfWeek)) {
246  $lengthOfWeek = 7; // 1 week = 7 days
247  }
248  $nbHbyDay = $lengthOfDay / 3600;
249 
250  if ($format == 'all' || $format == 'allwithouthour' || $format == 'allhour' || $format == 'allhourmin' || $format == 'allhourminsec') {
251  if ((int) $iSecond === 0) {
252  return '0'; // This is to avoid having 0 return a 12:00 AM for en_US
253  }
254 
255  $sTime = '';
256  $sDay = 0;
257  $sWeek = 0;
258 
259  if ($iSecond >= $lengthOfDay) {
260  for ($i = $iSecond; $i >= $lengthOfDay; $i -= $lengthOfDay) {
261  $sDay++;
262  $iSecond -= $lengthOfDay;
263  }
264  $dayTranslate = $langs->trans("Day");
265  if ($iSecond >= ($lengthOfDay * 2)) {
266  $dayTranslate = $langs->trans("Days");
267  }
268  }
269 
270  if ($lengthOfWeek < 7) {
271  if ($sDay) {
272  if ($sDay >= $lengthOfWeek) {
273  $sWeek = (int) (($sDay - $sDay % $lengthOfWeek) / $lengthOfWeek);
274  $sDay = $sDay % $lengthOfWeek;
275  $weekTranslate = $langs->trans("DurationWeek");
276  if ($sWeek >= 2) {
277  $weekTranslate = $langs->trans("DurationWeeks");
278  }
279  $sTime .= $sWeek.' '.$weekTranslate.' ';
280  }
281  }
282  }
283  if ($sDay > 0) {
284  $dayTranslate = $langs->trans("Day");
285  if ($sDay > 1) {
286  $dayTranslate = $langs->trans("Days");
287  }
288  $sTime .= $sDay.' '.$langs->trans("d").' ';
289  }
290 
291  if ($format == 'all') {
292  if ($iSecond || empty($sDay)) {
293  $sTime .= dol_print_date($iSecond, 'hourduration', true);
294  }
295  } elseif ($format == 'allhourminsec') {
296  return sprintf("%02d", ($sWeek * $lengthOfWeek * $nbHbyDay + $sDay * $nbHbyDay + (int) floor($iSecond/3600))).':'.sprintf("%02d", ((int) floor(($iSecond % 3600) / 60))).':'.sprintf("%02d", ((int) ($iSecond % 60)));
297  } elseif ($format == 'allhourmin') {
298  return sprintf("%02d", ($sWeek * $lengthOfWeek * $nbHbyDay + $sDay * $nbHbyDay + (int) floor($iSecond/3600))).':'.sprintf("%02d", ((int) floor(($iSecond % 3600)/60)));
299  } elseif ($format == 'allhour') {
300  return sprintf("%02d", ($sWeek * $lengthOfWeek * $nbHbyDay + $sDay * $nbHbyDay + (int) floor($iSecond/3600)));
301  }
302  } elseif ($format == 'hour') { // only hour part
303  $sTime = dol_print_date($iSecond, '%H', true);
304  } elseif ($format == 'fullhour') {
305  if (!empty($iSecond)) {
306  $iSecond = $iSecond / 3600;
307  } else {
308  $iSecond = 0;
309  }
310  $sTime = $iSecond;
311  } elseif ($format == 'min') { // only min part
312  $sTime = dol_print_date($iSecond, '%M', true);
313  } elseif ($format == 'sec') { // only sec part
314  $sTime = dol_print_date($iSecond, '%S', true);
315  } elseif ($format == 'month') { // only month part
316  $sTime = dol_print_date($iSecond, '%m', true);
317  } elseif ($format == 'year') { // only year part
318  $sTime = dol_print_date($iSecond, '%Y', true);
319  }
320  return trim($sTime);
321 }
322 
323 
330 function convertDurationtoHour($duration_value, $duration_unit)
331 {
332  $result = 0;
333 
334  if ($duration_unit == 's') $result = $duration_value / 3600;
335  if ($duration_unit == 'i') $result = $duration_value / 60;
336  if ($duration_unit == 'h') $result = $duration_value;
337  if ($duration_unit == 'd') $result = $duration_value * 24;
338  if ($duration_unit == 'w') $result = $duration_value * 24 * 7;
339  if ($duration_unit == 'm') $result = $duration_value * 730.484;
340  if ($duration_unit == 'y') $result = $duration_value * 365 * 24;
341 
342  return $result;
343 }
344 
358 function dolSqlDateFilter($datefield, $day_date, $month_date, $year_date, $excludefirstand = 0, $gm = false)
359 {
360  global $db;
361  $sqldate = '';
362 
363  $day_date = intval($day_date);
364  $month_date = intval($month_date);
365  $year_date = intval($year_date);
366 
367  if ($month_date > 0) {
368  if ($month_date > 12) { // protection for bad value of month
369  return " AND 1 = 2";
370  }
371  if ($year_date > 0 && empty($day_date)) {
372  $sqldate .= ($excludefirstand ? "" : " AND ").$datefield." BETWEEN '".$db->idate(dol_get_first_day($year_date, $month_date, $gm));
373  $sqldate .= "' AND '".$db->idate(dol_get_last_day($year_date, $month_date, $gm))."'";
374  } elseif ($year_date > 0 && !empty($day_date)) {
375  $sqldate .= ($excludefirstand ? "" : " AND ").$datefield." BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $month_date, $day_date, $year_date, $gm));
376  $sqldate .= "' AND '".$db->idate(dol_mktime(23, 59, 59, $month_date, $day_date, $year_date, $gm))."'";
377  } else {
378  // This case is not reliable on TZ, but we should not need it.
379  $sqldate .= ($excludefirstand ? "" : " AND ")." date_format( ".$datefield.", '%c') = '".$db->escape($month_date)."'";
380  }
381  } elseif ($year_date > 0) {
382  $sqldate .= ($excludefirstand ? "" : " AND ").$datefield." BETWEEN '".$db->idate(dol_get_first_day($year_date, 1, $gm));
383  $sqldate .= "' AND '".$db->idate(dol_get_last_day($year_date, 12, $gm))."'";
384  }
385  return $sqldate;
386 }
387 
407 function dol_stringtotime($string, $gm = 1)
408 {
409  $reg = array();
410  // Convert date with format DD/MM/YYY HH:MM:SS. This part of code should not be used.
411  if (preg_match('/^([0-9]+)\/([0-9]+)\/([0-9]+)\s?([0-9]+)?:?([0-9]+)?:?([0-9]+)?/i', $string, $reg)) {
412  dol_syslog("dol_stringtotime call to function with deprecated parameter format", LOG_WARNING);
413  // Date est au format 'DD/MM/YY' ou 'DD/MM/YY HH:MM:SS'
414  // Date est au format 'DD/MM/YYYY' ou 'DD/MM/YYYY HH:MM:SS'
415  $sday = $reg[1];
416  $smonth = $reg[2];
417  $syear = $reg[3];
418  $shour = $reg[4];
419  $smin = $reg[5];
420  $ssec = $reg[6];
421  if ($syear < 50) {
422  $syear += 1900;
423  }
424  if ($syear >= 50 && $syear < 100) {
425  $syear += 2000;
426  }
427  $string = sprintf("%04d%02d%02d%02d%02d%02d", $syear, $smonth, $sday, $shour, $smin, $ssec);
428  } 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)
429  || 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
430  || 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
431  ) {
432  $syear = $reg[1];
433  $smonth = $reg[2];
434  $sday = $reg[3];
435  $shour = $reg[4];
436  $smin = $reg[5];
437  $ssec = $reg[6];
438  $string = sprintf("%04d%02d%02d%02d%02d%02d", $syear, $smonth, $sday, $shour, $smin, $ssec);
439  }
440 
441  $string = preg_replace('/([^0-9])/i', '', $string);
442  $tmp = $string.'000000';
443  // Clean $gm
444  if ($gm === 1) {
445  $gm = 'gmt';
446  } elseif (empty($gm) || $gm === 'tzserver') {
447  $gm = 'tzserver';
448  }
449 
450  $date = dol_mktime(substr($tmp, 8, 2), substr($tmp, 10, 2), substr($tmp, 12, 2), substr($tmp, 4, 2), substr($tmp, 6, 2), substr($tmp, 0, 4), $gm);
451  return $date;
452 }
453 
454 
463 function dol_get_prev_day($day, $month, $year)
464 {
465  $time = dol_mktime(12, 0, 0, $month, $day, $year, 1, 0);
466  $time -= 24 * 60 * 60;
467  $tmparray = dol_getdate($time, true);
468  return array('year' => $tmparray['year'], 'month' => $tmparray['mon'], 'day' => $tmparray['mday']);
469 }
470 
479 function dol_get_next_day($day, $month, $year)
480 {
481  $time = dol_mktime(12, 0, 0, $month, $day, $year, 1, 0);
482  $time += 24 * 60 * 60;
483  $tmparray = dol_getdate($time, true);
484  return array('year' => $tmparray['year'], 'month' => $tmparray['mon'], 'day' => $tmparray['mday']);
485 }
486 
494 function dol_get_prev_month($month, $year)
495 {
496  if ($month == 1) {
497  $prev_month = 12;
498  $prev_year = $year - 1;
499  } else {
500  $prev_month = $month - 1;
501  $prev_year = $year;
502  }
503  return array('year' => $prev_year, 'month' => $prev_month);
504 }
505 
513 function dol_get_next_month($month, $year)
514 {
515  if ($month == 12) {
516  $next_month = 1;
517  $next_year = $year + 1;
518  } else {
519  $next_month = $month + 1;
520  $next_year = $year;
521  }
522  return array('year' => $next_year, 'month' => $next_month);
523 }
524 
534 function dol_get_prev_week($day, $week, $month, $year)
535 {
536  $tmparray = dol_get_first_day_week($day, $month, $year);
537 
538  $time = dol_mktime(12, 0, 0, $month, $tmparray['first_day'], $year, 1, 0);
539  $time -= 24 * 60 * 60 * 7;
540  $tmparray = dol_getdate($time, true);
541  return array('year' => $tmparray['year'], 'month' => $tmparray['mon'], 'day' => $tmparray['mday']);
542 }
543 
553 function dol_get_next_week($day, $week, $month, $year)
554 {
555  $tmparray = dol_get_first_day_week($day, $month, $year);
556 
557  $time = dol_mktime(12, 0, 0, $tmparray['first_month'], $tmparray['first_day'], $tmparray['first_year'], 1, 0);
558  $time += 24 * 60 * 60 * 7;
559  $tmparray = dol_getdate($time, true);
560 
561  return array('year' => $tmparray['year'], 'month' => $tmparray['mon'], 'day' => $tmparray['mday']);
562 }
563 
575 function dol_get_first_day($year, $month = 1, $gm = false)
576 {
577  if ($year > 9999) {
578  return '';
579  }
580  return dol_mktime(0, 0, 0, $month, 1, $year, $gm);
581 }
582 
583 
594 function dol_get_last_day($year, $month = 12, $gm = false)
595 {
596  if ($year > 9999) {
597  return '';
598  }
599  if ($month == 12) {
600  $month = 1;
601  $year += 1;
602  } else {
603  $month += 1;
604  }
605 
606  // On se deplace au debut du mois suivant, et on retire un jour
607  $datelim = dol_mktime(23, 59, 59, $month, 1, $year, $gm);
608  $datelim -= (3600 * 24);
609 
610  return $datelim;
611 }
612 
621 function dol_get_last_hour($date, $gm = 'tzserver')
622 {
623  $tmparray = dol_getdate($date, false, ($gm == 'gmt' ? 'gmt' : ''));
624  return dol_mktime(23, 59, 59, $tmparray['mon'], $tmparray['mday'], $tmparray['year'], $gm);
625 }
626 
635 function dol_get_first_hour($date, $gm = 'tzserver')
636 {
637  $tmparray = dol_getdate($date, false, ($gm == 'gmt' ? 'gmt' : ''));
638  return dol_mktime(0, 0, 0, $tmparray['mon'], $tmparray['mday'], $tmparray['year'], $gm);
639 }
640 
650 function dol_get_first_day_week($day, $month, $year, $gm = false)
651 {
652  global $conf;
653 
654  //$day=2; $month=2; $year=2015;
655  $date = dol_mktime(0, 0, 0, $month, $day, $year, $gm);
656 
657  //Checking conf of start week
658  $start_week = (isset($conf->global->MAIN_START_WEEK) ? $conf->global->MAIN_START_WEEK : 1);
659 
660  $tmparray = dol_getdate($date, true); // detail of current day
661 
662  //Calculate days = offset from current day
663  $days = $start_week - $tmparray['wday'];
664  if ($days >= 1) {
665  $days = 7 - $days;
666  }
667  $days = abs($days);
668  $seconds = $days * 24 * 60 * 60;
669  //print 'start_week='.$start_week.' tmparray[wday]='.$tmparray['wday'].' day offset='.$days.' seconds offset='.$seconds.'<br>';
670 
671  //Get first day of week
672  $tmpdaytms = date($tmparray[0]) - $seconds; // $tmparray[0] is day of parameters
673  $tmpday = date("d", $tmpdaytms);
674 
675  //Check first day of week is in same month than current day or not
676  if ($tmpday > $day) {
677  $prev_month = $month - 1;
678  $prev_year = $year;
679 
680  if ($prev_month == 0) {
681  $prev_month = 12;
682  $prev_year = $year - 1;
683  }
684  } else {
685  $prev_month = $month;
686  $prev_year = $year;
687  }
688  $tmpmonth = $prev_month;
689  $tmpyear = $prev_year;
690 
691  //Get first day of next week
692  $tmptime = dol_mktime(12, 0, 0, $month, $tmpday, $year, 1, 0);
693  $tmptime -= 24 * 60 * 60 * 7;
694  $tmparray = dol_getdate($tmptime, true);
695  $prev_day = $tmparray['mday'];
696 
697  //Check prev day of week is in same month than first day or not
698  if ($prev_day > $tmpday) {
699  $prev_month = $month - 1;
700  $prev_year = $year;
701 
702  if ($prev_month == 0) {
703  $prev_month = 12;
704  $prev_year = $year - 1;
705  }
706  }
707 
708  $week = date("W", dol_mktime(0, 0, 0, $tmpmonth, $tmpday, $tmpyear, $gm));
709 
710  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);
711 }
712 
720 function getGMTEasterDatetime($year)
721 {
722  $base = new DateTime("$year-03-21", new DateTimeZone("UTC"));
723  $days = easter_days($year); // Return number of days between 21 march and easter day.
724  $tmp = $base->add(new DateInterval("P{$days}D"));
725  return $tmp->getTimestamp();
726 }
727 
744 function num_public_holiday($timestampStart, $timestampEnd, $country_code = '', $lastday = 0, $includesaturday = -1, $includesunday = -1, $includefriday = -1, $includemonday = -1)
745 {
746  global $db, $conf, $mysoc;
747 
748  $nbFerie = 0;
749 
750  // Check to ensure we use correct parameters
751  if ((($timestampEnd - $timestampStart) % 86400) != 0) {
752  return 'Error Dates must use same hours and must be GMT dates';
753  }
754 
755  if (empty($country_code)) {
756  $country_code = $mysoc->country_code;
757  }
758  if ($includemonday < 0) {
759  $includemonday = (isset($conf->global->MAIN_NON_WORKING_DAYS_INCLUDE_MONDAY) ? $conf->global->MAIN_NON_WORKING_DAYS_INCLUDE_MONDAY : 0);
760  }
761  if ($includefriday < 0) {
762  $includefriday = (isset($conf->global->MAIN_NON_WORKING_DAYS_INCLUDE_FRIDAY) ? $conf->global->MAIN_NON_WORKING_DAYS_INCLUDE_FRIDAY : 0);
763  }
764  if ($includesaturday < 0) {
765  $includesaturday = (isset($conf->global->MAIN_NON_WORKING_DAYS_INCLUDE_SATURDAY) ? $conf->global->MAIN_NON_WORKING_DAYS_INCLUDE_SATURDAY : 1);
766  }
767  if ($includesunday < 0) {
768  $includesunday = (isset($conf->global->MAIN_NON_WORKING_DAYS_INCLUDE_SUNDAY) ? $conf->global->MAIN_NON_WORKING_DAYS_INCLUDE_SUNDAY : 1);
769  }
770 
771  $country_id = dol_getIdFromCode($db, $country_code, 'c_country', 'code', 'rowid');
772 
773  $i = 0;
774  while ((($lastday == 0 && $timestampStart < $timestampEnd) || ($lastday && $timestampStart <= $timestampEnd))
775  && ($i < 50000)) { // Loop end when equals (Test on i is a security loop to avoid infinite loop)
776  $ferie = false;
777  $specialdayrule = array();
778 
779  $jour = gmdate("d", $timestampStart);
780  $mois = gmdate("m", $timestampStart);
781  $annee = gmdate("Y", $timestampStart);
782 
783  //print "jour=".$jour." month=".$mois." year=".$annee." includesaturday=".$includesaturday." includesunday=".$includesunday."\n";
784 
785  // Loop on public holiday defined into hrm_public_holiday for the day, month and year analyzed
786  // TODO Execute this request first and store results into an array, then reuse this array.
787  $sql = "SELECT code, entity, fk_country, dayrule, year, month, day, active";
788  $sql .= " FROM ".MAIN_DB_PREFIX."c_hrm_public_holiday";
789  $sql .= " WHERE active = 1 and fk_country IN (0".($country_id > 0 ? ", ".$country_id : 0).")";
790  $sql .= " AND entity IN (0," .getEntity('holiday') .")";
791 
792  $resql = $db->query($sql);
793  if ($resql) {
794  $num_rows = $db->num_rows($resql);
795  $i = 0;
796  while ($i < $num_rows) {
797  $obj = $db->fetch_object($resql);
798 
799  if (!empty($obj->dayrule) && $obj->dayrule != 'date') { // For example 'easter', '...'
800  $specialdayrule[$obj->dayrule] = $obj->dayrule;
801  } else {
802  $match = 1;
803  if (!empty($obj->year) && $obj->year != $annee) {
804  $match = 0;
805  }
806  if ($obj->month != $mois) {
807  $match = 0;
808  }
809  if ($obj->day != $jour) {
810  $match = 0;
811  }
812 
813  if ($match) {
814  $ferie = true;
815  }
816  }
817 
818  $i++;
819  }
820  } else {
821  dol_syslog($db->lasterror(), LOG_ERR);
822  return 'Error sql '.$db->lasterror();
823  }
824  //var_dump($specialdayrule)."\n";
825  //print "ferie=".$ferie."\n";
826 
827  if (!$ferie) {
828  // Special dayrules
829  if (in_array('easter', $specialdayrule)) {
830  // Calculation for easter date
831  $date_paques = getGMTEasterDatetime($annee);
832  $jour_paques = gmdate("d", $date_paques);
833  $mois_paques = gmdate("m", $date_paques);
834  if ($jour_paques == $jour && $mois_paques == $mois) {
835  $ferie = true;
836  }
837  // Easter (sunday)
838  }
839 
840  if (in_array('eastermonday', $specialdayrule)) {
841  // Calculation for the monday of easter date
842  $date_paques = getGMTEasterDatetime($annee);
843  //print 'PPP'.$date_paques.' '.dol_print_date($date_paques, 'dayhour', 'gmt')." ";
844  $date_lundi_paques = $date_paques + (3600 * 24);
845  $jour_lundi_paques = gmdate("d", $date_lundi_paques);
846  $mois_lundi_paques = gmdate("m", $date_lundi_paques);
847  if ($jour_lundi_paques == $jour && $mois_lundi_paques == $mois) {
848  $ferie = true;
849  }
850  // Easter (monday)
851  //print 'annee='.$annee.' $jour='.$jour.' $mois='.$mois.' $jour_lundi_paques='.$jour_lundi_paques.' $mois_lundi_paques='.$mois_lundi_paques."\n";
852  }
853 
854  //Good Friday
855  if (in_array('goodfriday', $specialdayrule)) {
856  // Pulls the date of Easter
857  $easter = getGMTEasterDatetime($annee);
858 
859  // Calculates the date of Good Friday based on Easter
860  $date_good_friday = $easter - (2 * 3600 * 24);
861  $dom_good_friday = gmdate("d", $date_good_friday);
862  $month_good_friday = gmdate("m", $date_good_friday);
863 
864  if ($dom_good_friday == $jour && $month_good_friday == $mois) {
865  $ferie = true;
866  }
867  }
868 
869  if (in_array('ascension', $specialdayrule)) {
870  // Calcul du jour de l'ascension (39 days after easter day)
871  $date_paques = getGMTEasterDatetime($annee);
872  $date_ascension = $date_paques + (3600 * 24 * 39);
873  $jour_ascension = gmdate("d", $date_ascension);
874  $mois_ascension = gmdate("m", $date_ascension);
875  if ($jour_ascension == $jour && $mois_ascension == $mois) {
876  $ferie = true;
877  }
878  // Ascension (thursday)
879  }
880 
881  if (in_array('pentecote', $specialdayrule)) {
882  // Calculation of "Pentecote" (49 days after easter day)
883  $date_paques = getGMTEasterDatetime($annee);
884  $date_pentecote = $date_paques + (3600 * 24 * 49);
885  $jour_pentecote = gmdate("d", $date_pentecote);
886  $mois_pentecote = gmdate("m", $date_pentecote);
887  if ($jour_pentecote == $jour && $mois_pentecote == $mois) {
888  $ferie = true;
889  }
890  // "Pentecote" (sunday)
891  }
892  if (in_array('pentecotemonday', $specialdayrule)) {
893  // Calculation of "Pentecote" (49 days after easter day)
894  $date_paques = getGMTEasterDatetime($annee);
895  $date_pentecote = $date_paques + (3600 * 24 * 50);
896  $jour_pentecote = gmdate("d", $date_pentecote);
897  $mois_pentecote = gmdate("m", $date_pentecote);
898  if ($jour_pentecote == $jour && $mois_pentecote == $mois) {
899  $ferie = true;
900  }
901  // "Pentecote" (monday)
902  }
903 
904  if (in_array('viernessanto', $specialdayrule)) {
905  // Viernes Santo
906  $date_paques = getGMTEasterDatetime($annee);
907  $date_viernes = $date_paques - (3600 * 24 * 2);
908  $jour_viernes = gmdate("d", $date_viernes);
909  $mois_viernes = gmdate("m", $date_viernes);
910  if ($jour_viernes == $jour && $mois_viernes == $mois) {
911  $ferie = true;
912  }
913  //Viernes Santo
914  }
915 
916  if (in_array('fronleichnam', $specialdayrule)) {
917  // Fronleichnam (60 days after easter sunday)
918  $date_paques = getGMTEasterDatetime($annee);
919  $date_fronleichnam = $date_paques + (3600 * 24 * 60);
920  $jour_fronleichnam = gmdate("d", $date_fronleichnam);
921  $mois_fronleichnam = gmdate("m", $date_fronleichnam);
922  if ($jour_fronleichnam == $jour && $mois_fronleichnam == $mois) {
923  $ferie = true;
924  }
925  // Fronleichnam
926  }
927 
928  if (in_array('genevafast', $specialdayrule)) {
929  // Geneva fast in Switzerland (Thursday after the first sunday in September)
930  $date_1sunsept = strtotime('next thursday', strtotime('next sunday', mktime(0, 0, 0, 9, 1, $annee)));
931  $jour_1sunsept = date("d", $date_1sunsept);
932  $mois_1sunsept = date("m", $date_1sunsept);
933  if ($jour_1sunsept == $jour && $mois_1sunsept == $mois) $ferie=true;
934  // Geneva fast in Switzerland
935  }
936  }
937  //print "ferie=".$ferie."\n";
938 
939  // If we have to include Friday, Saturday and Sunday
940  if (!$ferie) {
941  if ($includefriday || $includesaturday || $includesunday) {
942  $jour_julien = unixtojd($timestampStart);
943  $jour_semaine = jddayofweek($jour_julien, 0);
944  if ($includefriday) { //Friday (5), Saturday (6) and Sunday (0)
945  if ($jour_semaine == 5) {
946  $ferie = true;
947  }
948  }
949  if ($includesaturday) { //Friday (5), Saturday (6) and Sunday (0)
950  if ($jour_semaine == 6) {
951  $ferie = true;
952  }
953  }
954  if ($includesunday) { //Friday (5), Saturday (6) and Sunday (0)
955  if ($jour_semaine == 0) {
956  $ferie = true;
957  }
958  }
959  }
960  }
961  //print "ferie=".$ferie."\n";
962 
963  // We increase the counter of non working day
964  if ($ferie) {
965  $nbFerie++;
966  }
967 
968  // Increase number of days (on go up into loop)
969  $timestampStart = dol_time_plus_duree($timestampStart, 1, 'd');
970  //var_dump($jour.' '.$mois.' '.$annee.' '.$timestampStart);
971 
972  $i++;
973  }
974 
975  //print "nbFerie=".$nbFerie."\n";
976  return $nbFerie;
977 }
978 
989 function num_between_day($timestampStart, $timestampEnd, $lastday = 0)
990 {
991  if ($timestampStart < $timestampEnd) {
992  if ($lastday == 1) {
993  $bit = 0;
994  } else {
995  $bit = 1;
996  }
997  $nbjours = (int) floor(($timestampEnd - $timestampStart) / (60 * 60 * 24)) + 1 - $bit;
998  }
999  //print ($timestampEnd - $timestampStart) - $lastday;
1000  return $nbjours;
1001 }
1002 
1015 function num_open_day($timestampStart, $timestampEnd, $inhour = 0, $lastday = 0, $halfday = 0, $country_code = '')
1016 {
1017  global $langs, $mysoc;
1018 
1019  if (empty($country_code)) {
1020  $country_code = $mysoc->country_code;
1021  }
1022 
1023  dol_syslog('num_open_day timestampStart='.$timestampStart.' timestampEnd='.$timestampEnd.' bit='.$lastday.' country_code='.$country_code);
1024 
1025  // Check parameters
1026  if (!is_int($timestampStart) && !is_float($timestampStart)) {
1027  return 'ErrorBadParameter_num_open_day';
1028  }
1029  if (!is_int($timestampEnd) && !is_float($timestampEnd)) {
1030  return 'ErrorBadParameter_num_open_day';
1031  }
1032 
1033  //print 'num_open_day timestampStart='.$timestampStart.' timestampEnd='.$timestampEnd.' bit='.$lastday;
1034  if ($timestampStart < $timestampEnd) {
1035  $numdays = num_between_day($timestampStart, $timestampEnd, $lastday);
1036 
1037  $numholidays = num_public_holiday($timestampStart, $timestampEnd, $country_code, $lastday);
1038  $nbOpenDay = ($numdays - $numholidays);
1039  if ($inhour == 1 && $nbOpenDay <= 3) {
1040  $nbOpenDay = ($nbOpenDay * 24);
1041  }
1042  return $nbOpenDay - (($inhour == 1 ? 12 : 0.5) * abs($halfday));
1043  } elseif ($timestampStart == $timestampEnd) {
1044  $numholidays = 0;
1045  if ($lastday) {
1046  $numholidays = num_public_holiday($timestampStart, $timestampEnd, $country_code, $lastday);
1047  if ($numholidays == 1) {
1048  return 0;
1049  }
1050  }
1051 
1052  $nbOpenDay = $lastday;
1053 
1054  if ($inhour == 1) {
1055  $nbOpenDay = ($nbOpenDay * 24);
1056  }
1057  return $nbOpenDay - (($inhour == 1 ? 12 : 0.5) * abs($halfday));
1058  } else {
1059  return $langs->trans("Error");
1060  }
1061 }
1062 
1063 
1064 
1073 function monthArray($outputlangs, $short = 0)
1074 {
1075  $montharray = array(
1076  1 => $outputlangs->trans("Month01"),
1077  2 => $outputlangs->trans("Month02"),
1078  3 => $outputlangs->trans("Month03"),
1079  4 => $outputlangs->trans("Month04"),
1080  5 => $outputlangs->trans("Month05"),
1081  6 => $outputlangs->trans("Month06"),
1082  7 => $outputlangs->trans("Month07"),
1083  8 => $outputlangs->trans("Month08"),
1084  9 => $outputlangs->trans("Month09"),
1085  10 => $outputlangs->trans("Month10"),
1086  11 => $outputlangs->trans("Month11"),
1087  12 => $outputlangs->trans("Month12")
1088  );
1089 
1090  if (!empty($short)) {
1091  $montharray = array(
1092  1 => $outputlangs->trans("MonthShort01"),
1093  2 => $outputlangs->trans("MonthShort02"),
1094  3 => $outputlangs->trans("MonthShort03"),
1095  4 => $outputlangs->trans("MonthShort04"),
1096  5 => $outputlangs->trans("MonthShort05"),
1097  6 => $outputlangs->trans("MonthShort06"),
1098  7 => $outputlangs->trans("MonthShort07"),
1099  8 => $outputlangs->trans("MonthShort08"),
1100  9 => $outputlangs->trans("MonthShort09"),
1101  10 => $outputlangs->trans("MonthShort10"),
1102  11 => $outputlangs->trans("MonthShort11"),
1103  12 => $outputlangs->trans("MonthShort12")
1104  );
1105  }
1106 
1107  return $montharray;
1108 }
1116 function getWeekNumbersOfMonth($month, $year)
1117 {
1118  $nb_days = cal_days_in_month(CAL_GREGORIAN, $month, $year);
1119  $TWeek = array();
1120  for ($day = 1; $day < $nb_days; $day++) {
1121  $week_number = getWeekNumber($day, $month, $year);
1122  $TWeek[$week_number] = $week_number;
1123  }
1124  return $TWeek;
1125 }
1133 function getFirstDayOfEachWeek($TWeek, $year)
1134 {
1135  $TFirstDayOfWeek = array();
1136  foreach ($TWeek as $weekNb) {
1137  if (in_array('01', $TWeek) && in_array('52', $TWeek) && $weekNb == '01') {
1138  $year++; //Si on a la 1re semaine et la semaine 52 c'est qu'on change d'annĂ©e
1139  }
1140  $TFirstDayOfWeek[$weekNb] = date('d', strtotime($year.'W'.$weekNb));
1141  }
1142  return $TFirstDayOfWeek;
1143 }
1151 function getLastDayOfEachWeek($TWeek, $year)
1152 {
1153  $TLastDayOfWeek = array();
1154  foreach ($TWeek as $weekNb) {
1155  $TLastDayOfWeek[$weekNb] = date('d', strtotime($year.'W'.$weekNb.'+6 days'));
1156  }
1157  return $TLastDayOfWeek;
1158 }
1167 function getWeekNumber($day, $month, $year)
1168 {
1169  $date = new DateTime($year.'-'.$month.'-'.$day);
1170  $week = $date->format("W");
1171  return $week;
1172 }
if(isModEnabled('facture') &&!empty($user->rights->facture->lire)) if((isModEnabled('fournisseur') &&empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) && $user->hasRight("fournisseur", "facture", "lire"))||(isModEnabled('supplier_invoice') && $user->hasRight("supplier_invoice", "lire"))) if(isModEnabled('don') &&!empty($user->rights->don->lire)) if(isModEnabled('tax') &&!empty($user->rights->tax->charges->lire)) if(isModEnabled('facture') &&isModEnabled('commande') && $user->hasRight("commande", "lire") &&empty($conf->global->WORKFLOW_DISABLE_CREATE_INVOICE_FROM_ORDER)) $resql
Social contributions to pay.
Definition: index.php:745
dol_get_prev_month($month, $year)
Return previous month.
Definition: date.lib.php:494
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:635
dol_get_next_day($day, $month, $year)
Return next day.
Definition: date.lib.php:479
dol_get_next_week($day, $week, $month, $year)
Return next week.
Definition: date.lib.php:553
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:358
getServerTimeZoneString()
Return server timezone string.
Definition: date.lib.php:72
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:621
getLastDayOfEachWeek($TWeek, $year)
Return array of last day of weeks.
Definition: date.lib.php:1151
getWeekNumbersOfMonth($month, $year)
Return array of week numbers.
Definition: date.lib.php:1116
getServerTimeZoneInt($refgmtdate='now')
Return server timezone int.
Definition: date.lib.php:83
dol_get_first_day_week($day, $month, $year, $gm=false)
Return first day of week for a date.
Definition: date.lib.php:650
getGMTEasterDatetime($year)
Return the easter day in GMT time.
Definition: date.lib.php:720
convertDurationtoHour($duration_value, $duration_unit)
Convert duration to hour.
Definition: date.lib.php:330
get_tz_array()
Return an array with timezone values.
Definition: date.lib.php:34
dol_get_prev_day($day, $month, $year)
Return previous day.
Definition: date.lib.php:463
dol_get_first_day($year, $month=1, $gm=false)
Return GMT time for first day of a month or year.
Definition: date.lib.php:575
getFirstDayOfEachWeek($TWeek, $year)
Return array of first day of weeks.
Definition: date.lib.php:1133
dol_get_next_month($month, $year)
Return next month.
Definition: date.lib.php:513
getWeekNumber($day, $month, $year)
Return week number.
Definition: date.lib.php:1167
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...
Definition: date.lib.php:989
convertTime2Seconds($iHours=0, $iMinutes=0, $iSeconds=0)
Convert hours and minutes into seconds.
Definition: date.lib.php:210
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)
Definition: date.lib.php:1015
dol_time_plus_duree($time, $duration_value, $duration_unit, $ruleforendofmonth=0)
Add a delay to a date.
Definition: date.lib.php:121
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:238
dol_get_prev_week($day, $week, $month, $year)
Return previous week.
Definition: date.lib.php:534
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:407
dol_get_last_day($year, $month=12, $gm=false)
Return GMT time for last day of a month or year.
Definition: date.lib.php:594
monthArray($outputlangs, $short=0)
Return array of translated months or selected month.
Definition: date.lib.php:1073
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:744
dol_mktime($hour, $minute, $second, $month, $day, $year, $gm='auto', $check=1)
Return a timestamp date built from detailed informations (by default a local PHP server timestamp) Re...
dol_print_error($db='', $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs='', $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
dol_now($mode='auto')
Return date for now.
dol_getIdFromCode($db, $key, $tablename, $fieldkey='code', $fieldid='id', $entityfilter=0, $filters='')
Return an id or code from a code or id.
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.