Projet

Général

Profil

Paste
Télécharger (25,1 ko) Statistiques
| Branche: | Révision:

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

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
    'mandatory' => 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
      'min' => '',
30
      'max' => '',
31
      'step' => '',
32
      'decimals' => '',
33
      'point' => '.',
34
      'separator' => ',',
35
      'integer' => 0,
36
      'excludezero' => 0,
37
    ),
38
  );
39
}
40

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

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

    
219
/**
220
 * Theme function to render a number component.
221
 */
222
function theme_webform_number($variables) {
223
  $element = $variables['element'];
224

    
225
  // This IF statement is mostly in place to allow our tests to set type="text"
226
  // because SimpleTest does not support type="number".
227
  if (!isset($element['#attributes']['type'])) {
228
    $element['#attributes']['type'] = 'number';
229
  }
230

    
231
  // Step property *must* be a full number with 0 prefix if a decimal.
232
  if (!empty($element['#step']) && !is_int($element['#step'] * 1)) {
233
    $decimals = strlen($element['#step']) - strrpos($element['#step'], '.') - 1;
234
    $element['#step'] = sprintf('%1.' . $decimals . 'F', $element['#step']);
235
  }
236

    
237
  // If the number is not an integer and step is undefined/empty, set the "any"
238
  // value to allow any decimal.
239
  if (empty($element['#integer']) && empty($element['#step'])) {
240
    $element['#step'] = 'any';
241
  }
242
  elseif ($element['#integer'] && empty($element['#step'])) {
243
    $element['#step'] = 1;
244
  }
245

    
246
  // Convert properties to attributes on the element if set.
247
  foreach (array('id', 'name', 'value', 'size', 'min', 'max', 'step') as $property) {
248
    if (isset($element['#' . $property]) && $element['#' . $property] !== '') {
249
      $element['#attributes'][$property] = $element['#' . $property];
250
    }
251
  }
252
  _form_set_class($element, array('form-text', 'form-number'));
253

    
254
  return '<input' . drupal_attributes($element['#attributes']) . ' />';
255
}
256

    
257
/**
258
 * Implements _webform_render_component().
259
 */
260
function _webform_render_number($component, $value = NULL, $filter = TRUE) {
261
  $node = isset($component['nid']) ? node_load($component['nid']) : NULL;
262

    
263
  $element = array(
264
    '#title' => $filter ? _webform_filter_xss($component['name']) : $component['name'],
265
    '#title_display' => $component['extra']['title_display'] ? $component['extra']['title_display'] : 'before',
266
    '#default_value' => $filter ? _webform_filter_values($component['value'], $node, NULL, NULL, FALSE) : $component['value'],
267
    '#required' => $component['mandatory'],
268
    '#weight' => $component['weight'],
269
    '#field_prefix' => empty($component['extra']['field_prefix']) ? NULL : ($filter ? _webform_filter_xss($component['extra']['field_prefix']) : $component['extra']['field_prefix']),
270
    '#field_suffix' => empty($component['extra']['field_suffix']) ? NULL : ($filter ? _webform_filter_xss($component['extra']['field_suffix']) : $component['extra']['field_suffix']),
271
    '#description' => $filter ? _webform_filter_descriptions($component['extra']['description'], $node) : $component['extra']['description'],
272
    '#attributes' => $component['extra']['attributes'],
273
    '#element_validate' => array('_webform_validate_number'),
274
    '#theme_wrappers' => array('webform_element'),
275
    '#min' => $component['extra']['min'],
276
    '#max' => $component['extra']['max'],
277
    '#step' => $component['extra']['step'] ? abs($component['extra']['step']) : '',
278
    '#integer' => $component['extra']['integer'],
279
    '#translatable' => array('title', 'description'),
280
  );
281

    
282
  // Flip the min and max properties to make min less than max if needed.
283
  if ($element['#min'] !== '' && $element['#max'] !== '' && $element['#min'] > $element['#max']) {
284
    $max = $element['#min'];
285
    $element['#min'] = $element['#max'];
286
    $element['#max'] = $max;
287
  }
288

    
289
  // Ensure #step starts with a zero if a decimal.
290
  if (!is_int($element['#step'] * 1)) {
291
    $decimals = strlen($element['#step']) - strrpos($element['#step'], '.') - 1;
292
    $element['#step'] = sprintf('%1.' . $decimals . 'F', $element['#step']);
293
  }
294

    
295
  if ($component['extra']['type'] == 'textfield') {
296
    // Render as textfield.
297
    $element['#type'] = 'webform_number';
298

    
299
    // Set the size property based on #max, to ensure consistent behavior for
300
    // browsers that do not support type = number.
301
    if ($element['#max']) {
302
      $element['#size'] =  strlen($element['#max']) + 1;
303
    }
304
  }
305
  else {
306
    // Render as select.
307
    $element['#type'] = 'select';
308

    
309
    // Create user-specified options list as an array.
310
    $element['#options'] = _webform_number_select_options($component);
311

    
312
    // Add default options if using a select list with no default. This trigger's
313
    // Drupal 7's adding of the option for us. See form_process_select().
314
    if ($component['extra']['type'] == 'select' && $element['#default_value'] === '') {
315
      $element['#empty_value'] = '';
316
    }
317
  }
318

    
319
  // Set user-entered values.
320
  if (isset($value[0])) {
321
    $element['#default_value'] = $value[0];
322
  }
323

    
324
  // Enforce uniqueness.
325
  if ($component['extra']['unique']) {
326
    $element['#element_validate'][] = 'webform_validate_unique';
327
  }
328

    
329
  // Set readonly if disabled.
330
  if ($component['extra']['disabled']) {
331
    if ($filter) {
332
      $element['#attributes']['readonly'] = 'readonly';
333
    }
334
    else {
335
      $element['#disabled'] = TRUE;
336
    }
337
  }
338

    
339
  return $element;
340
}
341

    
342
/**
343
 * Implements _webform_display_component().
344
 */
