Project

General

Profile

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

root / drupal7 / sites / all / modules / webform / components / select.inc @ 01f36513

1
<?php
2

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

    
8
/**
9
 * Implements _webform_defaults_component().
10
 */
11
function _webform_defaults_select() {
12
  return array(
13
    'name' => '',
14
    'form_key' => NULL,
15
    'required' => 0,
16
    'pid' => 0,
17
    'weight' => 0,
18
    'value' => '',
19
    'extra' => array(
20
      'items' => '',
21
      'multiple' => NULL,
22
      'aslist' => NULL,
23
      'empty_option' => '',
24
      'optrand' => 0,
25
      'other_option' => NULL,
26
      'other_text' => t('Other...'),
27
      'title_display' => 0,
28
      'description' => '',
29
      'description_above' => FALSE,
30
      'custom_keys' => FALSE,
31
      'options_source' => '',
32
      'private' => FALSE,
33
      'analysis' => TRUE,
34
    ),
35
  );
36
}
37

    
38
/**
39
 * Implements _webform_theme_component().
40
 */
41
function _webform_theme_select() {
42
  return array(
43
    'webform_display_select' => array(
44
      'render element' => 'element',
45
      'file' => 'components/select.inc',
46
    ),
47
  );
48
}
49

    
50
/**
51
 * Implements _webform_edit_component().
52
 */
53
function _webform_edit_select($component) {
54
  $form = array(
55
    '#attached' => array(
56
      'js' => array(
57
        drupal_get_path('module', 'webform') . '/js/select-admin.js' => array('preprocess' => FALSE),
58
        array('data' => array('webform' => array('selectOptionsUrl' => url('webform/ajax/options/' . $component['nid']))), 'type' => 'setting'),
59
      ),
60
    ),
61
  );
62

    
63
  // Default component if nested under a grid.
64
  if (!isset($component['cid']) && $component['pid'] &&
65
      ($node = node_load($component['nid'])) && ($parent = $node->webform['components'][$component['pid']]) &&
66
      $parent['type'] == 'grid') {
67
    $component['value'] = $parent['value'];
68
    $component['extra']['items'] = $parent['extra']['options'];
69
    $component['required'] = $parent['required'];
70
  }
71

    
72
  $other = array();
73
  if ($info = _webform_select_options_info()) {
74
    $options = array('' => t('None'));
75
    foreach ($info as $name => $source) {
76
      $options[$name] = $source['title'];
77
    }
78

    
79
    $other['options_source'] = array(
80
      '#title' => t('Load a pre-built option list'),
81
      '#type' => 'select',
82
      '#options' => $options,
83
      '#default_value' => $component['extra']['options_source'],
84
      '#description' => t('Use a pre-built list of options rather than entering options manually. Options will not be editable if using pre-built list.'),
85
      '#parents' => array('extra', 'options_source'),
86
      '#weight' => 5,
87
    );
88
  }
89

    
90
  if (module_exists('select_or_other')) {
91
    $other['other_option'] = array(
92
      '#type' => 'checkbox',
93
      '#title' => t('Allow "Other..." option'),
94
      '#default_value' => $component['extra']['other_option'],
95
      '#description' => t('Check this option if you want to allow users to enter an option not on the list.'),
96
      '#parents' => array('extra', 'other_option'),
97
      '#attributes' => array('class' => array('other-option-checkbox')),
98
      '#weight' => 2,
99
    );
100
    $other['other_text'] = array(
101
      '#type' => 'textfield',
102
      '#title' => t('Text for "Other..." option'),
103
      '#default_value' => $component['extra']['other_text'],
104
      '#description' => t('If allowing other options, enter text to be used for other-enabling option.'),
105
      '#parents' => array('extra', 'other_text'),
106
      '#weight' => 3,
107
      '#states' => array(
108
        'visible' => array(
109
          ':input.other-option-checkbox' => array('checked' => TRUE),
110
        ),
111
      ),
112
    );
113
  }
114

    
115
  if (module_exists('options_element')) {
116
    $options = _webform_select_options($component, FALSE, FALSE);
117

    
118
    $form['items'] = array(
119
      '#type' => 'fieldset',
120
      '#title' => t('Options'),
121
      '#collapsible' => TRUE,
122
      '#attributes' => array('class' => array('webform-options-element')),
123
      '#element_validate' => array('_webform_edit_validate_options'),
124
      '#weight' => 2,
125
    );
126

    
127
    $form['items']['options'] = array(
128
      '#type' => 'options',
129
      '#limit' => 500,
130
      '#optgroups' => TRUE,
131
      '#multiple' => $component['extra']['multiple'],
132
      '#multiple_toggle' => t('Multiple'),
133
      '#default_value' => $component['value'],
134
      '#options' => $options,
135
      '#options_readonly' => !empty($component['extra']['options_source']),
136
      '#key_type' => 'mixed',
137
      '#key_type_toggle' => t('Customize keys (Advanced)'),
138
      '#key_type_toggled' => $component['extra']['custom_keys'],
139
      '#default_value_pattern' => '^%.+\[.+\]$',
140
      '#weight' => 1,
141
    );
142

    
143
    $form['items']['options']['option_settings'] = $other;
144
  }
145
  else {
146
    $form['extra']['items'] = array(
147
      '#type' => 'textarea',
148
      '#title' => t('Options'),
149
      '#default_value' => $component['extra']['items'],
150
      '#description' => t('<strong>Key-value pairs MUST be specified as "safe_key|Some readable option"</strong>. Use of only alphanumeric characters and underscores is recommended in keys. One option per line. Option groups may be specified with &lt;Group Name&gt;. &lt;&gt; can be used to insert items at the root of the menu after specifying a group.') . ' ' . theme('webform_token_help'),
151
      '#cols' => 60,
152
      '#rows' => 5,
153
      '#weight' => 0,
154
      '#required' => TRUE,
155
      '#wysiwyg' => FALSE,
156
      '#element_validate' => array('_webform_edit_validate_select'),
157
    );
158

    
159
    if (!empty($component['extra']['options_source'])) {
160
      $form['extra']['items']['#attributes'] = array('readonly' => 'readonly');
161
    }
162

    
163
    $form['extra'] = array_merge($form['extra'], $other);
164
    $form['value'] = array(
165
      '#type' => 'textfield',
166
      '#title' => t('Default value'),
167
      '#default_value' => $component['value'],
168
      '#description' => t('The default value of the field identified by its key. For multiple selects use commas to separate multiple defaults.') . ' ' . theme('webform_token_help'),
169
      '#size' => 60,
170
      '#maxlength' => 1024,
171
      '#weight' => 0,
172
    );
173
    $form['extra']['multiple'] = array(
174
      '#type' => 'checkbox',
175
      '#title' => t('Multiple'),
176
      '#default_value' => $component['extra']['multiple'],
177
      '#description' => t('Check this option if the user should be allowed to choose multiple values.'),
178
      '#weight' => 0,
179
    );
180
  }
181

    
182
  $form['display']['aslist'] = array(
183
    '#type' => 'checkbox',
184
    '#title' => t('Listbox'),
185
    '#default_value' => $component['extra']['aslist'],
186
    '#description' => t('Check this option if you want the select component to be displayed as a select list box instead of radio buttons or checkboxes. Option groups (nested options) are only supported with listbox components.'),
187
    '#parents' => array('extra', 'aslist'),
188
  );
189
  $form['display']['empty_option'] = array(
190
    '#type' => 'textfield',
191
    '#title' => t('Empty option'),
192
    '#default_value' => $component['extra']['empty_option'],
193
    '#size' => 60,
194
    '#maxlength' => 255,
195
    '#description' => t('The list item to show when no default is provided. Leave blank for "- None -" or "- Select -".'),
196
    '#parents' => array('extra', 'empty_option'),
197
    '#states' => array(
198
      'visible' => array(
199
        ':input[name="extra[aslist]"]' => array('checked' => TRUE),
200
        ':input[name="extra[multiple]"]' => array('checked' => FALSE),
201
        ':input[name="value"]' => array('filled' => FALSE),
202
      ),
203
    ),
204
  );
205
  $form['display']['optrand'] = array(
206
    '#type' => 'checkbox',
207
    '#title' => t('Randomize options'),
208
    '#default_value' => $component['extra']['optrand'],
209
    '#description' => t('Randomizes the order of the options when they are displayed in the form.'),
210
    '#parents' => array('extra', 'optrand'),
211
  );
212

    
213
  return $form;
214
}
215

    
216
/**
217
 * Element validation callback. Ensure keys are not duplicated.
218
 */
