Projet

Général

Profil

Paste
Télécharger (17,8 ko) Statistiques
| Branche: | Révision:

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

1
<?php
2

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

    
8
// Time depends on functions provided by date.
9
webform_component_include('date');
10

    
11
/**
12
 * Implements _webform_defaults_component().
13
 */
14
function _webform_defaults_time() {
15
  return array(
16
    'name' => '',
17
    'form_key' => NULL,
18
    'pid' => 0,
19
    'weight' => 0,
20
    'value' => '',
21
    'required' => 0,
22
    'extra' => array(
23
      'timezone' => 'user',
24
      'start_time' => '',
25
      'end_time' => '',
26
      'hourformat' => '12-hour',
27
      'minuteincrements' => 1,
28
      'title_display' => 0,
29
      'description' => '',
30
      'private' => FALSE,
31
      'analysis' => FALSE,
32
    ),
33
  );
34
}
35

    
36
/**
37
 * Implements _webform_theme_component().
38
 */
39
function _webform_theme_time() {
40
  return array(
41
    'webform_time' => array(
42
      'render element' => 'element',
43
      'file' => 'components/time.inc',
44
    ),
45
    'webform_display_time' => array(
46
      'render element' => 'element',
47
      'file' => 'components/time.inc',
48
    ),
49
  );
50
}
51

    
52
/**
53
 * Implements _webform_edit_component().
54
 */
55
function _webform_edit_time($component) {
56
  $form = array();
57
  $form['value'] = array(
58
    '#type' => 'textfield',
59
    '#title' => t('Default value'),
60
    '#default_value' => $component['value'],
61
    '#description' => t('The default value of the field.') . '<br />' . t('Accepts a time 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 now, +2 hours, and 10:30pm are all valid.'),
62
    '#size' => 60,
63
    '#maxlength' => 127,
64
    '#weight' => 0,
65
  );
66
  $form['validation']['start_time'] = array(
67
    '#type' => 'textfield',
68
    '#title' => t('Start time'),
69
    '#default_value' => $component['extra']['start_time'],
70
    '#description' => t('The earliest time that may be entered into the field.'),
71
    '#size' => 10,
72
    '#weight' => 3,
73
    '#parents' => array('extra', 'start_time'),
74
  );
75
  $form['validation']['end_time'] = array(
76
    '#type' => 'textfield',
77
    '#title' => t('End time'),
78
    '#default_value' => $component['extra']['end_time'],
79
    '#description' => t('The latest time that may be entered into the field.'),
80
    '#size' => 10,
81
    '#weight' => 4,
82
    '#parents' => array('extra', 'end_time'),
83
  );
84
  $form['extra']['timezone'] = array(
85
    '#type' => 'radios',
86
    '#title' => t('Default value timezone'),
87
    '#default_value' => $component['extra']['timezone'],
88
    '#description' => t('If using relative dates for a default value (e.g. "now") base the current time on this timezone.'),
89
    '#options' => array('user' => t('User timezone'), 'site' => t('Website timezone')),
90
    '#weight' => 2,
91
    '#access' => variable_get('configurable_timezones', 1),
92
  );
93
  $form['display']['hourformat'] = array(
94
    '#type' => 'radios',
95
    '#title' => t('Time format'),
96
    '#default_value' => $component['extra']['hourformat'],
97
    '#options' => array('12-hour' => t('12-hour (am/pm)'), '24-hour' => t('24-hour')),
98
    '#weight' => 2,
99
    '#parents' => array('extra', 'hourformat'),
100
  );
101
  $form['display']['minuteincrements'] = array(
102
    '#type' => 'select',
103
    '#title' => t('Minute increments'),
104
    '#default_value' => $component['extra']['minuteincrements'],
105
    '#options' => array(
106
      1 => t('1 minute'),
107
      5 => t('5 minute'),
108
      10 => t('10 minute'),
109
      15 => t('15 minute'),
110
      30 => t('30 minute'),
111
    ),
112
    '#weight' => 3,
113
    '#parents' => array('extra', 'minuteincrements'),
114
  );
115
  $form['#validate'] = array('_webform_edit_time_validate');
116
  return $form;
117
}
118

    
119
/**
120
 * Implements hook_form_id_validate.
121
 *
122
 * Validate start and end times.
123
 */
