Projet

Général

Profil

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

root / drupal7 / sites / all / modules / webform / components / date.inc @ a6e869e4

1
<?php
2

    
3
/**
4
 * @file
5
 * Webform module date component.
6
 */
7

    
8
/**
9
 * Implements _webform_defaults_component().
10
 */
11
function _webform_defaults_date() {
12
  return array(
13
    'name' => '',
14
    'form_key' => NULL,
15
    'pid' => 0,
16
    'weight' => 0,
17
    'value' => '',
18
    'required' => 0,
19
    'extra' => array(
20
      'timezone' => 'user',
21
      'exclude' => array(),
22
      'start_date' => '-2 years',
23
      'end_date' => '+2 years',
24
      'year_textfield' => 0,
25
      'datepicker' => 1,
26
      'title_display' => 0,
27
      'description' => '',
28
      'private' => FALSE,
29
      'analysis' => FALSE,
30
    ),
31
  );
32
}
33

    
34
/**
35
 * Implements _webform_theme_component().
36
 */
37
function _webform_theme_date() {
38
  return array(
39
    'webform_date' => array(
40
      'render element' => 'element',
41
      'file' => 'components/date.inc',
42
    ),
43
    'webform_display_date' => array(
44
      'render element' => 'element',
45
      'file' => 'components/date.inc',
46
    ),
47
    'webform_calendar' => array(
48
      'variables' => array('component' => NULL, 'calendar_classes' => NULL),
49
      'template' => 'templates/webform-calendar',
50
    ),
51
  );
52
}
53

    
54
/**
55
 * Implements _webform_edit_component().
56
 */
57
function _webform_edit_date($component) {
58
  $form = array();
59
  $form['value'] = array(
60
    '#type' => 'textfield',
61
    '#title' => t('Default value'),
62
    '#default_value' => $component['value'],
63
    '#description' => t('The default value of the field.') . '<br />' . t('Accepts any date in any <a href="http://www.gnu.org/software/tar/manual/html_chapter/Date-input-formats.html">GNU Date Input Format</a>. Strings such as today, +2 months, and Dec 9 2004 are all valid.'),
64
    '#size' => 60,
65
    '#maxlength' => 127,
66
    '#weight' => 0,
67
  );
68
  $form['extra']['timezone'] = array(
69
    '#type' => 'radios',
70
    '#title' => t('Default value timezone'),
71
    '#default_value' => empty($component['extra']['timezone']) ? 'user' : $component['extra']['timezone'],
72
    '#description' => t('If using relative dates for a default value (e.g. "today") base the current day on this timezone.'),
73
    '#options' => array('user' => t('User timezone'), 'site' => t('Website timezone')),
74
    '#weight' => 2,
75
    '#access' => variable_get('configurable_timezones', 1),
76
  );
77

    
78
  $form['extra']['exclude'] = array(
79
    '#type' => 'checkboxes',
80
    '#title' => t('Hide'),
81
    '#default_value' => $component['extra']['exclude'],
82
    '#options' => array(
83
      'day' => t('Day'),
84
      'month' => t('Month'),
85
      'year' => t('Year'),
86
    ),
87
    '#description' => t('A hidden day or month will be set to 1. A hidden year will be set to the year of the default value.'),
88
    '#weight' => 3,
89
  );
90

    
91
  $form['display']['datepicker'] = array(
92
    '#type' => 'checkbox',
93
    '#title' => t('Enable popup calendar'),
94
    '#default_value' => $component['extra']['datepicker'],
95
    '#description' => t('Enable a JavaScript date picker next to the date field.'),
96
    '#weight' => 2,
97
    '#parents' => array('extra', 'datepicker'),
98
  );
99

    
100
  $form['display']['year_textfield'] = array(
101
    '#type' => 'checkbox',
102
    '#title' => t('Use a textfield for year'),
103
    '#default_value' => $component['extra']['year_textfield'],
104
    '#description' => t('If checked, the generated date field will use a textfield for the year. Otherwise it will use a select list.'),
105
    '#weight' => 5,
106
    '#parents' => array('extra', 'year_textfield'),
107
  );
108

    
109
  $form['validation']['start_date'] = array(
110
    '#type' => 'textfield',
111
    '#title' => t('Start date'),
112
    '#default_value' => $component['extra']['start_date'],
113
    '#description' => t('The earliest date that may be entered into the field.') . ' ' . t('Accepts any date in any <a href="http://www.gnu.org/software/tar/manual/html_chapter/Date-input-formats.html">GNU Date Input Format</a>.'),
114
    '#size' => 30,
115
    '#weight' => 3,
116
    '#parents' => array('extra', 'start_date'),
117
  );
118
  $form['validation']['end_date'] = array(
119
    '#type' => 'textfield',
120
    '#title' => t('End date'),
121
    '#default_value' => $component['extra']['end_date'],
122
    '#description' => t('The latest date that may be entered into the field.') . ' ' . t('Accepts any date in any <a href="http://www.gnu.org/software/tar/manual/html_chapter/Date-input-formats.html">GNU Date Input Format</a>.'),
123
    '#size' => 30,
124
    '#weight' => 4,
125
    '#parents' => array('extra', 'end_date'),
126
  );
127

    
128
  $form['#validate'] = array('_webform_edit_date_validate');
129
  return $form;
130
}
131

    
132
/**
133
 * Implements hook_form_id_validate.
134
 *
135
 * Warns user about hiding all the date fields and not using the date picker.
136
 */
