Project

General

Profile

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

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

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

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

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

    
240
/**
241
 * Theme function to render a number component.
242
 */
243
function theme_webform_number($variables) {
244
  $element = $variables['element'];
245

    
246
  // This IF statement is mostly in place to allow our tests to set type="text"
247
  // because SimpleTest does not support type="number".
248
  if (!isset($element['#attributes']['type'])) {
249
    // HTML5 number fields are no long used pending better browser support.
250
    // See issues #2290029, #2202905.
251
    // @code
252
    // $element['#attributes']['type'] = 'number';
253
    // @endcode
254
    $element['#attributes']['type'] = 'text';
255
  }
256

    
257
  // Step property *must* be a full number with 0 prefix if a decimal.
258
  if (!empty($element['#step']) && filter_var((float) $element['#step'], FILTER_VALIDATE_INT) === FALSE) {
259
    $decimals = strlen($element['#step']) - strrpos($element['#step'], '.') - 1;
260
    $element['#step'] = sprintf('%1.' . $decimals . 'F', $element['#step']);
261
  }
262

    
263
  // If the number is not an integer and step is undefined/empty, set the "any"
264
  // value to allow any decimal.
265
  if (empty($element['#integer']) && empty($element['#step'])) {
266
    $element['#step'] = 'any';
267
  }
268
  elseif ($element['#integer'] && empty($element['#step'])) {
269
    $element['#step'] = 1;
270
  }
271

    
272
  // Convert properties to attributes on the element if set.
273
  foreach (array('id', 'name', 'value', 'size', 'min', 'max', 'step') as $property) {
274
    if (isset($element['#' . $property]) && $element['#' . $property] !== '') {
275
      $element['#attributes'][$property] = $element['#' . $property];
276
    }
277
  }
278
  _form_set_class($element, array('form-text', 'form-number'));
279

    
280
  return '<input' . drupal_attributes($element['#attributes']) . ' />';
281
}
282

    
283
/**
284
 * Implements _webform_render_component().
285
 */
