date.lib.php 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960
  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 <http://www.gnu.org/licenses/>.
  20. * or see http://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 int An offset in hour (+1 for Europe/Paris on winter and +2 for Europe/Paris on summer)
  76. */
  77. function getServerTimeZoneInt($refgmtdate = 'now')
  78. {
  79. if (method_exists('DateTimeZone', 'getOffset'))
  80. {
  81. // Method 1 (include daylight)
  82. $gmtnow=dol_now('gmt'); $yearref=dol_print_date($gmtnow, '%Y'); $monthref=dol_print_date($gmtnow, '%m'); $dayref=dol_print_date($gmtnow, '%d');
  83. if ($refgmtdate == 'now') $newrefgmtdate=$yearref.'-'.$monthref.'-'.$dayref;
  84. elseif ($refgmtdate == 'summer') $newrefgmtdate=$yearref.'-08-01';
  85. else $newrefgmtdate=$yearref.'-01-01';
  86. $newrefgmtdate.='T00:00:00+00:00';
  87. $localtz = new DateTimeZone(getServerTimeZoneString());
  88. $localdt = new DateTime($newrefgmtdate, $localtz);
  89. $tmp=-1*$localtz->getOffset($localdt);
  90. //print $refgmtdate.'='.$tmp;
  91. }
  92. else
  93. {
  94. $tmp=0;
  95. dol_print_error('', 'PHP version must be 5.3+');
  96. }
  97. $tz=round(($tmp<0?1:-1)*abs($tmp/3600));
  98. return $tz;
  99. }
  100. /**
  101. * Add a delay to a date
  102. *
  103. * @param int $time Date timestamp (or string with format YYYY-MM-DD)
  104. * @param int $duration_value Value of delay to add
  105. * @param int $duration_unit Unit of added delay (d, m, y, w, h)
  106. * @return int New timestamp
  107. */
  108. function dol_time_plus_duree($time, $duration_value, $duration_unit)
  109. {
  110. global $conf;
  111. if ($duration_value == 0) return $time;
  112. if ($duration_unit == 'h') return $time + (3600*$duration_value);
  113. if ($duration_unit == 'w') return $time + (3600*24*7*$duration_value);
  114. $deltastring='P';
  115. if ($duration_value > 0){ $deltastring.=abs($duration_value); $sub= false; }
  116. if ($duration_value < 0){ $deltastring.=abs($duration_value); $sub= true; }
  117. if ($duration_unit == 'd') { $deltastring.="D"; }
  118. if ($duration_unit == 'm') { $deltastring.="M"; }
  119. if ($duration_unit == 'y') { $deltastring.="Y"; }
  120. $date = new DateTime();
  121. if (! empty($conf->global->MAIN_DATE_IN_MEMORY_ARE_GMT)) $date->setTimezone(new DateTimeZone('UTC'));
  122. $date->setTimestamp($time);
  123. $interval = new DateInterval($deltastring);
  124. if($sub) $date->sub($interval);
  125. else $date->add($interval);
  126. return $date->getTimestamp();
  127. }
  128. /**
  129. * Convert hours and minutes into seconds
  130. *
  131. * @param int $iHours Hours
  132. * @param int $iMinutes Minutes
  133. * @param int $iSeconds Seconds
  134. * @return int Time into seconds
  135. * @see convertSecondToTime()
  136. */
  137. function convertTime2Seconds($iHours = 0, $iMinutes = 0, $iSeconds = 0)
  138. {
  139. $iResult=($iHours*3600)+($iMinutes*60)+$iSeconds;
  140. return $iResult;
  141. }
  142. /** Return, in clear text, value of a number of seconds in days, hours and minutes.
  143. * Can be used to show a duration.
  144. *
  145. * @param int $iSecond Number of seconds
  146. * @param string $format Output format ('all': total delay days hour:min like "2 days 12:30",
  147. * - 'allwithouthour': total delay days without hour part like "2 days",
  148. * - 'allhourmin': total delay with format hours:min like "60:30",
  149. * - 'allhourminsec': total delay with format hours:min:sec like "60:30:10",
  150. * - 'allhour': total delay hours without min/sec like "60:30",
  151. * - 'fullhour': total delay hour decimal like "60.5" for 60:30,
  152. * - 'hour': only hours part "12",
  153. * - 'min': only minutes part "30",
  154. * - 'sec': only seconds part,
  155. * - 'month': only month part,
  156. * - 'year': only year part);
  157. * @param int $lengthOfDay Length of day (default 86400 seconds for 1 day, 28800 for 8 hour)
  158. * @param int $lengthOfWeek Length of week (default 7)
  159. * @return string Formated text of duration
  160. * Example: 0 return 00:00, 3600 return 1:00, 86400 return 1d, 90000 return 1 Day 01:00
  161. * @see convertTime2Seconds()
  162. */
  163. function convertSecondToTime($iSecond, $format = 'all', $lengthOfDay = 86400, $lengthOfWeek = 7)
  164. {
  165. global $langs;
  166. if (empty($lengthOfDay)) $lengthOfDay = 86400; // 1 day = 24 hours
  167. if (empty($lengthOfWeek)) $lengthOfWeek = 7; // 1 week = 7 days
  168. if ($format == 'all' || $format == 'allwithouthour' || $format == 'allhour' || $format == 'allhourmin' || $format == 'allhourminsec')
  169. {
  170. if ((int) $iSecond === 0) return '0'; // This is to avoid having 0 return a 12:00 AM for en_US
  171. $sTime='';
  172. $sDay=0;
  173. $sWeek=0;
  174. if ($iSecond >= $lengthOfDay)
  175. {
  176. for($i = $iSecond; $i >= $lengthOfDay; $i -= $lengthOfDay )
  177. {
  178. $sDay++;
  179. $iSecond-=$lengthOfDay;
  180. }
  181. $dayTranslate = $langs->trans("Day");
  182. if ($iSecond >= ($lengthOfDay*2)) $dayTranslate = $langs->trans("Days");
  183. }
  184. if ($lengthOfWeek < 7)
  185. {
  186. if ($sDay)
  187. {
  188. if ($sDay >= $lengthOfWeek)
  189. {
  190. $sWeek = (int) (($sDay - $sDay % $lengthOfWeek ) / $lengthOfWeek);
  191. $sDay = $sDay % $lengthOfWeek;
  192. $weekTranslate = $langs->trans("DurationWeek");
  193. if ($sWeek >= 2) $weekTranslate = $langs->trans("DurationWeeks");
  194. $sTime.=$sWeek.' '.$weekTranslate.' ';
  195. }
  196. }
  197. }
  198. if ($sDay>0)
  199. {
  200. $dayTranslate = $langs->trans("Day");
  201. if ($sDay > 1) $dayTranslate = $langs->trans("Days");
  202. $sTime.=$sDay.' '.$dayTranslate.' ';
  203. }
  204. if ($format == 'all')
  205. {
  206. if ($iSecond || empty($sDay))
  207. {
  208. $sTime.= dol_print_date($iSecond, 'hourduration', true);
  209. }
  210. }
  211. elseif ($format == 'allhourminsec')
  212. {
  213. return sprintf("%02d", ($sWeek*$lengthOfWeek*24 + $sDay*24 + (int) floor($iSecond/3600))).':'.sprintf("%02d", ((int) floor(($iSecond % 3600)/60))).':'.sprintf("%02d", ((int) ($iSecond % 60)));
  214. }
  215. elseif ($format == 'allhourmin')
  216. {
  217. return sprintf("%02d", ($sWeek*$lengthOfWeek*24 + $sDay*24 + (int) floor($iSecond/3600))).':'.sprintf("%02d", ((int) floor(($iSecond % 3600)/60)));
  218. }
  219. elseif ($format == 'allhour')
  220. {
  221. return sprintf("%02d", ($sWeek*$lengthOfWeek*24 + $sDay*24 + (int) floor($iSecond/3600)));
  222. }
  223. }
  224. elseif ($format == 'hour') // only hour part
  225. {
  226. $sTime=dol_print_date($iSecond, '%H', true);
  227. }
  228. elseif ($format == 'fullhour')
  229. {
  230. if (!empty($iSecond)) {
  231. $iSecond=$iSecond/3600;
  232. }
  233. else {
  234. $iSecond=0;
  235. }
  236. $sTime=$iSecond;
  237. }
  238. elseif ($format == 'min') // only min part
  239. {
  240. $sTime=dol_print_date($iSecond, '%M', true);
  241. }
  242. elseif ($format == 'sec') // only sec part
  243. {
  244. $sTime=dol_print_date($iSecond, '%S', true);
  245. }
  246. elseif ($format == 'month') // only month part
  247. {
  248. $sTime=dol_print_date($iSecond, '%m', true);
  249. }
  250. elseif ($format == 'year') // only year part
  251. {
  252. $sTime=dol_print_date($iSecond, '%Y', true);
  253. }
  254. return trim($sTime);
  255. }
  256. /**
  257. * Generate a SQL string to make a filter into a range (for second of date until last second of date)
  258. *
  259. * @param string $datefield Name of SQL field where apply sql date filter
  260. * @param int $day_date Day date
  261. * @param int $month_date Month date
  262. * @param int $year_date Year date
  263. * @return string $sqldate String with SQL filter
  264. */
  265. function dolSqlDateFilter($datefield, $day_date, $month_date, $year_date)
  266. {
  267. global $db;
  268. $sqldate="";
  269. if ($month_date > 0) {
  270. if ($year_date > 0 && empty($day_date)) {
  271. $sqldate.= " AND ".$datefield." BETWEEN '".$db->idate(dol_get_first_day($year_date, $month_date, false));
  272. $sqldate.= "' AND '".$db->idate(dol_get_last_day($year_date, $month_date, false))."'";
  273. } elseif ($year_date > 0 && ! empty($day_date)) {
  274. $sqldate.= " AND ".$datefield." BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $month_date, $day_date, $year_date));
  275. $sqldate.= "' AND '".$db->idate(dol_mktime(23, 59, 59, $month_date, $day_date, $year_date))."'";
  276. } else
  277. $sqldate.= " AND date_format( ".$datefield.", '%m') = '".$db->escape($month_date)."'";
  278. } elseif ($year_date > 0){
  279. $sqldate.= " AND ".$datefield." BETWEEN '".$db->idate(dol_get_first_day($year_date, 1, false));
  280. $sqldate.= "' AND '".$db->idate(dol_get_last_day($year_date, 12, false))."'";
  281. }
  282. return $sqldate;
  283. }
  284. /**
  285. * Convert a string date into a GM Timestamps date
  286. * 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.
  287. *
  288. * @param string $string Date in a string
  289. * YYYYMMDD
  290. * YYYYMMDDHHMMSS
  291. * YYYYMMDDTHHMMSSZ
  292. * YYYY-MM-DDTHH:MM:SSZ (RFC3339)
  293. * DD/MM/YY or DD/MM/YYYY (deprecated)
  294. * DD/MM/YY HH:MM:SS or DD/MM/YYYY HH:MM:SS (deprecated)
  295. * @param int $gm 1 =Input date is GM date,
  296. * 0 =Input date is local date using PHP server timezone
  297. * @return int Date as a timestamp
  298. * 19700101020000 -> 7200 with gm=1
  299. *
  300. * @see dol_print_date(), dol_mktime(), dol_getdate()
  301. */
  302. function dol_stringtotime($string, $gm = 1)
  303. {
  304. $reg=array();
  305. // Convert date with format DD/MM/YYY HH:MM:SS. This part of code should not be used.
  306. if (preg_match('/^([0-9]+)\/([0-9]+)\/([0-9]+)\s?([0-9]+)?:?([0-9]+)?:?([0-9]+)?/i', $string, $reg))
  307. {
  308. dol_syslog("dol_stringtotime call to function with deprecated parameter format", LOG_WARNING);
  309. // Date est au format 'DD/MM/YY' ou 'DD/MM/YY HH:MM:SS'
  310. // Date est au format 'DD/MM/YYYY' ou 'DD/MM/YYYY HH:MM:SS'
  311. $sday = $reg[1];
  312. $smonth = $reg[2];
  313. $syear = $reg[3];
  314. $shour = $reg[4];
  315. $smin = $reg[5];
  316. $ssec = $reg[6];
  317. if ($syear < 50) $syear+=1900;
  318. if ($syear >= 50 && $syear < 100) $syear+=2000;
  319. $string=sprintf("%04d%02d%02d%02d%02d%02d", $syear, $smonth, $sday, $shour, $smin, $ssec);
  320. }
  321. elseif (
  322. 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)
  323. || 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
  324. || 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
  325. )
  326. {
  327. $syear = $reg[1];
  328. $smonth = $reg[2];
  329. $sday = $reg[3];
  330. $shour = $reg[4];
  331. $smin = $reg[5];
  332. $ssec = $reg[6];
  333. $string=sprintf("%04d%02d%02d%02d%02d%02d", $syear, $smonth, $sday, $shour, $smin, $ssec);
  334. }
  335. $string=preg_replace('/([^0-9])/i', '', $string);
  336. $tmp=$string.'000000';
  337. $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?1:0));
  338. return $date;
  339. }
  340. /** Return previous day
  341. *
  342. * @param int $day Day
  343. * @param int $month Month
  344. * @param int $year Year
  345. * @return array Previous year,month,day
  346. */
  347. function dol_get_prev_day($day, $month, $year)
  348. {
  349. $time=dol_mktime(12, 0, 0, $month, $day, $year, 1, 0);
  350. $time-=24*60*60;
  351. $tmparray=dol_getdate($time, true);
  352. return array('year' => $tmparray['year'], 'month' => $tmparray['mon'], 'day' => $tmparray['mday']);
  353. }
  354. /** Return next day
  355. *
  356. * @param int $day Day
  357. * @param int $month Month
  358. * @param int $year Year
  359. * @return array Next year,month,day
  360. */
  361. function dol_get_next_day($day, $month, $year)
  362. {
  363. $time=dol_mktime(12, 0, 0, $month, $day, $year, 1, 0);
  364. $time+=24*60*60;
  365. $tmparray=dol_getdate($time, true);
  366. return array('year' => $tmparray['year'], 'month' => $tmparray['mon'], 'day' => $tmparray['mday']);
  367. }
  368. /** Return previous month
  369. *
  370. * @param int $month Month
  371. * @param int $year Year
  372. * @return array Previous year,month
  373. */
  374. function dol_get_prev_month($month, $year)
  375. {
  376. if ($month == 1)
  377. {
  378. $prev_month = 12;
  379. $prev_year = $year - 1;
  380. }
  381. else
  382. {
  383. $prev_month = $month-1;
  384. $prev_year = $year;
  385. }
  386. return array('year' => $prev_year, 'month' => $prev_month);
  387. }
  388. /** Return next month
  389. *
  390. * @param int $month Month
  391. * @param int $year Year
  392. * @return array Next year,month
  393. */
  394. function dol_get_next_month($month, $year)
  395. {
  396. if ($month == 12)
  397. {
  398. $next_month = 1;
  399. $next_year = $year + 1;
  400. }
  401. else
  402. {
  403. $next_month = $month + 1;
  404. $next_year = $year;
  405. }
  406. return array('year' => $next_year, 'month' => $next_month);
  407. }
  408. /** Return previous week
  409. *
  410. * @param int $day Day
  411. * @param int $week Week
  412. * @param int $month Month
  413. * @param int $year Year
  414. * @return array Previous year,month,day
  415. */
  416. function dol_get_prev_week($day, $week, $month, $year)
  417. {
  418. $tmparray = dol_get_first_day_week($day, $month, $year);
  419. $time=dol_mktime(12, 0, 0, $month, $tmparray['first_day'], $year, 1, 0);
  420. $time-=24*60*60*7;
  421. $tmparray=dol_getdate($time, true);
  422. return array('year' => $tmparray['year'], 'month' => $tmparray['mon'], 'day' => $tmparray['mday']);
  423. }
  424. /** Return next week
  425. *
  426. * @param int $day Day
  427. * @param int $week Week
  428. * @param int $month Month
  429. * @param int $year Year
  430. * @return array Next year,month,day
  431. */
  432. function dol_get_next_week($day, $week, $month, $year)
  433. {
  434. $tmparray = dol_get_first_day_week($day, $month, $year);
  435. $time=dol_mktime(12, 0, 0, $tmparray['first_month'], $tmparray['first_day'], $tmparray['first_year'], 1, 0);
  436. $time+=24*60*60*7;
  437. $tmparray=dol_getdate($time, true);
  438. return array('year' => $tmparray['year'], 'month' => $tmparray['mon'], 'day' => $tmparray['mday']);
  439. }
  440. /** Return GMT time for first day of a month or year
  441. *
  442. * @param int $year Year
  443. * @param int $month Month
  444. * @param mixed $gm False or 0 or 'server' = Return date to compare with server TZ, True or 1 to compare with GM date.
  445. * Exemple: dol_get_first_day(1970,1,false) will return -3600 with TZ+1, after a dol_print_date will return 1970-01-01 00:00:00
  446. * Exemple: dol_get_first_day(1970,1,true) will return 0 whatever is TZ, after a dol_print_date will return 1970-01-01 00:00:00
  447. * @return int Date for first day, '' if error
  448. */
  449. function dol_get_first_day($year, $month = 1, $gm = false)
  450. {
  451. if ($year > 9999) return '';
  452. return dol_mktime(0, 0, 0, $month, 1, $year, $gm);
  453. }
  454. /** Return GMT time for last day of a month or year
  455. *
  456. * @param int $year Year
  457. * @param int $month Month
  458. * @param boolean $gm False or 0 or 'server' = Return date to compare with server TZ, True or 1 to compare with GM date.
  459. * @return int Date for first day, '' if error
  460. */
  461. function dol_get_last_day($year, $month = 12, $gm = false)
  462. {
  463. if ($year > 9999) return '';
  464. if ($month == 12)
  465. {
  466. $month = 1;
  467. $year += 1;
  468. }
  469. else
  470. {
  471. $month += 1;
  472. }
  473. // On se deplace au debut du mois suivant, et on retire un jour
  474. $datelim=dol_mktime(23, 59, 59, $month, 1, $year, $gm);
  475. $datelim -= (3600 * 24);
  476. return $datelim;
  477. }
  478. /** Return first day of week for a date. First day of week may be monday if option MAIN_START_WEEK is 1.
  479. *
  480. * @param int $day Day
  481. * @param int $month Month
  482. * @param int $year Year
  483. * @param int $gm False or 0 or 'server' = Return date to compare with server TZ, True or 1 to compare with GM date.
  484. * @return array year,month,week,first_day,first_month,first_year,prev_day,prev_month,prev_year
  485. */
  486. function dol_get_first_day_week($day, $month, $year, $gm = false)
  487. {
  488. global $conf;
  489. //$day=2; $month=2; $year=2015;
  490. $date = dol_mktime(0, 0, 0, $month, $day, $year, $gm);
  491. //Checking conf of start week
  492. $start_week = (isset($conf->global->MAIN_START_WEEK)?$conf->global->MAIN_START_WEEK:1);
  493. $tmparray = dol_getdate($date, true); // detail of current day
  494. //Calculate days = offset from current day
  495. $days = $start_week - $tmparray['wday'];
  496. if ($days>=1) $days=7-$days;
  497. $days = abs($days);
  498. $seconds = $days*24*60*60;
  499. //print 'start_week='.$start_week.' tmparray[wday]='.$tmparray['wday'].' day offset='.$days.' seconds offset='.$seconds.'<br>';
  500. //Get first day of week
  501. $tmpdaytms = date($tmparray[0])-$seconds; // $tmparray[0] is day of parameters
  502. $tmpday = date("d", $tmpdaytms);
  503. //Check first day of week is in same month than current day or not
  504. if ($tmpday>$day)
  505. {
  506. $prev_month = $month-1;
  507. $prev_year = $year;
  508. if ($prev_month==0)
  509. {
  510. $prev_month = 12;
  511. $prev_year = $year-1;
  512. }
  513. }
  514. else
  515. {
  516. $prev_month = $month;
  517. $prev_year = $year;
  518. }
  519. $tmpmonth = $prev_month;
  520. $tmpyear = $prev_year;
  521. //Get first day of next week
  522. $tmptime=dol_mktime(12, 0, 0, $month, $tmpday, $year, 1, 0);
  523. $tmptime-=24*60*60*7;
  524. $tmparray=dol_getdate($tmptime, true);
  525. $prev_day = $tmparray['mday'];
  526. //Check prev day of week is in same month than first day or not
  527. if ($prev_day > $tmpday)
  528. {
  529. $prev_month = $month-1;
  530. $prev_year = $year;
  531. if ($prev_month==0)
  532. {
  533. $prev_month = 12;
  534. $prev_year = $year-1;
  535. }
  536. }
  537. $week = date("W", dol_mktime(0, 0, 0, $tmpmonth, $tmpday, $tmpyear, $gm));
  538. 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);
  539. }
  540. /**
  541. * Return the number of non working days including saturday and sunday (or not) between 2 dates in timestamp.
  542. * Dates must be UTC with hour, day, min to 0.
  543. * Called by function num_open_day
  544. *
  545. * @param int $timestampStart Timestamp de debut
  546. * @param int $timestampEnd Timestamp de fin
  547. * @param string $country_code Country code
  548. * @param int $lastday Last day is included, 0: no, 1:yes
  549. * @param int $includesaturday Include saturday as non working day (-1=use setup, 0=no, 1=yes)
  550. * @param int $includesunday Include sunday as non working day (-1=use setup, 0=no, 1=yes)
  551. * @return int|string Number of non working days or error message string if error
  552. * @see num_between_day(), num_open_day()
  553. */
  554. function num_public_holiday($timestampStart, $timestampEnd, $country_code = '', $lastday = 0, $includesaturday = -1, $includesunday = -1)
  555. {
  556. global $db, $conf, $mysoc;
  557. $nbFerie = 0;
  558. $specialdayrule = array();
  559. // Check to ensure we use correct parameters
  560. if ((($timestampEnd - $timestampStart) % 86400) != 0) return 'ErrorDates must use same hours and must be GMT dates';
  561. if (empty($country_code)) $country_code = $mysoc->country_code;
  562. if ($includesaturday < 0) $includesaturday = (isset($conf->global->MAIN_NON_WORKING_DAYS_INCLUDE_SATURDAY) ? $conf->global->MAIN_NON_WORKING_DAYS_INCLUDE_SATURDAY : 1);
  563. if ($includesunday < 0) $includesunday = (isset($conf->global->MAIN_NON_WORKING_DAYS_INCLUDE_SUNDAY) ? $conf->global->MAIN_NON_WORKING_DAYS_INCLUDE_SUNDAY : 1);
  564. $i=0;
  565. while (( ($lastday == 0 && $timestampStart < $timestampEnd) || ($lastday && $timestampStart <= $timestampEnd) )
  566. && ($i < 50000)) // Loop end when equals (Test on i is a security loop to avoid infinite loop)
  567. {
  568. $ferie=false;
  569. $jour = date("d", $timestampStart);
  570. $mois = date("m", $timestampStart);
  571. $annee = date("Y", $timestampStart);
  572. // Check into var $conf->global->HOLIDAY_MORE_DAYS MM-DD,YYYY-MM-DD, ...
  573. // Do not use this anymore, use instead the dictionary of public holidays.
  574. if (! empty($conf->global->HOLIDAY_MORE_PUBLIC_HOLIDAYS))
  575. {
  576. $arrayofdaystring=explode(',', $conf->global->HOLIDAY_MORE_PUBLIC_HOLIDAYS);
  577. foreach($arrayofdaystring as $daystring)
  578. {
  579. $tmp=explode('-', $daystring);
  580. if ($tmp[2])
  581. {
  582. if ($tmp[0] == $annee && $tmp[1] == $mois && $tmp[2] == $jour) $ferie=true;
  583. }
  584. else
  585. {
  586. if ($tmp[0] == $mois && $tmp[1] == $jour) $ferie=true;
  587. }
  588. }
  589. }
  590. $country_id = dol_getIdFromCode($db, $country_code, 'c_country', 'code', 'rowid');
  591. // Loop on public holiday defined into hrm_public_holiday
  592. $sql = "SELECT code, entity, fk_country, dayrule, year, month, day, active";
  593. $sql.= " FROM ".MAIN_DB_PREFIX."c_hrm_public_holiday";
  594. $sql.= " WHERE active = 1 and fk_country IN (0".($country_id > 0 ? ", ".$country_id : 0).")";
  595. $resql = $db->query($sql);
  596. if ($resql)
  597. {
  598. $num_rows = $db->num_rows($resql);
  599. $i=0;
  600. while ($i < $num_rows)
  601. {
  602. $obj = $db->fetch_object($resql);
  603. if (! empty($obj->dayrule) && $obj->dayrule != 'date') // For example 'easter', '...'
  604. {
  605. $specialdayrule[$obj->dayrule] = $obj->dayrule;
  606. }
  607. else
  608. {
  609. $match = 1;
  610. if (! empty($obj->year) && $obj->year != $annee) $match = 0;
  611. if ($obj->month != $mois) $match = 0;
  612. if ($obj->day != $jour) $match = 0;
  613. if ($match) $ferie = true;
  614. }
  615. $i++;
  616. }
  617. }
  618. else
  619. {
  620. dol_syslog($db->lasterror(), LOG_ERR);
  621. return 'Error sql '.$db->lasterror();
  622. }
  623. // Special dayrules
  624. if (in_array('easter', $specialdayrule))
  625. {
  626. // Calculation for easter date
  627. $date_paques = easter_date($annee);
  628. $jour_paques = date("d", $date_paques);
  629. $mois_paques = date("m", $date_paques);
  630. if($jour_paques == $jour && $mois_paques == $mois) $ferie=true;
  631. // Easter (sunday)
  632. }
  633. if (in_array('eastermonday', $specialdayrule))
  634. {
  635. // Calculation for the monday of easter date
  636. $date_paques = easter_date($annee);
  637. $date_lundi_paques = mktime(
  638. date("H", $date_paques),
  639. date("i", $date_paques),
  640. date("s", $date_paques),
  641. date("m", $date_paques),
  642. date("d", $date_paques) + 1,
  643. date("Y", $date_paques)
  644. );
  645. $jour_lundi_ascension = date("d", $date_lundi_paques);
  646. $mois_lundi_ascension = date("m", $date_lundi_paques);
  647. if ($jour_lundi_ascension == $jour && $mois_lundi_ascension == $mois) $ferie=true;
  648. // Easter (monday)
  649. }
  650. if (in_array('ascension', $specialdayrule))
  651. {
  652. // Calcul du jour de l'ascension (39 days after easter day)
  653. $date_paques = easter_date($annee);
  654. $date_ascension = mktime(
  655. date("H", $date_paques),
  656. date("i", $date_paques),
  657. date("s", $date_paques),
  658. date("m", $date_paques),
  659. date("d", $date_paques) + 39,
  660. date("Y", $date_paques)
  661. );
  662. $jour_ascension = date("d", $date_ascension);
  663. $mois_ascension = date("m", $date_ascension);
  664. if($jour_ascension == $jour && $mois_ascension == $mois) $ferie=true;
  665. // Ascension (thursday)
  666. }
  667. if (in_array('pentecote', $specialdayrule))
  668. {
  669. // Calculation of "Pentecote" (49 days after easter day)
  670. $date_paques = easter_date($annee);
  671. $date_pentecote = mktime(
  672. date("H", $date_paques),
  673. date("i", $date_paques),
  674. date("s", $date_paques),
  675. date("m", $date_paques),
  676. date("d", $date_paques) + 49,
  677. date("Y", $date_paques)
  678. );
  679. $jour_pentecote = date("d", $date_pentecote);
  680. $mois_pentecote = date("m", $date_pentecote);
  681. if($jour_pentecote == $jour && $mois_pentecote == $mois) $ferie=true;
  682. // "Pentecote" (sunday)
  683. }
  684. if (in_array('pentecotemonday', $specialdayrule))
  685. {
  686. // Calculation of "Pentecote" (49 days after easter day)
  687. $date_paques = easter_date($annee);
  688. $date_pentecote = mktime(
  689. date("H", $date_paques),
  690. date("i", $date_paques),
  691. date("s", $date_paques),
  692. date("m", $date_paques),
  693. date("d", $date_paques) + 50,
  694. date("Y", $date_paques)
  695. );
  696. $jour_pentecote = date("d", $date_pentecote);
  697. $mois_pentecote = date("m", $date_pentecote);
  698. if($jour_pentecote == $jour && $mois_pentecote == $mois) $ferie=true;
  699. // "Pentecote" (monday)
  700. }
  701. if (in_array('viernessanto', $specialdayrule))
  702. {
  703. // Viernes Santo
  704. $date_paques = easter_date($annee);
  705. $date_viernes = mktime(
  706. date("H", $date_paques),
  707. date("i", $date_paques),
  708. date("s", $date_paques),
  709. date("m", $date_paques),
  710. date("d", $date_paques) -2,
  711. date("Y", $date_paques)
  712. );
  713. $jour_viernes = date("d", $date_viernes);
  714. $mois_viernes = date("m", $date_viernes);
  715. if($jour_viernes == $jour && $mois_viernes == $mois) $ferie=true;
  716. //Viernes Santo
  717. }
  718. if (in_array('fronleichnam', $specialdayrule))
  719. {
  720. // Fronleichnam (60 days after easter sunday)
  721. $date_fronleichnam = mktime(
  722. date("H", $date_paques),
  723. date("i", $date_paques),
  724. date("s", $date_paques),
  725. date("m", $date_paques),
  726. date("d", $date_paques) + 60,
  727. date("Y", $date_paques)
  728. );
  729. $jour_fronleichnam = date("d", $date_fronleichnam);
  730. $mois_fronleichnam = date("m", $date_fronleichnam);
  731. if($jour_fronleichnam == $jour && $mois_fronleichnam == $mois) $ferie=true;
  732. // Fronleichnam
  733. }
  734. // If we have to include saturday and sunday
  735. if ($includesaturday || $includesunday)
  736. {
  737. $jour_julien = unixtojd($timestampStart);
  738. $jour_semaine = jddayofweek($jour_julien, 0);
  739. if ($includesaturday) //Saturday (6) and Sunday (0)
  740. {
  741. if ($jour_semaine == 6) $ferie=true;
  742. }
  743. if ($includesunday) //Saturday (6) and Sunday (0)
  744. {
  745. if($jour_semaine == 0) $ferie=true;
  746. }
  747. }
  748. // We increase the counter of non working day
  749. if ($ferie) $nbFerie++;
  750. // Increase number of days (on go up into loop)
  751. $timestampStart=dol_time_plus_duree($timestampStart, 1, 'd');
  752. //var_dump($jour.' '.$mois.' '.$annee.' '.$timestampStart);
  753. $i++;
  754. }
  755. return $nbFerie;
  756. }
  757. /**
  758. * Function to return number of days between two dates (date must be UTC date !)
  759. * Example: 2012-01-01 2012-01-02 => 1 if lastday=0, 2 if lastday=1
  760. *
  761. * @param int $timestampStart Timestamp start UTC
  762. * @param int $timestampEnd Timestamp end UTC
  763. * @param int $lastday Last day is included, 0: no, 1:yes
  764. * @return int Number of days
  765. * @seealso num_public_holiday(), num_open_day()
  766. */
  767. function num_between_day($timestampStart, $timestampEnd, $lastday = 0)
  768. {
  769. if ($timestampStart < $timestampEnd)
  770. {
  771. if ($lastday == 1)
  772. {
  773. $bit = 0;
  774. }
  775. else
  776. {
  777. $bit = 1;
  778. }
  779. $nbjours = (int) floor(($timestampEnd - $timestampStart)/(60*60*24)) + 1 - $bit;
  780. }
  781. //print ($timestampEnd - $timestampStart) - $lastday;
  782. return $nbjours;
  783. }
  784. /**
  785. * Function to return number of working days (and text of units) between two dates (working days)
  786. *
  787. * @param int $timestampStart Timestamp for start date (date must be UTC to avoid calculation errors)
  788. * @param int $timestampEnd Timestamp for end date (date must be UTC to avoid calculation errors)
  789. * @param int $inhour 0: return number of days, 1: return number of hours
  790. * @param int $lastday We include last day, 0: no, 1:yes
  791. * @param int $halfday Tag to define half day when holiday start and end
  792. * @param string $country_code Country code (company country code if not defined)
  793. * @return int Number of days or hours
  794. * @seealso num_between_day(), num_public_holiday()
  795. */
  796. function num_open_day($timestampStart, $timestampEnd, $inhour = 0, $lastday = 0, $halfday = 0, $country_code = '')
  797. {
  798. global $langs,$mysoc;
  799. if (empty($country_code)) $country_code=$mysoc->country_code;
  800. dol_syslog('num_open_day timestampStart='.$timestampStart.' timestampEnd='.$timestampEnd.' bit='.$lastday.' country_code='.$country_code);
  801. // Check parameters
  802. if (! is_int($timestampStart) && ! is_float($timestampStart)) return 'ErrorBadParameter_num_open_day';
  803. if (! is_int($timestampEnd) && ! is_float($timestampEnd)) return 'ErrorBadParameter_num_open_day';
  804. //print 'num_open_day timestampStart='.$timestampStart.' timestampEnd='.$timestampEnd.' bit='.$lastday;
  805. if ($timestampStart < $timestampEnd)
  806. {
  807. $numdays = num_between_day($timestampStart, $timestampEnd, $lastday);
  808. $numholidays = num_public_holiday($timestampStart, $timestampEnd, $country_code, $lastday);
  809. $nbOpenDay = $numdays - $numholidays;
  810. $nbOpenDay.= " " . $langs->trans("Days");
  811. if ($inhour == 1 && $nbOpenDay <= 3) $nbOpenDay = $nbOpenDay*24 . $langs->trans("HourShort");
  812. return $nbOpenDay - (($inhour == 1 ? 12 : 0.5) * abs($halfday));
  813. }
  814. elseif ($timestampStart == $timestampEnd)
  815. {
  816. $nbOpenDay=$lastday;
  817. if ($inhour == 1) $nbOpenDay = $nbOpenDay*24 . $langs->trans("HourShort");
  818. return $nbOpenDay - (($inhour == 1 ? 12 : 0.5) * abs($halfday));
  819. }
  820. else
  821. {
  822. return $langs->trans("Error");
  823. }
  824. }
  825. /**
  826. * Return array of translated months or selected month.
  827. * This replace old function monthArrayOrSelected.
  828. *
  829. * @param Translate $outputlangs Object langs
  830. * @param int $short 0=Return long label, 1=Return short label
  831. * @return array Month string or array if selected < 0
  832. */
  833. function monthArray($outputlangs, $short = 0)
  834. {
  835. $montharray = array (
  836. 1 => $outputlangs->trans("Month01"),
  837. 2 => $outputlangs->trans("Month02"),
  838. 3 => $outputlangs->trans("Month03"),
  839. 4 => $outputlangs->trans("Month04"),
  840. 5 => $outputlangs->trans("Month05"),
  841. 6 => $outputlangs->trans("Month06"),
  842. 7 => $outputlangs->trans("Month07"),
  843. 8 => $outputlangs->trans("Month08"),
  844. 9 => $outputlangs->trans("Month09"),
  845. 10 => $outputlangs->trans("Month10"),
  846. 11 => $outputlangs->trans("Month11"),
  847. 12 => $outputlangs->trans("Month12")
  848. );
  849. if (! empty($short))
  850. {
  851. $montharray = array (
  852. 1 => $outputlangs->trans("MonthShort01"),
  853. 2 => $outputlangs->trans("MonthShort02"),
  854. 3 => $outputlangs->trans("MonthShort03"),
  855. 4 => $outputlangs->trans("MonthShort04"),
  856. 5 => $outputlangs->trans("MonthShort05"),
  857. 6 => $outputlangs->trans("MonthShort06"),
  858. 7 => $outputlangs->trans("MonthShort07"),
  859. 8 => $outputlangs->trans("MonthShort08"),
  860. 9 => $outputlangs->trans("MonthShort09"),
  861. 10 => $outputlangs->trans("MonthShort10"),
  862. 11 => $outputlangs->trans("MonthShort11"),
  863. 12 => $outputlangs->trans("MonthShort12")
  864. );
  865. }
  866. return $montharray;
  867. }