date.lib.php 39 KB

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