Projet

Général

Profil

Paste
Télécharger (31,3 ko) Statistiques
| Branche: | Révision:

root / drupal7 / sites / all / modules / webform / components / number.inc @ cb17e347

1
<?php
2

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

    
8
/**
9
 * Implements _webform_defaults_component().
10
 */
11
function _webform_defaults_number() {
12
  return array(
13
    'name' => '',
14
    'form_key' => NULL,
15
    'pid' => 0,
16
    'weight' => 0,
17
    'value' => '',
18
    'required' => 0,
19
    'extra' => array(
20
      'type' => 'textfield',
21
      'field_prefix' => '',
22
      'field_suffix' => '',
23
      'disabled' => 0,
24
      'unique' => 0,
25
      'title_display' => 0,
26
      'description' => '',
27
      'attributes' => array(),
28
      'private' => FALSE,
29
      'analysis' => FALSE,
30
      'min' => '',
31
      'max' => '',
32
      'step' => '',
33
      'decimals' => '',
34
      'point' => '.',
35
      'separator' => ',',
36
      'integer' => 0,
37
      'excludezero' => 0,
38
    ),
39
  );
40
}
41

    
42
/**
43
 * Implements _webform_theme_component().
44
 */
45
function _webform_theme_number() {
46
  return array(
47
    'webform_number' => array(
48
      'render element' => 'element',
49
      'file' => 'components/number.inc',
50
    ),
51
    'webform_display_number' => array(
52
      'render element' => 'element',
53
      'file' => 'components/number.inc',
54
    ),
55
  );
56
}
57

    
58
/**
59
 * Adjusts the view field(s) that are automatically generated for number
60
 * components.
61
 */
62
function _webform_view_field_number($component, $fields) {
63
  foreach ($fields as &$field) {
64
    $field['webform_datatype'] = 'number';
65
  }
66
  return $fields;
67
}
68

    
69
/**
70
 * Implements _webform_edit_component().
71
 */
