Projet

Général

Profil

Paste
Télécharger (23,3 ko) Statistiques
| Branche: | Révision:

root / drupal7 / sites / all / modules / date / date_repeat / date_repeat_calc.inc @ b720ea3e

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
/**
29
 * Private implementation of date_repeat_calc().
30
 *
31
 * Compute dates that match the requested rule, within a specified date range.
32
 */
33
function _date_repeat_calc($rrule, $start, $end, $exceptions, $timezone, $additions) {
34
  module_load_include('inc', 'date_api', 'date_api_ical');
35

    
36
  if (empty($timezone)) {
37
    $timezone = date_default_timezone();
38
  }
39

    
40
  // Make sure the 'EXCEPTIONS' string isn't appended to the rule.
41
  $parts = explode("\n", $rrule);
42
  if (count($parts)) {
43
    $rrule = $parts[0];
44
  }
45
  // Get the parsed array of rule values.
46
  $rrule = date_ical_parse_rrule('RRULE:', $rrule);
47

    
48
  // These default values indicate there is no RRULE here.
49
  if ($rrule['FREQ'] == 'NONE' || (isset($rrule['INTERVAL']) && $rrule['INTERVAL'] == 0)) {
50
    return array();
51
  }
52

    
53
  // Create a date object for the start and end dates.
54
  $start_date = new DateObject($start, $timezone);
55

    
56
  // Versions of PHP greater than PHP 5.3.5 require
57
  // that we set an explicit time when using date_modify()
58
  // or the time may not match the original value.
59
  // Adding this modifier gives us the same results in both older
60
  // and newer versions of PHP.
61
  $modify_time = ' ' . $start_date->format('g:ia');
62

    
63
  // If the rule has an UNTIL, see if that is earlier than the end date.
64
  if (!empty($rrule['UNTIL'])) {
65
    $end_date = new DateObject($end, $timezone);
66
    $until_date = date_ical_date($rrule['UNTIL'], $timezone);
67
    if (date_format($until_date, 'U') < date_format($end_date, 'U')) {
68
      $end_date = $until_date;
69
    }
70
  }
71
  // The only valid option for an empty end date is when we have a count.
72
  elseif (empty($end)) {
73
    if (!empty($rrule['COUNT'])) {
74
      $end_date = NULL;
75
    }
76
    else {
77
      return array();
78
    }
79
  }
80
  else {
81
    $end_date = new DateObject($end, $timezone);
82
  }
83

    
84
  // Get an integer value for the interval, if none given, '1' is implied.
85
  if (empty($rrule['INTERVAL'])) {
86
    $rrule['INTERVAL'] = 1;
87
  }
88
  $interval = max(1, $rrule['INTERVAL']);
89
  $count = isset($rrule['COUNT']) ? $rrule['COUNT'] : NULL;
90

    
91
  if (empty($rrule['FREQ'])) {
92
    $rrule['FREQ'] = 'DAILY';
93
  }
94

    
95
  // Make sure DAILY frequency isn't used in places it won't work;
96
  if (!empty($rrule['BYMONTHDAY']) &&
97
    !in_array($rrule['FREQ'], array('MONTHLY', 'YEARLY'))) {
98
    $rrule['FREQ'] = 'MONTHLY';
99
  }
100
  elseif (!empty($rrule['BYDAY'])
101
    && !in_array($rrule['FREQ'], array('MONTHLY', 'WEEKLY', 'YEARLY'))) {
102
    $rrule['FREQ'] = 'WEEKLY';
103
  }
104

    
105
  // Find the time period to jump forward between dates.
106
  switch ($rrule['FREQ']) {
107
    case 'DAILY':
108
      $jump = $interval . ' days';
109
      break;
110

    
111
    case 'WEEKLY':
112
      $jump = $interval . ' weeks';
113
      break;
114

    
115
    case 'MONTHLY':
116
      $jump = $interval . ' months';
117
      break;
118

    
119
    case 'YEARLY':
120
      $jump = $interval . ' years';
121
      break;
122
  }
123
  $rrule = date_repeat_adjust_rrule($rrule, $start_date);
124

    
125
  // The start date always goes into the results, whether or not it meets
126
  // the rules. RFC 2445 includes examples where the start date DOES NOT
127
  // meet the rules, but the expected results always include the start date.
128
  $days = array(date_format($start_date, DATE_FORMAT_DATETIME));
129

    
130
  // BYMONTHDAY will look for specific days of the month in one or more months.
131
  // This process is only valid when frequency is monthly or yearly.
132

    
133
  if (!empty($rrule['BYMONTHDAY'])) {
134
    $finished = FALSE;
135
    $current_day = clone($start_date);
136
    $direction_days = array();
137
    // Deconstruct the day in case it has a negative modifier.
138
    foreach ($rrule['BYMONTHDAY'] as $day) {
139
      preg_match("@(-)?([0-9]{1,2})@", $day, $regs);
140
      if (!empty($regs[2])) {
141
        // Convert parameters into full day name, count, and direction.
142
        $direction_days[$day] = array(
143
          'direction' => !empty($regs[1]) ? $regs[1] : '+',
144
          'direction_count' => $regs[2],
145
        );
146
      }
147
    }
148
    while (!$finished) {
149
      $period_finished = FALSE;
150
      while (!$period_finished) {
151
        foreach ($rrule['BYMONTHDAY'] as $monthday) {
152
          $day = $direction_days[$monthday];
153
          $current_day = date_repeat_set_month_day($current_day, NULL, $day['direction_count'], $day['direction'], $timezone, $modify_time);
154
          date_repeat_add_dates($days, $current_day, $start_date, $end_date, $exceptions, $rrule);
155
          if ($finished = date_repeat_is_finished($current_day, $days, $count, $end_date)) {
156
            $period_finished = TRUE;
157
          }
158
        }
159
        // If it's monthly, keep looping through months, one INTERVAL at a time.
160
        if ($rrule['FREQ'] == 'MONTHLY') {
161
          if ($finished = date_repeat_is_finished($current_day, $days, $count, $end_date)) {
162
            $period_finished = TRUE;
163
          }
164
          // Back up to first of month and jump.
165
          $current_day = date_repeat_set_month_day($current_day, NULL, 1, '+', $timezone, $modify_time);
166
          date_modify($current_day, '+' . $jump . $modify_time);
167
        }
168
        // If it's yearly, break out of the loop at the
169
        // end of every year, and jump one INTERVAL in years.
170
        else {
171
          if (date_format($current_day, 'n') == 12) {
172
            $period_finished = TRUE;
173
          }
174
          else {
175
            // Back up to first of month and jump.
176
            $current_day = date_repeat_set_month_day($current_day, NULL, 1, '+', $timezone, $modify_time);
177
            date_modify($current_day, '+1 month' . $modify_time);
178
          }
179
        }
180
      }
181
      if ($rrule['FREQ'] == 'YEARLY') {
182
        // Back up to first of year and jump.
183
        $current_day = date_repeat_set_year_day($current_day, NULL, NULL, 1, '+', $timezone, $modify_time);
184
        date_modify($current_day, '+' . $jump . $modify_time);
185
      }
186
      $finished = date_repeat_is_finished($current_day, $days, $count, $end_date);
187
    }
188
  }
189

    
190
  // This is the simple fallback case, not looking for any BYDAY,
191
  // just repeating the start date. Because of imputed BYDAY above, this
192
  // will only test TRUE for a DAILY or less frequency (like HOURLY).
193

    
194
  elseif (empty($rrule['BYDAY'])) {
195
    // $current_day will keep track of where we are in the calculation.
196
    $current_day = clone($start_date);
197
    $finished = FALSE;
198
    $months = !empty($rrule['BYMONTH']) ? $rrule['BYMONTH'] : array();
199
    while (!$finished) {
200
      date_repeat_add_dates($days, $current_day, $start_date, $end_date, $exceptions, $rrule);
201
      $finished = date_repeat_is_finished($current_day, $days, $count, $end_date);
202
      date_modify($current_day, '+' . $jump . $modify_time);
203
    }
204
  }
205

    
206
  else {
207

    
208
    // More complex searches for day names and criteria
209
    // like '-1SU' or '2TU,2TH', require that we interate through
210
    // the whole time period checking each BYDAY.
211

    
212
    // Create helper array to pull day names out of iCal day strings.
213
    $day_names = date_repeat_dow_day_options(FALSE);
214
    $days_of_week = array_keys($day_names);
215

    
216
    // Parse out information about the BYDAYs and separate them
217
    // depending on whether they have directional parameters like -1SU or 2TH.
218
    $month_days = array();
219
    $week_days = array();
220

    
221
    // Find the right first day of the week to use, iCal rules say Monday
222
    // should be used if none is specified.
223
    $week_start_rule = !empty($rrule['WKST']) ? trim($rrule['WKST']) : 'MO';
224
    $week_start_day = $day_names[$week_start_rule];
225

    
226
    // Make sure the week days array is sorted into week order,
227
    // we use the $ordered_keys to get the right values into the key
228
    // and force the array to that order. Needed later when we
229
    // iterate through each week looking for days so we don't
230
    // jump to the next week when we hit a day out of order.
231
    $ordered = date_repeat_days_ordered($week_start_rule);
232
    $ordered_keys = array_flip($ordered);
233

    
234
    if ($rrule['FREQ'] == 'YEARLY' && !empty($rrule['BYMONTH'])) {
235
      // Additional cycle to apply month preferences.
236
      foreach ($rrule['BYMONTH'] as $month) {
237
        foreach ($rrule['BYDAY'] as $day) {
238
          preg_match("@(-)?([0-9]+)?([SU|MO|TU|WE|TH|FR|SA]{2})@", trim($day), $regs);
239
          // Convert parameters into full day name, count, and direction.
240
          // Add leading zero to first 9 months.
241
          if (!empty($regs[2])) {
242
            $direction_days[] = array(
243
              'day' => $day_names[$regs[3]],
244
              'direction' => !empty($regs[1]) ? $regs[1] : '+',
245
              'direction_count' => $regs[2],
246
              'month' => strlen($month) > 1 ? $month : '0' . $month,
247
            );
248
          }
249
          else {
250
            $week_days[$ordered_keys[$regs[3]]] = $day_names[$regs[3]];
251
          }
252
        }
253
      }
254
    }
255
    else {
256
      foreach ($rrule['BYDAY'] as $day) {
257
        preg_match("@(-)?([0-9]+)?([SU|MO|TU|WE|TH|FR|SA]{2})@", trim($day), $regs);
258
        if (!empty($regs[2])) {
259
          // Convert parameters into full day name, count, and direction.
260
          $direction_days[] = array(
261
            'day' => $day_names[$regs[3]],
262
            'direction' => !empty($regs[1]) ? $regs[1] : '+',
263
            'direction_count' => $regs[2],
264
            'month' => NULL,
265
          );
266
        }
267
        else {
268
          $week_days[$ordered_keys[$regs[3]]] = $day_names[$regs[3]];
269
        }
270
      }
271
    }
272
    ksort($week_days);
273

    
274
    // BYDAYs with parameters like -1SU (last Sun) or 2TH (second Thur)
275
    // need to be processed one month or year at a time.
276
    if (!empty($direction_days) && in_array($rrule['FREQ'], array('MONTHLY', 'YEARLY'))) {
277
      $finished = FALSE;
278
      $current_day = clone($start_date);
279
      while (!$finished) {
280
        foreach ($direction_days as $day) {
281
          // Find the BYDAY date in the current month.
282
          if ($rrule['FREQ'] == 'MONTHLY') {
283
            $current_day = date_repeat_set_month_day($current_day, $day['day'], $day['direction_count'], $day['direction'], $timezone, $modify_time);
284
          }
285
          else {
286
            $current_day = date_repeat_set_year_day($current_day, $day['month'], $day['day'], $day['direction_count'], $day['direction'], $timezone, $modify_time);
287
          }
288
          date_repeat_add_dates($days, $current_day, $start_date, $end_date, $exceptions, $rrule);
289
        }
290
        $finished = date_repeat_is_finished($current_day, $days, $count, $end_date);
291
        // Reset to beginning of period before jumping to next period.
292
        // Needed especially when working with values like 'last Saturday'
293
        // to be sure we don't skip months like February.
294
        $year = date_format($current_day, 'Y');
295
        $month = date_format($current_day, 'n');
296
        if ($rrule['FREQ'] == 'MONTHLY') {
297
          date_date_set($current_day, $year, $month, 1);
298
        }
299
        else {
300
          date_date_set($current_day, $year, 1, 1);
301
        }
302
        // Jump to the next period.
303
        date_modify($current_day, '+' . $jump . $modify_time);
304
      }
305
    }
306

    
307
    // For BYDAYs without parameters,like TU,TH (every Tues and Thur),
308
    // we look for every one of those days during the frequency period.
309
    // Iterate through periods of a WEEK, MONTH, or YEAR, checking for
310
    // the days of the week that match our criteria for each week in the
311
    // period, then jumping ahead to the next week, month, or year,
312
    // an INTERVAL at a time.
313

    
314
    if (!empty($week_days) &&
315
      in_array($rrule['FREQ'], array('MONTHLY', 'WEEKLY', 'YEARLY'))) {
316
      $finished = FALSE;
317
      $current_day = clone($start_date);
318
      $format = $rrule['FREQ'] == 'YEARLY' ? 'Y' : 'n';
319
      $current_period = date_format($current_day, $format);
320

    
321
      // Back up to the beginning of the week in case we are somewhere in the
322
      // middle of the possible week days, needed so we don't prematurely
323
      // jump to the next week. The date_repeat_add_dates() function will
324
      // keep dates outside the range from getting added.
325
      if (date_format($current_day, 'l') != $day_names[$day]) {
326
        date_modify($current_day, '-1 ' . $week_start_day . $modify_time);
327
      }
328
      while (!$finished) {
329
        $period_finished = FALSE;
330
        while (!$period_finished) {
331
          $moved = FALSE;
332
          foreach ($week_days as $delta => $day) {
333
            // Find the next occurence of each day in this week, only add it
334
            // if we are still in the current month or year.
335
            // The date_repeat_add_dates function is insufficient
336
            // to test whether to include this date
337
            // if we are using a rule like 'every other month', so we must
338
            // explicitly test it here.
339

    
340
            // If we're already on the right day, don't jump or we
341
            // will prematurely move into the next week.
342
            if (date_format($current_day, 'l') != $day) {
343
              date_modify($current_day, '+1 ' . $day . $modify_time);
344
              $moved = TRUE;
345
            }
346
            if ($rrule['FREQ'] == 'WEEKLY' || date_format($current_day, $format) == $current_period) {
347
              date_repeat_add_dates($days, $current_day, $start_date, $end_date, $exceptions, $rrule);
348
            }
349
          }
350
          $finished = date_repeat_is_finished($current_day, $days, $count, $end_date);
351

    
352
          // Make sure we don't get stuck in endless loop if the current
353
          // day never got changed above.
354
          if (!$moved) {
355
            date_modify($current_day, '+1 day' . $modify_time);
356
          }
357

    
358
          // If this is a WEEKLY frequency, stop after each week,
359
          // otherwise, stop when we've moved outside the current period.
360
          // Jump to the end of the week, then test the period.
361
          if ($finished || $rrule['FREQ'] == 'WEEKLY') {
362
            $period_finished = TRUE;
363
          }
364
          elseif ($rrule['FREQ'] != 'WEEKLY' && date_format($current_day, $format) != $current_period) {
365
            $period_finished = TRUE;
366
          }
367
        }
368

    
369
        if ($finished) {
370
          continue;
371
        }
372

    
373
        // We'll be at the end of a week, month, or year when
374
        // we get to this point in the code.
375

    
376
        // Go back to the beginning of this period before we jump, to
377
        // ensure we jump to the first day of the next period.
378
        switch ($rrule['FREQ']) {
379
          case 'WEEKLY':
380
            date_modify($current_day, '+1 ' . $week_start_day . $modify_time);
381
            date_modify($current_day, '-1 week' . $modify_time);
382
            break;
383

    
384
          case 'MONTHLY':
385
            date_modify($current_day, '-' . (date_format($current_day, 'j') - 1) . ' days' . $modify_time);
386
            date_modify($current_day, '-1 month' . $modify_time);
387
            break;
388

    
389
          case 'YEARLY':
390
            date_modify($current_day, '-' . date_format($current_day, 'z') . ' days' . $modify_time);
391
            date_modify($current_day, '-1 year' . $modify_time);
392
            break;
393
        }
394
        // Jump ahead to the next period to be evaluated.
395
        date_modify($current_day, '+' . $jump . $modify_time);
396
        $current_period = date_format($current_day, $format);
397
        $finished = date_repeat_is_finished($current_day, $days, $count, $end_date);
398
      }
399
    }
400
  }
401

    
402
  // Add additional dates.
403
  foreach ($additions as $addition) {
404
    $date = new dateObject($addition . ' ' . $start_date->format('H:i:s'), $timezone);
405
    $days[] = date_format($date, DATE_FORMAT_DATETIME);
406
  }
407

    
408
  sort($days);
409
  return $days;
410
}
411

    
412
/**
413
 * See if the RRULE needs some imputed values added to it.
414
 */