286
function _webform_render_number($component, $value = NULL, $filter = TRUE, $submission = NULL) {
287
  $node = isset($component['nid']) ? node_load($component['nid']) : NULL;
288

    
289
  $element = array(
290
    '#title' => $filter ? webform_filter_xss($component['name']) : $component['name'],
291
    '#title_display' => $component['extra']['title_display'] ? $component['extra']['title_display'] : 'before',
292
    '#default_value' => $filter ? webform_replace_tokens($component['value'], $node) : $component['value'],
293
    '#required' => $component['required'],
294
    '#weight' => $component['weight'],
295
    '#field_prefix' => empty($component['extra']['field_prefix']) ? NULL : ($filter ? webform_filter_xss($component['extra']['field_prefix']) : $component['extra']['field_prefix']),
296
    '#field_suffix' => empty($component['extra']['field_suffix']) ? NULL : ($filter ? webform_filter_xss($component['extra']['field_suffix']) : $component['extra']['field_suffix']),
297
    '#description' => $filter ? webform_filter_descriptions($component['extra']['description'], $node) : $component['extra']['description'],
298
    '#attributes' => $component['extra']['attributes'],
299
    '#element_validate' => array('_webform_validate_number'),
300
    '#theme_wrappers' => array('webform_element'),
301
    '#min' => $component['extra']['min'],
302
    '#max' => $component['extra']['max'],
303
    '#step' => $component['extra']['step'] ? abs($component['extra']['step']) : '',
304
    '#integer' => $component['extra']['integer'],
305
    '#point' => $component['extra']['point'],
306
    '#separator' => $component['extra']['separator'],
307
    '#decimals' => $component['extra']['decimals'],
308
    '#translatable' => array('title', 'description', 'field_prefix', 'field_suffix', 'placeholder'),
309
  );
310

    
311
  if ($component['required']) {
312
    $element['#attributes']['required'] = 'required';
313
  }
314

    
315
  if ($component['extra']['placeholder']) {
316
    $element['#attributes']['placeholder'] = $component['extra']['placeholder'];
317
  }
318

    
319
  // Set the decimal count to zero for integers.
320
  if ($element['#integer'] && $element['#decimals'] === '') {
321
    $element['#decimals'] = 0;
322
  }
323

    
324
  // Flip the min and max properties to make min less than max if needed.
325
  if ($element['#min'] !== '' && $element['#max'] !== '' && $element['#min'] > $element['#max']) {
326
    $max = $element['#min'];
327
    $element['#min'] = $element['#max'];
328
    $element['#max'] = $max;
329
  }
330

    
331
  // Ensure #step starts with a zero if a decimal.
332
  if (filter_var((float) $element['#step'], FILTER_VALIDATE_INT) === FALSE) {
333
    $decimals = strlen($element['#step']) - strrpos($element['#step'], '.') - 1;
334
    $element['#step'] = sprintf('%1.' . $decimals . 'F', $element['#step']);
335
  }
336

    
337
  if ($component['extra']['type'] == 'textfield') {
338
    // Render as textfield.
339
    $element['#type'] = 'webform_number';
340

    
341
    // Set the size property based on #max, to ensure consistent behavior for
342
    // browsers that do not support type = number.
343
    if ($element['#max']) {
344
      $element['#size'] = strlen($element['#max']) + 1;
345
    }
346
  }
347
  else {
348
    // Render as select.
349
    $element['#type'] = 'select';
350

    
351
    // Create user-specified options list as an array.
352
    $element['#options'] = _webform_number_select_options($component);
353

    
354
    // Add default options if using a select list with no default. This trigger's
355
    // Drupal 7's adding of the option for us. See form_process_select().
356
    if ($component['extra']['type'] == 'select' && $element['#default_value'] === '') {
357
      $element['#empty_value'] = '';
358
    }
359
  }
360

    
361
  // Set user-entered values.
362
  if (isset($value[0])) {
363
    // If the value has been standardized, convert it to the expected format
364
    // for display to the user.
365
    if (webform_number_format_match($value[0], '.', '')) {
366
      $element['#default_value'] = _webform_number_format($component, $value[0]);
367
    }
368
    // Otherwise use the user-defined input.
369
    else {
370
      $element['#default_value'] = $value[0];
371
    }
372
  }
373

    
374
  // Enforce uniqueness.
375
  if ($component['extra']['unique']) {
376
    $element['#element_validate'][] = 'webform_validate_unique';
377
  }
378

    
379
  // Set readonly if disabled.
380
  if ($component['extra']['disabled']) {
381
    if ($filter) {
382
      $element['#attributes']['readonly'] = 'readonly';
383
    }
384
    else {
385
      $element['#disabled'] = TRUE;
386
    }
387
  }
388

    
389
  return $element;
390
}
391

    
392
/**
393
 * Implements _webform_display_component().
394
 */
395
function _webform_display_number($component, $value, $format = 'html', $submission = array()) {
396
  $empty = !isset($value[0]) || $value[0] === '';
397
  return array(
398
    '#title' => $component['name'],
399
    '#title_display' => $component['extra']['title_display'] ? $component['extra']['title_display'] : 'before',
400
    '#weight' => $component['weight'],
401
    '#theme' => 'webform_display_number',
402
    '#theme_wrappers' => $format == 'html' ? array('webform_element') : array('webform_element_text'),
403
    '#field_prefix' => $empty ? '' : $component['extra']['field_prefix'],
404
    '#field_suffix' => $empty ? '' : $component['extra']['field_suffix'],
405
    '#format' => $format,
406
    '#value' => $empty ? '' : _webform_number_format($component, $value[0]),
407
    '#translatable' => array('title', 'placeholder'),
408
  );
409
}
410

    
411
/**
412
 * Format the output of data for this component.
413
 */
414
function theme_webform_display_number($variables) {
415
  $element = $variables['element'];
416
  $prefix = $element['#format'] == 'html' ? '' : $element['#field_prefix'];
417
  $suffix = $element['#format'] == 'html' ? '' : $element['#field_suffix'];
418
  $value = $element['#format'] == 'html' ? check_plain($element['#value']) : $element['#value'];
419
  return $value !== '' ? ($prefix . $value . $suffix) : ' ';
420
}
421

    
422
/**
423
 * Implements _webform_analysis_component().
424
 */