72
function _webform_edit_number($component) {
73
  $form = array();
74
  $form['value'] = array(
75
    '#type' => 'textfield',
76
    '#title' => t('Default value'),
77
    '#default_value' => $component['value'],
78
    '#description' => t('The default value of the field.') . ' ' . theme('webform_token_help'),
79
    '#size' => 60,
80
    '#maxlength' => 1024,
81
    '#weight' => 0,
82
  );
83
  $form['display']['type'] = array(
84
    '#type' => 'radios',
85
    '#title' => t('Element type'),
86
    '#options' => array(
87
      'textfield' => t('Text field'),
88
      'select' => t('Select list'),
89
    ),
90
    '#default_value' => $component['extra']['type'],
91
    '#description' => t('A minimum and maximum value are required if displaying as a select.'),
92
    '#weight' => -1,
93
    '#parents' => array('extra', 'type'),
94
  );
95
  $form['display']['field_prefix'] = array(
96
    '#type' => 'textfield',
97
    '#title' => t('Prefix text placed to the left of the field'),
98
    '#default_value' => $component['extra']['field_prefix'],
99
    '#description' => t('Examples: $, #, -.'),
100
    '#size' => 20,
101
    '#maxlength' => 127,
102
    '#weight' => 1.1,
103
    '#parents' => array('extra', 'field_prefix'),
104
  );
105
  $form['display']['field_suffix'] = array(
106
    '#type' => 'textfield',
107
    '#title' => t('Postfix text placed to the right of the field'),
108
    '#default_value' => $component['extra']['field_suffix'],
109
    '#description' => t('Examples: lb, kg, %.'),
110
    '#size' => 20,
111
    '#maxlength' => 127,
112
    '#weight' => 1.2,
113
    '#parents' => array('extra', 'field_suffix'),
114
  );
115
  $form['display']['disabled'] = array(
116
    '#type' => 'checkbox',
117
    '#title' => t('Disabled'),
118
    '#return_value' => 1,
119
    '#description' => t('Make this field non-editable. Useful for setting an unchangeable default value.'),
120
    '#weight' => 11,
121
    '#default_value' => $component['extra']['disabled'],
122
    '#parents' => array('extra', 'disabled'),
123
  );
124
  $form['display']['decimals'] = array(
125
    '#type' => 'select',
126
    '#title' => t('Decimal places'),
127
    '#options' => array('' => t('Automatic')) + drupal_map_assoc(range(0, 10)),
128
    '#description' => t('Automatic will display up to @count decimals places if needed. A value of "2" is common to format currency amounts.', array('@count' => '4')),
129
    '#default_value' => $component['extra']['decimals'],
130
    '#weight' => 2,
131
    '#parents' => array('extra', 'decimals'),
132
    '#element_validate' => array('_webform_edit_number_validate'),
133
  );
134
  $form['display']['separator'] = array(
135
    '#type' => 'select',
136
    '#title' => t('Thousands separator'),
137
    '#options' => array(
138
      ',' => t('Comma (,)'),
139
      '.' => t('Period (.)'),
140
      ' ' => t('Space ( )'),
141
      '' => t('None'),
142
    ),
143
    '#default_value' => $component['extra']['separator'],
144
    '#weight' => 3,
145
    '#parents' => array('extra', 'separator'),
146
    '#element_validate' => array('_webform_edit_number_validate'),
147
  );
148
  $form['display']['point'] = array(
149
    '#type' => 'select',
150
    '#title' => t('Decimal point'),
151
    '#options' => array(
152
      ',' => t('Comma (,)'),
153
      '.' => t('Period (.)'),
154
    ),
155
    '#default_value' => $component['extra']['point'],
156
    '#weight' => 4,
157
    '#parents' => array('extra', 'point'),
158
    '#element_validate' => array('_webform_edit_number_validate'),
159
  );
160
  $form['validation']['unique'] = array(
161
    '#type' => 'checkbox',
162
    '#title' => t('Unique'),
163
    '#return_value' => 1,
164
    '#description' => t('Check that all entered values for this field are unique. The same value is not allowed to be used twice.'),
165
    '#weight' => 1,
166
    '#default_value' => $component['extra']['unique'],
167
    '#parents' => array('extra', 'unique'),
168
  );
169
  $form['validation']['integer'] = array(
170
    '#type' => 'checkbox',
171
    '#title' => t('Integer'),
172
    '#return_value' => 1,
173
    '#description' => t('Permit only integer values as input. e.g. 12.34 would be invalid.'),
174
    '#weight' => 1.5,
175
    '#default_value' => $component['extra']['integer'],
176
    '#parents' => array('extra', 'integer'),
177
  );
178
  $form['validation']['min'] = array(
179
    '#type' => 'textfield',
180
    '#title' => t('Minimum'),
181
    '#default_value' => $component['extra']['min'],
182
    '#description' => t('Minimum numeric value. e.g. 0 would ensure positive numbers.'),
183
    '#size' => 5,
184
    '#maxlength' => 10,
185
    '#weight' => 2.1,
186
    '#parents' => array('extra', 'min'),
187
    '#element_validate' => array('_webform_edit_number_validate'),
188
  );
189
  $form['validation']['max'] = array(
190
    '#type' => 'textfield',
191
    '#title' => t('Maximum'),
192
    '#default_value' => $component['extra']['max'],
193
    '#description' => t('Maximum numeric value. This may also determine the display width of your field.'),
194
    '#size' => 5,
195
    '#maxlength' => 10,
196
    '#weight' => 2.2,
197
    '#parents' => array('extra', 'max'),
198
    '#element_validate' => array('_webform_edit_number_validate'),
199
  );
200
  $form['validation']['step'] = array(
201
    '#type' => 'textfield',
202
    '#title' => t('Step'),
203
    '#default_value' => $component['extra']['step'],
204
    '#description' => t('Limit options to a specific increment. e.g. a step of "5" would allow values 5, 10, 15, etc.'),
205
    '#size' => 5,
206
    '#maxlength' => 10,
207
    '#weight' => 3,
208
    '#parents' => array('extra', 'step'),
209
    '#element_validate' => array('_webform_edit_number_validate'),
210
  );
211
  // Analysis settings.
212
  $form['analysis'] = array(
213
    '#type' => 'fieldset',
214
    '#title' => t('Analysis'),
215
    '#collapsible' => TRUE,
216
    '#collapsed' => FALSE,
217
    '#weight' => 10,
218
  );
219
  $form['analysis']['excludezero'] = array(
220
    '#type' => 'checkbox',
221
    '#title' => t('Exclude zero'),
222
    '#return_value' => 1,
223
    '#description' => t('Exclude entries of zero (or blank) when counting submissions to calculate average and standard deviation.'),
224
    '#weight' => 1.5,
225
    '#default_value' => $component['extra']['excludezero'],
226
    '#parents' => array('extra', 'excludezero'),
227
  );
228
  return $form;
229
}
230

    
231
/**
232
 * Theme function to render a number component.
233
 */