415
function date_repeat_adjust_rrule($rrule, $start_date) {
416
  // If this is not a valid value, do nothing;
417
  if (empty($rrule) || empty($rrule['FREQ'])) {
418
    return array();
419
  }
420

    
421
  // RFC 2445 says if no day or monthday is specified when creating repeats for
422
  // weeks, months, or years, impute the value from the start date.
423

    
424
  if (empty($rrule['BYDAY']) && $rrule['FREQ'] == 'WEEKLY') {
425
    $rrule['BYDAY'] = array(date_repeat_dow2day(date_format($start_date, 'w')));
426
  }
427
  elseif (empty($rrule['BYDAY']) && empty($rrule['BYMONTHDAY']) && $rrule['FREQ'] == 'MONTHLY') {
428
    $rrule['BYMONTHDAY'] = array(date_format($start_date, 'j'));
429
  }
430
  elseif (empty($rrule['BYDAY']) && empty($rrule['BYMONTHDAY']) && empty($rrule['BYYEARDAY']) && $rrule['FREQ'] == 'YEARLY') {
431
    $rrule['BYMONTHDAY'] = array(date_format($start_date, 'j'));
432
    if (empty($rrule['BYMONTH'])) {
433
      $rrule['BYMONTH'] = array(date_format($start_date, 'n'));
434
    }
435
  }
436
  // If we are processing rules for period other than YEARLY or MONTHLY
437
  // and have BYDAYS like 2SU or -1SA, simplify them to SU or SA since the
438
  // position rules make no sense in other periods and just add complexity.
439

    
440
  elseif (!empty($rrule['BYDAY']) && !in_array($rrule['FREQ'], array('MONTHLY', 'YEARLY'))) {
441
    foreach ($rrule['BYDAY'] as $delta => $by_day) {
442
      $rrule['BYDAY'][$delta] = substr($by_day, -2);
443
    }
444
  }
445

    
446
  return $rrule;
447
}
448

    
449
/**
450
 * Helper function to add found date to the $dates array.
451
 *
452
 * Check that the date to be added is between the start and end date
453
 * and that it is not in the $exceptions, nor already in the $days array,
454
 * and that it meets other criteria in the RRULE.
455
 */
