Projet

Général

Profil

Paste
Télécharger (15,1 ko) Statistiques
| Branche: | Révision:

root / drupal7 / sites / all / modules / date / date_repeat / date_repeat.module @ b720ea3e

1
<?php
2
/**
3
 * @file
4
 * This module creates a form element that allows users to select
5
 * repeat rules for a date, and reworks the result into an iCal
6
 * RRULE string that can be stored in the database.
7
 *
8
 * The module also parses iCal RRULEs to create an array of dates
9
 * that meet their criteria.
10
 *
11
 * Other modules can use this API to add self-validating form elements
12
 * to their dates, and identify dates that meet the RRULE criteria.
13
 */
14

    
15
/**
16
 * Implements hook_element_info().
17
 */
18
function date_repeat_element_info() {
19
  $type['date_repeat_rrule'] = array(
20
    '#input' => TRUE,
21
    '#process' => array('date_repeat_rrule_process'),
22
    '#element_validate' => array('date_repeat_rrule_validate'),
23
    '#theme_wrappers' => array('date_repeat_rrule'),
24
  );
25
  $type['date_repeat_form_element_radios'] = array(
26
    '#input' => TRUE,
27
    '#process' => array('date_repeat_form_element_radios_process'),
28
    '#theme_wrappers' => array('radios'),
29
    '#pre_render' => array('form_pre_render_conditional_form_element'),
30
  );
31
  if (module_exists('ctools')) {
32
    $type['date_repeat_rrule']['#pre_render'] = array('ctools_dependent_pre_render');
33
  }
34
  return $type;
35
}
36

    
37
/**
38
 * Implements hook_theme().
39
 */
40
function date_repeat_theme() {
41
  return array(
42
    'date_repeat_current_exceptions' => array('render element' => 'element'),
43
    'date_repeat_current_additions' => array('render element' => 'element'),
44
    'date_repeat_rrule' => array('render element' => 'element'),
45
  );
46
}
47

    
48
/**
49
 * Helper function for FREQ options.
50
 */
51
function date_repeat_freq_options() {
52
  return array(
53
    'DAILY' => t('Daily', array(), array('context' => 'datetime_singular')),
54
    'WEEKLY' => t('Weekly', array(), array('context' => 'datetime_singular')),
55
    'MONTHLY' => t('Monthly', array(), array('context' => 'datetime_singular')),
56
    'YEARLY' => t('Yearly', array(), array('context' => 'datetime_singular')),
57
  );
58
}
59

    
60
/**
61
 * Helper function for interval options.
62
 */
63
function date_repeat_interval_options() {
64
  $options = range(0, 366);
65
  unset($options[0]);
66

    
67
  return $options;
68
}
69

    
70
/**
71
 * Helper function for FREQ options.
72
 *
73
 * Translated and untranslated arrays of the iCal day of week names.
74
 * We need the untranslated values for date_modify(), translated
75
 * values when displayed to user.
76
 */
77
function date_repeat_dow_day_options($translated = TRUE) {
78
  return array(
79
    'SU' => $translated ? t('Sunday', array(), array('context' => 'day_name')) : 'Sunday',
80
    'MO' => $translated ? t('Monday', array(), array('context' => 'day_name')) : 'Monday',
81
    'TU' => $translated ? t('Tuesday', array(), array('context' => 'day_name')) : 'Tuesday',
82
    'WE' => $translated ? t('Wednesday', array(), array('context' => 'day_name')) : 'Wednesday',
83
    'TH' => $translated ? t('Thursday', array(), array('context' => 'day_name')) : 'Thursday',
84
    'FR' => $translated ? t('Friday', array(), array('context' => 'day_name')) : 'Friday',
85
    'SA' => $translated ? t('Saturday', array(), array('context' => 'day_name')) : 'Saturday',
86
  );
87
}
88

    
89
/**
90
 * Helper function for FREQ options.
91
 *
92
 * Translated and untranslated arrays of the iCal abbreviated day of week names.
93
 */
94
function date_repeat_dow_day_options_abbr($translated = TRUE, $length = 3) {
95
  $return = array();
96
  switch ($length) {
97
    case 1:
98
      $context = 'day_abbr1';
99
      break;
100

    
101
    case 2:
102
      $context = 'day_abbr2';
103
      break;
104

    
105
    default:
106
      $context = '';
107
      break;
108
  }
109
  foreach (date_repeat_dow_day_untranslated() as $key => $day) {
110
    $return[$key] = $translated ? t(substr($day, 0, $length), array(), array('context' => $context)) : substr($day, 0, $length);
111
  }
112
  return $return;
113
}
114

    
115
/**
116
 * Helper function for weekdays translated.
117
 */