124
function _webform_edit_time_validate($form, &$form_state) {
125
  // Validate that the start and end times are valid. Don't validate the default
126
  // time because with token substitution, it might not be valid at component
127
  // definition time. The end time may be before the start time to faciliate
128
  // time ranges spanning midnight.
129
  foreach (array('start_time', 'end_time') as $field) {
130
    $time[$field] = FALSE;
131
    if (trim($form_state['values']['extra'][$field]) && ($time[$field] = strtotime('1-1-1970 UTC ' . $form_state['values']['extra'][$field])) === FALSE) {
132
      form_set_error("extra][$field", t('The @field isn\'t a valid time.', array('@field' => $form['validation'][$field]['#title'])));
133
    }
134
  }
135
}
136

    
137
/**
138
 * Implements _webform_render_component().
139
 */
140
function _webform_render_time($component, $value = NULL, $filter = TRUE, $submission = NULL) {
141
  $node = isset($component['nid']) ? node_load($component['nid']) : NULL;
142

    
143
  $element = array(
144
    '#type' => 'webform_time',
145
    '#title' => $filter ? webform_filter_xss($component['name']) : $component['name'],
146
    '#title_display' => $component['extra']['title_display'] ? $component['extra']['title_display'] : 'before',
147
    '#required' => $component['required'],
148
    '#weight' => $component['weight'],
149
    '#description' => $filter ? webform_filter_descriptions($component['extra']['description'], $node) : $component['extra']['description'],
150
    '#element_validate' => array('webform_validate_time'),
151
    '#start_time' => trim($component['extra']['start_time']),
152
    '#end_time' => trim($component['extra']['end_time']),
153
    '#hourformat' => $component['extra']['hourformat'],
154
    '#minuteincrements' => $component['extra']['minuteincrements'],
155
    '#default_value' => $filter ? webform_replace_tokens($component['value'], $node) : $component['value'],
156
    '#timezone' => $component['extra']['timezone'],
157
    '#process' => array('webform_expand_time'),
158
    '#theme' => 'webform_time',
159
    '#theme_wrappers' => array('webform_element'),
160
    '#translatable' => array('title', 'description'),
161
  );
162

    
163
  // Set the value from Webform if available.
164
  if (!empty($value[0])) {
165
    $element['#default_value'] = $value[0];
166
  }
167

    
168
  return $element;
169
}
170

    
171
/**
172
 * Form API #process function for Webform time fields.
173
 */