456
function date_repeat_add_dates(&$days, $current_day, $start_date, $end_date, $exceptions, $rrule) {
457
  if (isset($rrule['COUNT']) && count($days) >= $rrule['COUNT']) {
458
    return FALSE;
459
  }
460
  $formatted = date_format($current_day, DATE_FORMAT_DATETIME);
461
  if (!empty($end_date) && $formatted > date_format($end_date, DATE_FORMAT_DATETIME)) {
462
    return FALSE;
463
  }
464
  if ($formatted < date_format($start_date, DATE_FORMAT_DATETIME)) {
465
    return FALSE;
466
  }
467
  if (in_array(date_format($current_day, 'Y-m-d'), $exceptions)) {
468
    return FALSE;
469
  }
470
  if (!empty($rrule['BYDAY'])) {
471
    $by_days = $rrule['BYDAY'];
472
    foreach ($by_days as $delta => $by_day) {
473
      $by_days[$delta] = substr($by_day, -2);
474
    }
475
    if (!in_array(date_repeat_dow2day(date_format($current_day, 'w')), $by_days)) {
476
      return FALSE;
477
    }
478
  }
479
  if (!empty($rrule['BYYEAR']) && !in_array(date_format($current_day, 'Y'), $rrule['BYYEAR'])) {
480
    return FALSE;
481
  }
482
  if (!empty($rrule['BYMONTH']) && !in_array(date_format($current_day, 'n'), $rrule['BYMONTH'])) {
483
    return FALSE;
484
  }
485
  if (!empty($rrule['BYMONTHDAY'])) {
486
    // Test month days, but only if there are no negative numbers.
487
    $test = TRUE;
488
    $by_month_days = array();
489
    foreach ($rrule['BYMONTHDAY'] as $day) {
490
      if ($day > 0) {
491
        $by_month_days[] = $day;
492
      }
493
      else {
494
        $test = FALSE;
495
        break;
496
      }
497
    }
498
    if ($test && !empty($by_month_days) && !in_array(date_format($current_day, 'j'), $by_month_days)) {
499
      return FALSE;
500
    }
501
  }
502
  // Don't add a day if it is already saved so we don't throw the count off.
503
  if (in_array($formatted, $days)) {
504
    return TRUE;
505
  }
506
  else {
507
    $days[] = $formatted;
508
  }
509
}
510

    
511
/**
512
 * Stop when $current_day is greater than $end_date or $count is reached.
513
 */