118
function date_repeat_dow_day_untranslated() {
119
  static $date_repeat_weekdays;
120
  if (empty($date_repeat_weekdays)) {
121
    $date_repeat_weekdays = array(
122
      'SU' => 'Sunday',
123
      'MO' => 'Monday',
124
      'TU' => 'Tuesday',
125
      'WE' => 'Wednesday',
126
      'TH' => 'Thursday',
127
      'FR' => 'Friday',
128
      'SA' => 'Saturday'
129
    );
130
  }
131
  return $date_repeat_weekdays;
132
}
133

    
134
/**
135
 * Helper function for weekdays order.
136
 */
137
function date_repeat_dow_day_options_ordered($weekdays) {
138
  $day_keys = array_keys($weekdays);
139
  $day_values = array_values($weekdays);
140
  for ($i = 1; $i <= variable_get('date_first_day', 0); $i++) {
141
    $last_key = array_shift($day_keys);
142
    array_push($day_keys, $last_key);
143
    $last_value = array_shift($day_values);
144
    array_push($day_values, $last_value);
145
  }
146
  $weekdays = array_combine($day_keys, $day_values);
147
  return $weekdays;
148
}
149

    
150
/**
151
 * Helper function for BYDAY options.
152
 */
153
function date_repeat_dow_count_options() {
154
  return array('' => t('Every', array(), array('context' => 'date_order'))) + date_order_translated();
155
}
156

    
157
/**
158
 * Helper function for BYDAY options.
159
 *
160
 * Creates options like -1SU and 2TU
161
 */
162
function date_repeat_dow_options() {
163
  $options = array();
164
  foreach (date_repeat_dow_count_options() as $count_key => $count_value) {
165
    foreach (date_repeat_dow_day_options() as $dow_key => $dow_value) {
166
      $options[$count_key . $dow_key] = $count_value . ' ' . $dow_value;
167
    }
168
  }
169
  return $options;
170
}
171

    
172
/**
173
 * Translate a day of week position to the iCal day name.
174
 *
175
 * Used with date_format($date, 'w') or get_variable('date_first_day'),
176
 * which return 0 for Sunday, 1 for Monday, etc.
177
 *
178
 * dow 2 becomes 'TU', dow 3 becomes 'WE', and so on.
179
 */
180
function date_repeat_dow2day($dow) {
181
  $days_of_week = array_keys(date_repeat_dow_day_options(FALSE));
182
  return $days_of_week[$dow];
183
}
184

    
185
/**
186
 * Shift the array of iCal day names into the right order for a specific week start day.
187
 */
188
function date_repeat_days_ordered($week_start_day) {
189
  $days = array_flip(array_keys(date_repeat_dow_day_options(FALSE)));
190
  $start_position = $days[$week_start_day];
191
  $keys = array_flip($days);
192
  if ($start_position > 0) {
193
    for ($i = 1; $i <= $start_position; $i++) {
194
      $last = array_shift($keys);
195
      array_push($keys, $last);
196
    }
197
  }
198
  return $keys;
199
}
200

    
201
/**
202
 * Build a description of an iCal rule.
203
 *
204
 * Constructs a human-readable description of the rule.
205
 */