219
function _webform_edit_validate_select($element, &$form_state) {
220
  // Check for duplicate key values to prevent unexpected data loss. Require
221
  // all options to include a safe_key.
222
  if (!empty($element['#value'])) {
223
    $lines = explode("\n", trim($element['#value']));
224
    $existing_keys = array();
225
    $duplicate_keys = array();
226
    $missing_keys = array();
227
    $long_keys = array();
228
    $group = '';
229
    foreach ($lines as $line) {
230
      $matches = array();
231
      $line = trim($line);
232
      if (preg_match('/^\<([^>]*)\>$/', $line, $matches)) {
233
        $group = $matches[1];
234
        // No need to store group names.
235
        $key = NULL;
236
      }
237
      elseif (preg_match('/^([^|]*)\|(.*)$/', $line, $matches)) {
238
        $key = $matches[1];
239
        if (strlen($key) > 128) {
240
          $long_keys[] = $key;
241
        }
242
      }
243
      else {
244
        $missing_keys[] = $line;
245
      }
246

    
247
      if (isset($key)) {
248
        if (isset($existing_keys[$group][$key])) {
249
          $duplicate_keys[$key] = $key;
250
        }
251
        else {
252
          $existing_keys[$group][$key] = $key;
253
        }
254
      }
255
    }
256

    
257
    if (!empty($missing_keys)) {
258
      form_error($element, t('Every option must have a key specified. Specify each option as "safe_key|Some readable option".'));
259
    }
260

    
261
    if (!empty($long_keys)) {
262
      form_error($element, t('Option keys must be less than 128 characters. The following keys exceed this limit:') . theme('item_list', $long_keys));
263
    }
264

    
265
    if (!empty($duplicate_keys)) {
266
      form_error($element, t('Options within the select list must be unique. The following keys have been used multiple times:') . theme('item_list', array('items' => $duplicate_keys)));
267
    }
268

    
269
    // Set the listbox option if needed.
270
    if (empty($missing_keys) && empty($long_keys) && empty($duplicate_keys)) {
271
      $options = _webform_select_options_from_text($element['#value']);
272
      _webform_edit_validate_set_aslist($options, $form_state);
273
    }
274
  }
275

    
276
  return TRUE;
277
}
278

    
279
/**
280
 * Set the appropriate webform values when using the options element module.
281
 */
