date_repeat_calc.inc 23 KB

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