select.inc 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937
  1. <?php
  2. /**
  3. * @file
  4. * Webform module multiple select component.
  5. */
  6. /**
  7. * Implements _webform_defaults_component().
  8. */
  9. function _webform_defaults_select() {
  10. return array(
  11. 'name' => '',
  12. 'form_key' => NULL,
  13. 'mandatory' => 0,
  14. 'pid' => 0,
  15. 'weight' => 0,
  16. 'value' => '',
  17. 'extra' => array(
  18. 'items' => '',
  19. 'multiple' => NULL,
  20. 'aslist' => NULL,
  21. 'optrand' => 0,
  22. 'other_option' => NULL,
  23. 'other_text' => t('Other...'),
  24. 'title_display' => 0,
  25. 'description' => '',
  26. 'custom_keys' => FALSE,
  27. 'options_source' => '',
  28. 'private' => FALSE,
  29. ),
  30. );
  31. }
  32. /**
  33. * Implements _webform_theme_component().
  34. */
  35. function _webform_theme_select() {
  36. return array(
  37. 'webform_display_select' => array(
  38. 'render element' => 'element',
  39. 'file' => 'components/select.inc',
  40. ),
  41. );
  42. }
  43. /**
  44. * Implements _webform_edit_component().
  45. */
  46. function _webform_edit_select($component) {
  47. $form = array(
  48. '#attached' => array(
  49. 'js' => array(
  50. drupal_get_path('module', 'webform') . '/js/select-admin.js' => array('preprocess' => FALSE),
  51. array('data' => array('webform' => array('selectOptionsUrl' => url('webform/ajax/options/' . $component['nid']))), 'type' => 'setting'),
  52. ),
  53. ),
  54. );
  55. $other = array();
  56. if ($info = _webform_select_options_info()) {
  57. $options = array('' => t('None'));
  58. foreach ($info as $name => $source) {
  59. $options[$name] = $source['title'];
  60. }
  61. $other['options_source'] = array(
  62. '#title' => t('Load a pre-built option list'),
  63. '#type' => 'select',
  64. '#options' => $options,
  65. '#default_value' => $component['extra']['options_source'],
  66. '#weight' => 1,
  67. '#description' => t('Use a pre-built list of options rather than entering options manually. Options will not be editable if using pre-built list.'),
  68. '#parents' => array('extra', 'options_source'),
  69. '#weight' => 5,
  70. );
  71. }
  72. if (module_exists('select_or_other')) {
  73. $other['other_option'] = array(
  74. '#type' => 'checkbox',
  75. '#title' => t('Allow "Other..." option'),
  76. '#default_value' => $component['extra']['other_option'],
  77. '#description' => t('Check this option if you want to allow users to enter an option not on the list.'),
  78. '#parents' => array('extra', 'other_option'),
  79. '#weight' => 2,
  80. );
  81. $other['other_text'] = array(
  82. '#type' => 'textfield',
  83. '#title' => t('Text for "Other..." option'),
  84. '#default_value' => $component['extra']['other_text'],
  85. '#description' => t('If allowing other options, enter text to be used for other-enabling option.'),
  86. '#parents' => array('extra', 'other_text'),
  87. '#weight' => 3,
  88. );
  89. }
  90. if (module_exists('options_element')) {
  91. $options = _webform_select_options($component, FALSE, FALSE);
  92. $form['items'] = array(
  93. '#type' => 'fieldset',
  94. '#title' => t('Options'),
  95. '#collapsible' => TRUE,
  96. '#attributes' => array('class' => array('webform-options-element')),
  97. '#element_validate' => array('_webform_edit_validate_options'),
  98. '#weight' => 2,
  99. );
  100. $form['items']['options'] = array(
  101. '#type' => 'options',
  102. '#limit' => 500,
  103. '#optgroups' => $component['extra']['aslist'],
  104. '#multiple' => $component['extra']['multiple'],
  105. '#multiple_toggle' => t('Multiple'),
  106. '#default_value' => $component['value'],
  107. '#options' => $options,
  108. '#options_readonly' => !empty($component['extra']['options_source']),
  109. '#key_type' => 'mixed',
  110. '#key_type_toggle' => t('Customize keys (Advanced)'),
  111. '#key_type_toggled' => $component['extra']['custom_keys'],
  112. '#default_value_pattern' => '^%.+\[.+\]$',
  113. '#weight' => 1,
  114. );
  115. $form['items']['options']['option_settings'] = $other;
  116. }
  117. else {
  118. $form['extra']['items'] = array(
  119. '#type' => 'textarea',
  120. '#title' => t('Options'),
  121. '#default_value' => $component['extra']['items'],
  122. '#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'),
  123. '#cols' => 60,
  124. '#rows' => 5,
  125. '#weight' => 0,
  126. '#required' => TRUE,
  127. '#wysiwyg' => FALSE,
  128. '#element_validate' => array('_webform_edit_validate_select'),
  129. );
  130. if (!empty($component['extra']['options_source'])) {
  131. $form['extra']['items']['#attributes'] = array('readonly' => 'readonly');
  132. }
  133. $form['extra'] = array_merge($form['extra'], $other);
  134. $form['value'] = array(
  135. '#type' => 'textfield',
  136. '#title' => t('Default value'),
  137. '#default_value' => $component['value'],
  138. '#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'),
  139. '#size' => 60,
  140. '#maxlength' => 1024,
  141. '#weight' => 0,
  142. );
  143. $form['extra']['multiple'] = array(
  144. '#type' => 'checkbox',
  145. '#title' => t('Multiple'),
  146. '#default_value' => $component['extra']['multiple'],
  147. '#description' => t('Check this option if the user should be allowed to choose multiple values.'),
  148. '#weight' => 0,
  149. );
  150. }
  151. $form['display']['aslist'] = array(
  152. '#type' => 'checkbox',
  153. '#title' => t('Listbox'),
  154. '#default_value' => $component['extra']['aslist'],
  155. '#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.'),
  156. '#parents' => array('extra', 'aslist'),
  157. );
  158. $form['display']['optrand'] = array(
  159. '#type' => 'checkbox',
  160. '#title' => t('Randomize options'),
  161. '#default_value' => $component['extra']['optrand'],
  162. '#description' => t('Randomizes the order of the options when they are displayed in the form.'),
  163. '#parents' => array('extra', 'optrand'),
  164. );
  165. return $form;
  166. }
  167. /**
  168. * Element validation callback. Ensure keys are not duplicated.
  169. */
  170. function _webform_edit_validate_select($element, &$form_state) {
  171. // Check for duplicate key values to prevent unexpected data loss. Require
  172. // all options to include a safe_key.
  173. if (!empty($element['#value'])) {
  174. $lines = explode("\n", trim($element['#value']));
  175. $existing_keys = array();
  176. $duplicate_keys = array();
  177. $missing_keys = array();
  178. $long_keys = array();
  179. $group = '';
  180. foreach ($lines as $line) {
  181. $matches = array();
  182. $line = trim($line);
  183. if (preg_match('/^\<([^>]*)\>$/', $line, $matches)) {
  184. $group = $matches[1];
  185. $key = NULL; // No need to store group names.
  186. }
  187. elseif (preg_match('/^([^|]*)\|(.*)$/', $line, $matches)) {
  188. $key = $matches[1];
  189. if (strlen($key) > 128) {
  190. $long_keys[] = $key;
  191. }
  192. }
  193. else {
  194. $missing_keys[] = $line;
  195. }
  196. if (isset($key)) {
  197. if (isset($existing_keys[$group][$key])) {
  198. $duplicate_keys[$key] = $key;
  199. }
  200. else {
  201. $existing_keys[$group][$key] = $key;
  202. }
  203. }
  204. }
  205. if (!empty($missing_keys)) {
  206. form_error($element, t('Every option must have a key specified. Specify each option as "safe_key|Some readable option".'));
  207. }
  208. if (!empty($long_keys)) {
  209. form_error($element, t('Option keys must be less than 128 characters. The following keys exceed this limit:') . theme('item_list', $long_keys));
  210. }
  211. if (!empty($duplicate_keys)) {
  212. 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)));
  213. }
  214. // Set the listbox option if needed.
  215. if (empty($missing_keys) && empty($long_keys) && empty($duplicate_keys)) {
  216. $options = _webform_select_options_from_text($element['#value']);
  217. _webform_edit_validate_set_aslist($options, $form_state);
  218. }
  219. }
  220. return TRUE;
  221. }
  222. /**
  223. * Set the appropriate webform values when using the options element module.
  224. */
  225. function _webform_edit_validate_options($element, &$form_state) {
  226. $key = end($element['#parents']);
  227. $element_options = $form_state['values'][$key]['options'];
  228. unset($form_state['values'][$key]);
  229. $form_state['values']['extra'][$key] = form_options_to_text($element_options['options'], 'custom');
  230. // Options saved for select components.
  231. if ($key == 'items') {
  232. $form_state['values']['extra']['multiple'] = $element_options['multiple'];
  233. $form_state['values']['extra']['custom_keys'] = $element_options['custom_keys'];
  234. $form_state['values']['value'] = is_array($element_options['default_value']) ? implode(', ', $element_options['default_value']) : $element_options['default_value'];
  235. // Set the listbox option if needed.
  236. _webform_edit_validate_set_aslist($element_options['options'], $form_state);
  237. }
  238. // Options saved for grid components.
  239. else {
  240. $form_state['values']['extra']['custom_' . rtrim($key, 's') . '_keys'] = $element_options['custom_keys'];
  241. }
  242. }
  243. /**
  244. * Ensure "aslist" is used for option groups. Called from options validations.
  245. */
  246. function _webform_edit_validate_set_aslist($options, &$form_state) {
  247. if (empty($form_state['values']['extra']['aslist']) && !empty($options)) {
  248. foreach ($options as $option) {
  249. if (is_array($option)) {
  250. $form_state['values']['extra']['aslist'] = 1;
  251. 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');
  252. break;
  253. }
  254. }
  255. }
  256. }
  257. /**
  258. * Implements _webform_render_component().
  259. */
  260. function _webform_render_select($component, $value = NULL, $filter = TRUE) {
  261. $node = isset($component['nid']) ? node_load($component['nid']) : NULL;
  262. $element = array(
  263. '#title' => $filter ? _webform_filter_xss($component['name']) : $component['name'],
  264. '#title_display' => $component['extra']['title_display'] ? $component['extra']['title_display'] : 'before',
  265. '#required' => $component['mandatory'],
  266. '#weight' => $component['weight'],
  267. '#description' => $filter ? _webform_filter_descriptions($component['extra']['description'], $node) : $component['extra']['description'],
  268. '#theme_wrappers' => array('webform_element'),
  269. '#pre_render' => array(), // Needed to disable double-wrapping of radios and checkboxes.
  270. '#translatable' => array('title', 'description', 'options'),
  271. );
  272. // Convert the user-entered options list into an array.
  273. $default_value = $filter ? _webform_filter_values($component['value'], $node, NULL, NULL, FALSE) : $component['value'];
  274. $options = _webform_select_options($component, !$component['extra']['aslist'], $filter);
  275. if ($component['extra']['optrand']) {
  276. _webform_shuffle_options($options);
  277. }
  278. // Add default options if using a select list with no default. This trigger's
  279. // Drupal 7's adding of the option for us. See @form_process_select().
  280. if ($component['extra']['aslist'] && !$component['extra']['multiple'] && $default_value === '') {
  281. $element['#empty_value'] = '';
  282. }
  283. // Set the component options.
  284. $element['#options'] = $options;
  285. // Use the component's default value if the component is currently empty.
  286. if (!isset($value)) {
  287. // The default for multiple selects is a comma-delimited list, without white-space or empty entries.
  288. $value = $component['extra']['multiple'] ? array_filter(array_map('trim', explode(',', $default_value)), 'strlen') : $default_value;
  289. }
  290. // Convert all values into an array; component may now be single but was previously multiple, or vice-versa
  291. $value = (array)$value;
  292. // Set the default value. Note: "No choice" is stored as an empty string,
  293. // which will match a 0 key for radios; NULL is used to avoid unintentional
  294. // defaulting to the 0 option.
  295. if ($component['extra']['multiple']) {
  296. // Set the value as an array.
  297. $element['#default_value'] = array();
  298. foreach ($value as $option_value) {
  299. $element['#default_value'][] = $option_value === '' ? NULL : $option_value;
  300. }
  301. }
  302. else {
  303. // Set the value as a single string.
  304. $option_value = reset($value);
  305. $element['#default_value'] = $option_value === '' ? NULL : $option_value;
  306. }
  307. if ($component['extra']['other_option'] && module_exists('select_or_other')) {
  308. // Set display as a select_or_other element:
  309. $element['#type'] = 'select_or_other';
  310. $element['#other'] = !empty($component['extra']['other_text']) ? check_plain($component['extra']['other_text']) : t('Other...');
  311. $element['#translatable'][] = 'other';
  312. $element['#other_title'] = $element['#title'] . ' ' . $element['#other'];
  313. $element['#other_title_display'] = 'invisible';
  314. $element['#other_unknown_defaults'] = 'other';
  315. $element['#other_delimiter'] = ', ';
  316. // Merge in Webform's #process function for Select or other.
  317. $element['#process'] = array_merge(element_info_property('select_or_other', '#process'), array('webform_expand_select_or_other'));
  318. if ($component['extra']['multiple']) {
  319. $element['#multiple'] = TRUE;
  320. $element['#select_type'] = 'checkboxes';
  321. }
  322. else {
  323. $element['#multiple'] = FALSE;
  324. $element['#select_type'] = 'radios';
  325. }
  326. if ($component['extra']['aslist']) {
  327. $element['#select_type'] = 'select';
  328. }
  329. }
  330. elseif ($component['extra']['aslist']) {
  331. // Set display as a select list:
  332. $element['#type'] = 'select';
  333. if ($component['extra']['multiple']) {
  334. $element['#size'] = 4;
  335. $element['#multiple'] = TRUE;
  336. }
  337. }
  338. else {
  339. if ($component['extra']['multiple']) {
  340. // Set display as a checkbox set.
  341. $element['#type'] = 'checkboxes';
  342. $element['#theme_wrappers'] = array_merge(array('checkboxes'), $element['#theme_wrappers']);
  343. $element['#process'] = array_merge(element_info_property('checkboxes', '#process'), array('webform_expand_select_ids'));
  344. }
  345. else {
  346. // Set display as a radio set.
  347. $element['#type'] = 'radios';
  348. $element['#theme_wrappers'] = array_merge(array('radios'), $element['#theme_wrappers']);
  349. $element['#process'] = array_merge(element_info_property('radios', '#process'), array('webform_expand_select_ids'));
  350. }
  351. }
  352. return $element;
  353. }
  354. /**
  355. * Process function to ensure select_or_other elements validate properly.
  356. */
  357. function webform_expand_select_or_other($element) {
  358. // Disable validation for back-button and save draft.
  359. $element['select']['#validated'] = TRUE;
  360. $element['select']['#webform_validated'] = FALSE;
  361. $element['other']['#validated'] = TRUE;
  362. $element['other']['#webform_validated'] = FALSE;
  363. // The Drupal FAPI does not support #title_display inline so we need to move
  364. // to a supported value here to be compatible with select_or_other.
  365. $element['select']['#title_display'] = $element['#title_display'] === 'inline' ? 'before' : $element['#title_display'];
  366. // If the default value contains "select_or_other" (the key of the select
  367. // element for the "other..." choice), discard it and set the "other" value.
  368. if (is_array($element['#default_value']) && in_array('select_or_other', $element['#default_value'])) {
  369. $key = array_search('select_or_other', $element['#default_value']);
  370. unset($element['#default_value'][$key]);
  371. $element['#default_value'] = array_values($element['#default_value']);
  372. $element['other']['#default_value'] = implode(', ', $element['#default_value']);
  373. }
  374. // Sanitize the options in Select or other check boxes and radio buttons.
  375. if ($element['#select_type'] == 'checkboxes' || $element['#select_type'] == 'radios') {
  376. $element['select']['#process'] = array_merge(element_info_property($element['#select_type'], '#process'), array('webform_expand_select_ids'));
  377. }
  378. return $element;
  379. }
  380. /**
  381. * FAPI process function to rename IDs attached to checkboxes and radios.
  382. */
  383. function webform_expand_select_ids($element) {
  384. $id = $element['#id'] = str_replace('_', '-', _webform_safe_name(strip_tags($element['#id'])));
  385. $delta = 0;
  386. foreach (element_children($element) as $key) {
  387. $delta++;
  388. // Convert the #id for each child to a safe name, regardless of key.
  389. $element[$key]['#id'] = $id . '-' . $delta;
  390. // Prevent scripts or CSS in the labels for each checkbox or radio.
  391. $element[$key]['#title'] = _webform_filter_xss($element[$key]['#title']);
  392. }
  393. return $element;
  394. }
  395. /**
  396. * Implements _webform_display_component().
  397. */
  398. function _webform_display_select($component, $value, $format = 'html') {
  399. return array(
  400. '#title' => $component['name'],
  401. '#weight' => $component['weight'],
  402. '#multiple' => $component['extra']['multiple'],
  403. '#theme' => 'webform_display_select',
  404. '#theme_wrappers' => $format == 'html' ? array('webform_element') : array('webform_element_text'),
  405. '#format' => $format,
  406. '#options' => _webform_select_options($component, !$component['extra']['aslist']),
  407. '#value' => (array) $value,
  408. '#translatable' => array('title', 'options'),
  409. );
  410. }
  411. /**
  412. * Implements _webform_submit_component().
  413. *
  414. * Convert FAPI 0/1 values into something saveable.
  415. */
  416. function _webform_submit_select($component, $value) {
  417. // Build a list of all valid keys expected to be submitted.
  418. $options = _webform_select_options($component, TRUE);
  419. $return = NULL;
  420. if (is_array($value)) {
  421. $return = array();
  422. foreach ($value as $key => $option_value) {
  423. // Handle options that are specified options.
  424. if ($option_value !== '' && isset($options[$option_value])) {
  425. // Checkboxes submit an integer value of 0 when unchecked. A checkbox
  426. // with a value of '0' is valid, so we can't use empty() here.
  427. if ($option_value === 0 && !$component['extra']['aslist'] && $component['extra']['multiple']) {
  428. unset($value[$option_value]);
  429. }
  430. else {
  431. $return[] = $option_value;
  432. }
  433. }
  434. // Handle options that are added through the "other" field. Specifically
  435. // exclude the "select_or_other" value, which is added by the select list.
  436. elseif ($component['extra']['other_option'] && module_exists('select_or_other') && $option_value != 'select_or_other') {
  437. $return[] = $option_value;
  438. }
  439. }
  440. }
  441. elseif (is_string($value)) {
  442. $return = $value;
  443. }
  444. return $return;
  445. }
  446. /**
  447. * Format the text output for this component.
  448. */
  449. function theme_webform_display_select($variables) {
  450. $element = $variables['element'];
  451. // Flatten the list of options so we can get values easily. These options
  452. // may be translated by hook_webform_display_component_alter().
  453. $options = array();
  454. foreach ($element['#options'] as $key => $value) {
  455. if (is_array($value)) {
  456. foreach ($value as $subkey => $subvalue) {
  457. $options[$subkey] = $subvalue;
  458. }
  459. }
  460. else {
  461. $options[$key] = $value;
  462. }
  463. }
  464. $items = array();
  465. if ($element['#multiple']) {
  466. foreach ((array) $element['#value'] as $option_value) {
  467. if ($option_value !== '') {
  468. // Administer provided values.
  469. if (isset($options[$option_value])) {
  470. $items[] = $element['#format'] == 'html' ? _webform_filter_xss($options[$option_value]) : $options[$option_value];
  471. }
  472. // User-specified in the "other" field.
  473. else {
  474. $items[] = $element['#format'] == 'html' ? check_plain($option_value) : $option_value;
  475. }
  476. }
  477. }
  478. }
  479. else {
  480. if (isset($element['#value'][0]) && $element['#value'][0] !== '') {
  481. // Administer provided values.
  482. if (isset($options[$element['#value'][0]])) {
  483. $items[] = $element['#format'] == 'html' ? _webform_filter_xss($options[$element['#value'][0]]) : $options[$element['#value'][0]];
  484. }
  485. // User-specified in the "other" field.
  486. else {
  487. $items[] = $element['#format'] == 'html' ? check_plain($element['#value'][0]) : $element['#value'][0];
  488. }
  489. }
  490. }
  491. if ($element['#format'] == 'html') {
  492. $output = count($items) > 1 ? theme('item_list', array('items' => $items)) : (isset($items[0]) ? $items[0] : ' ');
  493. }
  494. else {
  495. if (count($items) > 1) {
  496. foreach ($items as $key => $item) {
  497. $items[$key] = ' - ' . $item;
  498. }
  499. $output = implode("\n", $items);
  500. }
  501. else {
  502. $output = isset($items[0]) ? $items[0] : ' ';
  503. }
  504. }
  505. return $output;
  506. }
  507. /**
  508. * Implements _webform_analysis_component().
  509. */
  510. function _webform_analysis_select($component, $sids = array(), $single = FALSE) {
  511. $options = _webform_select_options($component, TRUE);
  512. $show_other_results = $single;
  513. $sid_placeholders = count($sids) ? array_fill(0, count($sids), "'%s'") : array();
  514. $sid_filter = count($sids) ? " AND sid IN (" . implode(",", $sid_placeholders) . ")" : "";
  515. $option_operator = $show_other_results ? 'NOT IN' : 'IN';
  516. $query = db_select('webform_submitted_data', 'wsd', array('fetch' => PDO::FETCH_ASSOC))
  517. ->fields('wsd', array('data'))
  518. ->condition('nid', $component['nid'])
  519. ->condition('cid', $component['cid'])
  520. ->condition('data', '', '<>')
  521. ->condition('data', array_keys($options), $option_operator)
  522. ->groupBy('data');
  523. $query->addExpression('COUNT(data)', 'datacount');
  524. if (count($sids)) {
  525. $query->condition('sid', $sids, 'IN');
  526. }
  527. $count_query = db_select('webform_submitted_data', 'wsd', array('fetch' => PDO::FETCH_ASSOC))
  528. ->condition('nid', $component['nid'])
  529. ->condition('cid', $component['cid'])
  530. ->condition('data', '', '<>');
  531. $count_query->addExpression('COUNT(*)', 'datacount');
  532. if (count($sids)) {
  533. $count_query->condition('sid', $sids, 'IN');
  534. }
  535. $result = $query->execute();
  536. $rows = array();
  537. $normal_count = 0;
  538. foreach ($result as $data) {
  539. $display_option = $single ? $data['data'] : $options[$data['data']];
  540. $rows[$data['data']] = array(_webform_filter_xss($display_option), $data['datacount']);
  541. $normal_count += $data['datacount'];
  542. }
  543. if (!$show_other_results) {
  544. // Order the results according to the normal options array.
  545. $ordered_rows = array();
  546. foreach (array_intersect_key($options, $rows) as $key => $label) {
  547. $ordered_rows[] = $rows[$key];
  548. }
  549. // Add a row for any unknown or user-entered values.
  550. if ($component['extra']['other_option']) {
  551. $full_count = $count_query->execute()->fetchField();
  552. $other_count = $full_count - $normal_count;
  553. $display_option = !empty($component['extra']['other_text']) ? check_plain($component['extra']['other_text']) : t('Other...');
  554. $other_text = $other_count ? $other_count . ' (' . l(t('view'), 'node/' . $component['nid'] . '/webform-results/analysis/' . $component['cid']) . ')' : $other_count;
  555. $ordered_rows[] = array($display_option, $other_text);
  556. }
  557. $rows = $ordered_rows;
  558. }
  559. return $rows;
  560. }
  561. /**
  562. * Implements _webform_table_component().
  563. */
  564. function _webform_table_select($component, $value) {
  565. // Convert submitted 'safe' values to un-edited, original form.
  566. $options = _webform_select_options($component, TRUE);
  567. $value = (array) $value;
  568. $items = array();
  569. // Set the value as a single string.
  570. foreach ($value as $option_value) {
  571. if ($option_value !== '') {
  572. if (isset($options[$option_value])) {
  573. $items[] = _webform_filter_xss($options[$option_value]);
  574. }
  575. else {
  576. $items[] = check_plain($option_value);
  577. }
  578. }
  579. }
  580. return implode('<br />', $items);
  581. }
  582. /**
  583. * Implements _webform_csv_headers_component().
  584. */
  585. function _webform_csv_headers_select($component, $export_options) {
  586. $headers = array(
  587. 0 => array(),
  588. 1 => array(),
  589. 2 => array(),
  590. );
  591. if ($component['extra']['multiple'] && $export_options['select_format'] == 'separate') {
  592. $headers[0][] = '';
  593. $headers[1][] = $component['name'];
  594. $items = _webform_select_options($component, TRUE, FALSE);
  595. if ($component['extra']['other_option']) {
  596. $other_label = !empty($component['extra']['other_text']) ? check_plain($component['extra']['other_text']) : t('Other...');
  597. $items[$other_label] = $other_label;
  598. }
  599. $count = 0;
  600. foreach ($items as $key => $item) {
  601. // Empty column per sub-field in main header.
  602. if ($count != 0) {
  603. $headers[0][] = '';
  604. $headers[1][] = '';
  605. }
  606. if ($export_options['select_keys']) {
  607. $headers[2][] = $key;
  608. }
  609. else {
  610. $headers[2][] = $item;
  611. }
  612. $count++;
  613. }
  614. }
  615. else {
  616. $headers[0][] = '';
  617. $headers[1][] = '';
  618. $headers[2][] = $component['name'];
  619. }
  620. return $headers;
  621. }
  622. /**
  623. * Implements _webform_csv_data_component().
  624. */
  625. function _webform_csv_data_select($component, $export_options, $value) {
  626. $options = _webform_select_options($component, TRUE, FALSE);
  627. $return = array();
  628. if ($component['extra']['multiple']) {
  629. foreach ($options as $key => $item) {
  630. $index = array_search($key, (array) $value);
  631. if ($index !== FALSE) {
  632. if ($export_options['select_format'] == 'separate') {
  633. $return[] = 'X';
  634. }
  635. else {
  636. $return[] = $export_options['select_keys'] ? $key : $item;
  637. }
  638. unset($value[$index]);
  639. }
  640. elseif ($export_options['select_format'] == 'separate') {
  641. $return[] = '';
  642. }
  643. }
  644. // Any remaining items in the $value array will be user-added options.
  645. if ($component['extra']['other_option']) {
  646. $return[] = count($value) ? implode(',', $value) : '';
  647. }
  648. }
  649. else {
  650. $key = $value[0];
  651. if ($export_options['select_keys']) {
  652. $return = $key;
  653. }
  654. else {
  655. $return = isset($options[$key]) ? $options[$key] : $key;
  656. }
  657. }
  658. if ($component['extra']['multiple'] && $export_options['select_format'] == 'compact') {
  659. $return = implode(',', (array) $return);
  660. }
  661. return $return;
  662. }
  663. /**
  664. * Menu callback; Return a predefined list of select options as JSON.
  665. */
  666. function webform_select_options_ajax($source_name = '') {
  667. $info = _webform_select_options_info();
  668. $component['extra']['options_source'] = $source_name;
  669. if ($source_name && isset($info[$source_name])) {
  670. $options = _webform_select_options_to_text(_webform_select_options($component, !$component['extra']['aslist'], FALSE));
  671. }
  672. else {
  673. $options = '';
  674. }
  675. $return = array(
  676. 'elementId' => module_exists('options_element') ? 'edit-items-options-options-field-widget' : 'edit-extra-items',
  677. 'options' => $options,
  678. );
  679. drupal_json_output($return);
  680. }
  681. /**
  682. * Generate a list of options for a select list.
  683. */
  684. function _webform_select_options($component, $flat = FALSE, $filter = TRUE) {
  685. if ($component['extra']['options_source']) {
  686. $options = _webform_select_options_callback($component['extra']['options_source'], $component, $flat, $filter);
  687. }
  688. else {
  689. $options = _webform_select_options_from_text($component['extra']['items'], $flat, $filter);
  690. }
  691. return isset($options) ? $options : array();
  692. }
  693. /**
  694. * Load Webform select option info from 3rd party modules.
  695. */
  696. function _webform_select_options_info() {
  697. static $info;
  698. if (!isset($info)) {
  699. $info = array();
  700. foreach (module_implements('webform_select_options_info') as $module) {
  701. $additions = module_invoke($module, 'webform_select_options_info');
  702. foreach ($additions as $key => $addition) {
  703. $additions[$key]['module'] = $module;
  704. }
  705. $info = array_merge($info, $additions);
  706. }
  707. drupal_alter('webform_select_options_info', $info);
  708. }
  709. return $info;
  710. }
  711. /**
  712. * Execute a select option callback.
  713. *
  714. * @param $name
  715. * The name of the options group.
  716. * @param $component
  717. * The full Webform component.
  718. * @param $flat
  719. * Whether the information returned should exclude any nested groups.
  720. * @param $filter
  721. * Whether information returned should be sanitized. Defaults to TRUE.
  722. */
  723. function _webform_select_options_callback($name, $component, $flat = FALSE, $filter = TRUE) {
  724. $info = _webform_select_options_info();
  725. // Include any necessary files.
  726. if (isset($info[$name]['file'])) {
  727. $pathinfo = pathinfo($info[$name]['file']);
  728. $path = ($pathinfo['dirname'] ? $pathinfo['dirname'] . '/' : '') . basename($pathinfo['basename'], '.' . $pathinfo['extension']);
  729. module_load_include($pathinfo['extension'], $info[$name]['module'], $path);
  730. }
  731. // Execute the callback function.
  732. if (isset($info[$name]['options callback']) && function_exists($info[$name]['options callback'])) {
  733. $function = $info[$name]['options callback'];
  734. $arguments = array();
  735. if (isset($info[$name]['options arguments'])) {
  736. $arguments = $info[$name]['options arguments'];
  737. }
  738. return $function($component, $flat, $filter, $arguments);
  739. }
  740. }
  741. /**
  742. * Utility function to split user-entered values from new-line separated
  743. * text into an array of options.
  744. *
  745. * @param $text
  746. * Text to be converted into a select option array.
  747. * @param $flat
  748. * Optional. If specified, return the option array and exclude any optgroups.
  749. * @param $filter
  750. * Optional. Whether or not to filter returned values.
  751. */
  752. function _webform_select_options_from_text($text, $flat = FALSE, $filter = TRUE) {
  753. static $option_cache = array();
  754. // Keep each processed option block in an array indexed by the MD5 hash of
  755. // the option text and the value of the $flat variable.
  756. $md5 = md5($text);
  757. // Check if this option block has been previously processed.
  758. if (!isset($option_cache[$flat][$md5])) {
  759. $options = array();
  760. $rows = array_filter(explode("\n", trim($text)));
  761. $group = NULL;
  762. foreach ($rows as $option) {
  763. $option = trim($option);
  764. /**
  765. * If the Key of the option is within < >, treat as an optgroup
  766. *
  767. * <Group 1>
  768. * creates an optgroup with the label "Group 1"
  769. *
  770. * <>
  771. * Unsets the current group, allowing items to be inserted at the root element.
  772. */
  773. if (preg_match('/^\<([^>]*)\>$/', $option, $matches)) {
  774. if (empty($matches[1])) {
  775. unset($group);
  776. }
  777. elseif (!$flat) {
  778. $group = $filter ? _webform_filter_values($matches[1], NULL, NULL, NULL, FALSE) : $matches[1];
  779. }
  780. }
  781. elseif (preg_match('/^([^|]+)\|(.*)$/', $option, $matches)) {
  782. $key = $filter ? _webform_filter_values($matches[1], NULL, NULL, NULL, FALSE) : $matches[1];
  783. $value = $filter ? _webform_filter_values($matches[2], NULL, NULL, NULL, FALSE) : $matches[2];
  784. isset($group) ? $options[$group][$key] = $value : $options[$key] = $value;
  785. }
  786. else {
  787. $filtered_option = $filter ? _webform_filter_values($option, NULL, NULL, NULL, FALSE) : $option;
  788. isset($group) ? $options[$group][$filtered_option] = $filtered_option : $options[$filtered_option] = $filtered_option;
  789. }
  790. }
  791. $option_cache[$flat][$md5] = $options;
  792. }
  793. // Return our options from the option_cache array.
  794. return $option_cache[$flat][$md5];
  795. }
  796. /**
  797. * Convert an array of options into text.
  798. */
  799. function _webform_select_options_to_text($options) {
  800. $output = '';
  801. $previous_key = FALSE;
  802. foreach ($options as $key => $value) {
  803. // Convert groups.
  804. if (is_array($value)) {
  805. $output .= '<' . $key . '>' . "\n";
  806. foreach ($value as $subkey => $subvalue) {
  807. $output .= $subkey . '|' . $subvalue . "\n";
  808. }
  809. $previous_key = $key;
  810. }
  811. // Typical key|value pairs.
  812. else {
  813. // Exit out of any groups.
  814. if (isset($options[$previous_key]) && is_array($options[$previous_key])) {
  815. $output .= "<>\n";
  816. }
  817. // Skip empty rows.
  818. if ($options[$key] !== '') {
  819. $output .= $key . '|' . $value . "\n";
  820. }
  821. $previous_key = $key;
  822. }
  823. }
  824. return $output;
  825. }
  826. /**
  827. * Utility function to shuffle an array while preserving key-value pairs.
  828. */
  829. function _webform_shuffle_options(&$array) {
  830. // First shuffle the array keys, then use them as the basis for ordering
  831. // the options.
  832. $aux = array();
  833. $keys = array_keys($array);
  834. shuffle($keys);
  835. foreach ($keys as $key) {
  836. $aux[$key] = $array[$key];
  837. }
  838. $array = $aux;
  839. }