234
function theme_webform_number($variables) {
235
  $element = $variables['element'];
236

    
237
  // This IF statement is mostly in place to allow our tests to set type="text"
238
  // because SimpleTest does not support type="number".
239
  if (!isset($element['#attributes']['type'])) {
240
    // HTML5 number fields are no long used pending better browser support.
241
    // See issues #2290029, #2202905.
242
    // $element['#attributes']['type'] = 'number';
243
    $element['#attributes']['type'] = 'text';
244
  }
245

    
246
  // Step property *must* be a full number with 0 prefix if a decimal.
247
  if (!empty($element['#step']) && !is_int($element['#step'] * 1)) {
248
    $decimals = strlen($element['#step']) - strrpos($element['#step'], '.') - 1;
249
    $element['#step'] = sprintf('%1.' . $decimals . 'F', $element['#step']);
250
  }
251

    
252
  // If the number is not an integer and step is undefined/empty, set the "any"
253
  // value to allow any decimal.
254
  if (empty($element['#integer']) && empty($element['#step'])) {
255
    $element['#step'] = 'any';
256
  }
257
  elseif ($element['#integer'] && empty($element['#step'])) {
258
    $element['#step'] = 1;
259
  }
260

    
261
  // Convert properties to attributes on the element if set.
262
  foreach (array('id', 'name', 'value', 'size', 'min', 'max', 'step') as $property) {
263
    if (isset($element['#' . $property]) && $element['#' . $property] !== '') {
264
      $element['#attributes'][$property] = $element['#' . $property];
265
    }
266
  }
267
  _form_set_class($element, array('form-text', 'form-number'));
268

    
269
  return '<input' . drupal_attributes($element['#attributes']) . ' />';
270
}
271

    
272
/**
273
 * Implements _webform_render_component().
274
 */
275
function _webform_render_number($component, $value = NULL, $filter = TRUE, $submission = NULL) {
276
  $node = isset($component['nid']) ? node_load($component['nid']) : NULL;
277

    
278
  $element = array(
279
    '#title' => $filter ? webform_filter_xss($component['name']) : $component['name'],
280
    '#title_display' => $component['extra']['title_display'] ? $component['extra']['title_display'] : 'before',
281
    '#default_value' => $filter ? webform_replace_tokens($component['value'], $node) : $component['value'],
282
    '#required' => $component['required'],
283
    '#weight' => $component['weight'],
284
    '#field_prefix' => empty($component['extra']['field_prefix']) ? NULL : ($filter ? webform_filter_xss($component['extra']['field_prefix']) : $component['extra']['field_prefix']),
285
    '#field_suffix' => empty($component['extra']['field_suffix']) ? NULL : ($filter ? webform_filter_xss($component['extra']['field_suffix']) : $component['extra']['field_suffix']),
286
    '#description' => $filter ? webform_filter_descriptions($component['extra']['description'], $node) : $component['extra']['description'],
287
    '#attributes' => $component['extra']['attributes'],
288
    '#element_validate' => array('_webform_validate_number'),
289
    '#theme_wrappers' => array('webform_element'),
290
    '#min' => $component['extra']['min'],
291
    '#max' => $component['extra']['max'],
292
    '#step' => $component['extra']['step'] ? abs($component['extra']['step']) : '',
293
    '#integer' => $component['extra']['integer'],
294
    '#point' => $component['extra']['point'],
295
    '#separator' => $component['extra']['separator'],
296
    '#decimals' => $component['extra']['decimals'],
297
    '#translatable' => array('title', 'description', 'field_prefix', 'field_suffix'),
298
  );
299

    
300
  if ($component['required']) {
301
    $element['#attributes']['required'] = 'required';
302
  }
303

    
304
  // Set the decimal count to zero for integers.
305
  if ($element['#integer'] && $element['#decimals'] === '') {
306
    $element['#decimals'] = 0;
307
  }
308

    
309
  // Flip the min and max properties to make min less than max if needed.
310
  if ($element['#min'] !== '' && $element['#max'] !== '' && $element['#min'] > $element['#max']) {
311
    $max = $element['#min'];
312
    $element['#min'] = $element['#max'];
313
    $element['#max'] = $max;
314
  }
315

    
316
  // Ensure #step starts with a zero if a decimal.
317
  if (!is_int($element['#step'] * 1)) {
318
    $decimals = strlen($element['#step']) - strrpos($element['#step'], '.') - 1;
319
    $element['#step'] = sprintf('%1.' . $decimals . 'F', $element['#step']);
320
  }
321

    
322
  if ($component['extra']['type'] == 'textfield') {
323
    // Render as textfield.
324
    $element['#type'] = 'webform_number';
325

    
326
    // Set the size property based on #max, to ensure consistent behavior for
327
    // browsers that do not support type = number.
328
    if ($element['#max']) {
329
      $element['#size'] =  strlen($element['#max']) + 1;
330
    }
331
  }
332
  else {
333
    // Render as select.
334
    $element['#type'] = 'select';
335

    
336
    // Create user-specified options list as an array.
337
    $element['#options'] = _webform_number_select_options($component);
338

    
339
    // Add default options if using a select list with no default. This trigger's
340
    // Drupal 7's adding of the option for us. See form_process_select().
341
    if ($component['extra']['type'] == 'select' && $element['#default_value'] === '') {
342
      $element['#empty_value'] = '';
343
    }
344
  }
345

    
346
  // Set user-entered values.
347
  if (isset($value[0])) {
348
    // If the value has been standardized, convert it to the expected format
349
    // for display to the user.
350
    if (webform_number_format_match($value[0], '.', '')) {
351
      $element['#default_value'] = _webform_number_format($component, $value[0]);
352
    }
353
    // Otherwise use the user-defined input.
354
    else {
355
      $element['#default_value'] = $value[0];
356
    }
357
  }
358

    
359
  // Enforce uniqueness.
360
  if ($component['extra']['unique']) {
361
    $element['#element_validate'][] = 'webform_validate_unique';
362
  }
363

    
364
  // Set readonly if disabled.
365
  if ($component['extra']['disabled']) {
366
    if ($filter) {
367
      $element['#attributes']['readonly'] = 'readonly';
368
    }
369
    else {
370
      $element['#disabled'] = TRUE;
371
    }
372
  }
373

    
374
  return $element;
375
}
376

    
377
/**
378
 * Implements _webform_display_component().
379
 */