137
function _webform_edit_date_validate($form, &$form_state) {
138
  // Reduce checkbox values to simple non-associative array of values.
139
  form_set_value($form['extra']['exclude'], array_filter(array_values($form_state['values']['extra']['exclude'])), $form_state);
140

    
141
  // Note that Drupal 7 doesn't support setting errors no checkboxes due to
142
  // browser issues. @see https://www.drupal.org/node/222380
143
  if (count($form_state['values']['extra']['exclude']) == 3) {
144
    form_set_error('extra][exclude', 'The day, month and year can\'t all be hidden.');
145
  }
146
  if ($form_state['values']['extra']['exclude'] == array('month')) {
147
    form_set_error('extra][exclude', 'You cannot hide just the month.');
148
  }
149

    
150
  // Validate that the start and end dates are valid. Don't validate the default
151
  // date because with token substitution, it might not be valid at component
152
  // definition time. Also note that validation was introduced in 7.x-4.8 and
153
  // previously-defined webform may have invalid start and end dates.
154
  foreach (array('start_date', 'end_date') as $field) {
155
    if (trim($form_state['values']['extra'][$field]) && !($date[$field] = webform_strtodate('c', $form_state['values']['extra'][$field]))) {
156
      form_set_error("extra][$field", t('The @field could not be interpreted in <a href="http://www.gnu.org/software/tar/manual/html_chapter/Date-input-formats.html">GNU Date Input Format</a>.',
157
                                                 array('@field' => $form['validation'][$field]['#title'])));
158
    }
159
  }
160
  if (!empty($date['start_date']) && !empty($date['end_date']) && $date['end_date'] < $date['start_date']) {
161
    form_set_error('extra][end_date', t('The End date must be on or after the Start date.'));
162
  }
163
}
164

    
165
/**
166
 * Implements _webform_render_component().
167
 */
