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 @ 8c72e82a

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
      'description_above' => FALSE,
31
      'private' => FALSE,
32
      'analysis' => FALSE,
33
    ),
34
  );
35
}
36

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

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

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

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

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

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

    
169
  return $element;
170
}
171

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

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

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

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

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

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

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

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

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

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

    
273
  return $element;
274
}
275

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

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

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

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

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

    
303
  return $output;
304
}
305

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
523
  return $array;
524
}