380
function _webform_display_number($component, $value, $format = 'html', $submission = array()) {
381
  $empty = !isset($value[0]) || $value[0] === '';
382
  return array(
383
    '#title' => $component['name'],
384
    '#title_display' => $component['extra']['title_display'] ? $component['extra']['title_display'] : 'before',
385
    '#weight' => $component['weight'],
386
    '#theme' => 'webform_display_number',
387
    '#theme_wrappers' => $format == 'html' ? array('webform_element') : array('webform_element_text'),
388
    '#field_prefix' => $empty ? '' : $component['extra']['field_prefix'],
389
    '#field_suffix' => $empty ? '' : $component['extra']['field_suffix'],
390
    '#format' => $format,
391
    '#value' => $empty ? '' : _webform_number_format($component, $value[0]),
392
    '#translatable' => array('title'),
393
  );
394
}
395

    
396
/**
397
 * Format the output of data for this component.
398
 */
399
function theme_webform_display_number($variables) {
400
  $element = $variables['element'];
401
  $prefix = $element['#format'] == 'html' ? '' : $element['#field_prefix'];
402
  $suffix = $element['#format'] == 'html' ? '' : $element['#field_suffix'];
403
  $value = $element['#format'] == 'html' ? check_plain($element['#value']) : $element['#value'];
404
  return $value !== '' ? ($prefix . $value . $suffix) : ' ';
405
}
406

    
407
/**
408
 * Implements _webform_analysis_component().
409
 */