345
function _webform_display_number($component, $value, $format = 'html') {
346
  $empty = !isset($value[0]) || $value[0] === '';
347
  return array(
348
    '#title' => $component['name'],
349
    '#weight' => $component['weight'],
350
    '#theme' => 'webform_display_number',
351
    '#theme_wrappers' => $format == 'html' ? array('webform_element') : array('webform_element_text'),
352
    '#field_prefix' => $empty ? '' : $component['extra']['field_prefix'],
353
    '#field_suffix' => $empty ? '' : $component['extra']['field_suffix'],
354
    '#format' => $format,
355
    '#value' => $empty ? '' : _webform_number_format($component, $value[0]),
356
    '#translatable' => array('title'),
357
  );
358
}
359

    
360
/**
361
 * Format the output of data for this component.
362
 */
363
function theme_webform_display_number($variables) {
364
  $element = $variables['element'];
365
  $prefix = $element['#format'] == 'html' ? '' : $element['#field_prefix'];
366
  $suffix = $element['#format'] == 'html' ? '' : $element['#field_suffix'];
367
  $value = $element['#format'] == 'html' ? check_plain($element['#value']) : $element['#value'];
368
  return $value !== '' ? ($prefix . $value . $suffix) : ' ';
369
}
370

    
371
/**
372
 * Implements _webform_analysis_component().
373
 */