168
function _webform_render_date($component, $value = NULL, $filter = TRUE, $submission = NULL) {
169
  $node = isset($component['nid']) ? node_load($component['nid']) : NULL;
170

    
171
  $element = array(
172
    '#type' => 'date',
173
    '#title' => $filter ? webform_filter_xss($component['name']) : $component['name'],
174
    '#title_display' => $component['extra']['title_display'] ? $component['extra']['title_display'] : 'before',
175
    '#weight' => $component['weight'],
176
    '#description' => $filter ? webform_filter_descriptions($component['extra']['description'], $node) : $component['extra']['description'],
177
    '#required' => $component['required'],
178
    '#start_date' => trim($component['extra']['start_date']),
179
    '#end_date' => trim($component['extra']['end_date']),
180
    '#reference_timestamp' => $submission && $submission->completed ? $submission->completed : NULL,
181
    '#year_textfield' => $component['extra']['year_textfield'],
182
    '#default_value' => $filter ? webform_replace_tokens($component['value'], $node) : $component['value'],
183
    '#timezone' => $component['extra']['timezone'],
184
    '#exclude' => $component['extra']['exclude'],
185
    '#process' => array('webform_expand_date'),
186
    '#theme' => 'webform_date',
187
    '#theme_wrappers' => array('webform_element'),
188
    '#element_validate' => array('webform_validate_date'),
189
    '#translatable' => array('title', 'description'),
190
  );
191

    
192
  if ($component['extra']['datepicker']) {
193
    $element['#datepicker'] = TRUE;
194
    $element['#attached'] = array(
195
      'library' => array(
196
        array('system', 'ui.datepicker'),
197
      ),
198
    );
199
  }
200

    
201
  // Set the value from Webform.
202
  if (isset($value[0]) && $value[0] !== '') {
203
    $value = webform_date_array($value[0], 'date');
204
    $element['#default_value'] = $value;
205
  }
206

    
207
  return $element;
208
}
209

    
210
/**
211
 * Form API #process function for Webform date fields.
212
 */