410
function _webform_analysis_number($component, $sids = array(), $single = FALSE, $join = NULL) {
411
  $advanced_stats = $single;
412

    
413
  $query = db_select('webform_submitted_data', 'wsd', array('fetch' => PDO::FETCH_ASSOC))
414
    ->fields('wsd', array('data'))
415
    ->condition('wsd.nid', $component['nid'])
416
    ->condition('wsd.cid', $component['cid']);
417

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

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

    
426
  $population = array();
427
  $submissions = 0;
428
  $non_zero = 0;
429
  $non_empty = 0;
430
  $sum = 0;
431

    
432
  $result = $query->execute();
433
  foreach ($result as $data) {
434
    $value = trim($data['data']);
435
    $number = (float)$value;
436
    $non_empty += (integer)($value !== '');
437
    $non_zero += (integer)($number != 0.0);
438
    $sum += $number;
439
    $population[] = $number;
440
    $submissions++;
441
  }
442
  sort($population, SORT_NUMERIC);
443

    
444
  // Average and population count.
445
  if ($component['extra']['excludezero']) {
446
    $average = $non_zero ? ($sum / $non_zero) : 0;
447
    $average_title = t('Average !mu excluding zeros/blanks', array('!mu' => $advanced_stats ? '(&mu;)' : ''));
448
    // Sample (sub-set of total population).
449
    $population_count = $non_zero - 1;
450
    $sigma = 'sd';
451
    $description = t('sample');
452
  }
453
  else {
454
    $average = $submissions ? ($sum / $submissions) : 0;
455
    $average_title = t('Average !mu including zeros/blanks', array('!mu' => $advanced_stats ? '(&mu;)' : ''));
456
    // Population.
457
    $population_count = $submissions;
458
    $sigma = '&sigma;';
459
    $description = t('population');
460
  }
461

    
462
  // Formatting.
463
  $average = _webform_number_format($component, $average);
464
  $sum = _webform_number_format($component, $sum);
465

    
466
  $rows[] = array(t('Zero/blank'), ($submissions - $non_zero));
467
  $rows[] = array(t('User entered value'), $non_empty);
468

    
469
  $other[] = array(t('Sum') . ($advanced_stats ? ' (&Sigma;)' : ''), $sum);
470
  $other[] = array($average_title, $average);
471

    
472
  if (!$advanced_stats && $sum != 0) {
473
    $other[] = l(t('More stats »'), 'node/' . $component['nid'] . '/webform-results/analysis/' . $component['cid']);
474
  }
475

    
476
  // Normal distribution information.
477
  if ($advanced_stats && $population_count && $sum != 0) {
478
    // Standard deviation.
479
    $stddev = 0;
480
    foreach ($population as $value) {
481
      // Obtain the total of squared variances.
482
      $stddev += pow(($value - $average), 2);
483
    }
484
    if ($population_count > 0) {
485
      $stddev = sqrt($stddev / $population_count);
486
    }
487
    else {
488
      $stddev = sqrt($stddev);
489
    }
490

    
491
    // Skip the rest of the distribution rows if standard deviation is 0.
492
    if (empty($stddev)) {
493
      return array(
494
        'table_rows' => $rows,
495
        'other_data' => $other,
496
      );
497
    }
498

    
499
    // Build normal distribution table rows.
500
    $count = array();
501
    $percent = array();
502
    $limit = array();
503
    $index = 0;
504

    
505
    $count[] = 0;
506
    $limit[] = $average - ($stddev * 4);
507
    foreach ($population as $value) {
508
      while ($value >= $limit[$index]) {
509
        $percent[] = number_format($count[$index] / $population_count * 100, 2, '.', '');
510
        $limit[] = $limit[$index] + $stddev;
511
        $index += 1;
512
        if ($limit[$index] == $average) {
513
          $limit[$index] = $limit[$index] + $stddev;
514
        }
515
        $count[$index] = 0;
516
      }
517
      $count[$index] += 1;
518
    }
519
    $percent[] = number_format($count[$index] / $population_count * 100, 2, '.', '');
520

    
521
    // Format normal distribution table output.
522
    $stddev = _webform_number_format($component, $stddev);
523
    $low = _webform_number_format($component, $population[0]);
524
    $high = _webform_number_format($component, end($population));
525
    foreach ($limit as $key => $value) {
526
      $limit[$key] = _webform_number_format($component, $value);
527
    }
528

    
529
    // Column headings (override potential theme uppercase, e.g. Seven in D7).
530
    $header = array(
531
      t('Normal Distribution'),
532
      array('data' => '-4' . $sigma, 'style' => 'text-transform: lowercase;'),
533
      array('data' => '-3' . $sigma, 'style' => 'text-transform: lowercase;'),
534
      array('data' => '-2' . $sigma, 'style' => 'text-transform: lowercase;'),
535
      array('data' => '-1' . $sigma, 'style' => 'text-transform: lowercase;'),
536
      array('data' => '+1' . $sigma, 'style' => 'text-transform: lowercase;'),
537
      array('data' => '+2' . $sigma, 'style' => 'text-transform: lowercase;'),
538
      array('data' => '+3' . $sigma, 'style' => 'text-transform: lowercase;'),
539
      array('data' => '+4' . $sigma, 'style' => 'text-transform: lowercase;'),
540
    );
541

    
542
    // Insert row labels.
543
    array_unshift($limit, t('Boundary'));
544
    array_unshift($count, t('Count'));
545
    array_unshift($percent, t('% of !description', array('!description' => $description)));
546

    
547
    $normal_distribution = theme('table', array('header' => $header, 'rows' => array($limit, $count, $percent), 'sticky' => FALSE));
548

    
549
    $other[] = array(t('Range'), t('!low to !high', array('!low' => $low, '!high' => $high)));
550
    $other[] = array(t('Standard deviation (!sigma)', array('!sigma' => $sigma)), $stddev);
551
    $other[] = $normal_distribution;
552
  }
553

    
554
  return array(
555
    'table_rows' => $rows,
556
    'other_data' => $other,
557
  );
558
}
559

    
560
/**
561
 * Implements _webform_table_component().
562
 */