174
function webform_expand_time($element) {
175
  // Expand the default value from a string into an array.
176
  if (!empty($element['#default_value'])) {
177
    // Adjust the time based on the user or site timezone.
178
    if (variable_get('configurable_timezones', 1) && $element['#timezone'] == 'user') {
179
      $timezone_name = isset($GLOBALS['user']->timezone) ? $GLOBALS['user']->timezone : 'UTC';
180
    }
181
    else {
182
      $timezone_name = variable_get('date_default_timezone', 'UTC');
183
    }
184

    
185
    $default_values = webform_date_array(webform_strtodate('c', $element['#default_value'], $timezone_name), 'time');
186
  }
187
  else {
188
    $default_values = array(
189
      'hour' => '',
190
      'minute' => '0',
191
      'second' => '',
192
    );
193
  }
194
  $start_hour = $element['#start_time'] ? date('G', strtotime('1-1-1970 ' . $element['#start_time'])) : FALSE;
195
  $end_hour = $element['#end_time'] ? date('G', strtotime('1-1-1970 ' . $element['#end_time'])) : FALSE;
196
  $reduced_range = ($start_hour !== FALSE && $start_hour > 0) || ($end_hour !== FALSE && $end_hour < 23);
197
  $format_12_hour = $element['#hourformat'] == '12-hour';
198

    
199
  // Generate the choices for the hour drop-down select.
200
  $hours = $format_12_hour && !$reduced_range ? array_slice(range(0, 12), 1, 12, TRUE) : range(0, 23);
201
  if ($format_12_hour && $reduced_range) {
202
    $hours = array_map(function($hour) {
203
      return (1 + ($hour + 11) % 12) . ($hour < 12 ? ' am' : ' pm');
204
    }, $hours);
205
  }
206

    
207
  // Prune the hours to the allowed range.
208
  if ($reduced_range) {
209
    // $start_hour of FALSE type-juggles nicely to 0.
210
    $end_hour = $end_hour === FALSE ? 23 : $end_hour;
211
    if ($start_hour <= $end_hour) {
212
      $hours = array_intersect_key($hours, array_flip(range($start_hour, $end_hour)));
213
    }
214
    else {
215
      $hours = array_intersect_key($hours, array_flip(range($start_hour, 23))) +
216
               array_intersect_key($hours, array_flip(range(0, $end_hour)));
217
    }
218
  }
219

    
220
  // Generate the choices for the minute drop-down select.
221
  $minutes = range(0, 59, $element['#minuteincrements']);
222
  $minutes = array_combine($minutes, array_map(function ($minute) {
223
    return substr('00' . $minute, -2);
224
  }, $minutes));
225

    
226
  // Add the labels to the drop-down selects.
227
  $hours = array('' => t('Hour')) + $hours;
228
  $minutes = array('' => t('Minute')) + $minutes;
229

    
230
  // Adjust the default for minutes if needed, rounding down if needed.
231
  // Rounding down eliminate the problem of rounding up going to the next hour.
232
  // Worse, rounding 23:59 up would actually be the next day, which can't be
233
  // represented because time components aren't linked to date components.
234
  if (!isset($minutes[$default_values['minute']])) {
235
    $default_values['minute'] -= $default_values['minute'] % $element['#minuteincrements'];
236
  }
237

    
238
  // Set the overall default value.
239
  if ($default_values['hour'] !== '') {
240
    $element['#default_value'] = webform_date_string($default_values);
241
  }
242

    
243
  // Convert default to 12-hour if needed.
244
  if ($format_12_hour && !$reduced_range) {
245
    $default_values = webform_time_convert($default_values, '12-hour');
246
  }
247

    
248
  $element['hour'] = array(
249
    '#prefix' => '',
250
    '#type' => 'select',
251
    '#title' => t('Hour'),
252
    '#title_display' => 'invisible',
253
    '#default_value' => $default_values['hour'],
254
    '#options' => $hours,
255
  );
256
  $element['minute'] = array(
257
    '#prefix' => ':',
258
    '#type' => 'select',
259
    '#title' => t('Minute'),
260
    '#title_display' => 'invisible',
261
    '#default_value' => $default_values['minute'],
262
    '#options' => $minutes,
263
  );
264
  if ($format_12_hour && !$reduced_range) {
265
    $element['ampm'] = array(
266
      '#type' => 'radios',
267
      '#default_value' => $default_values['ampm'] ? $default_values['ampm'] : 'am',
268
      '#options' => array('am' => t('am'), 'pm' => t('pm')),
269
    );
270
  }
271

    
272
  return $element;
273
}
274

    
275
/**
276
 * Theme a webform time element.
277
 */