374
function _webform_analysis_number($component, $sids = array(), $single = FALSE) {
375
  $advanced_stats = $single;
376

    
377
  $query = db_select('webform_submitted_data', 'wsd', array('fetch' => PDO::FETCH_ASSOC))
378
    ->fields('wsd', array('data'))
379
    ->condition('nid', $component['nid'])
380
    ->condition('cid', $component['cid']);
381

    
382
  if (count($sids)) {
383
    $query->condition('sid', $sids, 'IN');
384
  }
385

    
386
  $population = array();
387
  $submissions = 0;
388
  $nonzero = 0;
389
  $not_empty = 0;
390
  $sum = 0;
391

    
392
  $result = $query->execute();
393
  foreach ($result as $data) {
394
    $value = trim($data['data']);
395
    if ($value == '') {
396
      $number = 0.0;
397
    }
398
    else {
399
      $number = $value * 1.0;
400
    }
401

    
402
    if ($value !== '') {
403
      $not_empty++;
404
    }
405

    
406
    if ($number > 0) {
407
      $nonzero++;
408
      $sum += $number;
409
    }
410
    $population[] = $number;
411
    $submissions++;
412
  }
413
  sort($population, SORT_NUMERIC);
414

    
415
  // Average and population count.
416
  if ($component['extra']['excludezero']) {
417
    $average = $nonzero ? ($sum / $nonzero) : 0;
418
    $average_title = t('Average !mu excluding zeros/blanks', array('!mu' => $advanced_stats ? '(&mu;)' : ''));
419
    // Sample (sub-set of total population).
420
    $population_count = $nonzero - 1;
421
    $sigma = 'sd';
422
    $description = t('sample');
423
  }
424
  else {
425
    $average = $submissions ? ($sum / $submissions) : 0;
426
    $average_title = t('Average !mu including zeros/blanks', array('!mu' => $advanced_stats ? '(&mu;)' : ''));
427
    // Population.
428
    $population_count = $submissions;
429
    $sigma = '&sigma;';
430
    $description = t('population');
431
  }
432

    
433
  // Formatting.
434
  $average = _webform_number_format($component, $average);
435
  $sum = _webform_number_format($component, $sum);
436

    
437
  $rows[0] = array(t('Zero/blank'), ($submissions - $nonzero));
438
  $rows[1] = array(t('User entered value'), $not_empty);
439
  $rows[2] = array(t('Sum') . ($advanced_stats ? ' (&Sigma;)' : ''), $sum);
440
  $rows[3] = array($average_title, $average);
441

    
442
  if (!$advanced_stats && $sum != 0) {
443
    $rows[4] = array('', l(t('More stats »'), 'node/' . $component['nid'] . '/webform-results/analysis/' . $component['cid']));
444
  }
445

    
446
  // Normal distribution information.
447
  if ($advanced_stats && $population_count && $sum != 0) {
448
    // Standard deviation.
449
    $stddev = 0;
450
    foreach($population as $value) {
451
      // Obtain the total of squared variances.
452
      $stddev += pow(($value - $average), 2);
453
    }
454
    if ($population_count > 0) {
455
      $stddev = sqrt($stddev / $population_count);
456
    }
457
    else {
458
      $stddev = sqrt($stddev);
459
    }
460

    
461
    // Skip the rest of the distribution rows if standard deviation is 0.
462
    if (empty($stddev)) {
463
      return $rows;
464
    }
465

    
466
    // Build normal distribution table rows.
467
    $count = array();
468
    $percent = array();
469
    $limit = array();
470
    $index = 0;
471

    
472
    $count[] = 0;
473
    $limit[] = $average - ($stddev * 4);
474
    foreach ($population as $value) {
475
      while ($value >= $limit[$index]) {
476
        $percent[] = number_format($count[$index] / $population_count * 100, 2, '.', '');
477
        $limit[] = $limit[$index] + $stddev;
478
        $index += 1;
479
        if ($limit[$index] == $average) {
480
          $limit[$index] = $limit[$index] + $stddev;
481
        }
482
        $count[$index] = 0;
483
      }
484
      $count[$index] += 1;
485
    }
486
    $percent[] = number_format($count[$index] / $population_count * 100, 2, '.', '');
487

    
488
    // Format normal distribution table output.
489
    $stddev = _webform_number_format($component, $stddev);
490
    $low = _webform_number_format($component, $population[0]);
491
    $high = _webform_number_format($component, end($population));
492
    foreach($limit as $key => $value) {
493
      $limit[$key] = _webform_number_format($component, $value);
494
    }
495

    
496
    // Column headings (override potential theme uppercase, e.g. Seven in D7).
497
    $header = array(
498
      t('Normal Distribution'),
499
      array('data' => '-4' . $sigma, 'style' => 'text-transform: lowercase;',),
500
      array('data' => '-3' . $sigma, 'style' => 'text-transform: lowercase;',),
501
      array('data' => '-2' . $sigma, 'style' => 'text-transform: lowercase;',),
502
      array('data' => '-1' . $sigma, 'style' => 'text-transform: lowercase;',),
503
      array('data' => '+1' . $sigma, 'style' => 'text-transform: lowercase;',),
504
      array('data' => '+2' . $sigma, 'style' => 'text-transform: lowercase;',),
505
      array('data' => '+3' . $sigma, 'style' => 'text-transform: lowercase;',),
506
      array('data' => '+4' . $sigma, 'style' => 'text-transform: lowercase;',),
507
    );
508

    
509
    // Insert row labels.
510
    array_unshift($limit, t('Boundary'));
511
    array_unshift($count, t('Count'));
512
    array_unshift($percent, t('% of !description', array('!description' => $description)));
513

    
514
    $output = theme('table', array('header' => $header, 'rows' => array($limit, $count, $percent)));
515

    
516
    $rows[4] = array(t('Range'), t('!low to !high', array('!low' => $low, '!high' => $high)));
517
    $rows[5] = array(t('Standard deviation (!sigma)', array('!sigma' => $sigma)), $stddev);
518
    $rows[6] = array(array('data' => $output, 'colspan' => 2));
519
  }
520

    
521
  return $rows;
522
}
523

    
524
/**
525
 * Implements _webform_table_component().
526
 */