563
function _webform_table_number($component, $value) {
564
  return isset($value[0]) ? _webform_number_format($component, $value[0]) : '';
565
}
566

    
567
/**
568
 * Implements _webform_action_set_component().
569
 */
570
function _webform_action_set_number($component, &$element, &$form_state, $value) {
571
  $element['#value'] = $value;
572
  form_set_value($element, $value, $form_state);
573
}
574

    
575
/**
576
 * Implements _webform_csv_headers_component().
577
 */
578
function _webform_csv_headers_number($component, $export_options) {
579
  $header = array();
580
  $header[0] = '';
581
  $header[1] = '';
582
  $header[2] = $export_options['header_keys'] ? $component['form_key'] : $component['name'];
583
  return $header;
584
}
585

    
586
/**
587
 * Implements _webform_csv_data_component().
588
 */
589
function _webform_csv_data_number($component, $export_options, $value) {
590
  if (isset($value[0]) && is_numeric($value[0]) && $component['extra']['decimals'] !== '') {
591
    $value[0] = number_format($value[0], $component['extra']['decimals'], '.', '');
592
  }
593
  return isset($value[0]) ? $value[0] : '';
594
}
595

    
596
/**
597
 * A Drupal Form API Validation function. Validates the entered values from
598
 * number components on the client-side form.
599
 *
600
 * @param $element
601
 *   The form element. May either be a select or a webform_number element.
602
 * @param $form_state
603
 *   The full form state for the webform.
604
 * @return
605
 *   None. Calls a form_set_error if the number is not valid.
606
 */
607
function _webform_validate_number($element, &$form_state) {
608
  // Trim spaces for basic cleanup.
609
  $value = trim($element['#value']);
610
  form_set_value($element, $value, $form_state);
611

    
612
  if ($value != '') {
613
    // First check that the entered value matches the expected value.
614
    if (!webform_number_format_match($value, $element['#point'], $element['#separator'])) {
615
      form_error($element, t('!name field value must format numbers as "@example".', array('!name' => $element['#title'], '@example' => webform_number_format(12345.6789, $element['#decimals'], $element['#point'], $element['#separator']))));
616
      return;
617
    }
618

    
619
    // Numeric test.
620
    $numeric_value = webform_number_standardize($value, $element['#point']);
621
    if (is_numeric($numeric_value)) {
622
      // Range test.
623
      if ($element['#min'] != '' && $element['#max'] != '') {
624
        // Flip minimum and maximum if needed.
625
        if ($element['#max'] > $element['#min']) {
626
          $min = $element['#min'];
627
          $max = $element['#max'];
628
        }
629
        else {
630
          $min = $element['#max'];
631
          $max = $element['#min'];
632
        }
633
        if ($numeric_value > $max || $numeric_value < $min) {
634
          form_error($element, t('!name field value of @value should be in the range @min to @max.', array('!name' => $element['#title'], '@value' => $value, '@min' => $element['#min'], '@max' => $element['#max'])));
635
        }
636
      }
637
      elseif ($element['#max'] != '' && $numeric_value > $element['#max']) {
638
        form_error($element, t('!name field value must be less than @max.', array('!name' => $element['#title'], '@max' => $element['#max'])));
639
      }
640
      elseif ($element['#min'] != '' && $numeric_value < $element['#min']) {
641
        form_error($element, t('!name field value must be greater than @min.', array('!name' => $element['#title'], '@min' => $element['#min'])));
642
      }
643

    
644
      // Integer test.
645
      if ($element['#integer'] && !is_int($numeric_value * 1)) {
646
        form_error($element, t('!name field value of @value must be an integer.', array('!name' => $element['#title'], '@value' => $value)));
647
      }
648

    
649
      // Step test.
650
      $starting_number = $element['#min'] ? $element['#min'] : 0;
651
      if ($element['#step'] != 0 && webform_modulo($numeric_value - $starting_number, $element['#step']) != 0.0) {
652
        $samples = array(
653
          $starting_number,
654
          $starting_number + ($element['#step'] * 1),
655
          $starting_number + ($element['#step'] * 2),
656
          $starting_number + ($element['#step'] * 3),
657
        );
658
        if ($starting_number) {
659
          form_error($element, t('!name field value must be @start plus a multiple of @step. i.e. @samples, etc.', array('!name' => $element['#title'], '@start' => $element['#min'], '@step' => $element['#step'], '@samples' => implode(', ', $samples))));
660
        }
661
        else {
662
          form_error($element, t('!name field value must be a multiple of @step. i.e. @samples, etc.', array('!name' => $element['#title'], '@step' => $element['#step'], '@samples' => implode(', ', $samples))));
663
        }
664
      }
665
    }
666
    else {
667
      form_error($element, t('!name field value of @value must be numeric.', array('!name' => $element['#title'], '@value' => $value)));
668
    }
669
  }
670
}
671

    
672
/**
673
 * Implements _webform_submit_component().
674
 */