213
function webform_expand_date($element) {
214
  $timezone = $element['#timezone'] != 'user' ? NULL : 'user';
215
  
216
  // Accept a string or array value for #default_value.
217
  if (!empty($element['#default_value']) && is_string($element['#default_value'])) {
218
    $timestring = webform_strtodate('c', $element['#default_value'], $timezone);
219
    $element['#default_value'] = webform_date_array($timestring, 'date');
220
  }
221
  // Prevent an error in PHP 5.4 caused by core's treatment of the #value.
222
  if (isset($element['#value'])) {
223
    unset($element['#value']);
224
  }
225

    
226
  // Set defaults according to existing #default_value (set by Form API)
227
  if (isset($element['#default_value']['month']) || isset($element['#default_value']['day']) || isset($element['#default_value']['year'])) {
228
    $default_values = array(
229
      'month' => $element['#default_value']['month'],
230
      'day' => $element['#default_value']['day'],
231
      'year' => $element['#default_value']['year'],
232
    );
233
  }
234
  else {
235
    $default_values = array(
236
      'day' => NULL,
237
      'month' => NULL,
238
      'year' => NULL,
239
    );
240
  }
241

    
242
  // Let Drupal do it's normal expansion.
243
  $element = form_process_date($element);
244

    
245
  // Convert relative dates to absolute and calculate the year, month and day.
246
  $timezone = $element['#timezone'] != 'user' ? NULL : 'user';
247
  foreach (array('start', 'end') as $start_end) {
248
    $element_field = &$element["#{$start_end}_date"];
249
    $element_field = $element_field ? webform_strtodate('Y-m-d', $element_field, $timezone, $element['#reference_timestamp']) : '';
250
    if ($element_field) {
251
      $parts = explode('-', $element_field);
252
    }
253
    else {
254
      $parts = $start_end == 'start' ? array(webform_strtodate('Y', '-2 years'), 1, 1) : array(webform_strtodate('Y', '+2 years'), 12, 31);
255
      $element_field = '';
256
    }
257
    unset($element_field); // Drop PHP reference.
258
    $parts[3] = $parts[0] . '-' . $parts[1] . '-' . $parts[2];
259
    $range[$start_end] = array_combine(array('year', 'month', 'day', 'date'), $parts);
260
  }
261

    
262
  // The start date is not guaranteeed to be early than the end date for
263
  // historical reasons.
264
  if ($range['start']['date'] > $range['end']['date']) {
265
    $temp = $range['start'];
266
    $range['start'] = $range['end'];
267
    $range['end'] = $temp;
268
  }
269

    
270
  // Restrict the months and days when not all options are valid choices.
271
  if ($element['#start_date'] && $element['#end_date']) {
272
    $delta_months = ($range['end']['year'] * 12 + $range['end']['month']) - ($range['start']['year'] * 12 + $range['start']['month']);
273
    if ($delta_months < 11) {
274
      // There are 10 or fewer months between the start and end date. If there
275
      // were 11, then every month would be possible, and the menu select
276
      // should not be pruned.
277
      $month_options = &$element['month']['#options'];
278
      if ($range['start']['month'] <= $range['end']['month']) {
279
        $month_options = array_intersect_key($month_options, array_flip(range($range['start']['month'], $range['end']['month'])));
280
      }
281
      else {
282
        $month_options = array_intersect_key($month_options, array_flip(range($range['start']['month'], 12))) +
283
                         array_intersect_key($month_options, array_flip(range(1, $range['end']['month'])));
284
      }
285
      unset($month_options); // Drop PHP reference.
286
      if ($delta_months <= 1) {
287
        // The start and end date are either on the same month or consequtive
288
        // months. See if the days should be pruned.
289
        $day_options = &$element['day']['#options'];
290
        if ($range['start']['month'] == $range['end']['month']) {
291
          // Range is within the same month. The days are a simple range from
292
          // start day to end day.
293
          $day_options = array_intersect_key($day_options, array_flip(range($range['start']['day'], $range['end']['day'])));
294
        }
295
        elseif ($range['start']['day'] > $range['end']['day'] + 1) {
296
          // Range spans two months and at least one day would be omitted.
297
          $days_in_month = date('t', mktime(0, 0, 0, $range['start']['month'], 1, $range['start']['year']));
298
          $day_options = array_intersect_key($day_options, array_flip(range($range['start']['day'], $days_in_month))) +
299
                         array_intersect_key($day_options, array_flip(range(1, $range['end']['day'])));
300
        }
301
        unset($day_options); // Drop PHP reference.
302
      }
303
    }
304
  }
305

    
306
  // Set default values.
307
  foreach ($default_values as $type => $value) {
308
    switch ($type) {
309
      case 'month':
310
        $none = t('Month');
311
        $hidden_default = 1;
312
        break;
313
      case 'day':
314
        $none = t('Day');
315
        $hidden_default = 1;
316
        break;
317
      case 'year':
318
        $none = t('Year');
319
        $hidden_default = !empty($element['#default_value']['year']) ? $element['#default_value']['year'] : webform_strtodate('Y', 'today', $timezone);
320
        break;
321
    }
322
    unset($element[$type]['#value']);
323
    $element[$type]['#title'] = $none;
324
    $element[$type]['#title_display'] = 'invisible';
325
    $element[$type]['#default_value'] = $default_values[$type];
326
    $element[$type]['#options'] = array('' => $none) + $element[$type]['#options'];
327
    if (in_array($type, $element['#exclude'])) {
328
      $element[$type] += array(
329
        '#prefix' => '<div class="webform-date-field-wrapper element-invisible">',
330
        '#suffix' => '</div>',
331
      );
332
      $element[$type]['#default_value'] = $hidden_default;
333
    }
334
  }
335

    
336
  // Tweak the year field.
337
  if ($element['#year_textfield']) {
338
    $element['year']['#type'] = 'textfield';
339
    $element['year']['#size'] = 5;
340
    $element['year']['#maxlength'] = 4;
341
    unset($element['year']['#options']);
342
  }
343
  elseif ($element['#start_date'] || $element['#end_date']) {
344
    $element['year']['#options'] = array('' => t('Year')) + drupal_map_assoc(range($range['start']['year'], $range['end']['year']));
345
  }
346

    
347
  return $element;
348
}
349

    
350
/**
351
 * Theme a webform date element.
352
 */