282
function _webform_edit_validate_options($element, &$form_state) {
283
  $key = end($element['#parents']);
284
  $element_options = $form_state['values'][$key]['options'];
285
  unset($form_state['values'][$key]);
286

    
287
  $form_state['values']['extra'][$key] = form_options_to_text($element_options['options'], 'custom');
288

    
289
  // Options saved for select components.
290
  if ($key == 'items') {
291
    $form_state['values']['extra']['multiple'] = $element_options['multiple'];
292
    $form_state['values']['extra']['custom_keys'] = $element_options['custom_keys'];
293
    $form_state['values']['value'] = is_array($element_options['default_value']) ? implode(', ', $element_options['default_value']) : $element_options['default_value'];
294

    
295
    // Set the listbox option if needed.
296
    _webform_edit_validate_set_aslist($element_options['options'], $form_state);
297
  }
298
  // Options saved for grid components.
299
  else {
300
    $form_state['values']['extra']['custom_' . rtrim($key, 's') . '_keys'] = $element_options['custom_keys'];
301
    // There is only one 'value', but grids have two options widgets, one for questions and one for options.
302
    // Only options have a default 'value'. Note that multiple selection is now allowed for grid options.
303
    if ($key == 'options') {
304
      $form_state['values']['value'] = $element_options['default_value'];
305
    }
306
  }
307
}
308

    
309
/**
310
 * Ensure "aslist" is used for option groups. Called from options validations.
311
 */
312
function _webform_edit_validate_set_aslist($options, &$form_state) {
313
  if (empty($form_state['values']['extra']['aslist']) && !empty($options)) {
314
    foreach ($options as $option) {
315
      if (is_array($option)) {
316
        $form_state['values']['extra']['aslist'] = 1;
317
        drupal_set_message(t('The component %name has automatically been set to display as a listbox in order to support option groups.', array('%name' => $form_state['values']['name'])), 'warning');
318
        break;
319
      }
320
    }
321
  }
322
}
323

    
324
/**
325
 * Implements _webform_render_component().
326
 */
327
function _webform_render_select($component, $value = NULL, $filter = TRUE, $submission = NULL) {
328
  $node = isset($component['nid']) ? node_load($component['nid']) : NULL;
329

    
330
  $element = array(
331
    '#title' => $filter ? webform_filter_xss($component['name']) : $component['name'],
332
    '#title_display' => $component['extra']['title_display'] ? $component['extra']['title_display'] : 'before',
333
    '#required' => $component['required'],
334
    '#weight' => $component['weight'],
335
    '#description' => $filter ? webform_filter_descriptions($component['extra']['description'], $node) : $component['extra']['description'],
336
    '#theme_wrappers' => array('webform_element'),
337
    '#translatable' => array('title', 'description', 'options'),
338
  );
339

    
340
  // Prevent double-wrapping of radios and checkboxes.
341
  if (!$component['extra']['aslist']) {
342
    $element['#pre_render'] = array();
343
  }
344

    
345
  // Convert the user-entered options list into an array.
346
  $default_value = $filter ? webform_replace_tokens($component['value'], $node) : $component['value'];
347
  $options = _webform_select_options($component, !$component['extra']['aslist'], $filter);
348
  if (empty($options)) {
349
    // Make element inaccessible if there are no options as there is no point in showing it.
350
    $element['#access'] = FALSE;
351
  }
352

    
353
  if ($component['extra']['optrand']) {
354
    _webform_shuffle_options($options);
355
  }
356

    
357
  // Add HTML5 required attribute, if needed and possible (not working on more than one checkboxes).
358
  if ($component['required'] && ($component['extra']['aslist'] || !$component['extra']['multiple'] || count($options) == 1)) {
359
    $element['#attributes']['required'] = 'required';
360
  }
361

    
362
  // Add default options if using a select list with no default. This trigger's
363
  // Drupal 7's adding of the option for us. See @form_process_select().
364
  if ($component['extra']['aslist'] && !$component['extra']['multiple'] && $default_value === '') {
365
    $element['#empty_value'] = '';
366
    if (strlen($component['extra']['empty_option'])) {
367
      $element['#empty_option'] = $component['extra']['empty_option'];
368
      $element['#translatable'][] = 'empty_option';
369
    }
370
  }
371

    
372
  // Set the component options.
373
  $element['#options'] = $options;
374

    
375
  // Use the component's default value if the component is currently empty.
376
  if (!isset($value)) {
377
    // The default for multiple selects is a comma-delimited list, without white-space or empty entries.
378
    $value = $component['extra']['multiple'] ? array_filter(array_map('trim', explode(',', $default_value)), 'strlen') : $default_value;
379
  }
380

    
381
  // Convert all values into an array; component may now be single but was previously multiple, or vice-versa.
382
  $value = (array) $value;
383

    
384
  // Set the default value. Note: "No choice" is stored as an empty string,
385
  // which will match a 0 key for radios; NULL is used to avoid unintentional
386
  // defaulting to the 0 option.
387
  if ($component['extra']['multiple']) {
388
    // Set the value as an array.
389
    $element['#default_value'] = array();
390
    foreach ($value as $option_value) {
391
      $element['#default_value'][] = $option_value === '' ? NULL : $option_value;
392
    }
393
  }
394
  else {
395
    // Set the value as a single string.
396
    $option_value = reset($value);
397
    $element['#default_value'] = $option_value === '' ? NULL : $option_value;
398
  }
399

    
400
  if ($component['extra']['other_option'] && module_exists('select_or_other')) {
401
    // Set display as a select_or_other element:
402
    $element['#type'] = 'select_or_other';
403
    $element['#other'] = !empty($component['extra']['other_text']) ? check_plain($component['extra']['other_text']) : t('Other...');
404
    $element['#translatable'][] = 'other';
405
    $element['#other_title'] = $element['#title'] . ' ' . $element['#other'];
406
    $element['#other_title_display'] = 'invisible';
407
    $element['#other_unknown_defaults'] = 'other';
408
    $element['#other_delimiter'] = ', ';
409
    // Merge in Webform's #process function for Select or other.
410
    $element['#process'] = array_merge(element_info_property('select_or_other', '#process'), array('webform_expand_select_or_other'));
411
    // Inherit select_or_other settings or set defaults.
412
    $element['#disabled'] = isset($component['extra']['#disabled']) ? $component['extra']['#disabled'] : element_info_property('select_or_other', 'disabled');
413
    $element['#size'] = isset($component['extra']['#size']) ? $component['extra']['#size'] : element_info_property('select_or_other', 'size');
414

    
415
    if ($component['extra']['multiple']) {
416
      $element['#multiple'] = TRUE;
417
      $element['#select_type'] = 'checkboxes';
418
    }
419
    else {
420
      $element['#multiple'] = FALSE;
421
      $element['#select_type'] = 'radios';
422
    }
423
    if ($component['extra']['aslist']) {
424
      $element['#select_type'] = 'select';
425
    }
426
  }
427
  elseif ($component['extra']['aslist']) {
428
    // Set display as a select list:
429
    $element['#type'] = 'select';
430
    if ($component['extra']['multiple']) {
431
      $element['#size'] = 4;
432
      $element['#multiple'] = TRUE;
433
    }
434
  }
435
  else {
436
    if ($component['extra']['multiple']) {
437
      // Set display as a checkbox set.
438
      $element['#type'] = 'checkboxes';
439
      $element['#theme_wrappers'] = array_merge(array('checkboxes'), $element['#theme_wrappers']);
440
      $element['#process'] = array_merge(element_info_property('checkboxes', '#process'), array('webform_expand_select_ids'));
441
    }
442
    else {
443
      // Set display as a radio set.
444
      $element['#type'] = 'radios';
445
      $element['#theme_wrappers'] = array_merge(array('radios'), $element['#theme_wrappers']);
446
      $element['#process'] = array_merge(element_info_property('radios', '#process'), array('webform_expand_select_ids'));
447
    }
448
  }
449

    
450
  return $element;
451
}
452

    
453
/**
454
 * Process function to ensure select_or_other elements validate properly.
455
 */