206
function date_repeat_rrule_description($rrule, $format = 'D M d Y') {
207
  // Empty or invalid value.
208
  if (empty($rrule) || !strstr($rrule, 'RRULE')) {
209
    return;
210
  }
211

    
212
  module_load_include('inc', 'date_api', 'date_api_ical');
213
  module_load_include('inc', 'date_repeat', 'date_repeat_calc');
214

    
215
  $parts = date_repeat_split_rrule($rrule);
216
  $additions = $parts[2];
217
  $exceptions = $parts[1];
218
  $rrule = $parts[0];
219
  if ($rrule['FREQ'] == 'NONE') {
220
    return;
221
  }
222

    
223
  // Make sure there will be an empty description for any unused parts.
224
  $description = array(
225
    '!interval' => '',
226
    '!byday' => '',
227
    '!bymonth' => '',
228
    '!count' => '',
229
    '!until' => '',
230
    '!except' => '',
231
    '!additional' => '',
232
    '!week_starts_on' => '',
233
  );
234
  $interval = date_repeat_interval_options();
235
  switch ($rrule['FREQ']) {
236
    case 'WEEKLY':
237
      $description['!interval'] = format_plural($rrule['INTERVAL'], 'every week', 'every @count weeks') . ' ';
238
      break;
239

    
240
    case 'MONTHLY':
241
      $description['!interval'] = format_plural($rrule['INTERVAL'], 'every month', 'every @count months') . ' ';
242
      break;
243

    
244
    case 'YEARLY':
245
      $description['!interval'] = format_plural($rrule['INTERVAL'], 'every year', 'every @count years') . ' ';
246
      break;
247

    
248
    default:
249
      $description['!interval'] = format_plural($rrule['INTERVAL'], 'every day', 'every @count days') . ' ';
250
      break;
251
  }
252

    
253
  if (!empty($rrule['BYDAY'])) {
254
    $days = date_repeat_dow_day_options();
255
    $counts = date_repeat_dow_count_options();
256
    $results = array();
257
    foreach ($rrule['BYDAY'] as $byday) {
258
      // Get the numeric part of the BYDAY option, i.e. +3 from +3MO.
259
      $day = substr($byday, -2);
260
      $count = str_replace($day, '', $byday);
261
      if (!empty($count)) {
262
        // See if there is a 'pretty' option for this count, i.e. +1 => First.
263
        $order = array_key_exists($count, $counts) ? strtolower($counts[$count]) : $count;
264
        $results[] = trim(t('!repeats_every_interval on the !date_order !day_of_week',
265
        array(
266
          '!repeats_every_interval ' => '',
267
          '!date_order' => $order,
268
          '!day_of_week' => $days[$day]
269
        )));
270
      }
271
      else {
272
        $results[] = trim(t('!repeats_every_interval every !day_of_week',
273
        array('!repeats_every_interval ' => '', '!day_of_week' => $days[$day])));
274
      }
275
    }
276
    $description['!byday'] = implode(' ' . t('and') . ' ', $results);
277
  }
278
  if (!empty($rrule['BYMONTH'])) {
279
    if (count($rrule['BYMONTH']) < 12) {
280
      $results = array();
281
      $months = date_month_names();
282
      foreach ($rrule['BYMONTH'] as $month) {
283
        $results[] = $months[$month];
284
      }
285
      if (!empty($rrule['BYMONTHDAY'])) {
286
        $description['!bymonth'] = trim(t('!repeats_every_interval on the !month_days of !month_names',
287
        array(
288
          '!repeats_every_interval ' => '',
289
          '!month_days' => implode(', ', $rrule['BYMONTHDAY']),
290
          '!month_names' => implode(', ', $results)
291
        )));
292
      }
293
      else {
294
        $description['!bymonth'] = trim(t('!repeats_every_interval on !month_names',
295
        array(
296
          '!repeats_every_interval ' => '',
297
          '!month_names' => implode(', ', $results)
298
        )));
299
      }
300
    }
301
  }
302
  if ($rrule['INTERVAL'] < 1) {
303
    $rrule['INTERVAL'] = 1;
304
  }
305
  if (!empty($rrule['COUNT'])) {
306
    $description['!count'] = trim(t('!repeats_every_interval !count times',
307
    array('!repeats_every_interval ' => '', '!count' => $rrule['COUNT'])));
308
  }
309
  if (!empty($rrule['UNTIL'])) {
310
    $until = date_ical_date($rrule['UNTIL'], 'UTC');
311
    date_timezone_set($until, date_default_timezone_object());
312
    $description['!until'] = trim(t('!repeats_every_interval until !until_date',
313
    array(
314
      '!repeats_every_interval ' => '',
315
      '!until_date' => date_format_date($until, 'custom', $format)
316
    )));
317
  }
318
  if ($exceptions) {
319
    $values = array();
320
    foreach ($exceptions as $exception) {
321
      $except = date_ical_date($exception, 'UTC');
322
      date_timezone_set($except, date_default_timezone_object());
323
      $values[] = date_format_date($except, 'custom', $format);
324
    }
325
    $description['!except'] = trim(t('!repeats_every_interval except !except_dates',
326
    array(
327
      '!repeats_every_interval ' => '',
328
      '!except_dates' => implode(', ', $values)
329
    )));
330
  }
331
  if (!empty($rrule['WKST'])) {
332
    $day_names = date_repeat_dow_day_options();
333
    $description['!week_starts_on'] = trim(t('!repeats_every_interval where the week start on !day_of_week',
334
    array('!repeats_every_interval ' => '', '!day_of_week' => $day_names[trim($rrule['WKST'])])));
335
  }
336
  if ($additions) {
337
    $values = array();
338
    foreach ($additions as $addition) {
339
      $add = date_ical_date($addition, 'UTC');
340
      date_timezone_set($add, date_default_timezone_object());
341
      $values[] = date_format_date($add, 'custom', $format);
342
    }
343
    $description['!additional'] = trim(t('Also includes !additional_dates.',
344
    array('!additional_dates' => implode(', ', $values))));
345
  }
346
  $output = t('Repeats !interval !bymonth !byday !count !until !except. !additional', $description);
347
  // Removes double whitespaces from Repeat tile.
348
  $output = preg_replace('/\s+/', ' ', $output);
349
  // Removes whitespace before full stop ".", at the end of the title.
350
  $output = str_replace(' .', '.', $output);
351
  return $output;
352
}
353

    
354
/**
355
 * Parse an iCal rule into a parsed RRULE array and an EXDATE array.
356
 */