675
function _webform_submit_number($component, $value) {
676
  // Because _webform_validate_number() ensures the format matches when moving
677
  // forward through a form, this should always pass before saving into the
678
  // database. When moving backwards in a form, do not adjust the value, since
679
  // it has not yet been validated.
680
  if (webform_number_format_match($value, $component['extra']['point'], $component['extra']['separator'])) {
681
    $value = webform_number_standardize($value, $component['extra']['point']);
682
  }
683
  return $value;
684
}
685

    
686
/**
687
 * Validation of number edit form items.
688
 */
689
function _webform_edit_number_validate($element, &$form_state) {
690
  // Find the value of all related fields to this element.
691
  $parents = $element['#parents'];
692
  $key = array_pop($parents);
693
  $values = $form_state['values'];
694
  foreach ($parents as $parent) {
695
    $values = $values[$parent];
696
  }
697

    
698
  switch ($key) {
699
    case 'min':
700
      if ($values['min'] == '') {
701
        if (isset($values['type']) && $values['type'] === 'select') {
702
          form_error($element, t('Minimum is required when using a select list element.'));
703
        }
704
      }
705
      else {
706
        if (!is_numeric($values['min'])) {
707
          form_error($element, t('Minimum must be numeric.'));
708
        }
709
        if ($values['integer'] && !is_int($values['min'] * 1)) {
710
          form_error($element, t('Minimum must have an integer value.'));
711
        }
712
      }
713
      break;
714
    case 'max':
715
      if ($values['max'] == '') {
716
        if (isset($values['type']) && $values['type'] === 'select') {
717
          form_error($element, t('Maximum is required when using a select list element.'));
718
        }
719
      }
720
      else {
721
        if (!is_numeric($values['max'])) {
722
          form_error($element, t('Maximum must be numeric.'));
723
        }
724
        if ($values['integer'] && !is_int($values['max'] * 1)) {
725
          form_error($element, t('Maximum must have an integer value.'));
726
        }
727
      }
728
      break;
729
    case 'step':
730
      if ($values['step'] !== '') {
731
        if (!is_numeric($values['step'])) {
732
          form_error($element, t('Step must be numeric.'));
733
        }
734
        else {
735
          if ($values['integer'] && !is_int($values['step'] * 1)) {
736
            form_error($element, t('Step must have an integer value.'));
737
          }
738
        }
739
      }
740
      break;
741
  }
742
  return TRUE;
743
}
744

    
745
/**
746
 * Generate select list options.
747
 */
748
function _webform_number_select_options($component) {
749
  $options = array();
750
  $step = abs($component['extra']['step']);
751

    
752
  // Step is optional and defaults to 1.
753
  $step = empty($step) ? 1 : $step;
754

    
755
  // Generate list in correct direction.
756
  $min = $component['extra']['min'];
757
  $max = $component['extra']['max'];
758
  $flipped = FALSE;
759
  if ($max < $min) {
760
    $min = $component['extra']['max'];
761
    $max = $component['extra']['min'];
762
    $flipped = TRUE;
763
  }
764

    
765
  for ($f = $min; $f <= $max; $f += $step) {
766
    $options[$f . ''] = $f . '';
767
  }
768

    
769
  // TODO: HTML5 browsers apparently do not include the max value if it does
770
  // not line up with step. Restore this if needed in the future.
771
  // Add end limit if it's been skipped due to step.
772
  //if (end($options) != $max) {
773
  //  $options[$f] = $max;
774
  //}
775

    
776
  if ($flipped) {
777
    $options = array_reverse($options, TRUE);
778
  }
779

    
780
  // Apply requisite number formatting.
781
  foreach ($options as $key => $value) {
782
    $options[$key] = _webform_number_format($component, $value);
783
  }
784

    
785
  return $options;
786
}
787

    
788
/**
789
 * Apply number format based on a component and number value.
790
 */