456
function webform_expand_select_or_other($element) {
457
  // Disable validation for back-button and save draft.
458
  $element['select']['#validated'] = TRUE;
459
  $element['select']['#webform_validated'] = FALSE;
460

    
461
  $element['other']['#validated'] = TRUE;
462
  $element['other']['#webform_validated'] = FALSE;
463

    
464
  // The Drupal FAPI does not support #title_display inline so we need to move
465
  // to a supported value here to be compatible with select_or_other.
466
  $element['select']['#title_display'] = $element['#title_display'] === 'inline' ? 'before' : $element['#title_display'];
467

    
468
  // If the default value contains "select_or_other" (the key of the select
469
  // element for the "other..." choice), discard it and set the "other" value.
470
  if (is_array($element['#default_value']) && in_array('select_or_other', $element['#default_value'])) {
471
    $key = array_search('select_or_other', $element['#default_value']);
472
    unset($element['#default_value'][$key]);
473
    $element['#default_value'] = array_values($element['#default_value']);
474
    $element['other']['#default_value'] = implode(', ', $element['#default_value']);
475
  }
476

    
477
  // Sanitize the options in Select or other check boxes and radio buttons.
478
  if ($element['#select_type'] == 'checkboxes' || $element['#select_type'] == 'radios') {
479
    $element['select']['#process'] = array_merge(element_info_property($element['#select_type'], '#process'), array('webform_expand_select_ids'));
480
  }
481

    
482
  return $element;
483
}
484

    
485
/**
486
 * FAPI process function to rename IDs attached to checkboxes and radios.
487
 */
488
function webform_expand_select_ids($element) {
489
  $id = $element['#id'] = str_replace('_', '-', _webform_safe_name(strip_tags($element['#id'])));
490
  $delta = 0;
491
  foreach (element_children($element) as $key) {
492
    $delta++;
493
    // Convert the #id for each child to a safe name, regardless of key.
494
    $element[$key]['#id'] = $id . '-' . $delta;
495

    
496
    // Prevent scripts or CSS in the labels for each checkbox or radio.
497
    $element[$key]['#title'] = isset($element[$key]['#title']) ? webform_filter_xss($element[$key]['#title']) : '';
498
  }
499
  return $element;
500
}
501

    
502
/**
503
 * Implements _webform_display_component().
504
 */