425
function _webform_analysis_number($component, $sids = array(), $single = FALSE, $join = NULL) {
426
  $advanced_stats = $single;
427

    
428
  $query = db_select('webform_submitted_data', 'wsd', array('fetch' => PDO::FETCH_ASSOC))
429
    ->fields('wsd', array('data'))
430
    ->condition('wsd.nid', $component['nid'])
431
    ->condition('wsd.cid', $component['cid']);
432

    
433
  if (count($sids)) {
434
    $query->condition('wsd.sid', $sids, 'IN');
435
  }
436

    
437
  if ($join) {
438
    $query->innerJoin($join, 'ws2_', 'wsd.sid = ws2_.sid');
439
  }
440

    
441
  $population = array();
442
  $submissions = 0;
443
  $non_zero = 0;
444
  $non_empty = 0;
445
  $sum = 0;
446

    
447
  $result = $query->execute();
448
  foreach ($result as $data) {
449
    $value = trim($data['data']);
450
    $number = (float) $value;
451
    $non_empty += (integer) ($value !== '');
452
    $non_zero += (integer) ($number != 0.0);
453
    $sum += $number;
454
    $population[] = $number;
455
    $submissions++;
456
  }
457
  sort($population, SORT_NUMERIC);
458

    
459
  // Average and population count.
460
  if ($component['extra']['excludezero']) {
461
    $average = $non_zero ? ($sum / $non_zero) : 0;
462
    $average_title = t('Average !mu excluding zeros/blanks', array('!mu' => $advanced_stats ? '(&mu;)' : ''));
463
    // Sample (sub-set of total population).
464
    $population_count = $non_zero - 1;
465
    $sigma = 'sd';
466
    $description = t('sample');
467
  }
468
  else {
469
    $average = $submissions ? ($sum / $submissions) : 0;
470
    $average_title = t('Average !mu including zeros/blanks', array('!mu' => $advanced_stats ? '(&mu;)' : ''));
471
    // Population.
472
    $population_count = $submissions;
473
    $sigma = '&sigma;';
474
    $description = t('population');
475
  }
476

    
477
  // Formatting.
478
  $average = _webform_number_format($component, $average);
479
  $sum = _webform_number_format($component, $sum);
480

    
481
  $rows[] = array(t('Zero/blank'), ($submissions - $non_zero));
482
  $rows[] = array(t('User entered value'), $non_empty);
483

    
484
  $other[] = array(t('Sum') . ($advanced_stats ? ' (&Sigma;)' : ''), $sum);
485
  $other[] = array($average_title, $average);
486

    
487
  if (!$advanced_stats && $sum != 0) {
488
    $other[] = l(t('More stats ยป'), 'node/' . $component['nid'] . '/webform-results/analysis/' . $component['cid']);
489
  }
490

    
491
  // Normal distribution information.
492
  if ($advanced_stats && $population_count && $sum != 0) {
493
    // Standard deviation.
494
    $stddev = 0;
495
    foreach ($population as $value) {
496
      // Obtain the total of squared variances.
497
      $stddev += pow(($value - $average), 2);
498
    }
499
    if ($population_count > 0) {
500
      $stddev = sqrt($stddev / $population_count);
501
    }
502
    else {
503
      $stddev = sqrt($stddev);
504
    }
505

    
506
    // Skip the rest of the distribution rows if standard deviation is 0.
507
    if (empty($stddev)) {
508
      return array(
509
        'table_rows' => $rows,
510
        'other_data' => $other,
511
      );
512
    }
513

    
514
    // Build normal distribution table rows.
515
    $count = array();
516
    $percent = array();
517
    $limit = array();
518
    $index = 0;
519

    
520
    $count[] = 0;
521
    $limit[] = $average - ($stddev * 4);
522
    foreach ($population as $value) {
523
      while ($value >= $limit[$index]) {
524
        $percent[] = number_format($count[$index] / $population_count * 100, 2, '.', '');
525
        $limit[] = $limit[$index] + $stddev;
526
        $index += 1;
527
        if ($limit[$index] == $average) {
528
          $limit[$index] = $limit[$index] + $stddev;
529
        }
530
        $count[$index] = 0;
531
      }
532
      $count[$index] += 1;
533
    }
534
    $percent[] = number_format($count[$index] / $population_count * 100, 2, '.', '');
535

    
536
    // Format normal distribution table output.
537
    $stddev = _webform_number_format($component, $stddev);
538
    $low = _webform_number_format($component, $population[0]);
539
    $high = _webform_number_format($component, end($population));
540
    foreach ($limit as $key => $value) {
541
      $limit[$key] = _webform_number_format($component, $value);
542
    }
543

    
544
    // Column headings (override potential theme uppercase, for example, Seven in D7).
545
    $header = array(
546
      t('Normal Distribution'),
547
      array('data' => '-4' . $sigma, 'style' => 'text-transform: lowercase;'),
548
      array('data' => '-3' . $sigma, 'style' => 'text-transform: lowercase;'),
549
      array('data' => '-2' . $sigma, 'style' => 'text-transform: lowercase;'),
550
      array('data' => '-1' . $sigma, 'style' => 'text-transform: lowercase;'),
551
      array('data' => '+1' . $sigma, 'style' => 'text-transform: lowercase;'),
552
      array('data' => '+2' . $sigma, 'style' => 'text-transform: lowercase;'),
553
      array('data' => '+3' . $sigma, 'style' => 'text-transform: lowercase;'),
554
      array('data' => '+4' . $sigma, 'style' => 'text-transform: lowercase;'),
555
    );
556

    
557
    // Insert row labels.
558
    array_unshift($limit, t('Boundary'));
559
    array_unshift($count, t('Count'));
560
    array_unshift($percent, t('% of !description', array('!description' => $description)));
561

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

    
564
    $other[] = array(t('Range'), t('!low to !high', array('!low' => $low, '!high' => $high)));
565
    $other[] = array(t('Standard deviation (!sigma)', array('!sigma' => $sigma)), $stddev);
566
    $other[] = $normal_distribution;
567
  }
568

    
569
  return array(
570
    'table_rows' => $rows,
571
    'other_data' => $other,
572
  );
573
}
574

    
575
/**
576
 * Implements _webform_table_component().
577
 */
