dolibarr  19.0.0-dev
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 
239 function convertSecondToTime($iSecond, $format = 'all', $lengthOfDay = 86400, $lengthOfWeek = 7)
240 {
241  global $langs;
242 
243  if (empty($lengthOfDay)) {
244  $lengthOfDay = 86400; // 1 day = 24 hours
245  }
246  if (empty($lengthOfWeek)) {
247  $lengthOfWeek = 7; // 1 week = 7 days
248  }
249  $nbHbyDay = $lengthOfDay / 3600;
250 
251  if ($format == 'all' || $format == 'allwithouthour' || $format == 'allhour' || $format == 'allhourmin' || $format == 'allhourminsec') {
252  if ((int) $iSecond === 0) {
253  return '0'; // This is to avoid having 0 return a 12:00 AM for en_US
254  }
255 
256  $sTime = '';
257  $sDay = 0;
258  $sWeek = 0;
259 
260  if ($iSecond >= $lengthOfDay) {
261  for ($i = $iSecond; $i >= $lengthOfDay; $i -= $lengthOfDay) {
262  $sDay++;
263  $iSecond -= $lengthOfDay;
264  }
265  $dayTranslate = $langs->trans("Day");
266  if ($iSecond >= ($lengthOfDay * 2)) {
267  $dayTranslate = $langs->trans("Days");
268  }
269  }
270 
271  if ($lengthOfWeek < 7) {
272  if ($sDay) {
273  if ($sDay >= $lengthOfWeek) {
274  $sWeek = (int) (($sDay - $sDay % $lengthOfWeek) / $lengthOfWeek);
275  $sDay = $sDay % $lengthOfWeek;
276  $weekTranslate = $langs->trans("DurationWeek");
277  if ($sWeek >= 2) {
278  $weekTranslate = $langs->trans("DurationWeeks");
279  }
280  $sTime .= $sWeek.' '.$weekTranslate.' ';
281  }
282  }
283  }
284  if ($sDay > 0) {
285  $dayTranslate = $langs->trans("Day");
286  if ($sDay > 1) {
287  $dayTranslate = $langs->trans("Days");
288  }
289  $sTime .= $sDay.' '.$langs->trans("d").' ';
290  }
291 
292  if ($format == 'all') {
293  if ($iSecond || empty($sDay)) {
294  $sTime .= dol_print_date($iSecond, 'hourduration', true);
295  }
296  } elseif ($format == 'allhourminsec') {
297  return sprintf("%02d", ($sWeek * $lengthOfWeek * $nbHbyDay + $sDay * $nbHbyDay + (int) floor($iSecond/3600))).':'.sprintf("%02d", ((int) floor(($iSecond % 3600) / 60))).':'.sprintf("%02d", ((int) ($iSecond % 60)));
298  } elseif ($format == 'allhourmin') {
299  return sprintf("%02d", ($sWeek * $lengthOfWeek * $nbHbyDay + $sDay * $nbHbyDay + (int) floor($iSecond/3600))).':'.sprintf("%02d", ((int) floor(($iSecond % 3600)/60)));
300  } elseif ($format == 'allhour') {
301  return sprintf("%02d", ($sWeek * $lengthOfWeek * $nbHbyDay + $sDay * $nbHbyDay + (int) floor($iSecond/3600)));
302  }
303  } elseif ($format == 'hour') { // only hour part
304  $sTime = dol_print_date($iSecond, '%H', true);
305  } elseif ($format == 'fullhour') {
306  if (!empty($iSecond)) {
307  $iSecond = $iSecond / 3600;
308  } else {
309  $iSecond = 0;
310  }
311  $sTime = $iSecond;
312  } elseif ($format == 'min') { // only min part
313  $sTime = dol_print_date($iSecond, '%M', true);
314  } elseif ($format == 'sec') { // only sec part
315  $sTime = dol_print_date($iSecond, '%S', true);
316  } elseif ($format == 'month') { // only month part
317  $sTime = dol_print_date($iSecond, '%m', true);
318  } elseif ($format == 'year') { // only year part
319  $sTime = dol_print_date($iSecond, '%Y', true);
320  }
321  return trim($sTime);
322 }
323 
324 
331 function convertDurationtoHour($duration_value, $duration_unit)
332 {
333  $result = 0;
334 
335  if ($duration_unit == 's') $result = $duration_value / 3600;
336  if ($duration_unit == 'i') $result = $duration_value / 60;
337  if ($duration_unit == 'h') $result = $duration_value;
338  if ($duration_unit == 'd') $result = $duration_value * 24;
339  if ($duration_unit == 'w') $result = $duration_value * 24 * 7;
340  if ($duration_unit == 'm') $result = $duration_value * 730.484;
341  if ($duration_unit == 'y') $result = $duration_value * 365 * 24;
342 
343  return $result;
344 }
345 
359 function dolSqlDateFilter($datefield, $day_date, $month_date, $year_date, $excludefirstand = 0, $gm = false)
360 {
361  global $db;
362  $sqldate = '';
363 
364  $day_date = intval($day_date);
365  $month_date = intval($month_date);
366  $year_date = intval($year_date);
367 
368  if ($month_date > 0) {
369  if ($month_date > 12) { // protection for bad value of month
370  return " AND 1 = 2";
371  }
372  if ($year_date > 0 && empty($day_date)) {
373  $sqldate .= ($excludefirstand ? "" : " AND ").$datefield." BETWEEN '".$db->idate(dol_get_first_day($year_date, $month_date, $gm));
374  $sqldate .= "' AND '".$db->idate(dol_get_last_day($year_date, $month_date, $gm))."'";
375  } elseif ($year_date > 0 && !empty($day_date)) {
376  $sqldate .= ($excludefirstand ? "" : " AND ").$datefield." BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $month_date, $day_date, $year_date, $gm));
377  $sqldate .= "' AND '".$db->idate(dol_mktime(23, 59, 59, $month_date, $day_date, $year_date, $gm))."'";
378  } else {
379  // This case is not reliable on TZ, but we should not need it.
380  $sqldate .= ($excludefirstand ? "" : " AND ")." date_format( ".$datefield.", '%c') = '".$db->escape($month_date)."'";
381  }
382  } elseif ($year_date > 0) {
383  $sqldate .= ($excludefirstand ? "" : " AND ").$datefield." BETWEEN '".$db->idate(dol_get_first_day($year_date, 1, $gm));
384  $sqldate .= "' AND '".$db->idate(dol_get_last_day($year_date, 12, $gm))."'";
385  }
386  return $sqldate;
387 }
388 
408 function dol_stringtotime($string, $gm = 1)
409 {
410  $reg = array();
411  // Convert date with format DD/MM/YYY HH:MM:SS. This part of code should not be used.
412  if (preg_match('/^([0-9]+)\/([0-9]+)\/([0-9]+)\s?([0-9]+)?:?([0-9]+)?:?([0-9]+)?/i', $string, $reg)) {
413  dol_syslog("dol_stringtotime call to function with deprecated parameter format", LOG_WARNING);
414  // Date est au format 'DD/MM/YY' ou 'DD/MM/YY HH:MM:SS'
415  // Date est au format 'DD/MM/YYYY' ou 'DD/MM/YYYY HH:MM:SS'
416  $sday = $reg[1];
417  $smonth = $reg[2];
418  $syear = $reg[3];
419  $shour = $reg[4];
420  $smin = $reg[5];
421  $ssec = $reg[6];
422  if ($syear < 50) {
423  $syear += 1900;
424  }
425  if ($syear >= 50 && $syear < 100) {
426  $syear += 2000;
427  }
428  $string = sprintf("%04d%02d%02d%02d%02d%02d", $syear, $smonth, $sday, $shour, $smin, $ssec);
429  } 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)
430  || 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
431  || 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
432  ) {
433  $syear = $reg[1];
434  $smonth = $reg[2];
435  $sday = $reg[3];
436  $shour = $reg[4];
437  $smin = $reg[5];
438  $ssec = $reg[6];
439  $string = sprintf("%04d%02d%02d%02d%02d%02d", $syear, $smonth, $sday, $shour, $smin, $ssec);
440  }
441 
442  $string = preg_replace('/([^0-9])/i', '', $string);
443  $tmp = $string.'000000';
444  // Clean $gm
445  if ($gm === 1) {
446  $gm = 'gmt';
447  } elseif (empty($gm) || $gm === 'tzserver') {
448  $gm = 'tzserver';
449  }
450 
451  $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);
452  return $date;
453 }
454 
455 
464 function dol_get_prev_day($day, $month, $year)
465 {
466  $time = dol_mktime(12, 0, 0, $month, $day, $year, 1, 0);
467  $time -= 24 * 60 * 60;
468  $tmparray = dol_getdate($time, true);
469  return array('year' => $tmparray['year'], 'month' => $tmparray['mon'], 'day' => $tmparray['mday']);
470 }
471 
480 function dol_get_next_day($day, $month, $year)
481 {
482  $time = dol_mktime(12, 0, 0, $month, $day, $year, 1, 0);
483  $time += 24 * 60 * 60;
484  $tmparray = dol_getdate($time, true);
485  return array('year' => $tmparray['year'], 'month' => $tmparray['mon'], 'day' => $tmparray['mday']);
486 }
487 
495 function dol_get_prev_month($month, $year)
496 {
497  if ($month == 1) {
498  $prev_month = 12;
499  $prev_year = $year - 1;
500  } else {
501  $prev_month = $month - 1;
502  $prev_year = $year;
503  }
504  return array('year' => $prev_year, 'month' => $prev_month);
505 }
506 
514 function dol_get_next_month($month, $year)
515 {
516  if ($month == 12) {
517  $next_month = 1;
518  $next_year = $year + 1;
519  } else {
520  $next_month = $month + 1;
521  $next_year = $year;
522  }
523  return array('year' => $next_year, 'month' => $next_month);
524 }
525 
535 function dol_get_prev_week($day, $week, $month, $year)
536 {
537  $tmparray = dol_get_first_day_week($day, $month, $year);
538 
539  $time = dol_mktime(12, 0, 0, $month, $tmparray['first_day'], $year, 1, 0);
540  $time -= 24 * 60 * 60 * 7;
541  $tmparray = dol_getdate($time, true);
542  return array('year' => $tmparray['year'], 'month' => $tmparray['mon'], 'day' => $tmparray['mday']);
543 }
544 
554 function dol_get_next_week($day, $week, $month, $year)
555 {
556  $tmparray = dol_get_first_day_week($day, $month, $year);
557 
558  $time = dol_mktime(12, 0, 0, $tmparray['first_month'], $tmparray['first_day'], $tmparray['first_year'], 1, 0);
559  $time += 24 * 60 * 60 * 7;
560  $tmparray = dol_getdate($time, true);
561 
562  return array('year' => $tmparray['year'], 'month' => $tmparray['mon'], 'day' => $tmparray['mday']);
563 }
564 
576 function dol_get_first_day($year, $month = 1, $gm = false)
577 {
578  if ($year > 9999) {
579  return '';
580  }
581  return dol_mktime(0, 0, 0, $month, 1, $year, $gm);
582 }
583 
584 
595 function dol_get_last_day($year, $month = 12, $gm = false)
596 {
597  if ($year > 9999) {
598  return '';
599  }
600  if ($month == 12) {
601  $month = 1;
602  $year += 1;
603  } else {
604  $month += 1;
605  }
606 
607  // On se deplace au debut du mois suivant, et on retire un jour
608  $datelim = dol_mktime(23, 59, 59, $month, 1, $year, $gm);
609  $datelim -= (3600 * 24);
610 
611  return $datelim;
612 }
613 
622 function dol_get_last_hour($date, $gm = 'tzserver')
623 {
624  $tmparray = dol_getdate($date, false, ($gm == 'gmt' ? 'gmt' : ''));
625  return dol_mktime(23, 59, 59, $tmparray['mon'], $tmparray['mday'], $tmparray['year'], $gm);
626 }
627 
636 function dol_get_first_hour($date, $gm = 'tzserver')
637 {
638  $tmparray = dol_getdate($date, false, ($gm == 'gmt' ? 'gmt' : ''));
639  return dol_mktime(0, 0, 0, $tmparray['mon'], $tmparray['mday'], $tmparray['year'], $gm);
640 }
641 
651 function dol_get_first_day_week($day, $month, $year, $gm = false)
652 {
653  global $conf;
654 
655  //$day=2; $month=2; $year=2015;
656  $date = dol_mktime(0, 0, 0, $month, $day, $year, $gm);
657 
658  //Checking conf of start week
659  $start_week = (isset($conf->global->MAIN_START_WEEK) ? $conf->global->MAIN_START_WEEK : 1);
660 
661  $tmparray = dol_getdate($date, true); // detail of current day
662 
663  //Calculate days = offset from current day
664  $days = $start_week - $tmparray['wday'];
665  if ($days >= 1) {
666  $days = 7 - $days;
667  }
668  $days = abs($days);
669  $seconds = $days * 24 * 60 * 60;
670  //print 'start_week='.$start_week.' tmparray[wday]='.$tmparray['wday'].' day offset='.$days.' seconds offset='.$seconds.'<br>';
671 
672  //Get first day of week
673  $tmpdaytms = date($tmparray[0]) - $seconds; // $tmparray[0] is day of parameters
674  $tmpday = date("d", $tmpdaytms);
675 
676  //Check first day of week is in same month than current day or not
677  if ($tmpday > $day) {
678  $prev_month = $month - 1;
679  $prev_year = $year;
680 
681  if ($prev_month == 0) {
682  $prev_month = 12;
683  $prev_year = $year - 1;
684  }
685  } else {
686  $prev_month = $month;
687  $prev_year = $year;
688  }
689  $tmpmonth = $prev_month;
690  $tmpyear = $prev_year;
691 
692  //Get first day of next week
693  $tmptime = dol_mktime(12, 0, 0, $month, $tmpday, $year, 1, 0);
694  $tmptime -= 24 * 60 * 60 * 7;
695  $tmparray = dol_getdate($tmptime, true);
696  $prev_day = $tmparray['mday'];
697 
698  //Check prev day of week is in same month than first day or not
699  if ($prev_day > $tmpday) {
700  $prev_month = $month - 1;
701  $prev_year = $year;
702 
703  if ($prev_month == 0) {
704  $prev_month = 12;
705  $prev_year = $year - 1;
706  }
707  }
708 
709  $week = date("W", dol_mktime(0, 0, 0, $tmpmonth, $tmpday, $tmpyear, $gm));
710 
711  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);
712 }
713 
721 function getGMTEasterDatetime($year)
722 {
723  $base = new DateTime("$year-03-21", new DateTimeZone("UTC"));
724  $days = easter_days($year); // Return number of days between 21 march and easter day.
725  $tmp = $base->add(new DateInterval("P{$days}D"));
726  return $tmp->getTimestamp();
727 }
728 
745 function num_public_holiday($timestampStart, $timestampEnd, $country_code = '', $lastday = 0, $includesaturday = -1, $includesunday = -1, $includefriday = -1, $includemonday = -1)
746 {
747  global $db, $conf, $mysoc;
748 
749  $nbFerie = 0;
750 
751  // Check to ensure we use correct parameters
752  if ((($timestampEnd - $timestampStart) % 86400) != 0) {
753  return 'Error Dates must use same hours and must be GMT dates';
754  }
755 
756  if (empty($country_code)) {
757  $country_code = $mysoc->country_code;
758  }
759  if ($includemonday < 0) {
760  $includemonday = (isset($conf->global->MAIN_NON_WORKING_DAYS_INCLUDE_MONDAY) ? $conf->global->MAIN_NON_WORKING_DAYS_INCLUDE_MONDAY : 0);
761  }
762  if ($includefriday < 0) {
763  $includefriday = (isset($conf->global->MAIN_NON_WORKING_DAYS_INCLUDE_FRIDAY) ? $conf->global->MAIN_NON_WORKING_DAYS_INCLUDE_FRIDAY : 0);
764  }
765  if ($includesaturday < 0) {
766  $includesaturday = (isset($conf->global->MAIN_NON_WORKING_DAYS_INCLUDE_SATURDAY) ? $conf->global->MAIN_NON_WORKING_DAYS_INCLUDE_SATURDAY : 1);
767  }
768  if ($includesunday < 0) {
769  $includesunday = (isset($conf->global->MAIN_NON_WORKING_DAYS_INCLUDE_SUNDAY) ? $conf->global->MAIN_NON_WORKING_DAYS_INCLUDE_SUNDAY : 1);
770  }
771 
772  $country_id = dol_getIdFromCode($db, $country_code, 'c_country', 'code', 'rowid');
773 
774  $i = 0;
775  while ((($lastday == 0 && $timestampStart < $timestampEnd) || ($lastday && $timestampStart <= $timestampEnd))
776  && ($i < 50000)) { // Loop end when equals (Test on i is a security loop to avoid infinite loop)
777  $ferie = false;
778  $specialdayrule = array();
779 
780  $jour = gmdate("d", $timestampStart);
781  $mois = gmdate("m", $timestampStart);
782  $annee = gmdate("Y", $timestampStart);
783 
784  //print "jour=".$jour." month=".$mois." year=".$annee." includesaturday=".$includesaturday." includesunday=".$includesunday."\n";
785 
786  // Loop on public holiday defined into hrm_public_holiday for the day, month and year analyzed
787  // TODO Execute this request first and store results into an array, then reuse this array.
788  $sql = "SELECT code, entity, fk_country, dayrule, year, month, day, active";
789  $sql .= " FROM ".MAIN_DB_PREFIX."c_hrm_public_holiday";
790  $sql .= " WHERE active = 1 and fk_country IN (0".($country_id > 0 ? ", ".$country_id : 0).")";
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') && $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:495
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:636
dol_get_next_day($day, $month, $year)
Return next day.
Definition: date.lib.php:480
dol_get_next_week($day, $week, $month, $year)
Return next week.
Definition: date.lib.php:554
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:359
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:622
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:651
getGMTEasterDatetime($year)
Return the easter day in GMT time.
Definition: date.lib.php:721
convertDurationtoHour($duration_value, $duration_unit)
Convert duration to hour.
Definition: date.lib.php:331
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:464
dol_get_first_day($year, $month=1, $gm=false)
Return GMT time for first day of a month or year.
Definition: date.lib.php:576
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:514
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: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:1015
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:239
dol_get_prev_week($day, $week, $month, $year)
Return previous week.
Definition: date.lib.php:535
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:408
dol_get_last_day($year, $month=12, $gm=false)
Return GMT time for last day of a month or year.
Definition: date.lib.php:595
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:745
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.