278
function theme_webform_time($variables) {
279
  $element = $variables['element'];
280

    
281
  $element['hour']['#attributes']['class'][] = 'hour';
282
  $element['minute']['#attributes']['class'][] = 'minute';
283

    
284
  // Add error classes to all items within the element.
285
  if (form_get_error($element)) {
286
    $element['hour']['#attributes']['class'][] = 'error';
287
    $element['minute']['#attributes']['class'][] = 'error';
288
  }
289

    
290
  // Add HTML5 required attribute, if needed.
291
  if ($element['#required']) {
292
    $element['hour']['#attributes']['required'] = 'required';
293
    $element['minute']['#attributes']['required'] = 'required';
294
    if (!empty($element['ampm'])) {
295
      $element['ampm']['am']['#attributes']['required'] = 'required';
296
      $element['ampm']['pm']['#attributes']['required'] = 'required';
297
    }
298
  }
299

    
300
  $output = '<div class="webform-container-inline">' . drupal_render($element['hour']) . drupal_render($element['minute']) . drupal_render($element['ampm']) . '</div>';
301

    
302
  return $output;
303
}
304

    
305
function webform_validate_time($element, $form_state) {
306
  $form_key = $element['#webform_component']['form_key'];
307

    
308
  // Check if the user filled the required fields.
309
  if ($element['#required']) {
310
    foreach (array('hour', 'minute', 'ampm') as $field_type) {
311
      if (isset($element[$field_type]) && $element[$field_type]['#value'] === '') {
312
        form_error($element, t('!name field is required.', array('!name' => $element['#title'])));
313
        return;
314
      }
315
    }
316
  }
317

    
318
  // Check for a valid time. Allow a minute with no hour as "no time set".
319
  if ($element['hour']['#value'] !== '' ) {
320
    if (!is_numeric($element['hour']['#value']) || !is_numeric($element['minute']['#value']) || (isset($element['ampm']) && $element['ampm']['#value'] === '')) {
321
      form_error($element, t('Entered !name is not a valid time.', array('!name' => $element['#title'])));
322
      return;
323
    }
324

    
325
    // Enforce the start and end times, if any.
326
    $timestamp = strtotime($element['hour']['#value'] . ':' . $element['minute']['#value'] . ' ' .
327
                           (isset($element['ampm']) ?  $element['ampm']['#value'] : ''));
328
    $start_time = strtotime($element['#start_time']);
329
    $end_time = strtotime($element['#end_time']);
330
    $subs = array(
331
      '@start_time' => $element['#start_time'],
332
      '@end_time' => $element['#end_time'],
333
    );
334
    if ($start_time !== FALSE && $end_time !== FALSE && $start_time > $end_time) {
335
      // Validate as "over midnight" date range.
336
      if ($end_time < $timestamp && $timestamp < $start_time) {
337
        form_error($element, t('The entered time must be from @start_time to midnight to @end_time.', $subs));
338
      }
339
    }
340
    else {
341
      // Validate the start and end times are a regular (over noon) time range.
342
      if ($start_time !== FALSE && $timestamp < $start_time) {
343
        form_error($element, t('The entered time must be no earlier than @start_time.', $subs));
344
      }
345
      if ($end_time !== FALSE && $timestamp > $end_time) {
346
        form_error($element, t('The entered time must be no later than @end_time.', $subs));
347
      }
348
    }
349
  }
350
}
351

    
352
/**
353
 * Implements _webform_submit_component().
354
 */
355
function _webform_submit_time($component, $value) {
356
  // Convert to 24-hour time before string conversion.
357
  if ($component['extra']['hourformat'] == '12-hour') {
358
    $value = webform_time_convert($value, '24-hour');
359
  }
360

    
361
  // Convert the value into a ISO 8601 string.
362
  return $value['hour'] !== '' ? webform_date_string($value, 'time') : '';
363
}
364

    
365
/**
366
 * Implements _webform_display_component().
367
 */
368
function _webform_display_time($component, $value, $format = 'html', $submission = array()) {
369
  $value = webform_date_array(isset($value[0]) ? $value[0] : '', 'time');
370
  if ($component['extra']['hourformat'] == '12-hour') {
371
    $value = webform_time_convert($value, '12-hour');
372
  }
373

    
374
  return array(
375
    '#title' => $component['name'],
376
    '#title_display' => $component['extra']['title_display'] ? $component['extra']['title_display'] : 'before',
377
    '#weight' => $component['weight'],
378
    '#theme' => 'webform_display_time',
379
    '#theme_wrappers' => $format == 'html' ? array('webform_element') : array('webform_element_text'),
380
    '#format' => $format,
381
    '#hourformat' => $component['extra']['hourformat'],
382
    '#value' => $value,
383
    '#translatable' => array('title'),
384
  );
385
}
386

    
387
/**
388
 * Format the output of data for this component.
389
 */
390
function theme_webform_display_time($variables) {
391
  $element = $variables['element'];
392
  $output = ' ';
393
  if (isset($element['#value']['hour']) && $element['#value']['hour'] !== '' && isset($element['#value']['minute']) && $element['#value']['minute'] !== '') {
394
    if ($element['#hourformat'] == '24-hour') {
395
      $output = sprintf('%02d', $element['#value']['hour']) . ':' . sprintf('%02d', $element['#value']['minute']);
396
    }
397
    else {
398
      $output = $element['#value']['hour'] . ':' . sprintf('%02d', $element['#value']['minute']) . ' ' . $element['#value']['ampm'];
399
    }
400
  }
401
  return $output;
402
}
403

    
404
/**
405
 * Implements _webform_analysis_component().
406
 */