791
function _webform_number_format($component, $value) {
792
  return webform_number_format($value, $component['extra']['decimals'], $component['extra']['point'], $component['extra']['separator']);
793
}
794

    
795
/**
796
 * Validates if a provided number string matches an expected format.
797
 *
798
 * This function allows the thousands separator to be optional, but decimal
799
 * points must be in the right location.
800
 *
801
 * Based on http://stackoverflow.com/questions/5917082/regular-expression-to-match-numbers-with-or-without-commas-and-decimals-in-text.
802
 */
803
function webform_number_format_match($value, $point, $separator) {
804
  return preg_match('/^-? ?\d{1,3}(?:' . ($separator ? (preg_quote($separator, '/') . '?') : '') . '\d{2,3})*(?:' . preg_quote($point, '/') . '\d+)?$/', $value);
805
}
806

    
807
/**
808
 * Format a number with thousands separator, decimal point, and decimal places.
809
 *
810
 * This function is a wrapper around PHP's native number_format(), but allows
811
 * the decimal places parameter to be NULL or an empty string, resulting in a
812
 * behavior of no change to the decimal places.
813
 */
814
function webform_number_format($value, $decimals = NULL, $point = '.', $separator = ',') {
815
  if (!is_numeric($value)) {
816
    return '';
817
  }
818

    
819
  // If no decimal places are specified, do a best guess length of decimals.
820
  if (is_null($decimals) || $decimals === '') {
821
    // If it's an integer, no decimals needed.
822
    if (is_int(($value . '') * 1)) {
823
      $decimals = 0;
824
    }
825
    else {
826
      $decimals = strlen($value) - strrpos($value, '.') - 1;
827
    }
828
    if ($decimals > 4) {
829
      $decimals = 4;
830
    }
831
  }
832

    
833
  return number_format($value, $decimals, $point, $separator);
834
}
835

    
836
/**
837
 * Given a number, convert it to string compatible with a PHP float.
838
 *
839
 * @param string $value
840
 *   The string value to be standardized into a numeric string.
841
 * @param $point
842
 *   The point separator between the whole number and the decimals.
843
 */
844
function webform_number_standardize($value, $point) {
845
  // For simplicity, strip everything that's not the decimal point.
846
  $value = preg_replace('/[^\-0-9' . preg_quote($point, '/') . ']/', '', $value);
847
  // Convert the decimal point to a period.
848
  $value = str_replace($point, '.', $value);
849
  return $value;
850
}
851

    
852
/**
853
 * Custom modulo function that properly handles float division.
854
 *
855
 * See https://drupal.org/node/1601968.
856
 */
857
function webform_modulo($a, $b) {
858
  $modulo = $a - $b * (($b < 0) ? ceil($a / $b) : floor($a / $b));
859
  if (webform_compare_floats($modulo, 0.0) == 0 || webform_compare_floats($modulo, $b) == 0) {
860
    $modulo = 0.0;
861
  }
862
  return $modulo;
863
}
864

    
865
/**
866
 * Compare two floats.
867
 *
868
 * See @link http://php.net/manual/en/language.types.float.php @endlink
869
 *
870
 * Comparison of floating point numbers for equality is surprisingly difficult,
871
 * as evidenced by the references below. The simple test in this function works
872
 * for numbers that are relatively close to 1E1. For very small numbers, it will
873
 * show false equality. For very large numbers, it will show false inequality.
874
 * Better implementations are hidered by the absense of PHP platform-specific
875
 * floating point constants to properly set the minimum absolute and relative
876
 * error in PHP.
877
 *
878
 * The use case for webform conditionals excludes very small or very large
879
 * numeric comparisons.
880
 *
881
 * See @link http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm @endlink
882
 * See @link http://floating-point-gui.de/errors/comparison/ @endlink
883
 * See @link http://en.wikipedia.org/wiki/IEEE_754-1985#Denormalized_numbers @endlink
884
 *
885
 * @param float $number_1
886
 *   The first number.
887
 * @param float $number_2
888
 *   The second number.
889
 *
890
 * @return int|null
891
 *   < 0 if number_1 is less than number_2; > 0 if number_1 is greater than
892
 *   number_2, 0 if they are equal, and NULL if either is not numeric.
893
 */
894
function webform_compare_floats($number_1, $number_2) {
895
  if (!is_numeric($number_1) || !is_numeric($number_2)) {
896
    return NULL;
897
  }
898

    
899
  $number_1 = (float)$number_1;
900
  $number_2 = (float)$number_2;
901

    
902
  $epsilon = 0.000001;
903
  if (abs($number_1 - $number_2) < $epsilon) {
904
    return 0;
905
  }
906
  elseif ($number_1 > $number_2) {
907
    return 1;
908
  }
909
  else {
910
    return -1;
911
  }
912
}