578
function _webform_table_number($component, $value) {
579
  return isset($value[0]) ? _webform_number_format($component, $value[0]) : '';
580
}
581

    
582
/**
583
 * Implements _webform_action_set_component().
584
 */
585
function _webform_action_set_number($component, &$element, &$form_state, $value) {
586
  $element['#value'] = $value;
587
  form_set_value($element, $value, $form_state);
588
}
589

    
590
/**
591
 * Implements _webform_csv_headers_component().
592
 */
593
function _webform_csv_headers_number($component, $export_options) {
594
  $header = array();
595
  $header[0] = '';
596
  $header[1] = '';
597
  $header[2] = $export_options['header_keys'] ? $component['form_key'] : $component['name'];
598
  return $header;
599
}
600

    
601
/**
602
 * Implements _webform_csv_data_component().
603
 */
604
function _webform_csv_data_number($component, $export_options, $value) {
605
  if (isset($value[0]) && is_numeric($value[0]) && $component['extra']['decimals'] !== '') {
606
    $value[0] = number_format($value[0], $component['extra']['decimals'], '.', '');
607
  }
608
  return isset($value[0]) ? $value[0] : '';
609
}
610

    
611
/**
612
 * A Drupal Form API Validation function.
613
 *
614
 * Validates the entered values from number components on the client-side form.
615
 *
616
 * @param array $element
617
 *   The form element. May either be a select or a webform_number element.
618
 * @param array $form_state
619
 *   The full form state for the webform.
620
 */