353
function theme_webform_date($variables) {
354
  $element = $variables['element'];
355

    
356
  $element['year']['#attributes']['class'][] = 'year';
357
  $element['month']['#attributes']['class'][] = 'month';
358
  $element['day']['#attributes']['class'][] = 'day';
359

    
360
  // Add error classes to all items within the element.
361
  if (form_get_error($element)) {
362
    $element['year']['#attributes']['class'][] = 'error';
363
    $element['month']['#attributes']['class'][] = 'error';
364
    $element['day']['#attributes']['class'][] = 'error';
365
  }
366

    
367
  // Add HTML5 required attribute, if needed.
368
  if ($element['#required']) {
369
    $element['year']['#attributes']['required'] = 'required';
370
    $element['month']['#attributes']['required'] = 'required';
371
    $element['day']['#attributes']['required'] = 'required';
372
  }
373

    
374
  $class = array('webform-container-inline');
375

    
376
  // Add the JavaScript calendar if available (provided by Date module package).
377
  if (!empty($element['#datepicker'])) {
378
    $class[] = 'webform-datepicker';
379
    $calendar_class = array('webform-calendar');
380
    if ($element['#start_date']) {
381
      $calendar_class[] = 'webform-calendar-start-' . $element['#start_date'];
382
    }
383
    if ($element['#end_date']) {
384
      $calendar_class[] = 'webform-calendar-end-' . $element['#end_date'];
385
    }
386
    $calendar_class[] ='webform-calendar-day-' . variable_get('date_first_day', 0);
387

    
388
    $calendar = theme('webform_calendar', array('component' => $element['#webform_component'], 'calendar_classes' => $calendar_class));
389
  }
390

    
391
  $output = '';
392
  $output .= '<div class="' . implode(' ', $class) . '">';
393
  $output .= drupal_render_children($element);
394
  $output .= isset($calendar) ? $calendar : '';
395
  $output .= '</div>';
396

    
397
  return $output;
398
}
399

    
400
/**
401
 * Element validation for Webform date fields.
402
 */
403
function webform_validate_date($element, $form_state) {
404
  if ($element['month']['#value'] !== '' || $element['day']['#value'] !== '' || $element['year']['#value'] !== '') {
405
    // Check that each part of the date has been filled in.
406
    foreach (array('day', 'month', 'year') as $field_type) {
407
      if (empty($element[$field_type]['#value'])) {
408
        form_error($element[$field_type], t('!part in !name is missing.', array('!name' => $element['#title'], '!part' => $element[$field_type]['#title'])));
409
        $missing_fields = TRUE;
410
      }
411
    }
412
    if (isset($missing_fields)) {
413
      return;
414
    }
415

    
416
    // Check for a valid date.
417
    if (!checkdate($element['month']['#value'], $element['day']['#value'], $element['year']['#value'])) {
418
      form_error($element, t('Entered !name is not a valid date.', array('!name' => $element['#title'])));
419
      return;
420
    }
421

    
422
    // Create a timestamp of the entered value for comparison.
423
    $timestamp = strtotime($element['year']['#value'] . '-' . $element['month']['#value'] . '-' . $element['day']['#value']);
424
    $format = webform_date_format('short');
425

    
426
    // Flip start and end if needed. Prior to 7.x-4.8, it was possible to save
427
    // a date component with the end date earlier than the start date.
428
    $date1 = strtotime($element['#start_date']);
429
    $date2 = strtotime($element['#end_date']);
430
    if ($date1 !== FALSE && $date2 !== FALSE) {
431
      $start_date = $date1 < $date2 ? $date1 : $date2;
432
      $end_date = $date1 > $date2 ? $date1 : $date2;
433
    }
434
    else {
435
      $start_date = $date1;
436
      $end_date = $date2;
437
    }
438

    
439
    // Check that the date is after the start date.
440
    if ($start_date !== FALSE && $timestamp < $start_date) {
441
      form_error($element, t('The entered date must be @start_date or later.', array('@start_date' => date($format, $start_date))));
442
    }
443

    
444
    // Check that the date is before the end date.
445
    if ($end_date !== FALSE && $timestamp > $end_date) {
446
      form_error($element, t('The entered date must be @end_date or earlier.', array('@end_date' => date($format, $end_date))));
447
    }
448
  }
449
  elseif ($element['#required']) {
450
    form_error($element, t('!name field is required.', array('!name' => $element['#title'])));
451
  }
452
}
453

    
454
/**
455
 * Implements _webform_submit_component().
456
 */
457
function _webform_submit_date($component, $value) {
458
  // Convert the date to an ISO 8601 format.
459
  return ($value['year'] && $value['month'] && $value['day']) ? webform_date_string($value, 'date') : '';
460
}
461

    
462
/**
463
 * Implements _webform_display_component().
464
 */
