Project

General

Profile

Paste
Download (17.8 KB) Statistics
| Branch: | Revision:

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

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 facilitate
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
/**
307
 * Validate that the time data is valid, calling form_error() if not.
308
 */
309
function webform_validate_time($element, $form_state) {
310
  // Check if the user filled the required fields.
311
  if ($element['#required']) {
312
    foreach (array('hour', 'minute', 'ampm') as $field_type) {
313
      if (isset($element[$field_type]) && $element[$field_type]['#value'] === '') {
314
        form_error($element, t('!name field is required.', array('!name' => $element['#title'])));
315
        return;
316
      }
317
    }
318
  }
319

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
525
  return $array;
526
}