505
function _webform_display_select($component, $value, $format = 'html', $submission = array()) {
506
  // Sort values by numeric key. These may be in alphabetic order from the database query,
507
  // which is not numeric order for keys '10' and higher.
508
  $value = (array) $value;
509
  ksort($value, SORT_NUMERIC);
510
  return array(
511
    '#title' => $component['name'],
512
    '#title_display' => $component['extra']['title_display'] ? $component['extra']['title_display'] : 'before',
513
    '#weight' => $component['weight'],
514
    '#multiple' => $component['extra']['multiple'],
515
    '#theme' => 'webform_display_select',
516
    '#theme_wrappers' => $format == 'html' ? array('webform_element') : array('webform_element_text'),
517
    '#format' => $format,
518
    '#options' => _webform_select_options($component, !$component['extra']['aslist']),
519
    '#value' => $value,
520
    '#translatable' => array('title', 'options'),
521
  );
522
}
523

    
524
/**
525
 * Implements _webform_submit_component().
526
 *
527
 * Handle select or other... modifications and convert FAPI 0/1 values into
528
 * something saveable.
529
 */
530
function _webform_submit_select($component, $value) {
531
  if (module_exists('select_or_other') && $component['extra']['other_option'] && is_array($value) && count($value) == 2 && isset($value['select'])) {
532
    if (is_array($value['select']) && isset($value['select']['select_or_other'])) {
533
      unset($value['select']['select_or_other']);
534
      $value['select'][] = $value['other'];
535
    }
536
    elseif ($value['select'] == 'select_or_other') {
537
      $value['select'] = $value['other'];
538
    }
539
    $value = $value['select'];
540
  }
541

    
542
  // Build a list of all valid keys expected to be submitted.
543
  $options = _webform_select_options($component, TRUE);
544

    
545
  $return = NULL;
546
  if (is_array($value)) {
547
    $return = array();
548
    foreach ($value as $key => $option_value) {
549
      // Handle options that are specified options.
550
      if ($option_value !== '' && isset($options[$option_value])) {
551
        // Checkboxes submit an integer value of 0 when unchecked. A checkbox
552
        // with a value of '0' is valid, so we can't use empty() here.
553
        if ($option_value === 0 && !$component['extra']['aslist'] && $component['extra']['multiple']) {
554
          // Don't save unchecked values.
555
        }
556
        else {
557
          $return[] = $option_value;
558
        }
559
      }
560
      // Handle options that are added through the "other" field. Specifically
561
      // exclude the "select_or_other" value, which is added by the select list.
562
      elseif ($component['extra']['other_option'] && module_exists('select_or_other') && $option_value != 'select_or_other') {
563
        $return[] = $option_value;
564
      }
565
    }
566

    
567
    // If no elements are selected, then save an empty string to indicate that this components should not be defaulted again.
568
    if (!$return) {
569
      $return = array('');
570
    }
571
  }
572
  elseif (is_string($value)) {
573
    $return = $value;
574
  }
575

    
576
  return $return;
577
}
578

    
579
/**
580
 * Format the text output for this component.
581
 */
582
function theme_webform_display_select($variables) {
583
  $element = $variables['element'];
584

    
585
  // Flatten the list of options so we can get values easily. These options
586
  // may be translated by hook_webform_display_component_alter().
587
  $options = array();
588
  foreach ($element['#options'] as $key => $value) {
589
    if (is_array($value)) {
590
      foreach ($value as $subkey => $subvalue) {
591
        $options[$subkey] = $subvalue;
592
      }
593
    }
594
    else {
595
      $options[$key] = $value;
596
    }
597
  }
598

    
599
  $items = array();
600
  if ($element['#multiple']) {
601
    foreach ((array) $element['#value'] as $option_value) {
602
      if ($option_value !== '') {
603
        // Administer provided values.
604
        if (isset($options[$option_value])) {
605
          $items[] = $element['#format'] == 'html' ? webform_filter_xss($options[$option_value]) : $options[$option_value];
606
        }
607
        // User-specified in the "other" field.
608
        else {
609
          $items[] = $element['#format'] == 'html' ? check_plain($option_value) : $option_value;
610
        }
611
      }
612
    }
613
  }
614
  else {
615
    if (isset($element['#value'][0]) && $element['#value'][0] !== '') {
616
      // Administer provided values.
617
      if (isset($options[$element['#value'][0]])) {
618
        $items[] = $element['#format'] == 'html' ? webform_filter_xss($options[$element['#value'][0]]) : $options[$element['#value'][0]];
619
      }
620
      // User-specified in the "other" field.
621
      else {
622
        $items[] = $element['#format'] == 'html' ? check_plain($element['#value'][0]) : $element['#value'][0];
623
      }
624
    }
625
  }
626

    
627
  if ($element['#format'] == 'html') {
628
    $output = count($items) > 1 ? theme('item_list', array('items' => $items)) : (isset($items[0]) ? $items[0] : ' ');
629
  }
630
  else {
631
    if (count($items) > 1) {
632
      foreach ($items as $key => $item) {
633
        $items[$key] = ' - ' . $item;
634
      }
635
      $output = implode("\n", $items);
636
    }
637
    else {
638
      $output = isset($items[0]) ? $items[0] : ' ';
639
    }
640
  }
641

    
642
  return $output;
643
}
644

    
645
/**
646
 * Implements _webform_analysis_component().
647
 */
