dolibarr  18.0.6
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 
122 function dol_time_plus_duree($time, $duration_value, $duration_unit, $ruleforendofmonth = 0)
123 {
124  global $conf;
125  if ($duration_unit == 's') {
126  return $time + ($duration_value);
127  }
128  if ($duration_value == 0) {
129  return $time;
130  }
131  if ($duration_unit == 'i') {
132  return $time + (60 * $duration_value);
133  }
134  if ($duration_unit == 'h') {
135  return $time + (3600 * $duration_value);
136  }
137  if ($duration_unit == 'w') {
138  return $time + (3600 * 24 * 7 * $duration_value);
139  }
140 
141  $deltastring = 'P';
142 
143  if ($duration_value > 0) {
144  $deltastring .= abs($duration_value);
145  $sub = false;
146  }
147  if ($duration_value < 0) {
148  $deltastring .= abs($duration_value);
149  $sub = true;
150  }
151  if ($duration_unit == 'd') {
152  $deltastring .= "D";
153  }
154  if ($duration_unit == 'm') {
155  $deltastring .= "M";
156  }
157  if ($duration_unit == 'y') {
158  $deltastring .= "Y";
159  }
160 
161  $date = new DateTime();
162  if (!empty($conf->global->MAIN_DATE_IN_MEMORY_ARE_GMT)) {
163  $date->setTimezone(new DateTimeZone('UTC'));
164  }
165  $date->setTimestamp($time);
166  $interval = new DateInterval($deltastring);
167 
168  if ($sub) {
169  $date->sub($interval);
170  } else {
171  $date->add($interval);
172  }
173  //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)
174  if ($ruleforendofmonth == 1 && $duration_unit == 'm') {
175  $timeyear = dol_print_date($time, '%Y');
176  $timemonth = dol_print_date($time, '%m');
177  $timetotalmonths = (($timeyear * 12) + $timemonth);
178 
179  $monthsexpected = ($timetotalmonths + $duration_value);
180 
181  $newtime = $date->getTimestamp();
182 
183  $newtimeyear = dol_print_date($newtime, '%Y');
184  $newtimemonth = dol_print_date($newtime, '%m');
185  $newtimetotalmonths = (($newtimeyear * 12) + $newtimemonth);
186 
187  if ($monthsexpected < $newtimetotalmonths) {
188  $newtimehours = dol_print_date($newtime, '%H');
189  $newtimemins = dol_print_date($newtime, '%M');
190  $newtimesecs = dol_print_date($newtime, '%S');
191 
192  $datelim = dol_mktime($newtimehours, $newtimemins, $newtimesecs, $newtimemonth, 1, $newtimeyear);
193  $datelim -= (3600 * 24);
194 
195  $date->setTimestamp($datelim);
196  }
197  }
198  return $date->getTimestamp();
199 }
200 
201 
211 function convertTime2Seconds($iHours = 0, $iMinutes = 0, $iSeconds = 0)
212 {
213  $iResult = ((int) $iHours * 3600) + ((int) $iMinutes * 60) + (int) $iSeconds;
214  return $iResult;
215 }
216 
217 
240 function convertSecondToTime($iSecond, $format = 'all', $lengthOfDay = 86400, $lengthOfWeek = 7)
241 {
242  global $langs;
243 
244  if (empty($lengthOfDay)) {
245  $lengthOfDay = 86400; // 1 day = 24 hours
246  }
247  if (empty($lengthOfWeek)) {
248  $lengthOfWeek = 7; // 1 week = 7 days
249  }
250  $nbHbyDay = $lengthOfDay / 3600;
251 
252  if ($format == 'all' || $format == 'allwithouthour' || $format == 'allhour' || $format == 'allhourmin' || $format == 'allhourminsec') {
253  if ((int) $iSecond === 0) {
254  return '0'; // This is to avoid having 0 return a 12:00 AM for en_US
255  }
256 
257  $sTime = '';
258  $sDay = 0;
259  $sWeek = 0;
260 
261  if ($iSecond >= $lengthOfDay) {
262  for ($i = $iSecond; $i >= $lengthOfDay; $i -= $lengthOfDay) {
263  $sDay++;
264  $iSecond -= $lengthOfDay;
265  }
266  $dayTranslate = $langs->trans("Day");
267  if ($iSecond >= ($lengthOfDay * 2)) {
268  $dayTranslate = $langs->trans("Days");
269  }
270  }
271 
272  if ($lengthOfWeek < 7) {
273  if ($sDay) {
274  if ($sDay >= $lengthOfWeek) {
275  $sWeek = (int) (($sDay - $sDay % $lengthOfWeek) / $lengthOfWeek);
276  $sDay = $sDay % $lengthOfWeek;
277  $weekTranslate = $langs->trans("DurationWeek");
278  if ($sWeek >= 2) {
279  $weekTranslate = $langs->trans("DurationWeeks");
280  }
281  $sTime .= $sWeek.' '.$weekTranslate.' ';
282  }
283  }
284  }
285  if ($sDay > 0) {
286  $dayTranslate = $langs->trans("Day");
287  if ($sDay > 1) {
288  $dayTranslate = $langs->trans("Days");
289  }
290  $sTime .= $sDay.' '.$langs->trans("d").' ';
291  }
292 
293  if ($format == 'all') {
294  if ($iSecond || empty($sDay)) {
295  $sTime .= dol_print_date($iSecond, 'hourduration', true);
296  }
297  } elseif ($format == 'allhourminsec') {
298  return sprintf("%02d", ($sWeek * $lengthOfWeek * $nbHbyDay + $sDay * $nbHbyDay + (int) floor($iSecond/3600))).':'.sprintf("%02d", ((int) floor(($iSecond % 3600) / 60))).':'.sprintf("%02d", ((int) ($iSecond % 60)));
299  } elseif ($format == 'allhourmin') {
300  return sprintf("%02d", ($sWeek * $lengthOfWeek * $nbHbyDay + $sDay * $nbHbyDay + (int) floor($iSecond/3600))).':'.sprintf("%02d", ((int) floor(($iSecond % 3600)/60)));
301  } elseif ($format == 'allhour') {
302  return sprintf("%02d", ($sWeek * $lengthOfWeek * $nbHbyDay + $sDay * $nbHbyDay + (int) floor($iSecond/3600)));
303  }
304  } elseif ($format == 'hour') { // only hour part
305  $sTime = dol_print_date($iSecond, '%H', true);
306  } elseif ($format == 'fullhour') {
307  if (!empty($iSecond)) {
308  $iSecond = $iSecond / 3600;
309  } else {
310  $iSecond = 0;
311  }
312  $sTime = $iSecond;
313  } elseif ($format == 'min') { // only min part
314  $sTime = dol_print_date($iSecond, '%M', true);
315  } elseif ($format == 'sec') { // only sec part
316  $sTime = dol_print_date($iSecond, '%S', true);
317  } elseif ($format == 'month') { // only month part
318  $sTime = dol_print_date($iSecond, '%m', true);
319  } elseif ($format == 'year') { // only year part
320  $sTime = dol_print_date($iSecond, '%Y', true);
321  }
322  return trim($sTime);
323 }
324 
325 
332 function convertDurationtoHour($duration_value, $duration_unit)
333 {
334  $result = 0;
335 
336  if ($duration_unit == 's') $result = $duration_value / 3600;
337  if ($duration_unit == 'i') $result = $duration_value / 60;
338  if ($duration_unit == 'h') $result = $duration_value;
339  if ($duration_unit == 'd') $result = $duration_value * 24;
340  if ($duration_unit == 'w') $result = $duration_value * 24 * 7;
341  if ($duration_unit == 'm') $result = $duration_value * 730.484;
342  if ($duration_unit == 'y') $result = $duration_value * 365 * 24;
343 
344  return $result;
345 }
346 
360 function dolSqlDateFilter($datefield, $day_date, $month_date, $year_date, $excludefirstand = 0, $gm = false)
361 {
362  global $db;
363  $sqldate = '';
364 
365  $day_date = intval($day_date);
366  $month_date = intval($month_date);
367  $year_date = intval($year_date);
368 
369  if ($month_date > 0) {
370  if ($month_date > 12) { // protection for bad value of month
371  return " AND 1 = 2";
372  }
373  if ($year_date > 0 && empty($day_date)) {
374  $sqldate .= ($excludefirstand ? "" : " AND ").$datefield." BETWEEN '".$db->idate(dol_get_first_day($year_date, $month_date, $gm));
375  $sqldate .= "' AND '".$db->idate(dol_get_last_day($year_date, $month_date, $gm))."'";
376  } elseif ($year_date > 0 && !empty($day_date)) {
377  $sqldate .= ($excludefirstand ? "" : " AND ").$datefield." BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $month_date, $day_date, $year_date, $gm));
378  $sqldate .= "' AND '".$db->idate(dol_mktime(23, 59, 59, $month_date, $day_date, $year_date, $gm))."'";
379  } else {
380  // This case is not reliable on TZ, but we should not need it.
381  $sqldate .= ($excludefirstand ? "" : " AND ")." date_format( ".$datefield.", '%c') = '".$db->escape($month_date)."'";
382  }
383  } elseif ($year_date > 0) {
384  $sqldate .= ($excludefirstand ? "" : " AND ").$datefield." BETWEEN '".$db->idate(dol_get_first_day($year_date, 1, $gm));
385  $sqldate .= "' AND '".$db->idate(dol_get_last_day($year_date, 12, $gm))."'";
386  }
387  return $sqldate;
388 }
389 
409 function dol_stringtotime($string, $gm = 1)
410 {
411  $reg = array();
412  // Convert date with format DD/MM/YYY HH:MM:SS. This part of code should not be used.
413  if (preg_match('/^([0-9]+)\/([0-9]+)\/([0-9]+)\s?([0-9]+)?:?([0-9]+)?:?([0-9]+)?/i', $string, $reg)) {
414  dol_syslog("dol_stringtotime call to function with deprecated parameter format", LOG_WARNING);
415  // Date est au format 'DD/MM/YY' ou 'DD/MM/YY HH:MM:SS'
416  // Date est au format 'DD/MM/YYYY' ou 'DD/MM/YYYY HH:MM:SS'
417  $sday = $reg[1];
418  $smonth = $reg[2];
419  $syear = $reg[3];
420  $shour = $reg[4];
421  $smin = $reg[5];
422  $ssec = $reg[6];
423  if ($syear < 50) {
424  $syear += 1900;
425  }
426  if ($syear >= 50 && $syear < 100) {
427  $syear += 2000;
428  }
429  $string = sprintf("%04d%02d%02d%02d%02d%02d", $syear, $smonth, $sday, $shour, $smin, $ssec);
430  } 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)
431  || 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
432  || 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
433  ) {
434  $syear = $reg[1];
435  $smonth = $reg[2];
436  $sday = $reg[3];
437  $shour = $reg[4];
438  $smin = $reg[5];
439  $ssec = $reg[6];
440  $string = sprintf("%04d%02d%02d%02d%02d%02d", $syear, $smonth, $sday, $shour, $smin, $ssec);
441  }
442 
443  $string = preg_replace('/([^0-9])/i', '', $string);
444  $tmp = $string.'000000';
445  // Clean $gm
446  if ($gm === 1) {
447  $gm = 'gmt';
448  } elseif (empty($gm) || $gm === 'tzserver') {
449  $gm = 'tzserver';
450  }
451 
452  $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);
453  return $date;
454 }
455 
456 
465 function dol_get_prev_day($day, $month, $year)
466 {
467  $time = dol_mktime(12, 0, 0, $month, $day, $year, 1, 0);
468  $time -= 24 * 60 * 60;
469  $tmparray = dol_getdate($time, true);
470  return array('year' => $tmparray['year'], 'month' => $tmparray['mon'], 'day' => $tmparray['mday']);
471 }
472 
481 function dol_get_next_day($day, $month, $year)
482 {
483  $time = dol_mktime(12, 0, 0, $month, $day, $year, 1, 0);
484  $time += 24 * 60 * 60;
485  $tmparray = dol_getdate($time, true);
486  return array('year' => $tmparray['year'], 'month' => $tmparray['mon'], 'day' => $tmparray['mday']);
487 }
488 
496 function dol_get_prev_month($month, $year)
497 {
498  if ($month == 1) {
499  $prev_month = 12;
500  $prev_year = $year - 1;
501  } else {
502  $prev_month = $month - 1;
503  $prev_year = $year;
504  }
505  return array('year' => $prev_year, 'month' => $prev_month);
506 }
507 
515 function dol_get_next_month($month, $year)
516 {
517  if ($month == 12) {
518  $next_month = 1;
519  $next_year = $year + 1;
520  } else {
521  $next_month = $month + 1;
522  $next_year = $year;
523  }
524  return array('year' => $next_year, 'month' => $next_month);
525 }
526 
536 function dol_get_prev_week($day, $week, $month, $year)
537 {
538  $tmparray = dol_get_first_day_week($day, $month, $year);
539 
540  $time = dol_mktime(12, 0, 0, $month, $tmparray['first_day'], $year, 1, 0);
541  $time -= 24 * 60 * 60 * 7;
542  $tmparray = dol_getdate($time, true);
543  return array('year' => $tmparray['year'], 'month' => $tmparray['mon'], 'day' => $tmparray['mday']);
544 }
545 
555 function dol_get_next_week($day, $week, $month, $year)
556 {
557  $tmparray = dol_get_first_day_week($day, $month, $year);
558 
559  $time = dol_mktime(12, 0, 0, $tmparray['first_month'], $tmparray['first_day'], $tmparray['first_year'], 1, 0);
560  $time += 24 * 60 * 60 * 7;
561  $tmparray = dol_getdate($time, true);
562 
563  return array('year' => $tmparray['year'], 'month' => $tmparray['mon'], 'day' => $tmparray['mday']);
564 }
565 
577 function dol_get_first_day($year, $month = 1, $gm = false)
578 {
579  if ($year > 9999) {
580  return '';
581  }
582  return dol_mktime(0, 0, 0, $month, 1, $year, $gm);
583 }
584 
585 
596 function dol_get_last_day($year, $month = 12, $gm = false)
597 {
598  if ($year > 9999) {
599  return '';
600  }
601  if ($month == 12) {
602  $month = 1;
603  $year += 1;
604  } else {
605  $month += 1;
606  }
607 
608  // On se deplace au debut du mois suivant, et on retire un jour
609  $datelim = dol_mktime(23, 59, 59, $month, 1, $year, $gm);
610  $datelim -= (3600 * 24);
611 
612  return $datelim;
613 }
614 
623 function dol_get_last_hour($date, $gm = 'tzserver')
624 {
625  $tmparray = dol_getdate($date, false, ($gm == 'gmt' ? 'gmt' : ''));
626  return dol_mktime(23, 59, 59, $tmparray['mon'], $tmparray['mday'], $tmparray['year'], $gm);
627 }
628 
637 function dol_get_first_hour($date, $gm = 'tzserver')
638 {
639  $tmparray = dol_getdate($date, false, ($gm == 'gmt' ? 'gmt' : ''));
640  return dol_mktime(0, 0, 0, $tmparray['mon'], $tmparray['mday'], $tmparray['year'], $gm);
641 }
642 
652 function dol_get_first_day_week($day, $month, $year, $gm = false)
653 {
654  global $conf;
655 
656  //$day=2; $month=2; $year=2015;
657  $date = dol_mktime(0, 0, 0, $month, $day, $year, $gm);
658 
659  //Checking conf of start week
660  $start_week = (isset($conf->global->MAIN_START_WEEK) ? $conf->global->MAIN_START_WEEK : 1);
661 
662  $tmparray = dol_getdate($date, true); // detail of current day
663 
664  //Calculate days = offset from current day
665  $days = $start_week - $tmparray['wday'];
666  if ($days >= 1) {
667  $days = 7 - $days;
668  }
669  $days = abs($days);
670  $seconds = $days * 24 * 60 * 60;
671  //print 'start_week='.$start_week.' tmparray[wday]='.$tmparray['wday'].' day offset='.$days.' seconds offset='.$seconds.'<br>';
672 
673  //Get first day of week
674  $tmpdaytms = date($tmparray[0]) - $seconds; // $tmparray[0] is day of parameters
675  $tmpday = date("d", $tmpdaytms);
676 
677  //Check first day of week is in same month than current day or not
678  if ($tmpday > $day) {
679  $prev_month = $month - 1;
680  $prev_year = $year;
681 
682  if ($prev_month == 0) {
683  $prev_month = 12;
684  $prev_year = $year - 1;
685  }
686  } else {
687  $prev_month = $month;
688  $prev_year = $year;
689  }
690  $tmpmonth = $prev_month;
691  $tmpyear = $prev_year;
692 
693  //Get first day of next week
694  $tmptime = dol_mktime(12, 0, 0, $month, $tmpday, $year, 1, 0);
695  $tmptime -= 24 * 60 * 60 * 7;
696  $tmparray = dol_getdate($tmptime, true);
697  $prev_day = $tmparray['mday'];
698 
699  //Check prev day of week is in same month than first day or not
700  if ($prev_day > $tmpday) {
701  $prev_month = $month - 1;
702  $prev_year = $year;
703 
704  if ($prev_month == 0) {
705  $prev_month = 12;
706  $prev_year = $year - 1;
707  }
708  }
709 
710  $week = date("W", dol_mktime(0, 0, 0, $tmpmonth, $tmpday, $tmpyear, $gm));
711 
712  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);
713 }
714 
722 function getGMTEasterDatetime($year)
723 {
724  $base = new DateTime("$year-03-21", new DateTimeZone("UTC"));
725  $days = easter_days($year); // Return number of days between 21 march and easter day.
726  $tmp = $base->add(new DateInterval("P{$days}D"));
727  return $tmp->getTimestamp();
728 }
729 
746 function num_public_holiday($timestampStart, $timestampEnd, $country_code = '', $lastday = 0, $includesaturday = -1, $includesunday = -1, $includefriday = -1, $includemonday = -1)
747 {
748  global $db, $conf, $mysoc;
749 
750  $nbFerie = 0;
751 
752  // Check to ensure we use correct parameters
753  if ((($timestampEnd - $timestampStart) % 86400) != 0) {
754  return 'Error Dates must use same hours and must be GMT dates';
755  }
756 
757  if (empty($country_code)) {
758  $country_code = $mysoc->country_code;
759  }
760  if ($includemonday < 0) {
761  $includemonday = (isset($conf->global->MAIN_NON_WORKING_DAYS_INCLUDE_MONDAY) ? $conf->global->MAIN_NON_WORKING_DAYS_INCLUDE_MONDAY : 0);
762  }
763  if ($includefriday < 0) {
764  $includefriday = (isset($conf->global->MAIN_NON_WORKING_DAYS_INCLUDE_FRIDAY) ? $conf->global->MAIN_NON_WORKING_DAYS_INCLUDE_FRIDAY : 0);
765  }
766  if ($includesaturday < 0) {
767  $includesaturday = (isset($conf->global->MAIN_NON_WORKING_DAYS_INCLUDE_SATURDAY) ? $conf->global->MAIN_NON_WORKING_DAYS_INCLUDE_SATURDAY : 1);
768  }
769  if ($includesunday < 0) {
770  $includesunday = (isset($conf->global->MAIN_NON_WORKING_DAYS_INCLUDE_SUNDAY) ? $conf->global->MAIN_NON_WORKING_DAYS_INCLUDE_SUNDAY : 1);
771  }
772 
773  $country_id = dol_getIdFromCode($db, $country_code, 'c_country', 'code', 'rowid');
774 
775  $i = 0;
776  while ((($lastday == 0 && $timestampStart < $timestampEnd) || ($lastday && $timestampStart <= $timestampEnd))
777  && ($i < 50000)) { // Loop end when equals (Test on i is a security loop to avoid infinite loop)
778  $ferie = false;
779  $specialdayrule = array();
780 
781  $jour = gmdate("d", $timestampStart);
782  $mois = gmdate("m", $timestampStart);
783  $annee = gmdate("Y", $timestampStart);
784 
785  //print "jour=".$jour." month=".$mois." year=".$annee." includesaturday=".$includesaturday." includesunday=".$includesunday."\n";
786 
787  // Loop on public holiday defined into hrm_public_holiday for the day, month and year analyzed
788  // TODO Execute this request first and store results into an array, then reuse this array.
789  $sql = "SELECT code, entity, fk_country, dayrule, year, month, day, active";
790  $sql .= " FROM ".MAIN_DB_PREFIX."c_hrm_public_holiday";
791  $sql .= " WHERE active = 1 and fk_country IN (0".($country_id > 0 ? ", ".$country_id : 0).")";
792  $sql .= " AND entity IN (0," .getEntity('holiday') .")";
793 
794  $resql = $db->query($sql);
795  if ($resql) {
796  $num_rows = $db->num_rows($resql);
797  $i = 0;
798  while ($i < $num_rows) {
799  $obj = $db->fetch_object($resql);
800 
801  if (!empty($obj->dayrule) && $obj->dayrule != 'date') { // For example 'easter', '...'
802  $specialdayrule[$obj->dayrule] = $obj->dayrule;
803  } else {
804  $match = 1;
805  if (!empty($obj->year) && $obj->year != $annee) {
806  $match = 0;
807  }
808  if ($obj->month != $mois) {
809  $match = 0;
810  }
811  if ($obj->day != $jour) {
812  $match = 0;
813  }
814 
815  if ($match) {
816  $ferie = true;
817  }
818  }
819 
820  $i++;
821  }
822  } else {
823  dol_syslog($db->lasterror(), LOG_ERR);
824  return 'Error sql '.$db->lasterror();
825  }
826  //var_dump($specialdayrule)."\n";
827  //print "ferie=".$ferie."\n";
828 
829  if (!$ferie) {
830  // Special dayrules
831  if (in_array('easter', $specialdayrule)) {
832  // Calculation for easter date
833  $date_paques = getGMTEasterDatetime($annee);
834  $jour_paques = gmdate("d", $date_paques);
835  $mois_paques = gmdate("m", $date_paques);
836  if ($jour_paques == $jour && $mois_paques == $mois) {
837  $ferie = true;
838  }
839  // Easter (sunday)
840  }
841 
842  if (in_array('eastermonday', $specialdayrule)) {
843  // Calculation for the monday of easter date
844  $date_paques = getGMTEasterDatetime($annee);
845  //print 'PPP'.$date_paques.' '.dol_print_date($date_paques, 'dayhour', 'gmt')." ";
846  $date_lundi_paques = $date_paques + (3600 * 24);
847  $jour_lundi_paques = gmdate("d", $date_lundi_paques);
848  $mois_lundi_paques = gmdate("m", $date_lundi_paques);
849  if ($jour_lundi_paques == $jour && $mois_lundi_paques == $mois) {
850  $ferie = true;
851  }
852  // Easter (monday)
853  //print 'annee='.$annee.' $jour='.$jour.' $mois='.$mois.' $jour_lundi_paques='.$jour_lundi_paques.' $mois_lundi_paques='.$mois_lundi_paques."\n";
854  }
855 
856  //Good Friday
857  if (in_array('goodfriday', $specialdayrule)) {
858  // Pulls the date of Easter
859  $easter = getGMTEasterDatetime($annee);
860 
861  // Calculates the date of Good Friday based on Easter
862  $date_good_friday = $easter - (2 * 3600 * 24);
863  $dom_good_friday = gmdate("d", $date_good_friday);
864  $month_good_friday = gmdate("m", $date_good_friday);
865 
866  if ($dom_good_friday == $jour && $month_good_friday == $mois) {
867  $ferie = true;
868  }
869  }
870 
871  if (in_array('ascension', $specialdayrule)) {
872  // Calcul du jour de l'ascension (39 days after easter day)
873  $date_paques = getGMTEasterDatetime($annee);
874  $date_ascension = $date_paques + (3600 * 24 * 39);
875  $jour_ascension = gmdate("d", $date_ascension);
876  $mois_ascension = gmdate("m", $date_ascension);
877  if ($jour_ascension == $jour && $mois_ascension == $mois) {
878  $ferie = true;
879  }
880  // Ascension (thursday)
881  }
882 
883  if (in_array('pentecote', $specialdayrule)) {
884  // Calculation of "Pentecote" (49 days after easter day)
885  $date_paques = getGMTEasterDatetime($annee);
886  $date_pentecote = $date_paques + (3600 * 24 * 49);
887  $jour_pentecote = gmdate("d", $date_pentecote);
888  $mois_pentecote = gmdate("m", $date_pentecote);
889  if ($jour_pentecote == $jour && $mois_pentecote == $mois) {
890  $ferie = true;
891  }
892  // "Pentecote" (sunday)
893  }
894  if (in_array('pentecotemonday', $specialdayrule)) {
895  // Calculation of "Pentecote" (49 days after easter day)
896  $date_paques = getGMTEasterDatetime($annee);
897  $date_pentecote = $date_paques + (3600 * 24 * 50);
898  $jour_pentecote = gmdate("d", $date_pentecote);
899  $mois_pentecote = gmdate("m", $date_pentecote);
900  if ($jour_pentecote == $jour && $mois_pentecote == $mois) {
901  $ferie = true;
902  }
903  // "Pentecote" (monday)
904  }
905 
906  if (in_array('viernessanto', $specialdayrule)) {
907  // Viernes Santo
908  $date_paques = getGMTEasterDatetime($annee);
909  $date_viernes = $date_paques - (3600 * 24 * 2);
910  $jour_viernes = gmdate("d", $date_viernes);
911  $mois_viernes = gmdate("m", $date_viernes);
912  if ($jour_viernes == $jour && $mois_viernes == $mois) {
913  $ferie = true;
914  }
915  //Viernes Santo
916  }
917 
918  if (in_array('fronleichnam', $specialdayrule)) {
919  // Fronleichnam (60 days after easter sunday)
920  $date_paques = getGMTEasterDatetime($annee);
921  $date_fronleichnam = $date_paques + (3600 * 24 * 60);
922  $jour_fronleichnam = gmdate("d", $date_fronleichnam);
923  $mois_fronleichnam = gmdate("m", $date_fronleichnam);
924  if ($jour_fronleichnam == $jour && $mois_fronleichnam == $mois) {
925  $ferie = true;
926  }
927  // Fronleichnam
928  }
929 
930  if (in_array('genevafast', $specialdayrule)) {
931  // Geneva fast in Switzerland (Thursday after the first sunday in September)
932  $date_1sunsept = strtotime('next thursday', strtotime('next sunday', mktime(0, 0, 0, 9, 1, $annee)));
933  $jour_1sunsept = date("d", $date_1sunsept);
934  $mois_1sunsept = date("m", $date_1sunsept);
935  if ($jour_1sunsept == $jour && $mois_1sunsept == $mois) $ferie=true;
936  // Geneva fast in Switzerland
937  }
938  }
939  //print "ferie=".$ferie."\n";
940 
941  // If we have to include Friday, Saturday and Sunday
942  if (!$ferie) {
943  if ($includefriday || $includesaturday || $includesunday) {
944  $jour_julien = unixtojd($timestampStart);
945  $jour_semaine = jddayofweek($jour_julien, 0);
946  if ($includefriday) { //Friday (5), Saturday (6) and Sunday (0)
947  if ($jour_semaine == 5) {
948  $ferie = true;
949  }
950  }
951  if ($includesaturday) { //Friday (5), Saturday (6) and Sunday (0)
952  if ($jour_semaine == 6) {
953  $ferie = true;
954  }
955  }
956  if ($includesunday) { //Friday (5), Saturday (6) and Sunday (0)
957  if ($jour_semaine == 0) {
958  $ferie = true;
959  }
960  }
961  }
962  }
963  //print "ferie=".$ferie."\n";
964 
965  // We increase the counter of non working day
966  if ($ferie) {
967  $nbFerie++;
968  }
969 
970  // Increase number of days (on go up into loop)
971  $timestampStart = dol_time_plus_duree($timestampStart, 1, 'd');
972  //var_dump($jour.' '.$mois.' '.$annee.' '.$timestampStart);
973 
974  $i++;
975  }
976 
977  //print "nbFerie=".$nbFerie."\n";
978  return $nbFerie;
979 }
980 
991 function num_between_day($timestampStart, $timestampEnd, $lastday = 0)
992 {
993  if ($timestampStart < $timestampEnd) {
994  if ($lastday == 1) {
995  $bit = 0;
996  } else {
997  $bit = 1;
998  }
999  $nbjours = (int) floor(($timestampEnd - $timestampStart) / (60 * 60 * 24)) + 1 - $bit;
1000  }
1001  //print ($timestampEnd - $timestampStart) - $lastday;
1002  return $nbjours;
1003 }
1004 
1017 function num_open_day($timestampStart, $timestampEnd, $inhour = 0, $lastday = 0, $halfday = 0, $country_code = '')
1018 {
1019  global $langs, $mysoc;
1020 
1021  if (empty($country_code)) {
1022  $country_code = $mysoc->country_code;
1023  }
1024 
1025  dol_syslog('num_open_day timestampStart='.$timestampStart.' timestampEnd='.$timestampEnd.' bit='.$lastday.' country_code='.$country_code);
1026 
1027  // Check parameters
1028  if (!is_int($timestampStart) && !is_float($timestampStart)) {
1029  return 'ErrorBadParameter_num_open_day';
1030  }
1031  if (!is_int($timestampEnd) && !is_float($timestampEnd)) {
1032  return 'ErrorBadParameter_num_open_day';
1033  }
1034 
1035  //print 'num_open_day timestampStart='.$timestampStart.' timestampEnd='.$timestampEnd.' bit='.$lastday;
1036  if ($timestampStart < $timestampEnd) {
1037  $numdays = num_between_day($timestampStart, $timestampEnd, $lastday);
1038 
1039  $numholidays = num_public_holiday($timestampStart, $timestampEnd, $country_code, $lastday);
1040  $nbOpenDay = ($numdays - $numholidays);
1041  if ($inhour == 1 && $nbOpenDay <= 3) {
1042  $nbOpenDay = ($nbOpenDay * 24);
1043  }
1044  return $nbOpenDay - (($inhour == 1 ? 12 : 0.5) * abs($halfday));
1045  } elseif ($timestampStart == $timestampEnd) {
1046  $numholidays = 0;
1047  if ($lastday) {
1048  $numholidays = num_public_holiday($timestampStart, $timestampEnd, $country_code, $lastday);
1049  if ($numholidays == 1) {
1050  return 0;
1051  }
1052  }
1053 
1054  $nbOpenDay = $lastday;
1055 
1056  if ($inhour == 1) {
1057  $nbOpenDay = ($nbOpenDay * 24);
1058  }
1059  return $nbOpenDay - (($inhour == 1 ? 12 : 0.5) * abs($halfday));
1060  } else {
1061  return $langs->trans("Error");
1062  }
1063 }
1064 
1065 
1066 
1075 function monthArray($outputlangs, $short = 0)
1076 {
1077  $montharray = array(
1078  1 => $outputlangs->trans("Month01"),
1079  2 => $outputlangs->trans("Month02"),
1080  3 => $outputlangs->trans("Month03"),
1081  4 => $outputlangs->trans("Month04"),
1082  5 => $outputlangs->trans("Month05"),
1083  6 => $outputlangs->trans("Month06"),
1084  7 => $outputlangs->trans("Month07"),
1085  8 => $outputlangs->trans("Month08"),
1086  9 => $outputlangs->trans("Month09"),
1087  10 => $outputlangs->trans("Month10"),
1088  11 => $outputlangs->trans("Month11"),
1089  12 => $outputlangs->trans("Month12")
1090  );
1091 
1092  if (!empty($short)) {
1093  $montharray = array(
1094  1 => $outputlangs->trans("MonthShort01"),
1095  2 => $outputlangs->trans("MonthShort02"),
1096  3 => $outputlangs->trans("MonthShort03"),
1097  4 => $outputlangs->trans("MonthShort04"),
1098  5 => $outputlangs->trans("MonthShort05"),
1099  6 => $outputlangs->trans("MonthShort06"),
1100  7 => $outputlangs->trans("MonthShort07"),
1101  8 => $outputlangs->trans("MonthShort08"),
1102  9 => $outputlangs->trans("MonthShort09"),
1103  10 => $outputlangs->trans("MonthShort10"),
1104  11 => $outputlangs->trans("MonthShort11"),
1105  12 => $outputlangs->trans("MonthShort12")
1106  );
1107  }
1108 
1109  return $montharray;
1110 }
1118 function getWeekNumbersOfMonth($month, $year)
1119 {
1120  $nb_days = cal_days_in_month(CAL_GREGORIAN, $month, $year);
1121  $TWeek = array();
1122  for ($day = 1; $day < $nb_days; $day++) {
1123  $week_number = getWeekNumber($day, $month, $year);
1124  $TWeek[$week_number] = $week_number;
1125  }
1126  return $TWeek;
1127 }
1135 function getFirstDayOfEachWeek($TWeek, $year)
1136 {
1137  $TFirstDayOfWeek = array();
1138  foreach ($TWeek as $weekNb) {
1139  if (in_array('01', $TWeek) && in_array('52', $TWeek) && $weekNb == '01') {
1140  $year++; //Si on a la 1re semaine et la semaine 52 c'est qu'on change d'annĂ©e
1141  }
1142  $TFirstDayOfWeek[$weekNb] = date('d', strtotime($year.'W'.$weekNb));
1143  }
1144  return $TFirstDayOfWeek;
1145 }
1153 function getLastDayOfEachWeek($TWeek, $year)
1154 {
1155  $TLastDayOfWeek = array();
1156  foreach ($TWeek as $weekNb) {
1157  $TLastDayOfWeek[$weekNb] = date('d', strtotime($year.'W'.$weekNb.'+6 days'));
1158  }
1159  return $TLastDayOfWeek;
1160 }
1169 function getWeekNumber($day, $month, $year)
1170 {
1171  $date = new DateTime($year.'-'.$month.'-'.$day);
1172  $week = $date->format("W");
1173  return $week;
1174 }
if(isModEnabled('facture') && $user->hasRight('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') && $user->hasRight('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)) $sql
Social contributions to pay.
Definition: index.php:746
dol_get_prev_month($month, $year)
Return previous month.
Definition: date.lib.php:496
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:637
dol_get_next_day($day, $month, $year)
Return next day.
Definition: date.lib.php:481
dol_get_next_week($day, $week, $month, $year)
Return next week.
Definition: date.lib.php:555
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:360
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:623
getLastDayOfEachWeek($TWeek, $year)
Return array of last day of weeks.
Definition: date.lib.php:1153
getWeekNumbersOfMonth($month, $year)
Return array of week numbers.
Definition: date.lib.php:1118
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:652
getGMTEasterDatetime($year)
Return the easter day in GMT time.
Definition: date.lib.php:722
convertDurationtoHour($duration_value, $duration_unit)
Convert duration to hour.
Definition: date.lib.php:332
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:465
dol_get_first_day($year, $month=1, $gm=false)
Return GMT time for first day of a month or year.
Definition: date.lib.php:577
getFirstDayOfEachWeek($TWeek, $year)
Return array of first day of weeks.
Definition: date.lib.php:1135
dol_get_next_month($month, $year)
Return next month.
Definition: date.lib.php:515
getWeekNumber($day, $month, $year)
Return week number.
Definition: date.lib.php:1169
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:991
convertTime2Seconds($iHours=0, $iMinutes=0, $iSeconds=0)
Convert hours and minutes into seconds.
Definition: date.lib.php:211
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:1017
dol_time_plus_duree($time, $duration_value, $duration_unit, $ruleforendofmonth=0)
Add a delay to a date.
Definition: date.lib.php:122
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:240
dol_get_prev_week($day, $week, $month, $year)
Return previous week.
Definition: date.lib.php:536
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:409
dol_get_last_day($year, $month=12, $gm=false)
Return GMT time for last day of a month or year.
Definition: date.lib.php:596
monthArray($outputlangs, $short=0)
Return array of translated months or selected month.
Definition: date.lib.php:1075
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:746
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.