date.lib.php 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190
  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. /**
  23. * \file htdocs/core/lib/date.lib.php
  24. * \brief Set of function to manipulate dates
  25. */
  26. /**
  27. * Return an array with timezone values
  28. *
  29. * @return array Array with timezone values
  30. */
  31. function get_tz_array()
  32. {
  33. $tzarray = array(
  34. -11=>"Pacific/Midway",
  35. -10=>"Pacific/Fakaofo",
  36. -9=>"America/Anchorage",
  37. -8=>"America/Los_Angeles",
  38. -7=>"America/Dawson_Creek",
  39. -6=>"America/Chicago",
  40. -5=>"America/Bogota",
  41. -4=>"America/Anguilla",
  42. -3=>"America/Araguaina",
  43. -2=>"America/Noronha",
  44. -1=>"Atlantic/Azores",
  45. 0=>"Africa/Abidjan",
  46. 1=>"Europe/Paris",
  47. 2=>"Europe/Helsinki",
  48. 3=>"Europe/Moscow",
  49. 4=>"Asia/Dubai",
  50. 5=>"Asia/Karachi",
  51. 6=>"Indian/Chagos",
  52. 7=>"Asia/Jakarta",
  53. 8=>"Asia/Hong_Kong",
  54. 9=>"Asia/Tokyo",
  55. 10=>"Australia/Sydney",
  56. 11=>"Pacific/Noumea",
  57. 12=>"Pacific/Auckland",
  58. 13=>"Pacific/Enderbury"
  59. );
  60. return $tzarray;
  61. }
  62. /**
  63. * Return server timezone string
  64. *
  65. * @return string PHP server timezone string ('Europe/Paris')
  66. */
  67. function getServerTimeZoneString()
  68. {
  69. return @date_default_timezone_get();
  70. }
  71. /**
  72. * Return server timezone int.
  73. *
  74. * @param string $refgmtdate Reference period for timezone (timezone differs on winter and summer. May be 'now', 'winter' or 'summer')
  75. * @return float An offset in hour (+1 for Europe/Paris on winter and +2 for Europe/Paris on summer). Note some countries use half and even quarter hours.
  76. */
  77. function getServerTimeZoneInt($refgmtdate = 'now')
  78. {
  79. if (method_exists('DateTimeZone', 'getOffset')) {
  80. // Method 1 (include daylight)
  81. $gmtnow = dol_now('gmt');
  82. $yearref = dol_print_date($gmtnow, '%Y');
  83. $monthref = dol_print_date($gmtnow, '%m');
  84. $dayref = dol_print_date($gmtnow, '%d');
  85. if ($refgmtdate == 'now') {
  86. $newrefgmtdate = $yearref.'-'.$monthref.'-'.$dayref;
  87. } elseif ($refgmtdate == 'summer') {
  88. $newrefgmtdate = $yearref.'-08-01';
  89. } else {
  90. $newrefgmtdate = $yearref.'-01-01';
  91. }
  92. $newrefgmtdate .= 'T00:00:00+00:00';
  93. $localtz = new DateTimeZone(getServerTimeZoneString());
  94. $localdt = new DateTime($newrefgmtdate, $localtz);
  95. $tmp = -1 * $localtz->getOffset($localdt);
  96. //print $refgmtdate.'='.$tmp;
  97. } else {
  98. $tmp = 0;
  99. dol_print_error('', 'PHP version must be 5.3+');
  100. }
  101. $tz = round(($tmp < 0 ? 1 : -1) * abs($tmp / 3600));
  102. return $tz;
  103. }
  104. /**
  105. * Add a delay to a date
  106. *
  107. * @param int $time Date timestamp (or string with format YYYY-MM-DD)
  108. * @param int $duration_value Value of delay to add
  109. * @param int $duration_unit Unit of added delay (d, m, y, w, h, i)
  110. * @param int $ruleforendofmonth Change the behavior of PHP over data-interval, 0 or 1
  111. * @return int New timestamp
  112. * @see convertSecondToTime(), convertTimeToSeconds()
  113. */
  114. function dol_time_plus_duree($time, $duration_value, $duration_unit, $ruleforendofmonth = 0)
  115. {
  116. global $conf;
  117. if (empty($duration_value)) {
  118. return $time;
  119. }
  120. if ($duration_unit == 's') {
  121. return $time + ($duration_value);
  122. }
  123. if ($duration_unit == 'i') {
  124. return $time + (60 * $duration_value);
  125. }
  126. if ($duration_unit == 'h') {
  127. return $time + (3600 * $duration_value);
  128. }
  129. if ($duration_unit == 'w') {
  130. return $time + (3600 * 24 * 7 * $duration_value);
  131. }
  132. $deltastring = 'P';
  133. if ($duration_value > 0) {
  134. $deltastring .= abs($duration_value);
  135. $sub = false;
  136. }
  137. if ($duration_value < 0) {
  138. $deltastring .= abs($duration_value);
  139. $sub = true;
  140. }
  141. if ($duration_unit == 'd') {
  142. $deltastring .= "D";
  143. }
  144. if ($duration_unit == 'm') {
  145. $deltastring .= "M";
  146. }
  147. if ($duration_unit == 'y') {
  148. $deltastring .= "Y";
  149. }
  150. $date = new DateTime();
  151. if (getDolGlobalString('MAIN_DATE_IN_MEMORY_ARE_GMT')) {
  152. $date->setTimezone(new DateTimeZone('UTC'));
  153. }
  154. $date->setTimestamp($time);
  155. $interval = new DateInterval($deltastring);
  156. if ($sub) {
  157. $date->sub($interval);
  158. } else {
  159. $date->add($interval);
  160. }
  161. //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)
  162. if ($ruleforendofmonth == 1 && $duration_unit == 'm') {
  163. $timeyear = dol_print_date($time, '%Y');
  164. $timemonth = dol_print_date($time, '%m');
  165. $timetotalmonths = (($timeyear * 12) + $timemonth);
  166. $monthsexpected = ($timetotalmonths + $duration_value);
  167. $newtime = $date->getTimestamp();
  168. $newtimeyear = dol_print_date($newtime, '%Y');
  169. $newtimemonth = dol_print_date($newtime, '%m');
  170. $newtimetotalmonths = (($newtimeyear * 12) + $newtimemonth);
  171. if ($monthsexpected < $newtimetotalmonths) {
  172. $newtimehours = dol_print_date($newtime, '%H');
  173. $newtimemins = dol_print_date($newtime, '%M');
  174. $newtimesecs = dol_print_date($newtime, '%S');
  175. $datelim = dol_mktime($newtimehours, $newtimemins, $newtimesecs, $newtimemonth, 1, $newtimeyear);
  176. $datelim -= (3600 * 24);
  177. $date->setTimestamp($datelim);
  178. }
  179. }
  180. return $date->getTimestamp();
  181. }
  182. /**
  183. * Convert hours and minutes into seconds
  184. *
  185. * @param int $iHours Hours
  186. * @param int $iMinutes Minutes
  187. * @param int $iSeconds Seconds
  188. * @return int Time into seconds
  189. * @see convertSecondToTime()
  190. */
  191. function convertTime2Seconds($iHours = 0, $iMinutes = 0, $iSeconds = 0)
  192. {
  193. $iResult = ((int) $iHours * 3600) + ((int) $iMinutes * 60) + (int) $iSeconds;
  194. return $iResult;
  195. }
  196. /** Return, in clear text, value of a number of seconds in days, hours and minutes.
  197. * Can be used to show a duration.
  198. *
  199. * @param int $iSecond Number of seconds
  200. * @param string $format Output format
  201. * - 'all': total delay days hour:min like "2 days 12:30",
  202. * - 'allwithouthour': total delay days without hour part like "2 days",
  203. * - 'allhourmin': total delay with format hours:min like "60:30",
  204. * - 'allhourminsec': total delay with format hours:min:sec like "60:30:10",
  205. * - 'allhour': total delay hours without min/sec like "60:30",
  206. * - 'fullhour': total delay hour decimal like "60.5" for 60:30,
  207. * - 'hour': only hours part "12",
  208. * - 'min': only minutes part "30",
  209. * - 'sec': only seconds part,
  210. * - 'month': only month part,
  211. * - 'year': only year part);
  212. * @param int $lengthOfDay Length of day (default 86400 seconds for 1 day, 28800 for 8 hour)
  213. * @param int $lengthOfWeek Length of week (default 7)
  214. * @return string Formated text of duration
  215. * Example: 0 return 00:00, 3600 return 1:00, 86400 return 1d, 90000 return 1 Day 01:00
  216. * @see convertTime2Seconds()
  217. */
  218. function convertSecondToTime($iSecond, $format = 'all', $lengthOfDay = 86400, $lengthOfWeek = 7)
  219. {
  220. global $langs;
  221. if (empty($lengthOfDay)) {
  222. $lengthOfDay = 86400; // 1 day = 24 hours
  223. }
  224. if (empty($lengthOfWeek)) {
  225. $lengthOfWeek = 7; // 1 week = 7 days
  226. }
  227. $nbHbyDay = $lengthOfDay / 3600;
  228. if ($format == 'all' || $format == 'allwithouthour' || $format == 'allhour' || $format == 'allhourmin' || $format == 'allhourminsec') {
  229. if ((int) $iSecond === 0) {
  230. return '0'; // This is to avoid having 0 return a 12:00 AM for en_US
  231. }
  232. $sTime = '';
  233. $sDay = 0;
  234. $sWeek = 0;
  235. if ($iSecond >= $lengthOfDay) {
  236. for ($i = $iSecond; $i >= $lengthOfDay; $i -= $lengthOfDay) {
  237. $sDay++;
  238. $iSecond -= $lengthOfDay;
  239. }
  240. $dayTranslate = $langs->trans("Day");
  241. if ($iSecond >= ($lengthOfDay * 2)) {
  242. $dayTranslate = $langs->trans("Days");
  243. }
  244. }
  245. if ($lengthOfWeek < 7) {
  246. if ($sDay) {
  247. if ($sDay >= $lengthOfWeek) {
  248. $sWeek = (int) (($sDay - $sDay % $lengthOfWeek) / $lengthOfWeek);
  249. $sDay = $sDay % $lengthOfWeek;
  250. $weekTranslate = $langs->trans("DurationWeek");
  251. if ($sWeek >= 2) {
  252. $weekTranslate = $langs->trans("DurationWeeks");
  253. }
  254. $sTime .= $sWeek.' '.$weekTranslate.' ';
  255. }
  256. }
  257. }
  258. if ($sDay > 0) {
  259. $dayTranslate = $langs->trans("Day");
  260. if ($sDay > 1) {
  261. $dayTranslate = $langs->trans("Days");
  262. }
  263. $sTime .= $sDay.' '.$langs->trans("d").' ';
  264. }
  265. if ($format == 'all') {
  266. if ($iSecond || empty($sDay)) {
  267. $sTime .= dol_print_date($iSecond, 'hourduration', true);
  268. }
  269. } elseif ($format == 'allhourminsec') {
  270. return sprintf("%02d", ($sWeek * $lengthOfWeek * $nbHbyDay + $sDay * $nbHbyDay + (int) floor($iSecond/3600))).':'.sprintf("%02d", ((int) floor(($iSecond % 3600) / 60))).':'.sprintf("%02d", ((int) ($iSecond % 60)));
  271. } elseif ($format == 'allhourmin') {
  272. return sprintf("%02d", ($sWeek * $lengthOfWeek * $nbHbyDay + $sDay * $nbHbyDay + (int) floor($iSecond/3600))).':'.sprintf("%02d", ((int) floor(($iSecond % 3600)/60)));
  273. } elseif ($format == 'allhour') {
  274. return sprintf("%02d", ($sWeek * $lengthOfWeek * $nbHbyDay + $sDay * $nbHbyDay + (int) floor($iSecond/3600)));
  275. }
  276. } elseif ($format == 'hour') { // only hour part
  277. $sTime = dol_print_date($iSecond, '%H', true);
  278. } elseif ($format == 'fullhour') {
  279. if (!empty($iSecond)) {
  280. $iSecond = $iSecond / 3600;
  281. } else {
  282. $iSecond = 0;
  283. }
  284. $sTime = $iSecond;
  285. } elseif ($format == 'min') { // only min part
  286. $sTime = dol_print_date($iSecond, '%M', true);
  287. } elseif ($format == 'sec') { // only sec part
  288. $sTime = dol_print_date($iSecond, '%S', true);
  289. } elseif ($format == 'month') { // only month part
  290. $sTime = dol_print_date($iSecond, '%m', true);
  291. } elseif ($format == 'year') { // only year part
  292. $sTime = dol_print_date($iSecond, '%Y', true);
  293. }
  294. return trim($sTime);
  295. }
  296. /** Convert duration to hour
  297. *
  298. * @param int $duration_value Duration value
  299. * @param int $duration_unit Duration unit
  300. * @return int $result
  301. */
  302. function convertDurationtoHour($duration_value, $duration_unit)
  303. {
  304. $result = 0;
  305. if ($duration_unit == 's') {
  306. $result = $duration_value / 3600;
  307. }
  308. if ($duration_unit == 'i') {
  309. $result = $duration_value / 60;
  310. }
  311. if ($duration_unit == 'h') {
  312. $result = $duration_value;
  313. }
  314. if ($duration_unit == 'd') {
  315. $result = $duration_value * 24;
  316. }
  317. if ($duration_unit == 'w') {
  318. $result = $duration_value * 24 * 7;
  319. }
  320. if ($duration_unit == 'm') {
  321. $result = $duration_value * 730.484;
  322. }
  323. if ($duration_unit == 'y') {
  324. $result = $duration_value * 365 * 24;
  325. }
  326. return $result;
  327. }
  328. /**
  329. * Generate a SQL string to make a filter into a range (for second of date until last second of date).
  330. * This method allows to maje SQL request that will deal correctly the timezone of server.
  331. *
  332. * @param string $datefield Name of SQL field where apply sql date filter
  333. * @param int|string $day_date Day date (Can be 0 or '' for filter on a month)
  334. * @param int|string $month_date Month date (Can be 0 or '' for filter on a year)
  335. * @param int|string $year_date Year date
  336. * @param int $excludefirstand Exclude first and
  337. * @param mixed $gm False or 0 or 'tzserver' = Input date fields are date info in the server TZ. True or 1 or 'gmt' = Input are date info in GMT TZ.
  338. * Note: In database, dates are always fot the server TZ.
  339. * @return string $sqldate String with SQL filter
  340. */
  341. function dolSqlDateFilter($datefield, $day_date, $month_date, $year_date, $excludefirstand = 0, $gm = false)
  342. {
  343. global $db;
  344. $sqldate = '';
  345. $day_date = intval($day_date);
  346. $month_date = intval($month_date);
  347. $year_date = intval($year_date);
  348. if ($month_date > 0) {
  349. if ($month_date > 12) { // protection for bad value of month
  350. return " AND 1 = 2";
  351. }
  352. if ($year_date > 0 && empty($day_date)) {
  353. $sqldate .= ($excludefirstand ? "" : " AND ").$datefield." BETWEEN '".$db->idate(dol_get_first_day($year_date, $month_date, $gm));
  354. $sqldate .= "' AND '".$db->idate(dol_get_last_day($year_date, $month_date, $gm))."'";
  355. } elseif ($year_date > 0 && !empty($day_date)) {
  356. $sqldate .= ($excludefirstand ? "" : " AND ").$datefield." BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $month_date, $day_date, $year_date, $gm));
  357. $sqldate .= "' AND '".$db->idate(dol_mktime(23, 59, 59, $month_date, $day_date, $year_date, $gm))."'";
  358. } else {
  359. // This case is not reliable on TZ, but we should not need it.
  360. $sqldate .= ($excludefirstand ? "" : " AND ")." date_format( ".$datefield.", '%c') = '".$db->escape($month_date)."'";
  361. }
  362. } elseif ($year_date > 0) {
  363. $sqldate .= ($excludefirstand ? "" : " AND ").$datefield." BETWEEN '".$db->idate(dol_get_first_day($year_date, 1, $gm));
  364. $sqldate .= "' AND '".$db->idate(dol_get_last_day($year_date, 12, $gm))."'";
  365. }
  366. return $sqldate;
  367. }
  368. /**
  369. * Convert a string date into a GM Timestamps date
  370. * Warning: YYYY-MM-DDTHH:MM:SS+02:00 (RFC3339) is not supported. If parameter gm is 1, we will use no TZ, if not we will use TZ of server, not the one inside string.
  371. *
  372. * @param string $string Date in a string
  373. * YYYYMMDD
  374. * YYYYMMDDHHMMSS
  375. * YYYYMMDDTHHMMSSZ
  376. * YYYY-MM-DDTHH:MM:SSZ (RFC3339)
  377. * DD/MM/YY or DD/MM/YYYY (deprecated)
  378. * DD/MM/YY HH:MM:SS or DD/MM/YYYY HH:MM:SS (deprecated)
  379. * @param int|string $gm 'gmt' or 1 =Input date is GM date,
  380. * 'tzserver' or 0 =Input date is date using PHP server timezone
  381. * @return int Date as a timestamp
  382. * 19700101020000 -> 7200 with gm=1
  383. * 19700101000000 -> 0 with gm=1
  384. *
  385. * @see dol_print_date(), dol_mktime(), dol_getdate()
  386. */
  387. function dol_stringtotime($string, $gm = 1)
  388. {
  389. $reg = array();
  390. // Convert date with format DD/MM/YYY HH:MM:SS. This part of code should not be used.
  391. if (preg_match('/^([0-9]+)\/([0-9]+)\/([0-9]+)\s?([0-9]+)?:?([0-9]+)?:?([0-9]+)?/i', $string, $reg)) {
  392. dol_syslog("dol_stringtotime call to function with deprecated parameter format", LOG_WARNING);
  393. // Date est au format 'DD/MM/YY' ou 'DD/MM/YY HH:MM:SS'
  394. // Date est au format 'DD/MM/YYYY' ou 'DD/MM/YYYY HH:MM:SS'
  395. $sday = $reg[1];
  396. $smonth = $reg[2];
  397. $syear = $reg[3];
  398. $shour = $reg[4];
  399. $smin = $reg[5];
  400. $ssec = $reg[6];
  401. if ($syear < 50) {
  402. $syear += 1900;
  403. }
  404. if ($syear >= 50 && $syear < 100) {
  405. $syear += 2000;
  406. }
  407. $string = sprintf("%04d%02d%02d%02d%02d%02d", $syear, $smonth, $sday, $shour, $smin, $ssec);
  408. } 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)
  409. || 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
  410. || 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
  411. ) {
  412. $syear = $reg[1];
  413. $smonth = $reg[2];
  414. $sday = $reg[3];
  415. $shour = $reg[4];
  416. $smin = $reg[5];
  417. $ssec = $reg[6];
  418. $string = sprintf("%04d%02d%02d%02d%02d%02d", $syear, $smonth, $sday, $shour, $smin, $ssec);
  419. }
  420. $string = preg_replace('/([^0-9])/i', '', $string);
  421. $tmp = $string.'000000';
  422. // Clean $gm
  423. if ($gm === 1) {
  424. $gm = 'gmt';
  425. } elseif (empty($gm) || $gm === 'tzserver') {
  426. $gm = 'tzserver';
  427. }
  428. $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);
  429. return $date;
  430. }
  431. /**
  432. * Return previous day
  433. *
  434. * @param int $day Day
  435. * @param int $month Month
  436. * @param int $year Year
  437. * @return array Previous year,month,day
  438. */
  439. function dol_get_prev_day($day, $month, $year)
  440. {
  441. $time = dol_mktime(12, 0, 0, $month, $day, $year, 1, 0);
  442. $time -= 24 * 60 * 60;
  443. $tmparray = dol_getdate($time, true);
  444. return array('year' => $tmparray['year'], 'month' => $tmparray['mon'], 'day' => $tmparray['mday']);
  445. }
  446. /**
  447. * Return next day
  448. *
  449. * @param int $day Day
  450. * @param int $month Month
  451. * @param int $year Year
  452. * @return array Next year,month,day
  453. */
  454. function dol_get_next_day($day, $month, $year)
  455. {
  456. $time = dol_mktime(12, 0, 0, $month, $day, $year, 1, 0);
  457. $time += 24 * 60 * 60;
  458. $tmparray = dol_getdate($time, true);
  459. return array('year' => $tmparray['year'], 'month' => $tmparray['mon'], 'day' => $tmparray['mday']);
  460. }
  461. /**
  462. * Return previous month
  463. *
  464. * @param int $month Month
  465. * @param int $year Year
  466. * @return array Previous year,month
  467. */
  468. function dol_get_prev_month($month, $year)
  469. {
  470. if ($month == 1) {
  471. $prev_month = 12;
  472. $prev_year = $year - 1;
  473. } else {
  474. $prev_month = $month - 1;
  475. $prev_year = $year;
  476. }
  477. return array('year' => $prev_year, 'month' => $prev_month);
  478. }
  479. /**
  480. * Return next month
  481. *
  482. * @param int $month Month
  483. * @param int $year Year
  484. * @return array Next year,month
  485. */
  486. function dol_get_next_month($month, $year)
  487. {
  488. if ($month == 12) {
  489. $next_month = 1;
  490. $next_year = $year + 1;
  491. } else {
  492. $next_month = $month + 1;
  493. $next_year = $year;
  494. }
  495. return array('year' => $next_year, 'month' => $next_month);
  496. }
  497. /**
  498. * Return previous week
  499. *
  500. * @param int $day Day
  501. * @param int $week Week
  502. * @param int $month Month
  503. * @param int $year Year
  504. * @return array Previous year,month,day
  505. */
  506. function dol_get_prev_week($day, $week, $month, $year)
  507. {
  508. $tmparray = dol_get_first_day_week($day, $month, $year);
  509. $time = dol_mktime(12, 0, 0, $month, $tmparray['first_day'], $year, 1, 0);
  510. $time -= 24 * 60 * 60 * 7;
  511. $tmparray = dol_getdate($time, true);
  512. return array('year' => $tmparray['year'], 'month' => $tmparray['mon'], 'day' => $tmparray['mday']);
  513. }
  514. /**
  515. * Return next week
  516. *
  517. * @param int $day Day
  518. * @param int $week Week
  519. * @param int $month Month
  520. * @param int $year Year
  521. * @return array Next year,month,day
  522. */
  523. function dol_get_next_week($day, $week, $month, $year)
  524. {
  525. $tmparray = dol_get_first_day_week($day, $month, $year);
  526. $time = dol_mktime(12, 0, 0, $tmparray['first_month'], $tmparray['first_day'], $tmparray['first_year'], 1, 0);
  527. $time += 24 * 60 * 60 * 7;
  528. $tmparray = dol_getdate($time, true);
  529. return array('year' => $tmparray['year'], 'month' => $tmparray['mon'], 'day' => $tmparray['mday']);
  530. }
  531. /**
  532. * Return GMT time for first day of a month or year
  533. *
  534. * @param int $year Year
  535. * @param int $month Month
  536. * @param mixed $gm False or 0 or 'tzserver' = Return date to compare with server TZ,
  537. * True or 1 or 'gmt' to compare with GMT date.
  538. * Example: dol_get_first_day(1970,1,false) will return -3600 with TZ+1, a dol_print_date on it will return 1970-01-01 00:00:00
  539. * Example: dol_get_first_day(1970,1,true) will return 0 whatever is TZ, a dol_print_date on it will return 1970-01-01 00:00:00
  540. * @return int Date for first day, '' if error
  541. */
  542. function dol_get_first_day($year, $month = 1, $gm = false)
  543. {
  544. if ($year > 9999) {
  545. return '';
  546. }
  547. return dol_mktime(0, 0, 0, $month, 1, $year, $gm);
  548. }
  549. /**
  550. * Return GMT time for last day of a month or year.
  551. * Note: The timestamp contains last day and last hours (23:59:59)
  552. *
  553. * @param int $year Year
  554. * @param int $month Month
  555. * @param mixed $gm False or 0 or 'tzserver' = Return date to compare with server TZ,
  556. * True or 1 or 'gmt' to compare with GMT date.
  557. * @return int Date for first day, '' if error
  558. */
  559. function dol_get_last_day($year, $month = 12, $gm = false)
  560. {
  561. if ($year > 9999) {
  562. return '';
  563. }
  564. if ($month == 12) {
  565. $month = 1;
  566. $year += 1;
  567. } else {
  568. $month += 1;
  569. }
  570. // On se deplace au debut du mois suivant, et on retire un jour
  571. $datelim = dol_mktime(23, 59, 59, $month, 1, $year, $gm);
  572. $datelim -= (3600 * 24);
  573. return $datelim;
  574. }
  575. /**
  576. * Return GMT time for last hour of a given GMT date (it replaces hours, min and second part to 23:59:59)
  577. *
  578. * @param int $date Date GMT
  579. * @param mixed $gm False or 0 or 'tzserver' = Return date to compare with server TZ,
  580. * 'gmt' to compare with GMT date.
  581. * @return int Date for last hour of a given date
  582. */
  583. function dol_get_last_hour($date, $gm = 'tzserver')
  584. {
  585. $tmparray = dol_getdate($date, false, ($gm == 'gmt' ? 'gmt' : ''));
  586. return dol_mktime(23, 59, 59, $tmparray['mon'], $tmparray['mday'], $tmparray['year'], $gm);
  587. }
  588. /**
  589. * Return GMT time for first hour of a given GMT date (it removes hours, min and second part)
  590. *
  591. * @param int $date Date GMT
  592. * @param mixed $gm False or 0 or 'tzserver' = Return date to compare with server TZ,
  593. * 'gmt' to compare with GMT date.
  594. * @return int Date for last hour of a given date
  595. */
  596. function dol_get_first_hour($date, $gm = 'tzserver')
  597. {
  598. $tmparray = dol_getdate($date, false, ($gm == 'gmt' ? 'gmt' : ''));
  599. return dol_mktime(0, 0, 0, $tmparray['mon'], $tmparray['mday'], $tmparray['year'], $gm);
  600. }
  601. /** Return first day of week for a date. First day of week may be monday if option MAIN_START_WEEK is 1.
  602. *
  603. * @param int $day Day
  604. * @param int $month Month
  605. * @param int $year Year
  606. * @param mixed $gm False or 0 or 'tzserver' = Return date to compare with server TZ,
  607. * True or 1 or 'gmt' to compare with GMT date.
  608. * @return array year,month,week,first_day,first_month,first_year,prev_day,prev_month,prev_year
  609. */
  610. function dol_get_first_day_week($day, $month, $year, $gm = false)
  611. {
  612. global $conf;
  613. //$day=2; $month=2; $year=2015;
  614. $date = dol_mktime(0, 0, 0, $month, $day, $year, $gm);
  615. //Checking conf of start week
  616. $start_week = (isset($conf->global->MAIN_START_WEEK) ? $conf->global->MAIN_START_WEEK : 1);
  617. $tmparray = dol_getdate($date, true); // detail of current day
  618. //Calculate days = offset from current day
  619. $days = $start_week - $tmparray['wday'];
  620. if ($days >= 1) {
  621. $days = 7 - $days;
  622. }
  623. $days = abs($days);
  624. $seconds = $days * 24 * 60 * 60;
  625. //print 'start_week='.$start_week.' tmparray[wday]='.$tmparray['wday'].' day offset='.$days.' seconds offset='.$seconds.'<br>';
  626. //Get first day of week
  627. $tmpdaytms = date($tmparray[0]) - $seconds; // $tmparray[0] is day of parameters
  628. $tmpday = date("d", $tmpdaytms);
  629. //Check first day of week is in same month than current day or not
  630. if ($tmpday > $day) {
  631. $prev_month = $month - 1;
  632. $prev_year = $year;
  633. if ($prev_month == 0) {
  634. $prev_month = 12;
  635. $prev_year = $year - 1;
  636. }
  637. } else {
  638. $prev_month = $month;
  639. $prev_year = $year;
  640. }
  641. $tmpmonth = $prev_month;
  642. $tmpyear = $prev_year;
  643. //Get first day of next week
  644. $tmptime = dol_mktime(12, 0, 0, $month, $tmpday, $year, 1, 0);
  645. $tmptime -= 24 * 60 * 60 * 7;
  646. $tmparray = dol_getdate($tmptime, true);
  647. $prev_day = $tmparray['mday'];
  648. //Check prev day of week is in same month than first day or not
  649. if ($prev_day > $tmpday) {
  650. $prev_month = $month - 1;
  651. $prev_year = $year;
  652. if ($prev_month == 0) {
  653. $prev_month = 12;
  654. $prev_year = $year - 1;
  655. }
  656. }
  657. $week = date("W", dol_mktime(0, 0, 0, $tmpmonth, $tmpday, $tmpyear, $gm));
  658. 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);
  659. }
  660. /**
  661. * Return the easter day in GMT time.
  662. * This function replaces easter_date() that returns a date in local TZ.
  663. *
  664. * @param int $year Year
  665. * @return int GMT Date of easter day
  666. */
  667. function getGMTEasterDatetime($year)
  668. {
  669. $base = new DateTime("$year-03-21", new DateTimeZone("UTC"));
  670. $days = easter_days($year); // Return number of days between 21 march and easter day.
  671. $tmp = $base->add(new DateInterval("P{$days}D"));
  672. return $tmp->getTimestamp();
  673. }
  674. /**
  675. * Return the number of non working days including Friday, Saturday and Sunday (or not) between 2 dates in timestamp.
  676. * Dates must be UTC with hour, min, sec to 0.
  677. * Called by function num_open_day()
  678. *
  679. * @param int $timestampStart Timestamp start (UTC with hour, min, sec = 0)
  680. * @param int $timestampEnd Timestamp end (UTC with hour, min, sec = 0)
  681. * @param string $country_code Country code
  682. * @param int $lastday Last day is included, 0: no, 1:yes
  683. * @param int $includesaturday Include saturday as non working day (-1=use setup, 0=no, 1=yes)
  684. * @param int $includesunday Include sunday as non working day (-1=use setup, 0=no, 1=yes)
  685. * @param int $includefriday Include friday as non working day (-1=use setup, 0=no, 1=yes)
  686. * @param int $includemonday Include monday as non working day (-1=use setup, 0=no, 1=yes)
  687. * @return int|string Number of non working days or error message string if error
  688. * @see num_between_day(), num_open_day()
  689. */
  690. function num_public_holiday($timestampStart, $timestampEnd, $country_code = '', $lastday = 0, $includesaturday = -1, $includesunday = -1, $includefriday = -1, $includemonday = -1)
  691. {
  692. global $db, $conf, $mysoc;
  693. $nbFerie = 0;
  694. // Check to ensure we use correct parameters
  695. if (($timestampEnd - $timestampStart) % 86400 != 0) {
  696. return 'Error Dates must use same hours and must be GMT dates';
  697. }
  698. if (empty($country_code)) {
  699. $country_code = $mysoc->country_code;
  700. }
  701. if ($includemonday < 0) {
  702. $includemonday = (isset($conf->global->MAIN_NON_WORKING_DAYS_INCLUDE_MONDAY) ? $conf->global->MAIN_NON_WORKING_DAYS_INCLUDE_MONDAY : 0);
  703. }
  704. if ($includefriday < 0) {
  705. $includefriday = (isset($conf->global->MAIN_NON_WORKING_DAYS_INCLUDE_FRIDAY) ? $conf->global->MAIN_NON_WORKING_DAYS_INCLUDE_FRIDAY : 0);
  706. }
  707. if ($includesaturday < 0) {
  708. $includesaturday = (isset($conf->global->MAIN_NON_WORKING_DAYS_INCLUDE_SATURDAY) ? $conf->global->MAIN_NON_WORKING_DAYS_INCLUDE_SATURDAY : 1);
  709. }
  710. if ($includesunday < 0) {
  711. $includesunday = (isset($conf->global->MAIN_NON_WORKING_DAYS_INCLUDE_SUNDAY) ? $conf->global->MAIN_NON_WORKING_DAYS_INCLUDE_SUNDAY : 1);
  712. }
  713. $country_id = dol_getIdFromCode($db, $country_code, 'c_country', 'code', 'rowid');
  714. $i = 0;
  715. while ((($lastday == 0 && $timestampStart < $timestampEnd) || ($lastday && $timestampStart <= $timestampEnd))
  716. && ($i < 50000)) { // Loop end when equals (Test on i is a security loop to avoid infinite loop)
  717. $ferie = false;
  718. $specialdayrule = array();
  719. $jour = gmdate("d", $timestampStart);
  720. $mois = gmdate("m", $timestampStart);
  721. $annee = gmdate("Y", $timestampStart);
  722. //print "jour=".$jour." month=".$mois." year=".$annee." includesaturday=".$includesaturday." includesunday=".$includesunday."\n";
  723. // Loop on public holiday defined into hrm_public_holiday for the day, month and year analyzed
  724. // TODO Execute this request first and store results into an array, then reuse this array.
  725. $sql = "SELECT code, entity, fk_country, dayrule, year, month, day, active";
  726. $sql .= " FROM ".MAIN_DB_PREFIX."c_hrm_public_holiday";
  727. $sql .= " WHERE active = 1 and fk_country IN (0".($country_id > 0 ? ", ".$country_id : 0).")";
  728. $sql .= " AND entity IN (0," .getEntity('holiday') .")";
  729. $resql = $db->query($sql);
  730. if ($resql) {
  731. $num_rows = $db->num_rows($resql);
  732. $i = 0;
  733. while ($i < $num_rows) {
  734. $obj = $db->fetch_object($resql);
  735. if (!empty($obj->dayrule) && $obj->dayrule != 'date') { // For example 'easter', '...'
  736. $specialdayrule[$obj->dayrule] = $obj->dayrule;
  737. } else {
  738. $match = 1;
  739. if (!empty($obj->year) && $obj->year != $annee) {
  740. $match = 0;
  741. }
  742. if ($obj->month != $mois) {
  743. $match = 0;
  744. }
  745. if ($obj->day != $jour) {
  746. $match = 0;
  747. }
  748. if ($match) {
  749. $ferie = true;
  750. }
  751. }
  752. $i++;
  753. }
  754. } else {
  755. dol_syslog($db->lasterror(), LOG_ERR);
  756. return 'Error sql '.$db->lasterror();
  757. }
  758. //var_dump($specialdayrule)."\n";
  759. //print "ferie=".$ferie."\n";
  760. if (!$ferie) {
  761. // Special dayrules
  762. if (in_array('easter', $specialdayrule)) {
  763. // Calculation for easter date
  764. $date_paques = getGMTEasterDatetime($annee);
  765. $jour_paques = gmdate("d", $date_paques);
  766. $mois_paques = gmdate("m", $date_paques);
  767. if ($jour_paques == $jour && $mois_paques == $mois) {
  768. $ferie = true;
  769. }
  770. // Easter (sunday)
  771. }
  772. if (in_array('eastermonday', $specialdayrule)) {
  773. // Calculation for the monday of easter date
  774. $date_paques = getGMTEasterDatetime($annee);
  775. //print 'PPP'.$date_paques.' '.dol_print_date($date_paques, 'dayhour', 'gmt')." ";
  776. $date_lundi_paques = $date_paques + (3600 * 24);
  777. $jour_lundi_paques = gmdate("d", $date_lundi_paques);
  778. $mois_lundi_paques = gmdate("m", $date_lundi_paques);
  779. if ($jour_lundi_paques == $jour && $mois_lundi_paques == $mois) {
  780. $ferie = true;
  781. }
  782. // Easter (monday)
  783. //print 'annee='.$annee.' $jour='.$jour.' $mois='.$mois.' $jour_lundi_paques='.$jour_lundi_paques.' $mois_lundi_paques='.$mois_lundi_paques."\n";
  784. }
  785. //Good Friday
  786. if (in_array('goodfriday', $specialdayrule)) {
  787. // Pulls the date of Easter
  788. $easter = getGMTEasterDatetime($annee);
  789. // Calculates the date of Good Friday based on Easter
  790. $date_good_friday = $easter - (2 * 3600 * 24);
  791. $dom_good_friday = gmdate("d", $date_good_friday);
  792. $month_good_friday = gmdate("m", $date_good_friday);
  793. if ($dom_good_friday == $jour && $month_good_friday == $mois) {
  794. $ferie = true;
  795. }
  796. }
  797. if (in_array('ascension', $specialdayrule)) {
  798. // Calcul du jour de l'ascension (39 days after easter day)
  799. $date_paques = getGMTEasterDatetime($annee);
  800. $date_ascension = $date_paques + (3600 * 24 * 39);
  801. $jour_ascension = gmdate("d", $date_ascension);
  802. $mois_ascension = gmdate("m", $date_ascension);
  803. if ($jour_ascension == $jour && $mois_ascension == $mois) {
  804. $ferie = true;
  805. }
  806. // Ascension (thursday)
  807. }
  808. if (in_array('pentecote', $specialdayrule)) {
  809. // Calculation of "Pentecote" (49 days after easter day)
  810. $date_paques = getGMTEasterDatetime($annee);
  811. $date_pentecote = $date_paques + (3600 * 24 * 49);
  812. $jour_pentecote = gmdate("d", $date_pentecote);
  813. $mois_pentecote = gmdate("m", $date_pentecote);
  814. if ($jour_pentecote == $jour && $mois_pentecote == $mois) {
  815. $ferie = true;
  816. }
  817. // "Pentecote" (sunday)
  818. }
  819. if (in_array('pentecotemonday', $specialdayrule)) {
  820. // Calculation of "Pentecote" (49 days after easter day)
  821. $date_paques = getGMTEasterDatetime($annee);
  822. $date_pentecote = $date_paques + (3600 * 24 * 50);
  823. $jour_pentecote = gmdate("d", $date_pentecote);
  824. $mois_pentecote = gmdate("m", $date_pentecote);
  825. if ($jour_pentecote == $jour && $mois_pentecote == $mois) {
  826. $ferie = true;
  827. }
  828. // "Pentecote" (monday)
  829. }
  830. if (in_array('viernessanto', $specialdayrule)) {
  831. // Viernes Santo
  832. $date_paques = getGMTEasterDatetime($annee);
  833. $date_viernes = $date_paques - (3600 * 24 * 2);
  834. $jour_viernes = gmdate("d", $date_viernes);
  835. $mois_viernes = gmdate("m", $date_viernes);
  836. if ($jour_viernes == $jour && $mois_viernes == $mois) {
  837. $ferie = true;
  838. }
  839. //Viernes Santo
  840. }
  841. if (in_array('fronleichnam', $specialdayrule)) {
  842. // Fronleichnam (60 days after easter sunday)
  843. $date_paques = getGMTEasterDatetime($annee);
  844. $date_fronleichnam = $date_paques + (3600 * 24 * 60);
  845. $jour_fronleichnam = gmdate("d", $date_fronleichnam);
  846. $mois_fronleichnam = gmdate("m", $date_fronleichnam);
  847. if ($jour_fronleichnam == $jour && $mois_fronleichnam == $mois) {
  848. $ferie = true;
  849. }
  850. // Fronleichnam
  851. }
  852. if (in_array('genevafast', $specialdayrule)) {
  853. // Geneva fast in Switzerland (Thursday after the first sunday in September)
  854. $date_1sunsept = strtotime('next thursday', strtotime('next sunday', mktime(0, 0, 0, 9, 1, $annee)));
  855. $jour_1sunsept = date("d", $date_1sunsept);
  856. $mois_1sunsept = date("m", $date_1sunsept);
  857. if ($jour_1sunsept == $jour && $mois_1sunsept == $mois) {
  858. $ferie=true;
  859. }
  860. // Geneva fast in Switzerland
  861. }
  862. }
  863. //print "ferie=".$ferie."\n";
  864. // If we have to include Friday, Saturday and Sunday
  865. if (!$ferie) {
  866. if ($includefriday || $includesaturday || $includesunday) {
  867. $jour_julien = unixtojd($timestampStart);
  868. $jour_semaine = jddayofweek($jour_julien, 0);
  869. if ($includefriday) { //Friday (5), Saturday (6) and Sunday (0)
  870. if ($jour_semaine == 5) {
  871. $ferie = true;
  872. }
  873. }
  874. if ($includesaturday) { //Friday (5), Saturday (6) and Sunday (0)
  875. if ($jour_semaine == 6) {
  876. $ferie = true;
  877. }
  878. }
  879. if ($includesunday) { //Friday (5), Saturday (6) and Sunday (0)
  880. if ($jour_semaine == 0) {
  881. $ferie = true;
  882. }
  883. }
  884. }
  885. }
  886. //print "ferie=".$ferie."\n";
  887. // We increase the counter of non working day
  888. if ($ferie) {
  889. $nbFerie++;
  890. }
  891. // Increase number of days (on go up into loop)
  892. $timestampStart = dol_time_plus_duree($timestampStart, 1, 'd');
  893. //var_dump($jour.' '.$mois.' '.$annee.' '.$timestampStart);
  894. $i++;
  895. }
  896. //print "nbFerie=".$nbFerie."\n";
  897. return $nbFerie;
  898. }
  899. /**
  900. * Function to return number of days between two dates (date must be UTC date !)
  901. * Example: 2012-01-01 2012-01-02 => 1 if lastday=0, 2 if lastday=1
  902. *
  903. * @param int $timestampStart Timestamp start UTC
  904. * @param int $timestampEnd Timestamp end UTC
  905. * @param int $lastday Last day is included, 0: no, 1:yes
  906. * @return int Number of days
  907. * @seealso num_public_holiday(), num_open_day()
  908. */
  909. function num_between_day($timestampStart, $timestampEnd, $lastday = 0)
  910. {
  911. if ($timestampStart < $timestampEnd) {
  912. if ($lastday == 1) {
  913. $bit = 0;
  914. } else {
  915. $bit = 1;
  916. }
  917. $nbjours = (int) floor(($timestampEnd - $timestampStart) / (60 * 60 * 24)) + 1 - $bit;
  918. }
  919. //print ($timestampEnd - $timestampStart) - $lastday;
  920. return $nbjours;
  921. }
  922. /**
  923. * Function to return number of working days (and text of units) between two dates (working days)
  924. *
  925. * @param int $timestampStart Timestamp for start date (date must be UTC to avoid calculation errors)
  926. * @param int $timestampEnd Timestamp for end date (date must be UTC to avoid calculation errors)
  927. * @param int $inhour 0: return number of days, 1: return number of hours
  928. * @param int $lastday We include last day, 0: no, 1:yes
  929. * @param int $halfday Tag to define half day when holiday start and end
  930. * @param string $country_code Country code (company country code if not defined)
  931. * @return int|string Number of days or hours or string if error
  932. * @seealso num_between_day(), num_public_holiday()
  933. */
  934. function num_open_day($timestampStart, $timestampEnd, $inhour = 0, $lastday = 0, $halfday = 0, $country_code = '')
  935. {
  936. global $langs, $mysoc;
  937. if (empty($country_code)) {
  938. $country_code = $mysoc->country_code;
  939. }
  940. dol_syslog('num_open_day timestampStart='.$timestampStart.' timestampEnd='.$timestampEnd.' bit='.$lastday.' country_code='.$country_code);
  941. // Check parameters
  942. if (!is_int($timestampStart) && !is_float($timestampStart)) {
  943. return 'ErrorBadParameter_num_open_day';
  944. }
  945. if (!is_int($timestampEnd) && !is_float($timestampEnd)) {
  946. return 'ErrorBadParameter_num_open_day';
  947. }
  948. //print 'num_open_day timestampStart='.$timestampStart.' timestampEnd='.$timestampEnd.' bit='.$lastday;
  949. if ($timestampStart < $timestampEnd) {
  950. $numdays = num_between_day($timestampStart, $timestampEnd, $lastday);
  951. $numholidays = num_public_holiday($timestampStart, $timestampEnd, $country_code, $lastday);
  952. $nbOpenDay = ($numdays - $numholidays);
  953. if ($inhour == 1 && $nbOpenDay <= 3) {
  954. $nbOpenDay = ($nbOpenDay * 24);
  955. }
  956. return $nbOpenDay - (($inhour == 1 ? 12 : 0.5) * abs($halfday));
  957. } elseif ($timestampStart == $timestampEnd) {
  958. $numholidays = 0;
  959. if ($lastday) {
  960. $numholidays = num_public_holiday($timestampStart, $timestampEnd, $country_code, $lastday);
  961. if ($numholidays == 1) {
  962. return 0;
  963. }
  964. }
  965. $nbOpenDay = $lastday;
  966. if ($inhour == 1) {
  967. $nbOpenDay = ($nbOpenDay * 24);
  968. }
  969. return $nbOpenDay - (($inhour == 1 ? 12 : 0.5) * abs($halfday));
  970. } else {
  971. return $langs->trans("Error");
  972. }
  973. }
  974. /**
  975. * Return array of translated months or selected month.
  976. * This replace old function monthArrayOrSelected.
  977. *
  978. * @param Translate $outputlangs Object langs
  979. * @param int $short 0=Return long label, 1=Return short label
  980. * @return array Month string or array if selected < 0
  981. */
  982. function monthArray($outputlangs, $short = 0)
  983. {
  984. $montharray = array(
  985. 1 => $outputlangs->trans("Month01"),
  986. 2 => $outputlangs->trans("Month02"),
  987. 3 => $outputlangs->trans("Month03"),
  988. 4 => $outputlangs->trans("Month04"),
  989. 5 => $outputlangs->trans("Month05"),
  990. 6 => $outputlangs->trans("Month06"),
  991. 7 => $outputlangs->trans("Month07"),
  992. 8 => $outputlangs->trans("Month08"),
  993. 9 => $outputlangs->trans("Month09"),
  994. 10 => $outputlangs->trans("Month10"),
  995. 11 => $outputlangs->trans("Month11"),
  996. 12 => $outputlangs->trans("Month12")
  997. );
  998. if (!empty($short)) {
  999. $montharray = array(
  1000. 1 => $outputlangs->trans("MonthShort01"),
  1001. 2 => $outputlangs->trans("MonthShort02"),
  1002. 3 => $outputlangs->trans("MonthShort03"),
  1003. 4 => $outputlangs->trans("MonthShort04"),
  1004. 5 => $outputlangs->trans("MonthShort05"),
  1005. 6 => $outputlangs->trans("MonthShort06"),
  1006. 7 => $outputlangs->trans("MonthShort07"),
  1007. 8 => $outputlangs->trans("MonthShort08"),
  1008. 9 => $outputlangs->trans("MonthShort09"),
  1009. 10 => $outputlangs->trans("MonthShort10"),
  1010. 11 => $outputlangs->trans("MonthShort11"),
  1011. 12 => $outputlangs->trans("MonthShort12")
  1012. );
  1013. }
  1014. return $montharray;
  1015. }
  1016. /**
  1017. * Return array of week numbers.
  1018. *
  1019. * @param int $month Month number
  1020. * @param int $year Year number
  1021. * @return array Week numbers
  1022. */
  1023. function getWeekNumbersOfMonth($month, $year)
  1024. {
  1025. $nb_days = cal_days_in_month(CAL_GREGORIAN, $month, $year);
  1026. $TWeek = array();
  1027. for ($day = 1; $day < $nb_days; $day++) {
  1028. $week_number = getWeekNumber($day, $month, $year);
  1029. $TWeek[$week_number] = $week_number;
  1030. }
  1031. return $TWeek;
  1032. }
  1033. /**
  1034. * Return array of first day of weeks.
  1035. *
  1036. * @param array $TWeek array of week numbers
  1037. * @param int $year Year number
  1038. * @return array First day of week
  1039. */
  1040. function getFirstDayOfEachWeek($TWeek, $year)
  1041. {
  1042. $TFirstDayOfWeek = array();
  1043. foreach ($TWeek as $weekNb) {
  1044. if (in_array('01', $TWeek) && in_array('52', $TWeek) && $weekNb == '01') {
  1045. $year++; //Si on a la 1re semaine et la semaine 52 c'est qu'on change d'année
  1046. }
  1047. $TFirstDayOfWeek[$weekNb] = date('d', strtotime($year.'W'.$weekNb));
  1048. }
  1049. return $TFirstDayOfWeek;
  1050. }
  1051. /**
  1052. * Return array of last day of weeks.
  1053. *
  1054. * @param array $TWeek array of week numbers
  1055. * @param int $year Year number
  1056. * @return array Last day of week
  1057. */
  1058. function getLastDayOfEachWeek($TWeek, $year)
  1059. {
  1060. $TLastDayOfWeek = array();
  1061. foreach ($TWeek as $weekNb) {
  1062. $TLastDayOfWeek[$weekNb] = date('d', strtotime($year.'W'.$weekNb.'+6 days'));
  1063. }
  1064. return $TLastDayOfWeek;
  1065. }
  1066. /**
  1067. * Return week number.
  1068. *
  1069. * @param int $day Day number
  1070. * @param int $month Month number
  1071. * @param int $year Year number
  1072. * @return int Week number
  1073. */
  1074. function getWeekNumber($day, $month, $year)
  1075. {
  1076. $date = new DateTime($year.'-'.$month.'-'.$day);
  1077. $week = $date->format("W");
  1078. return $week;
  1079. }