648
function _webform_analysis_select($component, $sids = array(), $single = FALSE, $join = NULL) {
649
  $options = _webform_select_options($component, TRUE);
650

    
651
  // Create a generic query for the component.
652
  $query = db_select('webform_submitted_data', 'wsd', array('fetch' => PDO::FETCH_ASSOC))
653
    ->condition('wsd.nid', $component['nid'])
654
    ->condition('wsd.cid', $component['cid'])
655
    ->condition('wsd.data', '', '<>');
656

    
657
  if ($sids) {
658
    $query->condition('wsd.sid', $sids, 'IN');
659
  }
660

    
661
  if ($join) {
662
    $query->innerJoin($join, 'ws2_', 'wsd.sid = ws2_.sid');
663
  }
664

    
665
  // Clone the query for later use, if needed.
666
  if ($component['extra']['other_option']) {
667
    $count_query = clone $query;
668
    if ($single) {
669
      $other_query = clone $query;
670
    }
671
  }
672

    
673
  $rows = array();
674
  $other = array();
675
  $normal_count = 0;
676

    
677
  if ($options) {
678
    // Gather the normal results first (not "other" options).
679
    $query->addExpression('COUNT(wsd.data)', 'datacount');
680
    $result = $query
681
      ->condition('wsd.data', array_keys($options), 'IN')
682
      ->fields('wsd', array('data'))
683
      ->groupBy('wsd.data')
684
      ->execute();
685
    foreach ($result as $data) {
686
      $display_option = isset($options[$data['data']]) ? $options[$data['data']] : $data['data'];
687
      $rows[$data['data']] = array(webform_filter_xss($display_option), $data['datacount']);
688
      $normal_count += $data['datacount'];
689
    }
690

    
691
    // Order the results according to the normal options array.
692
    $ordered_rows = array();
693
    foreach (array_intersect_key($options, $rows) as $key => $label) {
694
      $ordered_rows[] = $rows[$key];
695
    }
696
    $rows = $ordered_rows;
697
  }
698

    
699
  // Add a row for displaying the total unknown or user-entered values.
700
  if ($component['extra']['other_option']) {
701
    $count_query->addExpression('COUNT(*)', 'datacount');
702
    $full_count = $count_query->execute()->fetchField();
703
    $other_count = $full_count - $normal_count;
704
    $display_option = !empty($component['extra']['other_text']) ? check_plain($component['extra']['other_text']) : t('Other...');
705
    $other_text = ($other_count && !$single) ? $other_count . ' (' . l(t('view'), 'node/' . $component['nid'] . '/webform-results/analysis/' . $component['cid']) . ')' : $other_count;
706
    $rows[] = array($display_option, $other_text);
707

    
708
    // If showing all results, execute the "other" query and append their rows.
709
    if ($single) {
710
      $other_query->addExpression('COUNT(wsd.data)', 'datacount');
711
      $other_query
712
        ->fields('wsd', array('data'))
713
        ->groupBy('wsd.data');
714
      if ($options) {
715
        $other_query->condition('wsd.data', array_keys($options), 'NOT IN');
716
      }
717
      $other_result = $other_query->execute();
718
      foreach ($other_result as $data) {
719
        $other[] = array(check_plain($data['data']), $data['datacount']);
720
      }
721
      if ($other) {
722
        array_unshift($other, '<strong>' . t('Other responses') . '</strong>');
723
      }
724
    }
725
  }
726

    
727
  return array(
728
    'table_rows' => $rows,
729
    'other_data' => $other,
730
  );
731
}
732

    
733
/**
734
 * Implements _webform_table_component().
735
 */
736
function _webform_table_select($component, $value) {
737
  // Convert submitted 'safe' values to un-edited, original form.
738
  $options = _webform_select_options($component, TRUE);
739

    
740
  $value = (array) $value;
741
  ksort($value, SORT_NUMERIC);
742
  $items = array();
743
  // Set the value as a single string.
744
  foreach ($value as $option_value) {
745
    if ($option_value !== '') {
746
      if (isset($options[$option_value])) {
747
        $items[] = webform_filter_xss($options[$option_value]);
748
      }
749
      else {
750
        $items[] = check_plain($option_value);
751
      }
752
    }
753
  }
754

    
755
  return implode('<br />', $items);
756
}
757

    
758
/**
759
 * Implements _webform_action_set_component().
760
 */
761
function _webform_action_set_select($component, &$element, &$form_state, $value) {
762
  // Set the value as an array for multiple select or single value otherwise.
763
  if ($element['#type'] == 'checkboxes') {
764
    $checkbox_values = $element['#options'];
765
    array_walk($checkbox_values, function (&$option_value, $key) use ($value) {
766
      $option_value = (int) (strval($key) === $value);
767
    });
768
  }
769
  else {
770
    $value = $component['extra']['multiple'] ? array($value) : $value;
771
  }
772
  $element['#value'] = $value;
773
  form_set_value($element, $value, $form_state);
774
}
775

    
776
/**
777
 * Implements _webform_csv_headers_component().
778
 */