514
function date_repeat_is_finished($current_day, $days, $count, $end_date) {
515
  if (($count && count($days) >= $count)
516
  || (!empty($end_date) && date_format($current_day, 'U') > date_format($end_date, 'U'))) {
517
    return TRUE;
518
  }
519
  else {
520
    return FALSE;
521
  }
522
}
523

    
524
/**
525
 * Set a date object to a specific day of the month.
526
 *
527
 * Example,
528
 *   date_set_month_day($date, 'Sunday', 2, '-')
529
 *   will reset $date to the second to last Sunday in the month.
530
 *   If $day is empty, will set to the number of days from the
531
 *   beginning or end of the month.
532
 */
533
function date_repeat_set_month_day($date_in, $day, $count = 1, $direction = '+', $timezone = 'UTC', $modify_time = '') {
534
  if (is_object($date_in)) {
535
    $current_month = date_format($date_in, 'n');
536

    
537
    // Reset to the start of the month.
538
    // We should be able to do this with date_date_set(), but
539
    // for some reason the date occasionally gets confused if run
540
    // through this function multiple times. It seems to work
541
    // reliably if we create a new object each time.
542
    $datetime = date_format($date_in, DATE_FORMAT_DATETIME);
543
    $datetime = substr_replace($datetime, '01', 8, 2);
544
    $date = new DateObject($datetime, $timezone);
545
    if ($direction == '-') {
546
      // For negative search, start from the end of the month.
547
      date_modify($date, '+1 month' . $modify_time);
548
    }
549
    else {
550
      // For positive search, back up one day to get outside the
551
      // current month, so we can catch the first of the month.
552
      date_modify($date, '-1 day' . $modify_time);
553
    }
554

    
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

    
566
    // If that takes us outside the current month, don't go there.
567
    if (date_format($date, 'n') == $current_month) {
568
      return $date;
569
    }
570
  }
571
  return $date_in;
572
}
573

    
574
/**
575
 * Set a date object to a specific day of the year.
576
 *
577
 * Example,
578
 *   date_set_year_day($date, 'Sunday', 2, '-')
579
 *   will reset $date to the second to last Sunday in the year.
580
 *   If $day is empty, will set to the number of days from the
581
 *   beginning or end of the year.
582
 */