465
function _webform_display_date($component, $value, $format = 'html', $submission = array()) {
466
  $value = webform_date_array(isset($value[0]) ? $value[0] : '', 'date');
467

    
468
  return array(
469
    '#title' => $component['name'],
470
    '#title_display' => $component['extra']['title_display'] ? $component['extra']['title_display'] : 'before',
471
    '#weight' => $component['weight'],
472
    '#theme' => 'webform_display_date',
473
    '#theme_wrappers' => $format == 'html' ? array('webform_element') : array('webform_element_text'),
474
    '#format' => $format,
475
    '#exclude' => $component['extra']['exclude'],
476

    
477
    '#value' => $value,
478
    '#translatable' => array('title'),
479
  );
480
}
481

    
482
/**
483
 * Format the text output for this component.
484
 */
485
function theme_webform_display_date($variables) {
486
  $element = $variables['element'];
487
  $output = ' ';
488
  if ($element['#value']['year'] && $element['#value']['month'] && $element['#value']['day']) {
489
    $timestamp = webform_strtotime($element['#value']['month'] . '/' . $element['#value']['day'] . '/' . $element['#value']['year']);
490
    $format = webform_date_format(NULL, $element['#exclude']);
491
    $output = format_date($timestamp, 'custom', $format, 'UTC');
492
  }
493

    
494
  return $output;
495
}
496

    
497
/**
498
 * Implements _webform_analysis_component().
499
 */
500
function _webform_analysis_date($component, $sids = array(), $single = FALSE, $join = NULL) {
501
  $query = db_select('webform_submitted_data', 'wsd', array('fetch' => PDO::FETCH_ASSOC))
502
    ->fields('wsd', array('no', 'data'))
503
    ->condition('wsd.nid', $component['nid'])
504
    ->condition('wsd.cid', $component['cid'])
505
    ->orderBy('wsd.sid');
506

    
507
  if (count($sids)) {
508
    $query->condition('wsd.sid', $sids, 'IN');
509
  }
510

    
511
  if ($join) {
512
    $query->innerJoin($join, 'ws2_', 'wsd.sid = ws2_.sid');
513
  }
514

    
515
  $result = $query->execute();
516

    
517
  $dates = array();
518
  $submissions = 0;
519
  foreach ($result as $row) {
520
    $submissions++;
521
    if ($row['data']) {
522
      $dates[] = webform_date_array($row['data']);
523
    }
524
  }
525

    
526
  // Display stats.
527
  $nonblanks = count($dates);
528
  $rows[0] = array(t('Left Blank'), ($submissions - $nonblanks));
529
  $rows[1] = array(t('User entered value'), $nonblanks);
530

    
531
  return array(
532
    'table_rows' => $rows,
533
  );
534
}
535

    
536
/**
537
 * Implements _webform_table_component().
538
 */
539
function _webform_table_date($component, $value) {
540
  if ($value[0]) {
541
    $timestamp = webform_strtotime($value[0]);
542
    $format = webform_date_format('short', $component['extra']['exclude']);
543
    return format_date($timestamp, 'custom', $format, 'UTC');
544
  }
545
  else {
546
    return '';
547
  }
548
}
549

    
550
/**
551
 * Implements _webform_csv_headers_component().
552
 */
553
function _webform_csv_headers_date($component, $export_options) {
554
  $header = array();
555
  $header[0] = '';
556
  $header[1] = '';
557
  $header[2] = $export_options['header_keys'] ? $component['form_key'] : $component['name'];
558
  return $header;
559
}
560

    
561
/**
562
 * Implements _webform_csv_data_component().
563
 */
564
function _webform_csv_data_date($component, $export_options, $value) {
565
  if ($value[0]) {
566
    $timestamp = webform_strtotime($value[0]);
567
    if (!empty($export_options['iso8601_date'])) {
568
      $format = 'Y-m-d'; // ISO 8601 date: 2004-02-12
569
    }
570
    else {
571
      $format = webform_date_format('short');
572
    }
573
    return format_date($timestamp, 'custom', $format, 'UTC');
574
  }
575
  else {
576
    return '';
577
  }
578
}