779
function _webform_csv_headers_select($component, $export_options) {
780
  $headers = array(
781
    0 => array(),
782
    1 => array(),
783
    2 => array(),
784
  );
785

    
786
  if ($component['extra']['multiple'] && $export_options['select_format'] == 'separate') {
787
    $headers[0][] = '';
788
    $headers[1][] = $export_options['header_keys'] ? $component['form_key'] : $component['name'];
789
    $items = _webform_select_options($component, TRUE);
790
    if ($component['extra']['other_option']) {
791
      if ($export_options['header_keys']) {
792
        $other_label = $component['form_key'] . '_other';
793
      }
794
      else {
795
        $other_label = !empty($component['extra']['other_text']) ? check_plain($component['extra']['other_text']) : t('Other...');
796
      }
797
      $items[$other_label] = $other_label;
798
    }
799
    $count = 0;
800
    foreach ($items as $key => $item) {
801
      // Empty column per sub-field in main header.
802
      if ($count != 0) {
803
        $headers[0][] = '';
804
        $headers[1][] = '';
805
      }
806
      if ($export_options['select_keys']) {
807
        $headers[2][] = $key;
808
      }
809
      else {
810
        $headers[2][] = $item;
811
      }
812
      $count++;
813
    }
814
  }
815
  else {
816
    $headers[0][] = '';
817
    $headers[1][] = '';
818
    $headers[2][] = $export_options['header_keys'] ? $component['form_key'] : $component['name'];
819
  }
820
  return $headers;
821
}
822

    
823
/**
824
 * Implements _webform_csv_data_component().
825
 */
826
function _webform_csv_data_select($component, $export_options, $value) {
827
  $options = _webform_select_options($component, TRUE);
828
  $return = array();
829

    
830
  if ($component['extra']['multiple']) {
831
    foreach ($options as $key => $item) {
832
      // Strict search is needed to avoid a key of 0 from matching an empty
833
      // value.
834
      $index = array_search((string) $key, (array) $value, TRUE);
835
      if ($index !== FALSE) {
836
        if ($export_options['select_format'] == 'separate') {
837
          $return[] = 'X';
838
        }
839
        else {
840
          $return[] = $export_options['select_keys'] ? $key : $item;
841
        }
842
        unset($value[$index]);
843
      }
844
      elseif ($export_options['select_format'] == 'separate') {
845
        $return[] = '';
846
      }
847
    }
848

    
849
    // Any remaining items in the $value array will be user-added options.
850
    if ($component['extra']['other_option']) {
851
      $return[] = count($value) ? implode(',', $value) : '';
852
    }
853
  }
854
  else {
855
    $key = $value[0];
856
    if ($export_options['select_keys']) {
857
      $return = $key;
858
    }
859
    else {
860
      $return = isset($options[$key]) ? $options[$key] : $key;
861
    }
862
  }
863

    
864
  if ($component['extra']['multiple'] && $export_options['select_format'] == 'compact') {
865
    $return = implode(',', (array) $return);
866
  }
867

    
868
  return $return;
869
}
870

    
871
/**
872
 * Implements _webform_options_component().
873
 *
874
 * This function is confusingly an alias of _webform_select_options(). However
875
 * this version is intended to be accessed publicly via
876
 * webform_component_invoke(), since it is a Webform "hook", rather than an
877
 * internal, private function. To get the list of select list options for
878
 * a component, use:
879
 *
880
 * @code
881
 * $options = webform_component_invoke($component['type'], 'options', $component);
882
 * @endcode
883
 */
884
function _webform_options_select($component, $flat = FALSE) {
885
  return _webform_select_options($component, $flat);
886
}
887

    
888
/**
889
 * Menu callback; Return a predefined list of select options as JSON.
890
 */
891
function webform_select_options_ajax($source_name = '') {
892
  $info = _webform_select_options_info();
893

    
894
  $component['extra']['options_source'] = $source_name;
895
  if ($source_name && isset($info[$source_name])) {
896
    $options = _webform_select_options_to_text(_webform_select_options($component, FALSE, FALSE));
897
  }
898
  else {
899
    $options = '';
900
  }
901

    
902
  $return = array(
903
    'elementId' => module_exists('options_element') ? 'edit-items-options-options-field-widget' : 'edit-extra-items',
904
    'options' => $options,
905
  );
906

    
907
  drupal_json_output($return);
908
}
909

    
910
/**
911
 * Generate a list of options for a select list.
912
 */
913
function _webform_select_options($component, $flat = FALSE, $filter = TRUE) {
914
  if ($component['extra']['options_source']) {
915
    $options = _webform_select_options_callback($component['extra']['options_source'], $component, $flat);
916
  }
917
  else {
918
    $options = _webform_select_options_from_text($component['extra']['items'], $flat);
919
  }
920

    
921
  // Replace tokens if needed in the options.
922
  if ($filter) {
923
    $node = node_load($component['nid']);
924
    $options = _webform_select_replace_tokens($options, $node);
925
  }
926

    
927
  return isset($options) ? $options : array();
928
}
929

    
930
/**
931
 * Replace tokens in the values of a list of select options.
932
 */
933
function _webform_select_replace_tokens($options, $node) {
934
  foreach ($options as $key => $option) {
935
    if (is_array($option)) {
936
      $options[$key] = _webform_select_replace_tokens($option, $node);
937
    }
938
    else {
939
      $options[$key] = webform_replace_tokens($option, $node);
940
    }
941
  }
942
  return $options;
943
}
944

    
945
/**
946
 * Load Webform select option info from 3rd party modules.
947
 */
