Projet

Général

Profil

Paste
Télécharger (32,7 ko) Statistiques
| Branche: | Révision:

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

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
      'description_above' => FALSE,
28
      'attributes' => array(),
29
      'private' => FALSE,
30
      'analysis' => FALSE,
31
      'min' => '',
32
      'max' => '',
33
      'step' => '',
34
      'decimals' => '',
35
      'point' => '.',
36
      'separator' => ',',
37
      'integer' => 0,
38
      'excludezero' => 0,
39
    ),
40
  );
41
}
42

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
375
  return $element;
376
}
377

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
611
  if ($value != '') {
612
    // First check that the entered value matches the expected value.
613
    if (!webform_number_format_match($value, $element['#point'], $element['#separator'])) {
614
      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']))));
615
      return;
616
    }
617

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

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

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

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

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

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

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

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

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

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

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

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

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

    
784
  return $options;
785
}
786

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

    
794
/**
795
 * Validates if a provided number string matches an expected format.
796
 *
797
 * This function allows the thousands separator to be optional, but decimal
798
 * points must be in the right location.
799
 *
800
 * Based on http://stackoverflow.com/questions/5917082/regular-expression-to-match-numbers-with-or-without-commas-and-decimals-in-text.
801
 */
802
function webform_number_format_match($value, $point, $separator) {
803
  // A valid number is:
804
  //   1. optional minus sign
805
  //   2. optional space
806
  //   3. the rest of the string can't be just a decimal or blank.
807
  //   3. optional integer portion, with thousands separators
808
  //   4. optional decimal portion, starting is a decimal separator
809

    
810
  // Don't use preg_quote because a space is a valid thousands separator and
811
  // needs quoting for the 'x' option to preg_match.
812
  $thousands = $separator ? "\\$separator?" : '';
813
  $decimal = "\\$point";
814
  return preg_match("/
815
                    ^               # Start of string
816
                    -?              # Optional minus sign
817
                    \ ?             # Optional space
818
                    (?!\.?$)        # Assert looking ahead, not just a decimal or nothing
819
                      (?:           # Interger portion (non-grouping)
820
                        \d{1,3}     #   1 to 3 digits
821
                        (?:         #   Thousands group(s)
822
                        $thousands  #     Optional thousands separator
823
                        \d{2,3}     #     2 or 3 digits. Some countries use groups of 2 sometimes
824
                      )*            #   0 or more of these thousands groups
825
                    )?              # End of optional integer portion
826
                    (?:             # Decimal portion (non-grouping)
827
                      $decimal      #   Decimal point
828
                      \d*           #   0 or more digits
829
                    )?              # End of optional decimal portion
830
                    $
831
                    /x", $value);
832
}
833

    
834
/**
835
 * Format a number with thousands separator, decimal point, and decimal places.
836
 *
837
 * This function is a wrapper around PHP's native number_format(), but allows
838
 * the decimal places parameter to be NULL or an empty string, resulting in a
839
 * behavior of no change to the decimal places.
840
 */
841
function webform_number_format($value, $decimals = NULL, $point = '.', $separator = ',') {
842
  if (!is_numeric($value)) {
843
    return '';
844
  }
845

    
846
  // If no decimal places are specified, do a best guess length of decimals.
847
  if (is_null($decimals) || $decimals === '') {
848
    // If it's an integer, no decimals needed.
849
    if (is_int(($value . '') * 1)) {
850
      $decimals = 0;
851
    }
852
    else {
853
      $decimals = strlen($value) - strrpos($value, '.') - 1;
854
    }
855
    if ($decimals > 4) {
856
      $decimals = 4;
857
    }
858
  }
859

    
860
  return number_format($value, $decimals, $point, $separator);
861
}
862

    
863
/**
864
 * Given a number, convert it to string compatible with a PHP float.
865
 *
866
 * @param string $value
867
 *   The string value to be standardized into a numeric string.
868
 * @param $point
869
 *   The point separator between the whole number and the decimals.
870
 *
871
 * @return mixed|string
872
 */
873
function webform_number_standardize($value, $point) {
874
  // For simplicity, strip everything that's not the decimal point.
875
  $value = preg_replace('/[^\-0-9' . preg_quote($point, '/') . ']/', '', $value);
876
  // Convert the decimal point to a period.
877
  $value = str_replace($point, '.', $value);
878
  return $value;
879
}
880

    
881
/**
882
 * Custom modulo function that properly handles float division.
883
 *
884
 * See https://drupal.org/node/1601968.
885
 */
886
function webform_modulo($a, $b) {
887
  $modulo = $a - $b * (($b < 0) ? ceil($a / $b) : floor($a / $b));
888
  if (webform_compare_floats($modulo, 0.0) == 0 || webform_compare_floats($modulo, $b) == 0) {
889
    $modulo = 0.0;
890
  }
891
  return $modulo;
892
}
893

    
894
/**
895
 * Compare two floats.
896
 *
897
 * See @link http://php.net/manual/en/language.types.float.php @endlink
898
 *
899
 * Comparison of floating point numbers for equality is surprisingly difficult,
900
 * as evidenced by the references below. The simple test in this function works
901
 * for numbers that are relatively close to 1E1. For very small numbers, it will
902
 * show false equality. For very large numbers, it will show false inequality.
903
 * Better implementations are hidered by the absense of PHP platform-specific
904
 * floating point constants to properly set the minimum absolute and relative
905
 * error in PHP.
906
 *
907
 * The use case for webform conditionals excludes very small or very large
908
 * numeric comparisons.
909
 *
910
 * See @link http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm @endlink
911
 * See @link http://floating-point-gui.de/errors/comparison/ @endlink
912
 * See @link http://en.wikipedia.org/wiki/IEEE_754-1985#Denormalized_numbers @endlink
913
 *
914
 * @param float $number_1
915
 *   The first number.
916
 * @param float $number_2
917
 *   The second number.
918
 *
919
 * @return int|null
920
 *   < 0 if number_1 is less than number_2; > 0 if number_1 is greater than
921
 *   number_2, 0 if they are equal, and NULL if either is not numeric.
922
 */
923
function webform_compare_floats($number_1, $number_2) {
924
  if (!is_numeric($number_1) || !is_numeric($number_2)) {
925
    return NULL;
926
  }
927

    
928
  $number_1 = (float)$number_1;
929
  $number_2 = (float)$number_2;
930

    
931
  $epsilon = 0.000001;
932
  if (abs($number_1 - $number_2) < $epsilon) {
933
    return 0;
934
  }
935
  elseif ($number_1 > $number_2) {
936
    return 1;
937
  }
938
  else {
939
    return -1;
940
  }
941
}