527
function _webform_table_number($component, $value) {
528
  return isset($value[0]) ? _webform_number_format($component, $value[0]) : '';
529
}
530

    
531
/**
532
 * Implements _webform_csv_headers_component().
533
 */
534
function _webform_csv_headers_number($component, $export_options) {
535
  $header = array();
536
  $header[0] = '';
537
  $header[1] = '';
538
  $header[2] = $component['name'];
539
  return $header;
540
}
541

    
542
/**
543
 * Implements _webform_csv_data_component().
544
 */
545
function _webform_csv_data_number($component, $export_options, $value) {
546
  if (isset($value[0]) && is_numeric($value[0]) && $component['extra']['decimals'] !== '') {
547
    $value[0] = number_format($value[0], $component['extra']['decimals'], '.', '');
548
  }
549
  return isset($value[0]) ? $value[0] : '';
550
}
551

    
552
/**
553
 * A Drupal Form API Validation function. Validates the entered values from
554
 * number components on the client-side form.
555
 *
556
 * @param $element
557
 *   The form element. May either be a select or a webform_number element.
558
 * @param $form_state
559
 *   The full form state for the webform.
560
 * @return
561
 *   None. Calls a form_set_error if the number is not valid.
562
 */
563
function _webform_validate_number($element, &$form_state) {
564
  $value = trim($element['#value']);
565
  form_set_value($element, $value, $form_state);
566

    
567
  if ($value != '') {
568
    // Numeric test.
569
    if (is_numeric($value)) {
570
      // Range test.
571
      if ($element['#min'] != '' && $element['#max'] != '') {
572
        // Flip minimum and maximum if needed.
573
        if ($element['#max'] > $element['#min']) {
574
          $min = $element['#min'];
575
          $max = $element['#max'];
576
        }
577
        else {
578
          $min = $element['#max'];
579
          $max = $element['#min'];
580
        }
581
        if ($value > $max || $value < $min) {
582
          form_error($element, t('%name field value of @value should be in the range @min to @max.', array('%name' => $element['#title'], '@value' => $value, '@min' => $min, '@max' => $max)));
583
        }
584
      }
585
      elseif ($element['#max'] != '' && $value > $element['#max']) {
586
        form_error($element, t('%name field value must be less than @max.', array('%name' => $element['#title'], '@max' => $element['#max'])));
587
      }
588
      elseif ($element['#min'] != '' && $value < $element['#min']) {
589
        form_error($element, t('%name field value must be greater than @min.', array('%name' => $element['#title'], '@min' => $element['#min'])));
590
      }
591

    
592
      // Integer test.
593
      if ($element['#integer'] && !is_int($value * 1)) {
594
        form_error($element, t('%name field value of @value must be an integer.', array('%name' => $element['#title'], '@value' => $value)));
595
      }
596

    
597
      // Step test.
598
      $starting_number = $element['#min'] ? $element['#min'] : 0;
599
      if ($element['#step'] != 0 && webform_modulo($element['#value'] - $starting_number, $element['#step']) != 0) {
600
        $samples = array(
601
          $starting_number,
602
          $starting_number + ($element['#step'] * 1),
603
          $starting_number + ($element['#step'] * 2),
604
          $starting_number + ($element['#step'] * 3),
605
        );
606
        if ($starting_number) {
607
          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))));
608
        }
609
        else {
610
          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))));
611
        }
612
      }
613
    }
614
    else {
615
      form_error($element, t('%name field value of @value must be numeric.', array('%name' => $element['#title'], '@value' => $value)));
616
    }
617
  }
618

    
619
}
620

    
621
/**
622
 * Validation of number edit form items.
623
 */