948
function _webform_select_options_info() {
949
  static $info;
950
  if (!isset($info)) {
951
    $info = array();
952

    
953
    foreach (module_implements('webform_select_options_info') as $module) {
954
      $additions = module_invoke($module, 'webform_select_options_info');
955
      foreach ($additions as $key => $addition) {
956
        $additions[$key]['module'] = $module;
957
      }
958
      $info = array_merge($info, $additions);
959
    }
960
    drupal_alter('webform_select_options_info', $info);
961
  }
962
  return $info;
963
}
964

    
965
/**
966
 * Execute a select option callback.
967
 *
968
 * @param $name
969
 *   The name of the options group.
970
 * @param $component
971
 *   The full Webform component.
972
 * @param $flat
973
 *   Whether the information returned should exclude any nested groups.
974
 */
975
function _webform_select_options_callback($name, $component, $flat = FALSE) {
976
  $info = _webform_select_options_info();
977

    
978
  // Include any necessary files.
979
  if (isset($info[$name]['file'])) {
980
    $pathinfo = pathinfo($info[$name]['file']);
981
    $path = ($pathinfo['dirname'] ? $pathinfo['dirname'] . '/' : '') . basename($pathinfo['basename'], '.' . $pathinfo['extension']);
982
    module_load_include($pathinfo['extension'], $info[$name]['module'], $path);
983
  }
984

    
985
  // Execute the callback function.
986
  if (isset($info[$name]['options callback']) && is_callable($info[$name]['options callback'])) {
987
    $function = $info[$name]['options callback'];
988

    
989
    $arguments = array();
990
    if (isset($info[$name]['options arguments'])) {
991
      $arguments = $info[$name]['options arguments'];
992
    }
993

    
994
    return $function($component, $flat, $arguments);
995
  }
996
}
997

    
998
/**
999
 * Splits user values from new-line separated text into an array of options.
1000
 *
1001
 * @param string $text
1002
 *   Text to be converted into a select option array.
1003
 * @param bool $flat
1004
 *   Optional. If specified, return the option array and exclude any optgroups.
1005
 *
1006
 * @return array
1007
 *   An array of options suitable for use as a #options property. Note that
1008
 *   values are not filtered and may contain tokens. Individual values should be
1009
 *   run through webform_replace_tokens() if displaying to an end-user.
1010
 */
1011
function _webform_select_options_from_text($text, $flat = FALSE) {
1012
  static $option_cache = array();
1013

    
1014
  // Keep each processed option block in an array indexed by the MD5 hash of
1015
  // the option text and the value of the $flat variable.
1016
  $md5 = md5($text);
1017

    
1018
  // Check if this option block has been previously processed.
1019
  if (!isset($option_cache[$flat][$md5])) {
1020
    $options = array();
1021
    $rows = array_filter(explode("\n", trim($text)));
1022
    $group = NULL;
1023
    foreach ($rows as $option) {
1024
      $option = trim($option);
1025
      /*
1026
       * If the Key of the option is within < >, treat as an optgroup
1027
       *
1028
       * <Group 1>
1029
       *   creates an optgroup with the label "Group 1"
1030
       *
1031
       * <>
1032
       *   Unsets the current group, allowing items to be inserted at the root element.
1033
       */
1034
      if (preg_match('/^\<([^>]*)\>$/', $option, $matches)) {
1035
        if (empty($matches[1])) {
1036
          unset($group);
1037
        }
1038
        elseif (!$flat) {
1039
          $group = $matches[1];
1040
        }
1041
      }
1042
      elseif (preg_match('/^([^|]+)\|(.*)$/', $option, $matches)) {
1043
        $key = $matches[1];
1044
        $value = $matches[2];
1045
        isset($group) ? $options[$group][$key] = $value : $options[$key] = $value;
1046
      }
1047
      else {
1048
        isset($group) ? $options[$group][$option] = $option : $options[$option] = $option;
1049
      }
1050
    }
1051

    
1052
    $option_cache[$flat][$md5] = $options;
1053
  }
1054

    
1055
  // Return our options from the option_cache array.
1056
  return $option_cache[$flat][$md5];
1057
}
1058

    
1059
/**
1060
 * Convert an array of options into text.
1061
 */
1062
function _webform_select_options_to_text($options) {
1063
  $output = '';
1064
  $previous_key = FALSE;
1065

    
1066
  foreach ($options as $key => $value) {
1067
    // Convert groups.
1068
    if (is_array($value)) {
1069
      $output .= '<' . $key . '>' . "\n";
1070
      foreach ($value as $subkey => $subvalue) {
1071
        $output .= $subkey . '|' . $subvalue . "\n";
1072
      }
1073
      $previous_key = $key;
1074
    }
1075
    // Typical key|value pairs.
1076
    else {
1077
      // Exit out of any groups.
1078
      if (isset($options[$previous_key]) && is_array($options[$previous_key])) {
1079
        $output .= "<>\n";
1080
      }
1081
      // Skip empty rows.
1082
      if ($options[$key] !== '') {
1083
        $output .= $key . '|' . $value . "\n";
1084
      }
1085
      $previous_key = $key;
1086
    }
1087
  }
1088

    
1089
  return $output;
1090
}
1091

    
1092
/**
1093
 * Utility function to shuffle an array while preserving key-value pairs.
1094
 */
1095
function _webform_shuffle_options(&$array) {
1096
  // First shuffle the array keys, then use them as the basis for ordering
1097
  // the options.
1098
  $aux = array();
1099
  $keys = array_keys($array);
1100
  shuffle($keys);
1101
  foreach ($keys as $key) {
1102
    $aux[$key] = $array[$key];
1103
  }
1104
  $array = $aux;
1105
}