357
function date_repeat_split_rrule($rrule) {
358
  $parts = explode("\n", str_replace("\r\n", "\n", $rrule));
359
  $rrule = array();
360
  $exceptions = array();
361
  $additions = array();
362
  $additions = array();
363
  foreach ($parts as $part) {
364
    if (strstr($part, 'RRULE')) {
365
      $cleanded_part = str_replace('RRULE:', '', $part);
366
      $rrule = (array) date_ical_parse_rrule('RRULE:', $cleanded_part);
367
    }
368
    elseif (strstr($part, 'EXDATE')) {
369
      $exdate = str_replace('EXDATE:', '', $part);
370
      $exceptions = (array) date_ical_parse_exceptions('EXDATE:', $exdate);
371
      unset($exceptions['DATA']);
372
    }
373
    elseif (strstr($part, 'RDATE')) {
374
      $rdate = str_replace('RDATE:', '', $part);
375
      $additions = (array) date_ical_parse_exceptions('RDATE:', $rdate);
376
      unset($additions['DATA']);
377
    }
378
  }
379
  return array($rrule, $exceptions, $additions);
380
}
381

    
382
/**
383
 * Analyze a RRULE and return dates that match it.
384
 */
385
function date_repeat_calc($rrule, $start, $end, $exceptions = array(), $timezone = NULL, $additions = array()) {
386
  module_load_include('inc', 'date_repeat', 'date_repeat_calc');
387
  return _date_repeat_calc($rrule, $start, $end, $exceptions, $timezone, $additions);
388
}
389

    
390
/**
391
 * Generate the repeat rule setting form.
392
 */
393
function date_repeat_rrule_process($element, &$form_state, $form) {
394
  module_load_include('inc', 'date_repeat', 'date_repeat_form');
395
  return _date_repeat_rrule_process($element, $form_state, $form);
396
}
397

    
398
/**
399
 * Process function for 'date_repeat_form_element_radios'.
400
 */
401
function date_repeat_form_element_radios_process($element) {
402
  $childrenkeys = element_children($element);
403

    
404
  if (count($element['#options']) &&
405
      count($element['#options']) == count($childrenkeys)) {
406
    $weight = 0;
407
    $children = array();
408
    $classes = isset($element['#div_classes']) ?
409
      $element['#div_classes'] : array();
410
    foreach ($childrenkeys as $childkey) {
411
      $children[$childkey] = $element[$childkey];
412
      unset($element[$childkey]);
413
    }
414
    foreach ($element['#options'] as $key => $choice) {
415
      $currentchildkey = array_shift($childrenkeys);
416
      $weight += 0.001;
417
      $class = array_shift($classes);
418
      $element += array($key => array());
419
      $parents_for_id = array_merge($element['#parents'], array($key));
420
      $element[$key] += array(
421
        '#prefix' => '<div' . ($class ? " class=\"{$class}\"" : '') . '>',
422
        '#type' => 'radio',
423
        '#title' => $choice,
424
        '#title_display' => 'invisible',
425
        '#return_value' => $key,
426
        '#default_value' => isset($element['#default_value']) ?
427
        $element['#default_value'] : NULL,
428
        '#attributes' => $element['#attributes'],
429
        '#parents' => $element['#parents'],
430
        '#id' => drupal_html_id('edit-' . implode('-', $parents_for_id)),
431
        '#ajax' => isset($element['#ajax']) ? $element['ajax'] : NULL,
432
        '#weight' => $weight,
433
        '#theme_wrappers' => array(),
434
        '#suffix' => ' ',
435
      );
436

    
437
      $child = $children[$currentchildkey];
438

    
439
      $weight += 0.001;
440

    
441
      $child['#weight'] = $weight;
442
      $child['#title_display'] = 'invisible';
443
      $child['#suffix'] = (!empty($child['#suffix']) ? $child['#suffix'] : '') .
444
        '</div>';
445
      $child['#parents'] = $element['#parents'];
446
      array_pop($child['#parents']);
447
      array_push($child['#parents'], $currentchildkey);
448

    
449
      $element_prototype = element_info($child['#type']);
450
      $old_wrappers = array();
451
      if (isset($child['#theme_wrappers'])) {
452
        $old_wrappers += $child['#theme_wrappers'];
453
      }
454
      if (isset($element_prototype['#theme_wrappers'])) {
455
        $old_wrappers += $element_prototype['#theme_wrappers'];
456
      }
457

    
458
      $child['#theme_wrappers'] = array();
459

    
460
      foreach ($old_wrappers as $wrapper) {
461
        if ($wrapper != 'form_element') {
462
          $child['#theme_wrappers'][] = $wrapper;
463
        }
464
      }
465

    
466
      $element[$currentchildkey] = $child;
467
    }
468
  }
469

    
470
  return $element;
471
}