624
function _webform_edit_number_validate($element, &$form_state) {
625
  // Find the value of all related fields to this element.
626
  $parents = $element['#parents'];
627
  $key = array_pop($parents);
628
  $values = $form_state['values'];
629
  foreach ($parents as $parent) {
630
    $values = $values[$parent];
631
  }
632

    
633
  switch ($key) {
634
    case 'min':
635
      if ($values['min'] == '') {
636
        if (isset($values['type']) && $values['type'] === 'select') {
637
          form_error($element, t('Minimum is required when using a select list element.'));
638
        }
639
      }
640
      else {
641
        if (!is_numeric($values['min'])) {
642
          form_error($element, t('Minimum must be numeric.'));
643
        }
644
        if ($values['integer'] && !is_int($values['min'] * 1)) {
645
          form_error($element, t('Minimum must have an integer value.'));
646
        }
647
      }
648
      break;
649
    case 'max':
650
      if ($values['max'] == '') {
651
        if (isset($values['type']) && $values['type'] === 'select') {
652
          form_error($element, t('Maximum is required when using a select list element.'));
653
        }
654
      }
655
      else {
656
        if (!is_numeric($values['max'])) {
657
          form_error($element, t('Maximum must be numeric.'));
658
        }
659
        if ($values['integer'] && !is_int($values['max'] * 1)) {
660
          form_error($element, t('Maximum must have an integer value.'));
661
        }
662
      }
663
      break;
664
    case 'step':
665
      if ($values['step'] !== '') {
666
        if (!is_numeric($values['step'])) {
667
          form_error($element, t('Step must be numeric.'));
668
        }
669
        else {
670
          if ($values['integer'] && !is_int($values['step'] * 1)) {
671
            form_error($element, t('Step must have an integer value.'));
672
          }
673
        }
674
      }
675
      break;
676
  }
677
  return TRUE;
678
}
679

    
680
/**
681
 * Generate select list options.
682
 */
683
function _webform_number_select_options($component) {
684
  $options = array();
685
  $step = abs($component['extra']['step']);
686

    
687
  // Step is optional and defaults to 1.
688
  $step = empty($step) ? 1 : $step;
689

    
690
  // Generate list in correct direction.
691
  $min = $component['extra']['min'];
692
  $max = $component['extra']['max'];
693
  $flipped = FALSE;
694
  if ($max < $min) {
695
    $min = $component['extra']['max'];
696
    $max = $component['extra']['min'];
697
    $flipped = TRUE;
698
  }
699

    
700
  for ($f = $min; $f <= $max; $f += $step) {
701
    $options[$f . ''] = $f . '';
702
  }
703

    
704
  // TODO: HTML5 browsers apparently do not include the max value if it does
705
  // not line up with step. Restore this if needed in the future.
706
  // Add end limit if it's been skipped due to step.
707
  //if (end($options) != $max) {
708
  //  $options[$f] = $max;
709
  //}
710

    
711
  if ($flipped) {
712
    $options = array_reverse($options, TRUE);
713
  }
714

    
715
  // Apply requisite number formatting.
716
  foreach ($options as $key => $value) {
717
    $options[$key] = _webform_number_format($component, $value);
718
  }
719

    
720
  return $options;
721
}
722

    
723
/**
724
 * Apply number format.
725
 */
726
function _webform_number_format($component, $value) {
727
  if (!is_numeric($value)) {
728
    return '';
729
  }
730
  // If no decimal places are specified, do a best guess length of decimals.
731
  $decimals = $component['extra']['decimals'];
732
  if ($decimals === '') {
733
    // If it's an integer, no decimals needed.
734
    if (is_int(($value . '') * 1)) {
735
      $decimals = 0;
736
    }
737
    else {
738
      $decimals = strlen($value) - strrpos($value, '.') - 1;
739
    }
740
    if ($decimals > 4) {
741
      $decimals = 4;
742
    }
743
  }
744

    
745
  return number_format($value, $decimals, $component['extra']['point'], $component['extra']['separator']);
746
}
747

    
748
/**
749
 * Custom modulo function that properly handles float division.
750
 *
751
 * See https://drupal.org/node/1601968.
752
 */
753
function webform_modulo($a, $b) {
754
  return $a - $b * (($b < 0) ? ceil($a / $b) : floor($a / $b));
755
}