621
function _webform_validate_number($element, &$form_state) {
622
  // Trim spaces for basic cleanup.
623
  $value = trim($element['#value']);
624
  form_set_value($element, $value, $form_state);
625

    
626
  if ($value != '') {
627
    // First check that the entered value matches the expected value.
628
    if (!webform_number_format_match($value, $element['#point'], $element['#separator'])) {
629
      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']))));
630
      return;
631
    }
632

    
633
    // Numeric test.
634
    $numeric_value = webform_number_standardize($value, $element['#point']);
635
    if (is_numeric($numeric_value)) {
636
      // Range test.
637
      if ($element['#min'] != '' && $element['#max'] != '') {
638
        // Flip minimum and maximum if needed.
639
        if ($element['#max'] > $element['#min']) {
640
          $min = $element['#min'];
641
          $max = $element['#max'];
642
        }
643
        else {
644
          $min = $element['#max'];
645
          $max = $element['#min'];
646
        }
647
        if ($numeric_value > $max || $numeric_value < $min) {
648
          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'])));
649
        }
650
      }
651
      elseif ($element['#max'] != '' && $numeric_value > $element['#max']) {
652
        form_error($element, t('!name field value must be less than @max.', array('!name' => $element['#title'], '@max' => $element['#max'])));
653
      }
654
      elseif ($element['#min'] != '' && $numeric_value < $element['#min']) {
655
        form_error($element, t('!name field value must be greater than @min.', array('!name' => $element['#title'], '@min' => $element['#min'])));
656
      }
657

    
658
      // Integer test.
659
      if ($element['#integer'] && filter_var((float) $numeric_value, FILTER_VALIDATE_INT) === FALSE) {
660
        form_error($element, t('!name field value of @value must be an integer.', array('!name' => $element['#title'], '@value' => $value)));
661
      }
662

    
663
      // Step test.
664
      $starting_number = $element['#min'] ? $element['#min'] : 0;
665
      if ($element['#step'] != 0 && webform_modulo($numeric_value - $starting_number, $element['#step']) != 0.0) {
666
        $samples = array(
667
          $starting_number,
668
          $starting_number + ($element['#step'] * 1),
669
          $starting_number + ($element['#step'] * 2),
670
          $starting_number + ($element['#step'] * 3),
671
        );
672
        if ($starting_number) {
673
          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))));
674
        }
675
        else {
676
          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))));
677
        }
678
      }
679
    }
680
    else {
681
      form_error($element, t('!name field value of @value must be numeric.', array('!name' => $element['#title'], '@value' => $value)));
682
    }
683
  }
684
}
685

    
686
/**
687
 * Implements _webform_submit_component().
688
 */
689
function _webform_submit_number($component, $value) {
690
  // Because _webform_validate_number() ensures the format matches when moving
691
  // forward through a form, this should always pass before saving into the
692
  // database. When moving backwards in a form, do not adjust the value, since
693
  // it has not yet been validated.
694
  if (webform_number_format_match($value, $component['extra']['point'], $component['extra']['separator'])) {
695
    $value = webform_number_standardize($value, $component['extra']['point']);
696
  }
697
  return $value;
698
}
699

    
700
/**
701
 * Validation of number edit form items.
702
 */
703
function _webform_edit_number_validate($element, &$form_state) {
704
  // Find the value of all related fields to this element.
705
  $parents = $element['#parents'];
706
  $key = array_pop($parents);
707
  $values = $form_state['values'];
708
  foreach ($parents as $parent) {
709
    $values = $values[$parent];
710
  }
711

    
712
  switch ($key) {
713
    case 'min':
714
      if ($values['min'] == '') {
715
        if (isset($values['type']) && $values['type'] === 'select') {
716
          form_error($element, t('Minimum is required when using a select list element.'));
717
        }
718
      }
719
      else {
720
        if (!is_numeric($values['min'])) {
721
          form_error($element, t('Minimum must be numeric.'));
722
        }
723
        if ($values['integer'] && filter_var((float) $values['min'], FILTER_VALIDATE_INT) === FALSE) {
724
          form_error($element, t('Minimum must have an integer value.'));
725
        }
726
      }
727
      break;
728

    
729
    case 'max':
730
      if ($values['max'] == '') {
731
        if (isset($values['type']) && $values['type'] === 'select') {
732
          form_error($element, t('Maximum is required when using a select list element.'));
733
        }
734
      }
735
      else {
736
        if (!is_numeric($values['max'])) {
737
          form_error($element, t('Maximum must be numeric.'));
738
        }
739
        if ($values['integer'] && filter_var((float) $values['max'], FILTER_VALIDATE_INT) === FALSE) {
740
          form_error($element, t('Maximum must have an integer value.'));
741
        }
742
      }
743
      break;
744

    
745
    case 'step':
746
      if ($values['step'] !== '') {
747
        if (!is_numeric($values['step'])) {
748
          form_error($element, t('Step must be numeric.'));
749
        }
750
        else {
751
          if ($values['integer'] && filter_var((float) $values['step'], FILTER_VALIDATE_INT) === FALSE) {
752
            form_error($element, t('Step must have an integer value.'));
753
          }
754
        }
755
      }
756
      break;
757
  }
758
  return TRUE;
759
}
760

    
761
/**
762
 * Generate select list options.
763
 */