407
function _webform_analysis_time($component, $sids = array(), $single = FALSE, $join = NULL) {
408
  $query = db_select('webform_submitted_data', 'wsd', array('fetch' => PDO::FETCH_ASSOC))
409
    ->fields('wsd', array('no', 'data'))
410
    ->condition('wsd.nid', $component['nid'])
411
    ->condition('wsd.cid', $component['cid'])
412
    ->orderBy('wsd.sid');
413

    
414
  if (count($sids)) {
415
    $query->condition('wsd.sid', $sids, 'IN');
416
  }
417

    
418
  if ($join) {
419
    $query->innerJoin($join, 'ws2_', 'wsd.sid = ws2_.sid');
420
  }
421

    
422
  $result = $query->execute();
423

    
424
  $times = array();
425
  $submissions = 0;
426
  foreach ($result as $row) {
427
    $submissions++;
428
    if ($row['data']) {
429
      $times[] = webform_date_array($row['data']);
430
    }
431
  }
432

    
433
  // Display stats.
434
  $nonblanks = count($times);
435
  $rows[0] = array(t('Left Blank'), ($submissions - $nonblanks));
436
  $rows[1] = array(t('User entered value'), $nonblanks);
437

    
438
  return array(
439
    'table_rows' => $rows,
440
  );
441
}
442

    
443
/**
444
 * Implements _webform_table_component().
445
 */
446
function _webform_table_time($component, $value) {
447
  if ($value[0]) {
448
    $time = webform_date_array($value[0], 'time');
449
    if ($component['extra']['hourformat'] == '24-hour') {
450
      return sprintf('%02d', $time['hour']) . ':' . sprintf('%02d', $time['minute']);
451
    }
452
    else {
453
      $time = webform_time_convert($time, '12-hour');
454
      return $time['hour'] . ':' . sprintf('%02d', $time['minute']) . ' ' . $time['ampm'];
455
    }
456
  }
457
  else {
458
    return '';
459
  }
460
}
461

    
462
/**
463
 * Implements _webform_csv_headers_component().
464
 */
465
function _webform_csv_headers_time($component, $export_options) {
466
  $header = array();
467
  $header[0] = '';
468
  $header[1] = '';
469
  $header[2] = $export_options['header_keys'] ? $component['form_key'] : $component['name'];
470
  return $header;
471
}
472

    
473
/**
474
 * Implements _webform_csv_data_component().
475
 */
476
function _webform_csv_data_time($component, $export_options, $value) {
477
  if ($value[0]) {
478
    $time = webform_date_array($value[0], 'time');
479
    // An ISO 8601 time is the same as 24-hour time.
480
    if (!empty($export_options['iso8601_time']) || $component['extra']['hourformat'] == '24-hour') {
481
      return sprintf('%02d', $time['hour']) . ':' . sprintf('%02d', $time['minute']);
482
    }
483
    else {
484
      $time = webform_time_convert($time, '12-hour');
485
      return $time['hour'] . ':' . sprintf('%02d', $time['minute']) . ' ' . $time['ampm'];
486
    }
487
  }
488
  else {
489
    return '';
490
  }
491
}
492

    
493
/**
494
 * Convert a time between a 24-hour and a 12-hour value.
495
 *
496
 * @param $array
497
 *   An array of hour, minute, second, and optionally ampm.
498
 * @param $format
499
 *   Either 12-hour or 24-hour.
500
 * @return
501
 *   An array with hour, minute, second, and ampm (if using "12-hour").
502
 */
503
function webform_time_convert($array, $format) {
504
  if ($array['hour'] !== '') {
505
    if ($format == '12-hour') {
506
      $array['ampm'] = ($array['hour'] >= 12 && $array['hour'] < 24) ? 'pm' : 'am';
507
      $array['hour'] = ($array['hour'] > 12 || $array['hour'] == 0) ? abs($array['hour'] - 12) : (int) $array['hour'];
508
    }
509
    elseif ($format == '24-hour' && isset($array['ampm'])) {
510
      $array['hour'] = ($array['hour'] < 12 && $array['ampm'] == 'pm') ? $array['hour'] + 12 : (int) $array['hour'];
511
      $array['hour'] = ($array['hour'] == 12 && $array['ampm'] == 'am') ? 0 : $array['hour'];
512
    }
513
  }
514

    
515
  if ($format == '12-hour' && !isset($array['ampm'])) {
516
    $array['ampm'] = '';
517
  }
518
  elseif ($format == '24-hour' && isset($array['ampm'])) {
519
    unset($array['ampm']);
520
  }
521

    
522
  return $array;
523
}