number.inc 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820
  1. <?php
  2. /**
  3. * @file
  4. * Webform module number component.
  5. */
  6. /**
  7. * Implements _webform_defaults_component().
  8. */
  9. function _webform_defaults_number() {
  10. return array(
  11. 'name' => '',
  12. 'form_key' => NULL,
  13. 'pid' => 0,
  14. 'weight' => 0,
  15. 'value' => '',
  16. 'mandatory' => 0,
  17. 'extra' => array(
  18. 'type' => 'textfield',
  19. 'field_prefix' => '',
  20. 'field_suffix' => '',
  21. 'disabled' => 0,
  22. 'unique' => 0,
  23. 'title_display' => 0,
  24. 'description' => '',
  25. 'attributes' => array(),
  26. 'private' => FALSE,
  27. 'min' => '',
  28. 'max' => '',
  29. 'step' => '',
  30. 'decimals' => '',
  31. 'point' => '.',
  32. 'separator' => ',',
  33. 'integer' => 0,
  34. 'excludezero' => 0,
  35. ),
  36. );
  37. }
  38. /**
  39. * Implements _webform_theme_component().
  40. */
  41. function _webform_theme_number() {
  42. return array(
  43. 'webform_number' => array(
  44. 'render element' => 'element',
  45. 'file' => 'components/number.inc',
  46. ),
  47. 'webform_display_number' => array(
  48. 'render element' => 'element',
  49. 'file' => 'components/number.inc',
  50. ),
  51. );
  52. }
  53. /**
  54. * Implements _webform_edit_component().
  55. */
  56. function _webform_edit_number($component) {
  57. $form = array();
  58. $form['value'] = array(
  59. '#type' => 'textfield',
  60. '#title' => t('Default value'),
  61. '#default_value' => $component['value'],
  62. '#description' => t('The default value of the field.') . theme('webform_token_help'),
  63. '#size' => 60,
  64. '#maxlength' => 1024,
  65. '#weight' => 0,
  66. );
  67. $form['display']['type'] = array(
  68. '#type' => 'radios',
  69. '#title' => t('Element type'),
  70. '#options' => array(
  71. 'textfield' => t('Text field'),
  72. 'select' => t('Select list'),
  73. ),
  74. '#default_value' => $component['extra']['type'],
  75. '#description' => t('A minimum and maximum value are required if displaying as a select.'),
  76. '#weight' => -1,
  77. '#parents' => array('extra', 'type'),
  78. );
  79. $form['display']['field_prefix'] = array(
  80. '#type' => 'textfield',
  81. '#title' => t('Prefix text placed to the left of the field'),
  82. '#default_value' => $component['extra']['field_prefix'],
  83. '#description' => t('Examples: $, #, -.'),
  84. '#size' => 20,
  85. '#maxlength' => 127,
  86. '#weight' => 1.1,
  87. '#parents' => array('extra', 'field_prefix'),
  88. );
  89. $form['display']['field_suffix'] = array(
  90. '#type' => 'textfield',
  91. '#title' => t('Postfix text placed to the right of the field'),
  92. '#default_value' => $component['extra']['field_suffix'],
  93. '#description' => t('Examples: lb, kg, %.'),
  94. '#size' => 20,
  95. '#maxlength' => 127,
  96. '#weight' => 1.2,
  97. '#parents' => array('extra', 'field_suffix'),
  98. );
  99. $form['display']['disabled'] = array(
  100. '#type' => 'checkbox',
  101. '#title' => t('Disabled'),
  102. '#return_value' => 1,
  103. '#description' => t('Make this field non-editable. Useful for setting an unchangeable default value.'),
  104. '#weight' => 11,
  105. '#default_value' => $component['extra']['disabled'],
  106. '#parents' => array('extra', 'disabled'),
  107. );
  108. $form['display']['decimals'] = array(
  109. '#type' => 'select',
  110. '#title' => t('Decimal places'),
  111. '#options' => array('' => t('Automatic')) + drupal_map_assoc(range(0, 10)),
  112. '#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')),
  113. '#default_value' => $component['extra']['decimals'],
  114. '#weight' => 2,
  115. '#parents' => array('extra', 'decimals'),
  116. '#element_validate' => array('_webform_edit_number_validate'),
  117. );
  118. $form['display']['separator'] = array(
  119. '#type' => 'select',
  120. '#title' => t('Thousands separator'),
  121. '#options' => array(
  122. ',' => t('Comma (,)'),
  123. '.' => t('Period (.)'),
  124. ' ' => t('Space ( )'),
  125. '' => t('None'),
  126. ),
  127. '#default_value' => $component['extra']['separator'],
  128. '#weight' => 3,
  129. '#parents' => array('extra', 'separator'),
  130. '#element_validate' => array('_webform_edit_number_validate'),
  131. );
  132. $form['display']['point'] = array(
  133. '#type' => 'select',
  134. '#title' => t('Decimal point'),
  135. '#options' => array(
  136. ',' => t('Comma (,)'),
  137. '.' => t('Period (.)'),
  138. ),
  139. '#default_value' => $component['extra']['point'],
  140. '#weight' => 4,
  141. '#parents' => array('extra', 'point'),
  142. '#element_validate' => array('_webform_edit_number_validate'),
  143. );
  144. $form['validation']['unique'] = array(
  145. '#type' => 'checkbox',
  146. '#title' => t('Unique'),
  147. '#return_value' => 1,
  148. '#description' => t('Check that all entered values for this field are unique. The same value is not allowed to be used twice.'),
  149. '#weight' => 1,
  150. '#default_value' => $component['extra']['unique'],
  151. '#parents' => array('extra', 'unique'),
  152. );
  153. $form['validation']['integer'] = array(
  154. '#type' => 'checkbox',
  155. '#title' => t('Integer'),
  156. '#return_value' => 1,
  157. '#description' => t('Permit only integer values as input. e.g. 12.34 would be invalid.'),
  158. '#weight' => 1.5,
  159. '#default_value' => $component['extra']['integer'],
  160. '#parents' => array('extra', 'integer'),
  161. );
  162. $form['validation']['min'] = array(
  163. '#type' => 'textfield',
  164. '#title' => t('Minimum'),
  165. '#default_value' => $component['extra']['min'],
  166. '#description' => t('Minimum numeric value. e.g. 0 would ensure positive numbers.'),
  167. '#size' => 5,
  168. '#maxlength' => 10,
  169. '#weight' => 2.1,
  170. '#parents' => array('extra', 'min'),
  171. '#element_validate' => array('_webform_edit_number_validate'),
  172. );
  173. $form['validation']['max'] = array(
  174. '#type' => 'textfield',
  175. '#title' => t('Maximum'),
  176. '#default_value' => $component['extra']['max'],
  177. '#description' => t('Maximum numeric value. This may also determine the display width of your field.'),
  178. '#size' => 5,
  179. '#maxlength' => 10,
  180. '#weight' => 2.2,
  181. '#parents' => array('extra', 'max'),
  182. '#element_validate' => array('_webform_edit_number_validate'),
  183. );
  184. $form['validation']['step'] = array(
  185. '#type' => 'textfield',
  186. '#title' => t('Step'),
  187. '#default_value' => $component['extra']['step'],
  188. '#description' => t('Limit options to a specific increment. e.g. a step of "5" would allow values 5, 10, 15, etc.'),
  189. '#size' => 5,
  190. '#maxlength' => 10,
  191. '#weight' => 3,
  192. '#parents' => array('extra', 'step'),
  193. '#element_validate' => array('_webform_edit_number_validate'),
  194. );
  195. // Analysis settings.
  196. $form['analysis'] = array(
  197. '#type' => 'fieldset',
  198. '#title' => t('Analysis'),
  199. '#collapsible' => TRUE,
  200. '#collapsed' => FALSE,
  201. '#weight' => 10,
  202. );
  203. $form['analysis']['excludezero'] = array(
  204. '#type' => 'checkbox',
  205. '#title' => t('Exclude zero'),
  206. '#return_value' => 1,
  207. '#description' => t('Exclude entries of zero (or blank) when counting submissions to calculate average and standard deviation.'),
  208. '#weight' => 1.5,
  209. '#default_value' => $component['extra']['excludezero'],
  210. '#parents' => array('extra', 'excludezero'),
  211. );
  212. return $form;
  213. }
  214. /**
  215. * Theme function to render a number component.
  216. */
  217. function theme_webform_number($variables) {
  218. $element = $variables['element'];
  219. // This IF statement is mostly in place to allow our tests to set type="text"
  220. // because SimpleTest does not support type="number".
  221. if (!isset($element['#attributes']['type'])) {
  222. $element['#attributes']['type'] = 'number';
  223. }
  224. // Step property *must* be a full number with 0 prefix if a decimal.
  225. if (!empty($element['#step']) && !is_int($element['#step'] * 1)) {
  226. $decimals = strlen($element['#step']) - strrpos($element['#step'], '.') - 1;
  227. $element['#step'] = sprintf('%1.' . $decimals . 'F', $element['#step']);
  228. }
  229. // If the number is not an integer and step is undefined/empty, set the "any"
  230. // value to allow any decimal.
  231. if (empty($element['#integer']) && empty($element['#step'])) {
  232. $element['#step'] = 'any';
  233. }
  234. elseif ($element['#integer'] && empty($element['#step'])) {
  235. $element['#step'] = 1;
  236. }
  237. // Convert properties to attributes on the element if set.
  238. foreach (array('id', 'name', 'value', 'size', 'min', 'max', 'step') as $property) {
  239. if (isset($element['#' . $property]) && $element['#' . $property] !== '') {
  240. $element['#attributes'][$property] = $element['#' . $property];
  241. }
  242. }
  243. _form_set_class($element, array('form-text', 'form-number'));
  244. return '<input' . drupal_attributes($element['#attributes']) . ' />';
  245. }
  246. /**
  247. * Implements _webform_render_component().
  248. */
  249. function _webform_render_number($component, $value = NULL, $filter = TRUE) {
  250. $node = isset($component['nid']) ? node_load($component['nid']) : NULL;
  251. $element = array(
  252. '#title' => $filter ? _webform_filter_xss($component['name']) : $component['name'],
  253. '#title_display' => $component['extra']['title_display'] ? $component['extra']['title_display'] : 'before',
  254. '#default_value' => $filter ? _webform_filter_values($component['value'], $node, NULL, NULL, FALSE) : $component['value'],
  255. '#required' => $component['mandatory'],
  256. '#weight' => $component['weight'],
  257. '#field_prefix' => empty($component['extra']['field_prefix']) ? NULL : ($filter ? _webform_filter_xss($component['extra']['field_prefix']) : $component['extra']['field_prefix']),
  258. '#field_suffix' => empty($component['extra']['field_suffix']) ? NULL : ($filter ? _webform_filter_xss($component['extra']['field_suffix']) : $component['extra']['field_suffix']),
  259. '#description' => $filter ? _webform_filter_descriptions($component['extra']['description'], $node) : $component['extra']['description'],
  260. '#attributes' => $component['extra']['attributes'],
  261. '#element_validate' => array('_webform_validate_number'),
  262. '#theme_wrappers' => array('webform_element'),
  263. '#min' => $component['extra']['min'],
  264. '#max' => $component['extra']['max'],
  265. '#step' => $component['extra']['step'] ? abs($component['extra']['step']) : '',
  266. '#integer' => $component['extra']['integer'],
  267. '#point' => $component['extra']['point'],
  268. '#separator' => $component['extra']['separator'],
  269. '#decimals' => $component['extra']['decimals'],
  270. '#translatable' => array('title', 'description', 'field_prefix', 'field_suffix'),
  271. );
  272. // Set the decimal count to zero for integers.
  273. if ($element['#integer'] && $element['#decimals'] === '') {
  274. $element['#decimals'] = 0;
  275. }
  276. // Flip the min and max properties to make min less than max if needed.
  277. if ($element['#min'] !== '' && $element['#max'] !== '' && $element['#min'] > $element['#max']) {
  278. $max = $element['#min'];
  279. $element['#min'] = $element['#max'];
  280. $element['#max'] = $max;
  281. }
  282. // Ensure #step starts with a zero if a decimal.
  283. if (!is_int($element['#step'] * 1)) {
  284. $decimals = strlen($element['#step']) - strrpos($element['#step'], '.') - 1;
  285. $element['#step'] = sprintf('%1.' . $decimals . 'F', $element['#step']);
  286. }
  287. if ($component['extra']['type'] == 'textfield') {
  288. // Render as textfield.
  289. $element['#type'] = 'webform_number';
  290. // Set the size property based on #max, to ensure consistent behavior for
  291. // browsers that do not support type = number.
  292. if ($element['#max']) {
  293. $element['#size'] = strlen($element['#max']) + 1;
  294. }
  295. }
  296. else {
  297. // Render as select.
  298. $element['#type'] = 'select';
  299. // Create user-specified options list as an array.
  300. $element['#options'] = _webform_number_select_options($component);
  301. // Add default options if using a select list with no default. This trigger's
  302. // Drupal 7's adding of the option for us. See form_process_select().
  303. if ($component['extra']['type'] == 'select' && $element['#default_value'] === '') {
  304. $element['#empty_value'] = '';
  305. }
  306. }
  307. // Set user-entered values.
  308. if (isset($value[0])) {
  309. // If the value has been standardized, convert it to the expected format
  310. // for display to the user.
  311. if (webform_number_format_match($value[0], '.', '')) {
  312. $element['#default_value'] = _webform_number_format($component, $value[0]);
  313. }
  314. // Otherwise use the user-defined input.
  315. else {
  316. $element['#default_value'] = $value[0];
  317. }
  318. }
  319. // Enforce uniqueness.
  320. if ($component['extra']['unique']) {
  321. $element['#element_validate'][] = 'webform_validate_unique';
  322. }
  323. // Set readonly if disabled.
  324. if ($component['extra']['disabled']) {
  325. if ($filter) {
  326. $element['#attributes']['readonly'] = 'readonly';
  327. }
  328. else {
  329. $element['#disabled'] = TRUE;
  330. }
  331. }
  332. return $element;
  333. }
  334. /**
  335. * Implements _webform_display_component().
  336. */
  337. function _webform_display_number($component, $value, $format = 'html') {
  338. $empty = !isset($value[0]) || $value[0] === '';
  339. return array(
  340. '#title' => $component['name'],
  341. '#weight' => $component['weight'],
  342. '#theme' => 'webform_display_number',
  343. '#theme_wrappers' => $format == 'html' ? array('webform_element') : array('webform_element_text'),
  344. '#field_prefix' => $empty ? '' : $component['extra']['field_prefix'],
  345. '#field_suffix' => $empty ? '' : $component['extra']['field_suffix'],
  346. '#format' => $format,
  347. '#value' => $empty ? '' : _webform_number_format($component, $value[0]),
  348. '#translatable' => array('title'),
  349. );
  350. }
  351. /**
  352. * Format the output of data for this component.
  353. */
  354. function theme_webform_display_number($variables) {
  355. $element = $variables['element'];
  356. $prefix = $element['#format'] == 'html' ? '' : $element['#field_prefix'];
  357. $suffix = $element['#format'] == 'html' ? '' : $element['#field_suffix'];
  358. $value = $element['#format'] == 'html' ? check_plain($element['#value']) : $element['#value'];
  359. return $value !== '' ? ($prefix . $value . $suffix) : ' ';
  360. }
  361. /**
  362. * Implements _webform_analysis_component().
  363. */
  364. function _webform_analysis_number($component, $sids = array(), $single = FALSE) {
  365. $advanced_stats = $single;
  366. $query = db_select('webform_submitted_data', 'wsd', array('fetch' => PDO::FETCH_ASSOC))
  367. ->fields('wsd', array('data'))
  368. ->condition('nid', $component['nid'])
  369. ->condition('cid', $component['cid']);
  370. if (count($sids)) {
  371. $query->condition('sid', $sids, 'IN');
  372. }
  373. $population = array();
  374. $submissions = 0;
  375. $non_zero = 0;
  376. $non_empty = 0;
  377. $sum = 0;
  378. $result = $query->execute();
  379. foreach ($result as $data) {
  380. $value = trim($data['data']);
  381. $number = (float)$value;
  382. $non_empty += (integer)($value !== '');
  383. $non_zero += (integer)($number != 0.0);
  384. $sum += $number;
  385. $population[] = $number;
  386. $submissions++;
  387. }
  388. sort($population, SORT_NUMERIC);
  389. // Average and population count.
  390. if ($component['extra']['excludezero']) {
  391. $average = $non_zero ? ($sum / $non_zero) : 0;
  392. $average_title = t('Average !mu excluding zeros/blanks', array('!mu' => $advanced_stats ? '(&mu;)' : ''));
  393. // Sample (sub-set of total population).
  394. $population_count = $non_zero - 1;
  395. $sigma = 'sd';
  396. $description = t('sample');
  397. }
  398. else {
  399. $average = $submissions ? ($sum / $submissions) : 0;
  400. $average_title = t('Average !mu including zeros/blanks', array('!mu' => $advanced_stats ? '(&mu;)' : ''));
  401. // Population.
  402. $population_count = $submissions;
  403. $sigma = '&sigma;';
  404. $description = t('population');
  405. }
  406. // Formatting.
  407. $average = _webform_number_format($component, $average);
  408. $sum = _webform_number_format($component, $sum);
  409. $rows[0] = array(t('Zero/blank'), ($submissions - $non_zero));
  410. $rows[1] = array(t('User entered value'), $non_empty);
  411. $rows[2] = array(t('Sum') . ($advanced_stats ? ' (&Sigma;)' : ''), $sum);
  412. $rows[3] = array($average_title, $average);
  413. if (!$advanced_stats && $sum != 0) {
  414. $rows[4] = array('', l(t('More stats »'), 'node/' . $component['nid'] . '/webform-results/analysis/' . $component['cid']));
  415. }
  416. // Normal distribution information.
  417. if ($advanced_stats && $population_count && $sum != 0) {
  418. // Standard deviation.
  419. $stddev = 0;
  420. foreach($population as $value) {
  421. // Obtain the total of squared variances.
  422. $stddev += pow(($value - $average), 2);
  423. }
  424. if ($population_count > 0) {
  425. $stddev = sqrt($stddev / $population_count);
  426. }
  427. else {
  428. $stddev = sqrt($stddev);
  429. }
  430. // Skip the rest of the distribution rows if standard deviation is 0.
  431. if (empty($stddev)) {
  432. return $rows;
  433. }
  434. // Build normal distribution table rows.
  435. $count = array();
  436. $percent = array();
  437. $limit = array();
  438. $index = 0;
  439. $count[] = 0;
  440. $limit[] = $average - ($stddev * 4);
  441. foreach ($population as $value) {
  442. while ($value >= $limit[$index]) {
  443. $percent[] = number_format($count[$index] / $population_count * 100, 2, '.', '');
  444. $limit[] = $limit[$index] + $stddev;
  445. $index += 1;
  446. if ($limit[$index] == $average) {
  447. $limit[$index] = $limit[$index] + $stddev;
  448. }
  449. $count[$index] = 0;
  450. }
  451. $count[$index] += 1;
  452. }
  453. $percent[] = number_format($count[$index] / $population_count * 100, 2, '.', '');
  454. // Format normal distribution table output.
  455. $stddev = _webform_number_format($component, $stddev);
  456. $low = _webform_number_format($component, $population[0]);
  457. $high = _webform_number_format($component, end($population));
  458. foreach($limit as $key => $value) {
  459. $limit[$key] = _webform_number_format($component, $value);
  460. }
  461. // Column headings (override potential theme uppercase, e.g. Seven in D7).
  462. $header = array(
  463. t('Normal Distribution'),
  464. array('data' => '-4' . $sigma, 'style' => 'text-transform: lowercase;',),
  465. array('data' => '-3' . $sigma, 'style' => 'text-transform: lowercase;',),
  466. array('data' => '-2' . $sigma, 'style' => 'text-transform: lowercase;',),
  467. array('data' => '-1' . $sigma, 'style' => 'text-transform: lowercase;',),
  468. array('data' => '+1' . $sigma, 'style' => 'text-transform: lowercase;',),
  469. array('data' => '+2' . $sigma, 'style' => 'text-transform: lowercase;',),
  470. array('data' => '+3' . $sigma, 'style' => 'text-transform: lowercase;',),
  471. array('data' => '+4' . $sigma, 'style' => 'text-transform: lowercase;',),
  472. );
  473. // Insert row labels.
  474. array_unshift($limit, t('Boundary'));
  475. array_unshift($count, t('Count'));
  476. array_unshift($percent, t('% of !description', array('!description' => $description)));
  477. $output = theme('table', array('header' => $header, 'rows' => array($limit, $count, $percent)));
  478. $rows[4] = array(t('Range'), t('!low to !high', array('!low' => $low, '!high' => $high)));
  479. $rows[5] = array(t('Standard deviation (!sigma)', array('!sigma' => $sigma)), $stddev);
  480. $rows[6] = array(array('data' => $output, 'colspan' => 2));
  481. }
  482. return $rows;
  483. }
  484. /**
  485. * Implements _webform_table_component().
  486. */
  487. function _webform_table_number($component, $value) {
  488. return isset($value[0]) ? _webform_number_format($component, $value[0]) : '';
  489. }
  490. /**
  491. * Implements _webform_csv_headers_component().
  492. */
  493. function _webform_csv_headers_number($component, $export_options) {
  494. $header = array();
  495. $header[0] = '';
  496. $header[1] = '';
  497. $header[2] = $component['name'];
  498. return $header;
  499. }
  500. /**
  501. * Implements _webform_csv_data_component().
  502. */
  503. function _webform_csv_data_number($component, $export_options, $value) {
  504. if (isset($value[0]) && is_numeric($value[0]) && $component['extra']['decimals'] !== '') {
  505. $value[0] = number_format($value[0], $component['extra']['decimals'], '.', '');
  506. }
  507. return isset($value[0]) ? $value[0] : '';
  508. }
  509. /**
  510. * A Drupal Form API Validation function. Validates the entered values from
  511. * number components on the client-side form.
  512. *
  513. * @param $element
  514. * The form element. May either be a select or a webform_number element.
  515. * @param $form_state
  516. * The full form state for the webform.
  517. * @return
  518. * None. Calls a form_set_error if the number is not valid.
  519. */
  520. function _webform_validate_number($element, &$form_state) {
  521. // Trim spaces for basic cleanup.
  522. $value = trim($element['#value']);
  523. form_set_value($element, $value, $form_state);
  524. if ($value != '') {
  525. // First check that the entered value matches the expected value.
  526. if (!webform_number_format_match($value, $element['#point'], $element['#separator'])) {
  527. 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']))));
  528. return;
  529. }
  530. // Numeric test.
  531. $numeric_value = webform_number_standardize($value, $element['#point']);
  532. if (is_numeric($numeric_value)) {
  533. // Range test.
  534. if ($element['#min'] != '' && $element['#max'] != '') {
  535. // Flip minimum and maximum if needed.
  536. if ($element['#max'] > $element['#min']) {
  537. $min = $element['#min'];
  538. $max = $element['#max'];
  539. }
  540. else {
  541. $min = $element['#max'];
  542. $max = $element['#min'];
  543. }
  544. if ($numeric_value > $max || $numeric_value < $min) {
  545. 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'])));
  546. }
  547. }
  548. elseif ($element['#max'] != '' && $numeric_value > $element['#max']) {
  549. form_error($element, t('%name field value must be less than @max.', array('%name' => $element['#title'], '@max' => $element['#max'])));
  550. }
  551. elseif ($element['#min'] != '' && $numeric_value < $element['#min']) {
  552. form_error($element, t('%name field value must be greater than @min.', array('%name' => $element['#title'], '@min' => $element['#min'])));
  553. }
  554. // Integer test.
  555. if ($element['#integer'] && !is_int($numeric_value * 1)) {
  556. form_error($element, t('%name field value of @value must be an integer.', array('%name' => $element['#title'], '@value' => $value)));
  557. }
  558. // Step test.
  559. $starting_number = $element['#min'] ? $element['#min'] : 0;
  560. if ($element['#step'] != 0 && webform_modulo($numeric_value - $starting_number, $element['#step']) != 0) {
  561. $samples = array(
  562. $starting_number,
  563. $starting_number + ($element['#step'] * 1),
  564. $starting_number + ($element['#step'] * 2),
  565. $starting_number + ($element['#step'] * 3),
  566. );
  567. if ($starting_number) {
  568. 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))));
  569. }
  570. else {
  571. 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))));
  572. }
  573. }
  574. }
  575. else {
  576. form_error($element, t('%name field value of @value must be numeric.', array('%name' => $element['#title'], '@value' => $value)));
  577. }
  578. }
  579. }
  580. /**
  581. * Implements _webform_submit_component().
  582. */
  583. function _webform_submit_number($component, $value) {
  584. // Because _webform_validate_number() ensures the format matches when moving
  585. // forward through a form, this should always pass before saving into the
  586. // database. When moving backwards in a form, do not adjust the value, since
  587. // it has not yet been validated.
  588. if (webform_number_format_match($value, $component['extra']['point'], $component['extra']['separator'])) {
  589. $value = webform_number_standardize($value, $component['extra']['point']);
  590. }
  591. return $value;
  592. }
  593. /**
  594. * Validation of number edit form items.
  595. */
  596. function _webform_edit_number_validate($element, &$form_state) {
  597. // Find the value of all related fields to this element.
  598. $parents = $element['#parents'];
  599. $key = array_pop($parents);
  600. $values = $form_state['values'];
  601. foreach ($parents as $parent) {
  602. $values = $values[$parent];
  603. }
  604. switch ($key) {
  605. case 'min':
  606. if ($values['min'] == '') {
  607. if (isset($values['type']) && $values['type'] === 'select') {
  608. form_error($element, t('Minimum is required when using a select list element.'));
  609. }
  610. }
  611. else {
  612. if (!is_numeric($values['min'])) {
  613. form_error($element, t('Minimum must be numeric.'));
  614. }
  615. if ($values['integer'] && !is_int($values['min'] * 1)) {
  616. form_error($element, t('Minimum must have an integer value.'));
  617. }
  618. }
  619. break;
  620. case 'max':
  621. if ($values['max'] == '') {
  622. if (isset($values['type']) && $values['type'] === 'select') {
  623. form_error($element, t('Maximum is required when using a select list element.'));
  624. }
  625. }
  626. else {
  627. if (!is_numeric($values['max'])) {
  628. form_error($element, t('Maximum must be numeric.'));
  629. }
  630. if ($values['integer'] && !is_int($values['max'] * 1)) {
  631. form_error($element, t('Maximum must have an integer value.'));
  632. }
  633. }
  634. break;
  635. case 'step':
  636. if ($values['step'] !== '') {
  637. if (!is_numeric($values['step'])) {
  638. form_error($element, t('Step must be numeric.'));
  639. }
  640. else {
  641. if ($values['integer'] && !is_int($values['step'] * 1)) {
  642. form_error($element, t('Step must have an integer value.'));
  643. }
  644. }
  645. }
  646. break;
  647. }
  648. return TRUE;
  649. }
  650. /**
  651. * Generate select list options.
  652. */
  653. function _webform_number_select_options($component) {
  654. $options = array();
  655. $step = abs($component['extra']['step']);
  656. // Step is optional and defaults to 1.
  657. $step = empty($step) ? 1 : $step;
  658. // Generate list in correct direction.
  659. $min = $component['extra']['min'];
  660. $max = $component['extra']['max'];
  661. $flipped = FALSE;
  662. if ($max < $min) {
  663. $min = $component['extra']['max'];
  664. $max = $component['extra']['min'];
  665. $flipped = TRUE;
  666. }
  667. for ($f = $min; $f <= $max; $f += $step) {
  668. $options[$f . ''] = $f . '';
  669. }
  670. // TODO: HTML5 browsers apparently do not include the max value if it does
  671. // not line up with step. Restore this if needed in the future.
  672. // Add end limit if it's been skipped due to step.
  673. //if (end($options) != $max) {
  674. // $options[$f] = $max;
  675. //}
  676. if ($flipped) {
  677. $options = array_reverse($options, TRUE);
  678. }
  679. // Apply requisite number formatting.
  680. foreach ($options as $key => $value) {
  681. $options[$key] = _webform_number_format($component, $value);
  682. }
  683. return $options;
  684. }
  685. /**
  686. * Apply number format based on a component and number value.
  687. */
  688. function _webform_number_format($component, $value) {
  689. return webform_number_format($value, $component['extra']['decimals'], $component['extra']['point'], $component['extra']['separator']);
  690. }
  691. /**
  692. * Validates if a provided number string matches an expected format.
  693. *
  694. * This function allows the thousands separator to be optional, but decimal
  695. * points must be in the right location.
  696. *
  697. * Based on http://stackoverflow.com/questions/5917082/regular-expression-to-match-numbers-with-or-without-commas-and-decimals-in-text.
  698. */
  699. function webform_number_format_match($value, $point, $separator) {
  700. return preg_match('/^(-? ?[1-9](?:\d{0,2})(?:' . ($separator ? (preg_quote($separator, '/') . '?') : '') . '\d{3})*(?:' . preg_quote($point, '/') . '\d*[0-9])?|0?' . preg_quote($point, '/') . '\d*[1-9]|0)$/', $value);
  701. }
  702. /**
  703. * Format a number with thousands separator, decimal point, and decimal places.
  704. *
  705. * This function is a wrapper around PHP's native number_format(), but allows
  706. * the decimal places parameter to be NULL or an empty string, resulting in a
  707. * behavior of no change to the decimal places.
  708. */
  709. function webform_number_format($value, $decimals = NULL, $point = '.', $separator = ',') {
  710. if (!is_numeric($value)) {
  711. return '';
  712. }
  713. // If no decimal places are specified, do a best guess length of decimals.
  714. if (is_null($decimals) || $decimals === '') {
  715. // If it's an integer, no decimals needed.
  716. if (is_int(($value . '') * 1)) {
  717. $decimals = 0;
  718. }
  719. else {
  720. $decimals = strlen($value) - strrpos($value, '.') - 1;
  721. }
  722. if ($decimals > 4) {
  723. $decimals = 4;
  724. }
  725. }
  726. return number_format($value, $decimals, $point, $separator);
  727. }
  728. /**
  729. * Given a number, convert it to string compatible with a PHP float.
  730. *
  731. * @param string $value
  732. * The string value to be standardized into a numeric string.
  733. * @param $point
  734. * The point separator between the whole number and the decimals.
  735. */
  736. function webform_number_standardize($value, $point) {
  737. // For simplicity, strip everything that's not the decimal point.
  738. $value = preg_replace('/[^\-0-9' . preg_quote($point, '/') . ']/', '', $value);
  739. // Convert the decimal point to a period.
  740. $value = str_replace($point, '.', $value);
  741. return $value;
  742. }
  743. /**
  744. * Custom modulo function that properly handles float division.
  745. *
  746. * See https://drupal.org/node/1601968.
  747. */
  748. function webform_modulo($a, $b) {
  749. return $a - $b * (($b < 0) ? ceil($a / $b) : floor($a / $b));
  750. }