583
function date_repeat_set_year_day($date_in, $month, $day, $count = 1, $direction = '+', $timezone = 'UTC', $modify_time = '') {
584
  if (is_object($date_in)) {
585
    $current_year = date_format($date_in, 'Y');
586

    
587
    // Reset to the start of the month.
588
    // See note above.
589
    $datetime = date_format($date_in, DATE_FORMAT_DATETIME);
590
    $month_key = isset($month) ? $month : '01';
591
    $datetime = substr_replace($datetime, $month_key . '-01', 5, 5);
592
    $date = new DateObject($datetime, $timezone);
593

    
594
    if (isset($month)) {
595
      if ($direction == '-') {
596
        // For negative search, start from the end of the month.
597
        $modifier = '+1 month';
598
      }
599
      else {
600
        // For positive search, back up one day to get outside the
601
        // current month, so we can catch the first of the month.
602
        $modifier = '-1 day';
603
      }
604
    }
605
    else {
606
      if ($direction == '-') {
607
        // For negative search, start from the end of the year.
608
        $modifier = '+1 year';
609
      }
610
      else {
611
        // For positive search, back up one day to get outside the
612
        // current year, so we can catch the first of the year.
613
        $modifier = '-1 day';
614
      }
615
    }
616

    
617
    date_modify($date, $modifier . $modify_time);
618

    
619
    if (empty($day)) {
620
      date_modify($date, $direction . $count . ' days' . $modify_time);
621
    }
622
    else {
623
      // Use the English text for order, like First Sunday
624
      // instead of +1 Sunday to overcome PHP5 bug, (see #369020).
625
      $order = date_order();
626
      $step = $count <= 5 ? $order[$direction . $count] : $count;
627
      date_modify($date, $step . ' ' . $day . $modify_time);
628
    }
629

    
630
    // If that takes us outside the current year, don't go there.
631
    if (date_format($date, 'Y') == $current_year) {
632
      return $date;
633
    }
634
  }
635
  return $date_in;
636
}