date_repeat_calc.inc 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623
  1. <?php
  2. /**
  3. * @file
  4. * Code to compute the dates that match an iCal RRULE.
  5. *
  6. * Moved to a separate file since it is not used on most pages
  7. * so the code is not parsed unless needed.
  8. *
  9. * Extensive simpletests have been created to test the RRULE calculation
  10. * results against official examples from RFC 2445.
  11. *
  12. * These calculations are expensive and results should be stored or cached
  13. * so the calculation code is not called more often than necessary.
  14. *
  15. * Currently implemented:
  16. * INTERVAL, UNTIL, COUNT, EXDATE, RDATE, BYDAY, BYMONTHDAY, BYMONTH,
  17. * YEARLY, MONTHLY, WEEKLY, DAILY
  18. *
  19. * Currently not implemented:
  20. *
  21. * BYYEARDAY, MINUTELY, HOURLY, SECONDLY, BYMINUTE, BYHOUR, BYSECOND
  22. * These could be implemented in the future.
  23. *
  24. * BYSETPOS
  25. * Seldom used anywhere, so no reason to complicated the code.
  26. */
  27. /**
  28. * Private implementation of date_repeat_calc().
  29. *
  30. * Compute dates that match the requested rule, within a specified date range.
  31. */
  32. function _date_repeat_calc($rrule, $start, $end, $exceptions, $timezone, $additions) {
  33. module_load_include('inc', 'date_api', 'date_api_ical');
  34. if (empty($timezone)) {
  35. $timezone = date_default_timezone();
  36. }
  37. // Make sure the 'EXCEPTIONS' string isn't appended to the rule.
  38. $parts = explode("\n", $rrule);
  39. if (count($parts)) {
  40. $rrule = $parts[0];
  41. }
  42. // Get the parsed array of rule values.
  43. $rrule = date_ical_parse_rrule('RRULE:', $rrule);
  44. // These default values indicate there is no RRULE here.
  45. if ($rrule['FREQ'] == 'NONE' || (isset($rrule['INTERVAL']) && $rrule['INTERVAL'] == 0)) {
  46. return array();
  47. }
  48. // Create a date object for the start and end dates.
  49. $start_date = new DateObject($start, $timezone);
  50. // Versions of PHP greater than PHP 5.3.5 require that we set an explicit time when
  51. // using date_modify() or the time may not match the original value. Adding this
  52. // modifier gives us the same results in both older and newer versions of PHP.
  53. $modify_time = ' ' . $start_date->format('g:ia');
  54. // If the rule has an UNTIL, see if that is earlier than the end date.
  55. if (!empty($rrule['UNTIL'])) {
  56. $end_date = new DateObject($end, $timezone);
  57. $until_date = date_ical_date($rrule['UNTIL'], $timezone);
  58. if (date_format($until_date, 'U') < date_format($end_date, 'U')) {
  59. $end_date = $until_date;
  60. }
  61. }
  62. // The only valid option for an empty end date is when we have a count.
  63. elseif (empty($end)) {
  64. if (!empty($rrule['COUNT'])) {
  65. $end_date = NULL;
  66. }
  67. else {
  68. return array();
  69. }
  70. }
  71. else {
  72. $end_date = new DateObject($end, $timezone);
  73. }
  74. // Get an integer value for the interval, if none given, '1' is implied.
  75. if (empty($rrule['INTERVAL'])) {
  76. $rrule['INTERVAL'] = 1;
  77. }
  78. $interval = max(1, $rrule['INTERVAL']);
  79. $count = isset($rrule['COUNT']) ? $rrule['COUNT'] : NULL;
  80. if (empty($rrule['FREQ'])) {
  81. $rrule['FREQ'] = 'DAILY';
  82. }
  83. // Make sure DAILY frequency isn't used in places it won't work;
  84. if (!empty($rrule['BYMONTHDAY']) && !in_array($rrule['FREQ'], array('MONTHLY', 'YEARLY'))) {
  85. $rrule['FREQ'] = 'MONTHLY';
  86. }
  87. elseif (!empty($rrule['BYDAY']) && !in_array($rrule['FREQ'], array('MONTHLY', 'WEEKLY', 'YEARLY'))) {
  88. $rrule['FREQ'] = 'WEEKLY';
  89. }
  90. // Find the time period to jump forward between dates.
  91. switch ($rrule['FREQ']) {
  92. case 'DAILY':
  93. $jump = $interval . ' days';
  94. break;
  95. case 'WEEKLY':
  96. $jump = $interval . ' weeks';
  97. break;
  98. case 'MONTHLY':
  99. $jump = $interval . ' months';
  100. break;
  101. case 'YEARLY':
  102. $jump = $interval . ' years';
  103. break;
  104. }
  105. $rrule = date_repeat_adjust_rrule($rrule, $start_date);
  106. // The start date always goes into the results, whether or not it meets
  107. // the rules. RFC 2445 includes examples where the start date DOES NOT
  108. // meet the rules, but the expected results always include the start date.
  109. $days = array(date_format($start_date, DATE_FORMAT_DATETIME));
  110. // BYMONTHDAY will look for specific days of the month in one or more months.
  111. // This process is only valid when frequency is monthly or yearly.
  112. if (!empty($rrule['BYMONTHDAY'])) {
  113. $finished = FALSE;
  114. $current_day = clone($start_date);
  115. $direction_days = array();
  116. // Deconstruct the day in case it has a negative modifier.
  117. foreach ($rrule['BYMONTHDAY'] as $day) {
  118. preg_match("@(-)?([0-9]{1,2})@", $day, $regs);
  119. if (!empty($regs[2])) {
  120. // Convert parameters into full day name, count, and direction.
  121. $direction_days[$day] = array(
  122. 'direction' => !empty($regs[1]) ? $regs[1] : '+',
  123. 'direction_count' => $regs[2],
  124. );
  125. }
  126. }
  127. while (!$finished) {
  128. $period_finished = FALSE;
  129. while (!$period_finished) {
  130. foreach ($rrule['BYMONTHDAY'] as $monthday) {
  131. $day = $direction_days[$monthday];
  132. $current_day = date_repeat_set_month_day($current_day, NULL, $day['direction_count'], $day['direction'], $timezone, $modify_time);
  133. date_repeat_add_dates($days, $current_day, $start_date, $end_date, $exceptions, $rrule);
  134. if ($finished = date_repeat_is_finished($current_day, $days, $count, $end_date)) {
  135. $period_finished = TRUE;
  136. }
  137. }
  138. // If it's monthly, keep looping through months, one INTERVAL at a time.
  139. if ($rrule['FREQ'] == 'MONTHLY') {
  140. if ($finished = date_repeat_is_finished($current_day, $days, $count, $end_date)) {
  141. $period_finished = TRUE;
  142. }
  143. // Back up to first of month and jump.
  144. $current_day = date_repeat_set_month_day($current_day, NULL, 1, '+', $timezone, $modify_time);
  145. date_modify($current_day, '+' . $jump . $modify_time);
  146. }
  147. // If it's yearly, break out of the loop at the
  148. // end of every year, and jump one INTERVAL in years.
  149. else {
  150. if (date_format($current_day, 'n') == 12) {
  151. $period_finished = TRUE;
  152. }
  153. else {
  154. // Back up to first of month and jump.
  155. $current_day = date_repeat_set_month_day($current_day, NULL, 1, '+', $timezone, $modify_time);
  156. date_modify($current_day, '+1 month' . $modify_time);
  157. }
  158. }
  159. }
  160. if ($rrule['FREQ'] == 'YEARLY') {
  161. // Back up to first of year and jump.
  162. $current_day = date_repeat_set_year_day($current_day, NULL, NULL, 1, '+', $timezone, $modify_time);
  163. date_modify($current_day, '+' . $jump . $modify_time);
  164. }
  165. $finished = date_repeat_is_finished($current_day, $days, $count, $end_date);
  166. }
  167. }
  168. // This is the simple fallback case, not looking for any BYDAY,
  169. // just repeating the start date. Because of imputed BYDAY above, this
  170. // will only test TRUE for a DAILY or less frequency (like HOURLY).
  171. elseif (empty($rrule['BYDAY'])) {
  172. // $current_day will keep track of where we are in the calculation.
  173. $current_day = clone($start_date);
  174. $finished = FALSE;
  175. $months = !empty($rrule['BYMONTH']) ? $rrule['BYMONTH'] : array();
  176. while (!$finished) {
  177. date_repeat_add_dates($days, $current_day, $start_date, $end_date, $exceptions, $rrule);
  178. $finished = date_repeat_is_finished($current_day, $days, $count, $end_date);
  179. date_modify($current_day, '+' . $jump . $modify_time);
  180. }
  181. }
  182. else {
  183. // More complex searches for day names and criteria like '-1SU' or '2TU,2TH',
  184. // require that we interate through the whole time period checking each BYDAY.
  185. // Create helper array to pull day names out of iCal day strings.
  186. $day_names = date_repeat_dow_day_options(FALSE);
  187. $days_of_week = array_keys($day_names);
  188. // Parse out information about the BYDAYs and separate them
  189. // depending on whether they have directional parameters like -1SU or 2TH.
  190. $month_days = array();
  191. $week_days = array();
  192. // Find the right first day of the week to use, iCal rules say Monday
  193. // should be used if none is specified.
  194. $week_start_rule = !empty($rrule['WKST']) ? trim($rrule['WKST']) : 'MO';
  195. $week_start_day = $day_names[$week_start_rule];
  196. // Make sure the week days array is sorted into week order,
  197. // we use the $ordered_keys to get the right values into the key
  198. // and force the array to that order. Needed later when we
  199. // iterate through each week looking for days so we don't
  200. // jump to the next week when we hit a day out of order.
  201. $ordered = date_repeat_days_ordered($week_start_rule);
  202. $ordered_keys = array_flip($ordered);
  203. if ($rrule['FREQ'] == 'YEARLY' && !empty($rrule['BYMONTH'])) {
  204. // Additional cycle to apply month preferences.
  205. foreach ($rrule['BYMONTH'] as $month) {
  206. foreach ($rrule['BYDAY'] as $day) {
  207. preg_match("@(-)?([0-9]+)?([SU|MO|TU|WE|TH|FR|SA]{2})@", trim($day), $regs);
  208. // Convert parameters into full day name, count, and direction.
  209. // Add leading zero to first 9 months.
  210. if (!empty($regs[2])) {
  211. $direction_days[] = array(
  212. 'day' => $day_names[$regs[3]],
  213. 'direction' => !empty($regs[1]) ? $regs[1] : '+',
  214. 'direction_count' => $regs[2],
  215. 'month' => strlen($month) > 1 ? $month : '0' . $month,
  216. );
  217. }
  218. else {
  219. $week_days[$ordered_keys[$regs[3]]] = $day_names[$regs[3]];
  220. }
  221. }
  222. }
  223. }
  224. else {
  225. foreach ($rrule['BYDAY'] as $day) {
  226. preg_match("@(-)?([0-9]+)?([SU|MO|TU|WE|TH|FR|SA]{2})@", trim($day), $regs);
  227. if (!empty($regs[2])) {
  228. // Convert parameters into full day name, count, and direction.
  229. $direction_days[] = array(
  230. 'day' => $day_names[$regs[3]],
  231. 'direction' => !empty($regs[1]) ? $regs[1] : '+',
  232. 'direction_count' => $regs[2],
  233. 'month' => NULL,
  234. );
  235. }
  236. else {
  237. $week_days[$ordered_keys[$regs[3]]] = $day_names[$regs[3]];
  238. }
  239. }
  240. }
  241. ksort($week_days);
  242. // BYDAYs with parameters like -1SU (last Sun) or 2TH (second Thur)
  243. // need to be processed one month or year at a time.
  244. if (!empty($direction_days) && in_array($rrule['FREQ'], array('MONTHLY', 'YEARLY'))) {
  245. $finished = FALSE;
  246. $current_day = clone($start_date);
  247. while (!$finished) {
  248. foreach ($direction_days as $day) {
  249. // Find the BYDAY date in the current month.
  250. if ($rrule['FREQ'] == 'MONTHLY') {
  251. $current_day = date_repeat_set_month_day($current_day, $day['day'], $day['direction_count'], $day['direction'], $timezone, $modify_time);
  252. }
  253. else {
  254. $current_day = date_repeat_set_year_day($current_day, $day['month'], $day['day'], $day['direction_count'], $day['direction'], $timezone, $modify_time);
  255. }
  256. date_repeat_add_dates($days, $current_day, $start_date, $end_date, $exceptions, $rrule);
  257. }
  258. $finished = date_repeat_is_finished($current_day, $days, $count, $end_date);
  259. // Reset to beginning of period before jumping to next period.
  260. // Needed especially when working with values like 'last Saturday'
  261. // to be sure we don't skip months like February.
  262. $year = date_format($current_day, 'Y');
  263. $month = date_format($current_day, 'n');
  264. if ($rrule['FREQ'] == 'MONTHLY') {
  265. date_date_set($current_day, $year, $month, 1);
  266. }
  267. else {
  268. date_date_set($current_day, $year, 1, 1);
  269. }
  270. // Jump to the next period.
  271. date_modify($current_day, '+' . $jump . $modify_time);
  272. }
  273. }
  274. // For BYDAYs without parameters,like TU,TH (every Tues and Thur),
  275. // we look for every one of those days during the frequency period.
  276. // Iterate through periods of a WEEK, MONTH, or YEAR, checking for
  277. // the days of the week that match our criteria for each week in the
  278. // period, then jumping ahead to the next week, month, or year,
  279. // an INTERVAL at a time.
  280. if (!empty($week_days) && in_array($rrule['FREQ'], array('MONTHLY', 'WEEKLY', 'YEARLY'))) {
  281. $finished = FALSE;
  282. $current_day = clone($start_date);
  283. $format = $rrule['FREQ'] == 'YEARLY' ? 'Y' : 'n';
  284. $current_period = date_format($current_day, $format);
  285. // Back up to the beginning of the week in case we are somewhere in the
  286. // middle of the possible week days, needed so we don't prematurely
  287. // jump to the next week. The date_repeat_add_dates() function will
  288. // keep dates outside the range from getting added.
  289. if (date_format($current_day, 'l') != $day_names[$day]) {
  290. date_modify($current_day, '-1 ' . $week_start_day . $modify_time);
  291. }
  292. while (!$finished) {
  293. $period_finished = FALSE;
  294. while (!$period_finished) {
  295. $moved = FALSE;
  296. foreach ($week_days as $delta => $day) {
  297. // Find the next occurence of each day in this week, only add it
  298. // if we are still in the current month or year. The date_repeat_add_dates
  299. // function is insufficient to test whether to include this date
  300. // if we are using a rule like 'every other month', so we must
  301. // explicitly test it here.
  302. // If we're already on the right day, don't jump or we
  303. // will prematurely move into the next week.
  304. if (date_format($current_day, 'l') != $day) {
  305. date_modify($current_day, '+1 ' . $day . $modify_time);
  306. $moved = TRUE;
  307. }
  308. if ($rrule['FREQ'] == 'WEEKLY' || date_format($current_day, $format) == $current_period) {
  309. date_repeat_add_dates($days, $current_day, $start_date, $end_date, $exceptions, $rrule);
  310. }
  311. }
  312. $finished = date_repeat_is_finished($current_day, $days, $count, $end_date);
  313. // Make sure we don't get stuck in endless loop if the current
  314. // day never got changed above.
  315. if (!$moved) {
  316. date_modify($current_day, '+1 day' . $modify_time);
  317. }
  318. // If this is a WEEKLY frequency, stop after each week,
  319. // otherwise, stop when we've moved outside the current period.
  320. // Jump to the end of the week, then test the period.
  321. if ($finished || $rrule['FREQ'] == 'WEEKLY') {
  322. $period_finished = TRUE;
  323. }
  324. elseif ($rrule['FREQ'] != 'WEEKLY' && date_format($current_day, $format) != $current_period) {
  325. $period_finished = TRUE;
  326. }
  327. }
  328. if ($finished) {
  329. continue;
  330. }
  331. // We'll be at the end of a week, month, or year when
  332. // we get to this point in the code.
  333. // Go back to the beginning of this period before we jump, to
  334. // ensure we jump to the first day of the next period.
  335. switch ($rrule['FREQ']) {
  336. case 'WEEKLY':
  337. date_modify($current_day, '+1 ' . $week_start_day . $modify_time);
  338. date_modify($current_day, '-1 week' . $modify_time);
  339. break;
  340. case 'MONTHLY':
  341. date_modify($current_day, '-' . (date_format($current_day, 'j') - 1) . ' days' . $modify_time);
  342. date_modify($current_day, '-1 month' . $modify_time);
  343. break;
  344. case 'YEARLY':
  345. date_modify($current_day, '-' . date_format($current_day, 'z') . ' days' . $modify_time);
  346. date_modify($current_day, '-1 year' . $modify_time);
  347. break;
  348. }
  349. // Jump ahead to the next period to be evaluated.
  350. date_modify($current_day, '+' . $jump . $modify_time);
  351. $current_period = date_format($current_day, $format);
  352. $finished = date_repeat_is_finished($current_day, $days, $count, $end_date);
  353. }
  354. }
  355. }
  356. // add additional dates
  357. foreach ($additions as $addition) {
  358. $date = new dateObject($addition . ' ' . $start_date->format('H:i:s'), $timezone);
  359. $days[] = date_format($date, DATE_FORMAT_DATETIME);
  360. }
  361. sort($days);
  362. return $days;
  363. }
  364. /**
  365. * See if the RRULE needs some imputed values added to it.
  366. */
  367. function date_repeat_adjust_rrule($rrule, $start_date) {
  368. // If this is not a valid value, do nothing;
  369. if (empty($rrule) || empty($rrule['FREQ'])) {
  370. return array();
  371. }
  372. // RFC 2445 says if no day or monthday is specified when creating repeats for
  373. // weeks, months, or years, impute the value from the start date.
  374. if (empty($rrule['BYDAY']) && $rrule['FREQ'] == 'WEEKLY') {
  375. $rrule['BYDAY'] = array(date_repeat_dow2day(date_format($start_date, 'w')));
  376. }
  377. elseif (empty($rrule['BYDAY']) && empty($rrule['BYMONTHDAY']) && $rrule['FREQ'] == 'MONTHLY') {
  378. $rrule['BYMONTHDAY'] = array(date_format($start_date, 'j'));
  379. }
  380. elseif (empty($rrule['BYDAY']) && empty($rrule['BYMONTHDAY']) && empty($rrule['BYYEARDAY']) && $rrule['FREQ'] == 'YEARLY') {
  381. $rrule['BYMONTHDAY'] = array(date_format($start_date, 'j'));
  382. if (empty($rrule['BYMONTH'])) {
  383. $rrule['BYMONTH'] = array(date_format($start_date, 'n'));
  384. }
  385. }
  386. // If we are processing rules for period other than YEARLY or MONTHLY
  387. // and have BYDAYS like 2SU or -1SA, simplify them to SU or SA since the
  388. // position rules make no sense in other periods and just add complexity.
  389. elseif (!empty($rrule['BYDAY']) && !in_array($rrule['FREQ'], array('MONTHLY', 'YEARLY'))) {
  390. foreach ($rrule['BYDAY'] as $delta => $BYDAY) {
  391. $rrule['BYDAY'][$delta] = substr($BYDAY, -2);
  392. }
  393. }
  394. return $rrule;
  395. }
  396. /**
  397. * Helper function to add found date to the $dates array.
  398. *
  399. * Check that the date to be added is between the start and end date
  400. * and that it is not in the $exceptions, nor already in the $days array,
  401. * and that it meets other criteria in the RRULE.
  402. */
  403. function date_repeat_add_dates(&$days, $current_day, $start_date, $end_date, $exceptions, $rrule) {
  404. if (isset($rrule['COUNT']) && sizeof($days) >= $rrule['COUNT']) {
  405. return FALSE;
  406. }
  407. $formatted = date_format($current_day, DATE_FORMAT_DATETIME);
  408. if (!empty($end_date) && $formatted > date_format($end_date, DATE_FORMAT_DATETIME)) {
  409. return FALSE;
  410. }
  411. if ($formatted < date_format($start_date, DATE_FORMAT_DATETIME)) {
  412. return FALSE;
  413. }
  414. if (in_array(date_format($current_day, 'Y-m-d'), $exceptions)) {
  415. return FALSE;
  416. }
  417. if (!empty($rrule['BYDAY'])) {
  418. $BYDAYS = $rrule['BYDAY'];
  419. foreach ($BYDAYS as $delta => $BYDAY) {
  420. $BYDAYS[$delta] = substr($BYDAY, -2);
  421. }
  422. if (!in_array(date_repeat_dow2day(date_format($current_day, 'w')), $BYDAYS)) {
  423. return FALSE;
  424. }}
  425. if (!empty($rrule['BYYEAR']) && !in_array(date_format($current_day, 'Y'), $rrule['BYYEAR'])) {
  426. return FALSE;
  427. }
  428. if (!empty($rrule['BYMONTH']) && !in_array(date_format($current_day, 'n'), $rrule['BYMONTH'])) {
  429. return FALSE;
  430. }
  431. if (!empty($rrule['BYMONTHDAY'])) {
  432. // Test month days, but only if there are no negative numbers.
  433. $test = TRUE;
  434. $BYMONTHDAYS = array();
  435. foreach ($rrule['BYMONTHDAY'] as $day) {
  436. if ($day > 0) {
  437. $BYMONTHDAYS[] = $day;
  438. }
  439. else {
  440. $test = FALSE;
  441. break;
  442. }
  443. }
  444. if ($test && !empty($BYMONTHDAYS) && !in_array(date_format($current_day, 'j'), $BYMONTHDAYS)) {
  445. return FALSE;
  446. }
  447. }
  448. // Don't add a day if it is already saved so we don't throw the count off.
  449. if (in_array($formatted, $days)) {
  450. return TRUE;
  451. }
  452. else {
  453. $days[] = $formatted;
  454. }
  455. }
  456. /**
  457. * Stop when $current_day is greater than $end_date or $count is reached.
  458. */
  459. function date_repeat_is_finished($current_day, $days, $count, $end_date) {
  460. if (($count && sizeof($days) >= $count)
  461. || (!empty($end_date) && date_format($current_day, 'U') > date_format($end_date, 'U'))) {
  462. return TRUE;
  463. }
  464. else {
  465. return FALSE;
  466. }
  467. }
  468. /**
  469. * Set a date object to a specific day of the month.
  470. *
  471. * Example,
  472. * date_set_month_day($date, 'Sunday', 2, '-')
  473. * will reset $date to the second to last Sunday in the month.
  474. * If $day is empty, will set to the number of days from the
  475. * beginning or end of the month.
  476. */
  477. function date_repeat_set_month_day($date_in, $day, $count = 1, $direction = '+', $timezone = 'UTC', $modify_time) {
  478. if (is_object($date_in)) {
  479. $current_month = date_format($date_in, 'n');
  480. // Reset to the start of the month.
  481. // We should be able to do this with date_date_set(), but
  482. // for some reason the date occasionally gets confused if run
  483. // through this function multiple times. It seems to work
  484. // reliably if we create a new object each time.
  485. $datetime = date_format($date_in, DATE_FORMAT_DATETIME);
  486. $datetime = substr_replace($datetime, '01', 8, 2);
  487. $date = new DateObject($datetime, $timezone);
  488. if ($direction == '-') {
  489. // For negative search, start from the end of the month.
  490. date_modify($date, '+1 month' . $modify_time);
  491. }
  492. else {
  493. // For positive search, back up one day to get outside the
  494. // current month, so we can catch the first of the month.
  495. date_modify($date, '-1 day' . $modify_time);
  496. }
  497. if (empty($day)) {
  498. date_modify($date, $direction . $count . ' days' . $modify_time);
  499. }
  500. else {
  501. // Use the English text for order, like First Sunday
  502. // instead of +1 Sunday to overcome PHP5 bug, (see #369020).
  503. $order = date_order();
  504. $step = $count <= 5 ? $order[$direction . $count] : $count;
  505. date_modify($date, $step . ' ' . $day . $modify_time);
  506. }
  507. // If that takes us outside the current month, don't go there.
  508. if (date_format($date, 'n') == $current_month) {
  509. return $date;
  510. }
  511. }
  512. return $date_in;
  513. }
  514. /**
  515. * Set a date object to a specific day of the year.
  516. *
  517. * Example,
  518. * date_set_year_day($date, 'Sunday', 2, '-')
  519. * will reset $date to the second to last Sunday in the year.
  520. * If $day is empty, will set to the number of days from the
  521. * beginning or end of the year.
  522. */
  523. function date_repeat_set_year_day($date_in, $month, $day, $count = 1, $direction = '+', $timezone = 'UTC', $modify_time) {
  524. if (is_object($date_in)) {
  525. $current_year = date_format($date_in, 'Y');
  526. // Reset to the start of the month.
  527. // See note above.
  528. $datetime = date_format($date_in, DATE_FORMAT_DATETIME);
  529. $month_key = isset($month) ? $month : '01';
  530. $datetime = substr_replace($datetime, $month_key . '-01', 5, 5);
  531. $date = new DateObject($datetime, $timezone);
  532. if (isset($month)) {
  533. if ($direction == '-') {
  534. // For negative search, start from the end of the month.
  535. $modifier = '+1 month';
  536. }
  537. else {
  538. // For positive search, back up one day to get outside the
  539. // current month, so we can catch the first of the month.
  540. $modifier = '-1 day';
  541. }
  542. }
  543. else {
  544. if ($direction == '-') {
  545. // For negative search, start from the end of the year.
  546. $modifier = '+1 year';
  547. }
  548. else {
  549. // For positive search, back up one day to get outside the
  550. // current year, so we can catch the first of the year.
  551. $modifier = '-1 day';
  552. }
  553. }
  554. date_modify($date, $modifier . $modify_time);
  555. if (empty($day)) {
  556. date_modify($date, $direction . $count . ' days' . $modify_time);
  557. }
  558. else {
  559. // Use the English text for order, like First Sunday
  560. // instead of +1 Sunday to overcome PHP5 bug, (see #369020).
  561. $order = date_order();
  562. $step = $count <= 5 ? $order[$direction . $count] : $count;
  563. date_modify($date, $step . ' ' . $day . $modify_time);
  564. }
  565. // If that takes us outside the current year, don't go there.
  566. if (date_format($date, 'Y') == $current_year) {
  567. return $date;
  568. }
  569. }
  570. return $date_in;
  571. }