764
function _webform_number_select_options($component) {
765
  $options = array();
766
  $step = abs($component['extra']['step']);
767

    
768
  // Step is optional and defaults to 1.
769
  $step = empty($step) ? 1 : $step;
770

    
771
  // Generate list in correct direction.
772
  $min = $component['extra']['min'];
773
  $max = $component['extra']['max'];
774
  $flipped = FALSE;
775
  if ($max < $min) {
776
    $min = $component['extra']['max'];
777
    $max = $component['extra']['min'];
778
    $flipped = TRUE;
779
  }
780

    
781
  for ($f = $min; $f <= $max; $f += $step) {
782
    $options[$f . ''] = $f . '';
783
  }
784

    
785
  // @todo: HTML5 browsers apparently do not include the max value if it does
786
  // not line up with step. Restore this if needed in the future.
787
  // Add end limit if it's been skipped due to step.
788
  // @code
789
  // if (end($options) != $max) {
790
  //   $options[$f] = $max;
791
  // }
792
  // @endcode
793
  if ($flipped) {
794
    $options = array_reverse($options, TRUE);
795
  }
796

    
797
  // Apply requisite number formatting.
798
  foreach ($options as $key => $value) {
799
    $options[$key] = _webform_number_format($component, $value);
800
  }
801

    
802
  return $options;
803
}
804

    
805
/**
806
 * Apply number format based on a component and number value.
807
 */
808
function _webform_number_format($component, $value) {
809
  return webform_number_format($value, $component['extra']['decimals'], $component['extra']['point'], $component['extra']['separator']);
810
}
811

    
812
/**
813
 * Validates if a provided number string matches an expected format.
814
 *
815
 * This function allows the thousands separator to be optional, but decimal
816
 * points must be in the right location.
817
 *
818
 * A valid number is:
819
 *   1. optional minus sign.
820
 *   2. optional space.
821
 *   3. the rest of the string can't be just a decimal or blank.
822
 *   4. optional integer portion, with thousands separators.
823
 *   5. optional decimal portion, starting is a decimal separator.
824
 * Don't use preg_quote because a space is a valid thousands separator and
825
 * needs quoting for the 'x' option to preg_match.
826
 *
827
 * Based on http://stackoverflow.com/questions/5917082/regular-expression-to-match-numbers-with-or-without-commas-and-decimals-in-text.
828
 */
829
function webform_number_format_match($value, $point, $separator) {
830
  $thousands = $separator ? "\\$separator?" : '';
831
  $decimal = "\\$point";
832
  return preg_match("/
833
                    ^               # Start of string
834
                    -?              # Optional minus sign
835
                    \ ?             # Optional space
836
                    (?!\.?$)        # Assert looking ahead, not just a decimal or nothing
837
                      (?:           # Interger portion (non-grouping)
838
                        \d{1,3}     #   1 to 3 digits
839
                        (?:         #   Thousands group(s)
840
                        $thousands  #     Optional thousands separator
841
                        \d{2,3}     #     2 or 3 digits. Some countries use groups of 2 sometimes
842
                      )*            #   0 or more of these thousands groups
843
                    )?              # End of optional integer portion
844
                    (?:             # Decimal portion (non-grouping)
845
                      $decimal      #   Decimal point
846
                      \d*           #   0 or more digits
847
                    )?              # End of optional decimal portion
848
                    $
849
                    /x", $value);
850
}
851

    
852
/**
853
 * Format a number with thousands separator, decimal point, and decimal places.
854
 *
855
 * This function is a wrapper around PHP's native number_format(), but allows
856
 * the decimal places parameter to be NULL or an empty string, resulting in a
857
 * behavior of no change to the decimal places.
858
 */
859
function webform_number_format($value, $decimals = NULL, $point = '.', $separator = ',') {
860
  if (!is_numeric($value)) {
861
    return '';
862
  }
863

    
864
  // If no decimal places are specified, do a best guess length of decimals.
865
  if (is_null($decimals) || $decimals === '') {
866
    // If it's an integer, no decimals needed.
867
    if (filter_var((float) $value, FILTER_VALIDATE_INT) !== FALSE) {
868
      $decimals = 0;
869
    }
870
    else {
871
      $decimals = strlen($value) - strrpos($value, '.') - 1;
872
    }
873
    if ($decimals > 4) {
874
      $decimals = 4;
875
    }
876
  }
877

    
878
  return number_format($value, $decimals, $point, $separator);
879
}
880

    
881
/**
882
 * Given a number, convert it to string compatible with a PHP float.
883
 *
884
 * @param string $value
885
 *   The string value to be standardized into a numeric string.
886
 * @param string $point
887
 *   The point separator between the whole number and the decimals.
888
 *
889
 * @return string
890
 *   The converted number.
891
 */
892
function webform_number_standardize($value, $point) {
893
  // For simplicity, strip everything that's not the decimal point.
894
  $value = preg_replace('/[^\-0-9' . preg_quote($point, '/') . ']/', '', $value);
895
  // Convert the decimal point to a period.
896
  $value = str_replace($point, '.', $value);
897
  return $value;
898
}
899

    
900
/**
901
 * Custom modulo function that properly handles float division.
902
 *
903
 * See https://drupal.org/node/1601968.
904
 */
905
function webform_modulo($a, $b) {
906
  $modulo = $a - $b * (($b < 0) ? ceil($a / $b) : floor($a / $b));
907
  if (webform_compare_floats($modulo, 0.0) == 0 || webform_compare_floats($modulo, $b) == 0) {
908
    $modulo = 0.0;
909
  }
910
  return $modulo;
911
}
912

    
913
/**
914
 * Compare two floats.
915
 *
916
 * See @link http://php.net/manual/en/language.types.float.php @endlink.
917
 *
918
 * Comparison of floating point numbers for equality is surprisingly difficult,
919
 * as evidenced by the references below. The simple test in this function works
920
 * for numbers that are relatively close to 1E1. For very small numbers, it will
921
 * show false equality. For very large numbers, it will show false inequality.
922
 * Better implementations are hidered by the absense of PHP platform-specific
923
 * floating point constants to properly set the minimum absolute and relative
924
 * error in PHP.
925
 *
926
 * The use case for webform conditionals excludes very small or very large
927
 * numeric comparisons.
928
 *
929
 * See @link http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm @endlink
930
 * See @link http://floating-point-gui.de/errors/comparison/ @endlink
931
 * See @link http://en.wikipedia.org/wiki/IEEE_754-1985#Denormalized_numbers @endlink
932
 *
933
 * @param float $number_1
934
 *   The first number.
935
 * @param float $number_2
936
 *   The second number.
937
 *
938
 * @return int|null
939
 *   < 0 if number_1 is less than number_2; > 0 if number_1 is greater than
940
 *   number_2, 0 if they are equal, and NULL if either is not numeric.
941
 */
942
function webform_compare_floats($number_1, $number_2) {
943
  if (!is_numeric($number_1) || !is_numeric($number_2)) {
944
    return NULL;
945
  }
946

    
947
  $number_1 = (float) $number_1;
948
  $number_2 = (float) $number_2;
949

    
950
  $epsilon = 0.000001;
951
  if (abs($number_1 - $number_2) < $epsilon) {
952
    return 0;
953
  }
954
  elseif ($number_1 > $number_2) {
955
    return 1;
956
  }
957
  else {
958
    return -1;
959
  }
960
}