Projet

Général

Profil

Paste
Télécharger (64,4 ko) Statistiques
| Branche: | Révision:

root / drupal7 / sites / all / modules / webform / includes / webform.conditionals.inc @ 8d02775b

1
<?php
2

    
3
/**
4
 * @file
5
 * Form elements and menu callbacks to provide conditional handling in Webform.
6
 */
7

    
8
/**
9
 * Form builder; Provide the form for adding conditionals to a webform node.
10
 */
11
function webform_conditionals_form($form, &$form_state, $node) {
12
  form_load_include($form_state, 'inc', 'webform', $name = 'includes/webform.components');
13
  form_load_include($form_state, 'inc', 'webform', $name = 'includes/webform.conditionals');
14

    
15
  // Add JavaScript settings to the page needed for conditional elements.
16
  _webform_conditional_expand_value_forms($node);
17

    
18
  if (isset($form_state['values']['conditionals'])) {
19
    // Remove the "new" conditional that always comes in.
20
    unset($form_state['values']['conditionals']['new']);
21

    
22
    $conditionals = $form_state['values']['conditionals'];
23
  }
24
  else {
25
    $conditionals = $node->webform['conditionals'];
26
  }
27
  // Empty out any conditionals that have no rules or actions.
28
  foreach ($conditionals as $rgid => &$conditional) {
29
    webform_delete_empty_subconditionals($conditional);
30
    if (empty($conditional['rules']) || empty($conditional['actions'])) {
31
      unset($conditionals[$rgid]);
32
    }
33
  }
34
  // Drop PHP reference.
35
  unset($conditional);
36

    
37
  // Check the current topological sort order for the conditionals and report
38
  // any errors, but only for actual form submissions and not for ajax-related
39
  // form builds, such as adding or removing a condition or conditional group.
40
  if (empty($form_state['triggering_element']['#ajax'])) {
41
    $node->webform['conditionals'] = $conditionals;
42
    webform_get_conditional_sorter($node)->reportErrors($conditionals);
43
  }
44

    
45
  $form['#tree'] = TRUE;
46
  $form['#node'] = $node;
47

    
48
  $form['#attached']['library'][] = array('webform', 'admin');
49
  $form['#attached']['css'][] = drupal_get_path('module', 'webform') . '/css/webform.css';
50

    
51
  // Wrappers used for AJAX addition/removal.
52
  $form['conditionals']['#theme'] = 'webform_conditional_groups';
53
  $form['conditionals']['#prefix'] = '<div id="webform-conditionals-ajax">';
54
  $form['conditionals']['#suffix'] = '</div>';
55

    
56
  // Keep track of the max conditional count to use as the range for weights.
57
  $form_state['conditional_count'] = isset($form_state['conditional_count']) ? $form_state['conditional_count'] : 1;
58
  $form_state['conditional_count'] = count($conditionals) > $form_state['conditional_count'] ? count($conditionals) : $form_state['conditional_count'];
59

    
60
  $source_list = webform_component_list($node, 'conditional', 'path', TRUE);
61
  $target_list = webform_component_list($node, TRUE, 'path', TRUE);
62
  $components = $node->webform['components'];
63
  $delta = $form_state['conditional_count'];
64
  $weight = -$delta - 1;
65
  $index = 0;
66
  foreach ($conditionals as $rgid => $conditional_group) {
67
    $weight = $conditional_group['weight'];
68
    $form['conditionals'][$rgid] = array(
69
      '#theme' => 'webform_conditional_group_row',
70
      '#even_odd' => ++$index % 2 ? 'odd' : 'even',
71
      '#weight' => $weight,
72
      'rgid' => array(
73
        '#type' => 'value',
74
        '#value' => $rgid,
75
      ),
76
      'conditional' => array(
77
        '#type' => 'webform_conditional',
78
        '#default_value' => $conditional_group,
79
        '#nid' => $node->nid,
80
        '#sources' => $source_list,
81
        '#actions' => array(
82
          'show' => t('shown'),
83
          'require' => t('required'),
84
          'set' => t('set to'),
85
        ),
86
        '#targets' => $target_list,
87
        '#parents' => array('conditionals', $rgid),
88
      ),
89
    );
90
    foreach ($conditional_group['actions'] as $action) {
91
      $cid = $action['target'];
92
      if ($action['action'] == 'require' && !$components[$cid]['required']) {
93
        drupal_set_message(t('Component %title must be configured as Required for Webform to conditionally change its required status. <a href="!url">Configure %title.</a>',
94
          array(
95
            '%title' => $components[$cid]['name'],
96
            '!url' => url("node/{$node->nid}/webform/components/$cid", array('query' => array('destination' => "node/{$node->nid}/webform/conditionals"))),
97
          )
98
          ), 'error');
99
      }
100
    }
101
    $form['conditionals'][$rgid]['weight'] = array(
102
      '#type' => 'weight',
103
      '#title' => t('Weight for rule group !rgid', array('!rgid' => $rgid)),
104
      '#title_display' => 'invisible',
105
      '#default_value' => $weight,
106
      '#delta' => $delta,
107
    );
108
  }
109

    
110
  $form['conditionals']['new']['#weight'] = $weight + 1;
111
  $form['conditionals']['new']['weight'] = array(
112
    '#type' => 'weight',
113
    '#title' => t('Weight for new rule group'),
114
    '#title_display' => 'invisible',
115
    '#default_value' => $weight + 1,
116
    '#delta' => $delta,
117
  );
118
  $form['conditionals']['new']['new'] = array(
119
    '#type' => 'submit',
120
    '#value' => t('+'),
121
    '#submit' => array('webform_conditionals_form_add'),
122
    '#ajax' => array(
123
      'progress' => 'none',
124
      'effect' => 'fade',
125
      'callback' => 'webform_conditionals_ajax',
126
    ),
127
  );
128
  // Create dummy remove button for form alignment only.
129
  $form['conditionals']['new']['remove'] = array(
130
    '#type' => 'submit',
131
    '#value' => t('-'),
132
    '#disabled' => TRUE,
133
  );
134

    
135
  $form['actions'] = array(
136
    '#type' => 'actions',
137
    '#tree' => FALSE,
138
  );
139
  $form['actions']['submit'] = array(
140
    '#type' => 'submit',
141
    '#value' => t('Save conditions'),
142
    '#validate' => array('webform_conditionals_form_validate'),
143
    '#submit' => array('webform_conditionals_form_submit'),
144
  );
145

    
146
  // Estimate if the form is too long for PHP max_input_vars and detect whether
147
  // a previous submission was truncated. The estimate will be accurate because
148
  // the form elements for this page are well known. Ajax use of this page will
149
  // not generate user-visible errors, so a preflight may be the only indication
150
  // to the user that the page is too long.
151
  webform_input_vars_check($form, $form_state, 'conditionals', '');
152
  return $form;
153
}
154

    
155
/**
156
 * Submit handler for webform_conditionals_form(). Add an additional choice.
157
 */
158
function webform_conditionals_form_add($form, &$form_state) {
159
  // Build a default new conditional.
160
  unset($form_state['values']['conditionals']['new']);
161
  $weight = count($form_state['values']['conditionals']) > 10 ? -count($form_state['values']['conditionals']) : -10;
162
  foreach ($form_state['values']['conditionals'] as $key => $conditional) {
163
    $weight = max($weight, $conditional['weight']);
164
  }
165

    
166
  // Add the conditional to form state and rebuild the form.
167
  $form_state['values']['conditionals'][] = array(
168
    'rules' => array(
169
      array(
170
        'source_type' => 'component',
171
        'source' => NULL,
172
        'operator' => NULL,
173
        'value' => NULL,
174
      ),
175
    ),
176
    'andor' => 'and',
177
    'actions' => array(
178
      array(
179
        'target_type' => 'component',
180
        'target' => NULL,
181
        'invert' => NULL,
182
        'action' => NULL,
183
        'argument' => NULL,
184
      ),
185
    ),
186
    'weight' => $weight + 1,
187
  );
188
  $form_state['rebuild'] = TRUE;
189
}
190

    
191
/**
192
 * Validate handler for webform_conditionals_form().
193
 *
194
 * Prohibit the source and target of a conditional rule from being the same.
195
 */
196
function webform_conditionals_form_validate($form, &$form_state) {
197
  // Skip validation unless this is saving the form.
198
  $button_key = end($form_state['triggering_element']['#array_parents']);
199
  if ($button_key !== 'submit') {
200
    return;
201
  }
202

    
203
  $node = $form['#node'];
204
  $components = $node->webform['components'];
205
  $component_options = webform_component_options();
206
  foreach ($form_state['complete form']['conditionals'] as $conditional_key => $element) {
207
    if (substr($conditional_key, 0, 1) !== '#' && $conditional_key !== 'new') {
208
      $conditional = $element['conditional'];
209
      $targets = array();
210
      foreach ($conditional['actions'] as $action_key => $action) {
211
        if (is_numeric($action_key)) {
212
          $operation = $action['action']['#value'];
213
          $target_id = $action['target']['#value'];
214
          if (isset($targets[$target_id][$operation])) {
215
            form_set_error('conditionals][' . $conditional_key . '][actions][' . $action_key . '][target',
216
              t('A operation %op cannot be made for a component more than once. (%target).',
217
              array(
218
                '%op' => $action['action']['#options'][$operation],
219
                '%target' => $components[$action['target']['#value']]['name'],
220
              )));
221
          }
222
          $component_type = $node->webform['components'][$action['target']['#value']]['type'];
223
          if (!webform_conditional_action_able($component_type, $action['action']['#value'])) {
224
            form_set_error('conditionals][' . $conditional_key . '][actions][' . $action_key . '][action',
225
              t("A component of type %type can't be %action. (%target)",
226
              array(
227
                '%action' => $action['action']['#options'][$action['action']['#value']],
228
                '%type' => $component_options[$component_type],
229
                '%target' => $components[$action['target']['#value']]['name'],
230
              )));
231
          }
232
          $targets[$target_id][$operation] = $target_id;
233
        }
234
      }
235
      foreach ($conditional['rules'] as $rule_key => $rule) {
236
        if (!is_numeric($rule_key)) {
237
          continue;
238
        }
239
        $source_cid = isset($rule['source']['#value']) ? $rule['source']['#value'] : NULL;
240
        // Validate component rules, but not conditional_start/end rules.
241
        if ($source_cid && $rule['source_type']['#value'] == 'component' && isset($targets[$source_cid])) {
242
          form_set_error('conditionals][' . $conditional_key . '][rules][' . $rule_key . '][source',
243
            t('The subject of the conditional cannot be the same as the component that is changed (%target).',
244
            array('%target' => $components[$source_cid]['name'])));
245
        }
246
        if ($source_cid && $components[$source_cid]['type'] === 'date' && strtotime($rule['value']['#value']) === FALSE) {
247
          form_set_error('conditionals][' . $conditional_key . '][rules][' . $rule_key . '][value', t('The conditional comparison value must be a valid date.'));
248
        }
249
      }
250
    }
251
  }
252

    
253
  // Form validation will not rebuild the form, so we need to ensure
254
  // necessary JavaScript will still exist.
255
  _webform_conditional_expand_value_forms($node);
256
}
257

    
258
/**
259
 * Submit handler for webform_conditionals_form().
260
 */
261
function webform_conditionals_form_submit($form, &$form_state) {
262
  $node = $form['#node'];
263

    
264
  // Remove the new conditional placeholder.
265
  unset($form_state['values']['conditionals']['new']);
266

    
267
  $node->webform['conditionals'] = $form_state['values']['conditionals'];
268
  node_save($node);
269
  drupal_set_message(t('Conditionals for %title saved.', array('%title' => $node->title)));
270
}
271

    
272
/**
273
 * AJAX callback to render out adding a new condition.
274
 */
275
function webform_conditionals_ajax($form, $form_state) {
276
  $rgids = element_children($form['conditionals']);
277
  $new_rgid = max($rgids);
278
  $form['conditionals'][$new_rgid]['#ajax_added'] = TRUE;
279

    
280
  $commands = array('#type' => 'ajax');
281
  $commands['#commands'][] = ajax_command_before('.webform-conditional-new-row', drupal_render($form['conditionals'][$new_rgid]));
282
  $commands['#commands'][] = ajax_command_restripe('#webform-conditionals-table');
283
  return $commands;
284
}
285

    
286
/**
287
 * Theme the $form['conditionals'] of webform_conditionals_form().
288
 */
289
function theme_webform_conditional_groups($variables) {
290
  $element = $variables['element'];
291
  drupal_add_tabledrag('webform-conditionals-table', 'order', 'sibling', 'webform-conditional-weight');
292
  drupal_add_js('Drupal.theme.prototype.tableDragChangedMarker = function() { return ""; }', 'inline');
293
  drupal_add_js('Drupal.theme.prototype.tableDragChangedWarning = function() { return "<span>&nbsp;</span>"; }', 'inline');
294

    
295
  $output = '<table id="webform-conditionals-table"><tbody>';
296
  $element_children = element_children($element, TRUE);
297
  $element_count = count($element_children);
298
  foreach ($element_children as $index => $key) {
299
    if ($key === 'new') {
300
      $even_odd = ($index + 1) % 2 ? 'odd' : 'even';
301
      $element[$key]['weight']['#attributes']['class'] = array('webform-conditional-weight');
302
      $data = '<div class="webform-conditional-new">';
303
      if ($element_count === 1) {
304
        $data .= t('There are no conditional actions on this form.') . ' ';
305
      }
306
      $data .= t('Add a new condition:') . ' ' . drupal_render($element[$key]['new']) . drupal_render($element[$key]['remove']);
307
      $data .= '</div>';
308
      $output .= '<tr class="webform-conditional-new-row ' . $even_odd . '">';
309
      $output .= '<td>' . $data . '</td>';
310
      $output .= '<td>' . drupal_render($element[$key]['weight']) . '</td>';
311
      $output .= '</tr>';
312
    }
313
    else {
314
      $output .= drupal_render($element[$key]);
315
    }
316
  }
317
  $output .= '</tbody></table>';
318
  $output .= drupal_render_children($element);
319

    
320
  return $output;
321
}
322

    
323
/**
324
 * Theme an individual conditional row of webform_conditionals_form().
325
 */
326
function theme_webform_conditional_group_row($variables) {
327
  $element = $variables['element'];
328

    
329
  $element['weight']['#attributes']['class'] = array('webform-conditional-weight');
330
  $weight = drupal_render($element['weight']);
331
  $classes = array('draggable');
332
  if (!empty($element['#even_odd'])) {
333
    $classes[] = $element['#even_odd'];
334
  }
335
  if (!empty($element['#ajax_added'])) {
336
    $classes[] = 'ajax-new-content';
337
  }
338

    
339
  $output = '';
340
  $output .= '<tr class="' . implode(' ', $classes) . '">';
341
  $output .= '<td>' . drupal_render_children($element) . '</td>';
342
  $output .= '<td>' . $weight . '</td>';
343
  $output .= '</tr>';
344

    
345
  return $output;
346
}
347

    
348
/**
349
 * Form API #process function to expand a webform conditional element.
350
 */
351
function _webform_conditional_expand($element) {
352
  $default_operator = 'and';
353

    
354
  $element['#tree'] = TRUE;
355
  $element['#default_value'] += array(
356
    'andor' => $default_operator,
357
  );
358

    
359
  $wrapper_id = drupal_clean_css_identifier(implode('-', $element['#parents'])) . '-ajax';
360
  $element['#prefix'] = '<div id="' . $wrapper_id . '">';
361
  $element['#suffix'] = '</div>';
362
  $element['#wrapper_id'] = $wrapper_id;
363

    
364
  // Note: When rules or actions are added, the new rules are inserted into
365
  // $form_state['values']. So that FAPI can merge data from the post,
366
  // $form_state['input'] must be adjusted to. To make this easier, hidden
367
  // fields are added to the conditional_start and _end rules to ensure that
368
  // each rule is represented in the POST.
369
  $level = 0;
370
  $andor_stack[0] = array(
371
    'value' => $element['#default_value']['andor'],
372
    'parents' => array_merge($element['#parents'], array('andor')),
373
    'rid' => 0,
374
    'first' => TRUE,
375
  );
376

    
377
  $last_rid = -1;
378
  foreach ($element['#default_value']['rules'] as $rid => $conditional) {
379
    switch ($conditional['source_type']) {
380
      case 'conditional_start':
381
        $element['rules'][$rid] = array(
382
          '#level' => $level,
383
          'source_type' => array(
384
            '#type' => 'hidden',
385
            '#value' => 'conditional_start',
386
          ),
387
          // The andor operator is located in the first child, which is
388
          // guaranteed to exist. Therefore, don't add a 'value' element here.
389
          'add_subconditional' => _webform_conditional_add_expand($element, $rid, TRUE),
390
          'add' => _webform_conditional_add_expand($element, $rid, FALSE),
391
          'remove' => _webform_conditional_remove_expand($element, $rid),
392
        );
393
        $andor_stack[++$level] = array(
394
          'value' => isset($conditional['operator']) ? $conditional['operator'] : $default_operator,
395
          'parents' => array_merge($element['#parents'], array('rules', $rid, 'operator')),
396
          'rid' => $rid,
397
          'first' => TRUE,
398
        );
399
        break;
400

    
401
      case 'conditional_end':
402
        --$level;
403
        $element['rules'][$rid] = array(
404
          '#level' => $level,
405
          'source_type' => array(
406
            '#type' => 'hidden',
407
            '#value' => 'conditional_end',
408
          ),
409
          'add_subconditional' => _webform_conditional_add_expand($element, $rid, TRUE),
410
          'add' => _webform_conditional_add_expand($element, $rid, FALSE),
411
          'remove' => _webform_conditional_remove_expand($element, $rid),
412
          'andor' => _webform_conditional_andor_expand($andor_stack[$level]),
413
        );
414
        // Remove the last nested and/or.
415
        unset($element['rules'][$last_rid]['andor']);
416
        break;
417

    
418
      case 'component':
419
        $element['rules'][$rid] = _webform_conditional_rule_expand($element, $rid, $conditional, $level, $andor_stack[$level]);
420
        break;
421

    
422
      default:
423
        drupal_set_message(t('Unexpected conditional rule source type found (rule id @rid). Contact the administrator.', array('@rid' => $rid)), 'error');
424
    }
425
    $last_rid = $rid;
426
  }
427

    
428
  // Remove the last and/or.
429
  unset($element['rules'][$rid]['andor']);
430

    
431
  foreach ($element['#default_value']['actions'] as $aid => $action) {
432
    $element['actions'][$aid] = _webform_conditional_action_expand($element, $aid, $action);
433
  }
434

    
435
  return $element;
436
}
437

    
438
/**
439
 * Helper. Generate the and/or select or static text.
440
 */
441
function _webform_conditional_andor_expand(&$andor) {
442
  if ($andor['first']) {
443
    $andor['first'] = FALSE;
444
    return array(
445
      '#type' => 'select',
446
      '#title' => t('And/or'),
447
      '#options' => array(
448
        'and' => t('and'),
449
        'or' => t('or'),
450
      ),
451
      '#parents' => $andor['parents'],
452
      '#default_value' => $andor['value'],
453
      '#attributes' => array('data-rid' => $andor['rid']),
454
    );
455
  }
456
  else {
457
    return array(
458
      '#type' => 'container',
459
      '#attributes' => array('class' => array('webform-andor'), 'data-rid' => $andor['rid']),
460
      'andor_text' => array(
461
        '#markup' => $andor['value'] == 'or' ? t('or') : t('and'),
462
      ),
463
    );
464
  }
465
}
466

    
467
/**
468
 * Helper. Generate the add_subconditional (+) or add + button.
469
 */
470
function _webform_conditional_add_expand($element, $rid, $subconditional) {
471
  return array(
472
    '#type' => 'submit',
473
    '#value' => $subconditional ? t('(+)') : t('+'),
474
    '#submit' => array('webform_conditional_element_add'),
475
    '#subconditional' => $subconditional,
476
    '#name' => implode('_', $element['#parents']) . '_rules_' . $rid . ($subconditional ? '_add_subconditional' : '_add'),
477
    '#attributes' => array('class' => array('webform-conditional-rule-add')),
478
    '#ajax' => array(
479
      'progress' => 'none',
480
      'callback' => 'webform_conditional_element_ajax',
481
      'wrapper' => $element['#wrapper_id'],
482
      'event' => 'click',
483
    ),
484
  );
485
}
486

    
487
/**
488
 * Helper. Generate the add_subconditional (+), add + or remove - button.
489
 */
490
function _webform_conditional_remove_expand($element, $rid) {
491
  return array(
492
    '#type' => 'submit',
493
    '#value' => t('-'),
494
    '#submit' => array('webform_conditional_element_remove'),
495
    '#name' => implode('_', $element['#parents']) . '_rules_' . $rid . '_remove',
496
    '#attributes' => array('class' => array('webform-conditional-rule-remove')),
497
    '#ajax' => array(
498
      'progress' => 'none',
499
      'callback' => 'webform_conditional_element_ajax',
500
      'wrapper' => $element['#wrapper_id'],
501
      'event' => 'click',
502
    ),
503
  );
504
}
505

    
506
/**
507
 * Helper. Generate form elements for one rule.
508
 */
509
function _webform_conditional_rule_expand($element, $rid, $conditional, $level, &$andor) {
510
  return array(
511
    '#level' => $level,
512
    'source_type' => array(
513
      '#type' => 'value',
514
      '#value' => $conditional['source_type'],
515
    ),
516
    'source' => array(
517
      '#type' => 'select',
518
      '#title' => t('Source'),
519
      '#options' => $element['#sources'],
520
      '#default_value' => $conditional['source'],
521
    ),
522
    'operator' => array(
523
      '#type' => 'select',
524
      '#title' => t('Operator'),
525
      '#options' => webform_conditional_operators_list(),
526
      '#default_value' => $conditional['operator'],
527
    ),
528
    'value' => array(
529
      '#type' => 'textfield',
530
      '#title' => t('Value'),
531
      '#size' => 20,
532
      '#default_value' => $conditional['value'],
533
    ),
534
    'add_subconditional' => _webform_conditional_add_expand($element, $rid, TRUE),
535
    'add' => _webform_conditional_add_expand($element, $rid, FALSE),
536
    'remove' => _webform_conditional_remove_expand($element, $rid),
537
    'andor' => _webform_conditional_andor_expand($andor),
538
  );
539
}
540

    
541
/**
542
 * Helper. Generate form elements for one action.
543
 */
544
function _webform_conditional_action_expand($element, $aid, $action) {
545
  return array(
546
    'target_type' => array(
547
      '#type' => 'value',
548
      '#value' => $action['target_type'],
549
    ),
550
    'target' => array(
551
      '#type' => 'select',
552
      '#title' => t('Target'),
553
      '#options' => $element['#targets'],
554
      '#default_value' => $action['target'],
555
    ),
556
    'invert' => array(
557
      '#type' => 'select',
558
      '#title' => t("Is/Isn't"),
559
      '#options' => array(
560
        '0' => t('is'),
561
        '1' => t("isn't"),
562
      ),
563
      '#default_value' => $action['invert'],
564
    ),
565
    'action' => array(
566
      '#type' => 'select',
567
      '#title' => t('Action'),
568
      '#options' => $element['#actions'],
569
      '#default_value' => $action['action'],
570
    ),
571
    'argument' => array(
572
      '#type' => 'textfield',
573
      '#title' => t('Argument'),
574
      '#size' => 20,
575
      '#maxlength' => NULL,
576
      '#default_value' => $action['argument'],
577
    ),
578
    'add' => array(
579
      '#type' => 'submit',
580
      '#value' => t('+'),
581
      '#submit' => array('webform_conditional_element_add'),
582
      '#name' => implode('_', $element['#parents']) . '_actions_' . $aid . '_add',
583
      '#attributes' => array('class' => array('webform-conditional-action-add')),
584
      '#ajax' => array(
585
        'progress' => 'none',
586
        'callback' => 'webform_conditional_element_ajax',
587
        'wrapper' => $element['#wrapper_id'],
588
        'event' => 'click',
589
      ),
590
    ),
591
    'remove' => array(
592
      '#type' => 'submit',
593
      '#value' => t('-'),
594
      '#submit' => array('webform_conditional_element_remove'),
595
      '#name' => implode('_', $element['#parents']) . '_actions_' . $aid . '_remove',
596
      '#attributes' => array('class' => array('webform-conditional-action-remove')),
597
      '#ajax' => array(
598
        'progress' => 'none',
599
        'callback' => 'webform_conditional_element_ajax',
600
        'wrapper' => $element['#wrapper_id'],
601
        'event' => 'click',
602
      ),
603
    ),
604
  );
605
}
606

    
607
/**
608
 * Expand out all the value forms that could potentially be used.
609
 *
610
 * These forms are added to the page via JavaScript and swapped in only when
611
 * needed. Because the user may change the source and operator at any time,
612
 * all these forms need to be generated ahead of time and swapped in. This
613
 * could have been done via AJAX, but having all forms available makes for a
614
 * faster user experience.
615
 *
616
 * Added to the JavaScript settings is conditionalValues which contains
617
 * an array settings suitable for adding to the page via JavaScript. This
618
 * array contains the following keys:
619
 *   - operators: An array containing a map of data types, operators, and form
620
 *     keys. This array is structured as follows:
621
 * @code
622
 *   - sources[$source_key] = array(
623
 *       'data_type' => $data_type,
624
 *     );
625
 *     $operators[$data_type][$operator] = array(
626
 *       'form' => $form_key,
627
 *     );
628
 * @endcode
629
 *   - forms[$form_key]: A string representing an HTML form for an operator.
630
 *   - forms[$form_key][$source]: Or instead of a single form for all
631
 *     components, if each component requires its own form, key each component
632
 *     by its source value (currently always the component ID).
633
 *
634
 * @param object $node
635
 *   The Webform node for which these forms are being generated.
636
 */
637
function _webform_conditional_expand_value_forms($node) {
638
  $operators = webform_conditional_operators();
639
  $data = array();
640
  foreach ($operators as $data_type => $operator_info) {
641
    foreach ($operator_info as $operator => $data_operator_info) {
642
      $data['operators'][$data_type][$operator]['form'] = 'default';
643
      if (isset($data_operator_info['form callback'])) {
644
        $form_callback = $data_operator_info['form callback'];
645
        $data['operators'][$data_type][$operator]['form'] = $form_callback;
646
        if ($form_callback !== FALSE && !isset($data['forms'][$form_callback])) {
647
          $data['forms'][$form_callback] = $form_callback($node);
648
        }
649
      }
650
    }
651
  }
652

    
653
  foreach ($node->webform['components'] as $cid => $component) {
654
    if (webform_component_feature($component['type'], 'conditional')) {
655
      $data['sources'][$cid]['data_type'] = webform_component_property($component['type'], 'conditional_type');
656
    }
657
  }
658

    
659
  drupal_add_js(array('webform' => array('conditionalValues' => $data)), 'setting');
660
}
661

    
662
/**
663
 * Helper. Find the matching end of a given subconditional.
664
 *
665
 * @param array $rules
666
 *   Array of conditional rules to be searched.
667
 * @param int $origin_rid
668
 *   The starting rule id for the search.
669
 * @param int $target_delta_level
670
 *   The level that is sought. 0 for current left. -1 for parent.
671
 *
672
 * @return int
673
 *   The rid of the found rule, or -1 if none. Note that NULL is not used as a
674
 *   semaphore for "not found" because it casts to 0, which is a valid rule id.
675
 */
676
function _webform_conditional_find_end(array $rules, $origin_rid, $target_delta_level = 0) {
677
  $rids = array_keys($rules);
678
  $offset = array_search($origin_rid, $rids);
679
  $delta_level = 0;
680
  foreach (array_slice($rules, $offset, NULL, TRUE) as $rid => $conditional) {
681
    switch ($conditional['source_type']) {
682
      case 'conditional_start':
683
        $delta_level++;
684
        break;
685

    
686
      case 'conditional_end':
687
        $delta_level--;
688
        break;
689
    }
690
    if ($delta_level == $target_delta_level) {
691
      return $rid;
692
    }
693
  }
694
  // Mis-matched conditional_start / _end. Return -1.
695
  return -1;
696
}
697

    
698
/**
699
 * Helper. Find the matching start or end of a given subconditional.
700
 *
701
 * @see _webform_conditional_find_end()
702
 */
703
function _webform_conditional_find_start($rules, $origin_rid, $target_delta_level = 0) {
704
  $rids = array_keys($rules);
705
  $offset = array_search($origin_rid, $rids);
706
  $delta_level = 0;
707
  foreach (array_reverse(array_slice($rules, 0, $offset + 1, TRUE), TRUE) as $rid => $conditional) {
708
    switch ($conditional['source_type']) {
709
      case 'conditional_end':
710
        $delta_level++;
711
        break;
712

    
713
      case 'conditional_start':
714
        $delta_level--;
715
        break;
716
    }
717
    if ($delta_level == $target_delta_level) {
718
      return $rid;
719
    }
720
  }
721
  // Mis-matched conditional_start / _end. Return -1.
722
  return -1;
723
}
724

    
725
/**
726
 * Submit handler for webform_conditional elements to add a new rule or action.
727
 */
728
function webform_conditional_element_add($form, &$form_state) {
729
  $button = $form_state['clicked_button'];
730
  $parents = $button['#parents'];
731
  array_pop($parents);
732
  $rid = array_pop($parents);
733

    
734
  // Recurse through the form values until we find the Webform conditional rules
735
  // or actions. Save the conditional prior to descending to rules/actions.
736
  $parent_values = &$form_state['values'];
737
  $input_values = &$form_state['input'];
738
  foreach ($parents as $key) {
739
    if (array_key_exists($key, $parent_values)) {
740
      $conditional = $parent_values;
741
      $parent_values = &$parent_values[$key];
742
    }
743
    if (array_key_exists($key, $input_values)) {
744
      $input_values = &$input_values[$key];
745
    }
746
  }
747

    
748
  // Split the list of rules/actions in this conditional and inject into the
749
  // right spot.
750
  $rids = array_keys($parent_values);
751
  $offset = array_search($rid, $rids);
752
  $default_rule = isset($button['#subconditional'])
753
                    ? array(
754
                      'source' => NULL,
755
                      'source_type' => 'component',
756
                      'operator' => NULL,
757
                      'value' => NULL,
758
                    )
759
                    : array(
760
                      'target_type' => 'component',
761
                      'target' => NULL,
762
                      'invert' => NULL,
763
                      'action' => NULL,
764
                      'argument' => NULL,
765
                    );
766

    
767
  if (empty($button['#subconditional'])) {
768
    $new[0] = (isset($parent_values[$rid]['source_type']) && $parent_values[$rid]['source_type'] == 'component') ? $parent_values[$rid] : $default_rule;
769
  }
770
  else {
771
    // The default andor operator is opposite of current subconditional's
772
    // operatior.
773
    $parent_rid = _webform_conditional_find_start($parent_values, $rid, -1);
774
    $current_op = $parent_rid < 0 ? $conditional['andor'] : $parent_values[$parent_rid]['operator'];
775
    $current_op = $current_op == 'and' ? 'or' : 'and';
776
    $new = array(
777
      array('source_type' => 'conditional_start', 'operator' => $current_op) + $default_rule,
778
      $default_rule,
779
      $default_rule,
780
      array('source_type' => 'conditional_end') + $default_rule,
781
    );
782
  }
783

    
784
  // Update both $form_state['values'] and ['input] so that FAPI can merge
785
  // input values from the POST into the new form.
786
  $parent_values = array_merge(array_slice($parent_values, 0, $offset + 1), $new, array_slice($parent_values, $offset + 1));
787
  $input_values = array_merge(array_slice($input_values, 0, $offset + 1), $new, array_slice($input_values, $offset + 1));
788
  $form_state['rebuild'] = TRUE;
789
}
790

    
791
/**
792
 * Submit handler for webform_conditional elements to remove a rule or action.
793
 */
794
function webform_conditional_element_remove($form, &$form_state) {
795
  $button = $form_state['clicked_button'];
796
  $parents = $button['#parents'];
797
  $action = array_pop($parents);
798
  $rid = array_pop($parents);
799

    
800
  // Recurse through the form values until we find the root Webform conditional.
801
  $parent_values = &$form_state['values'];
802
  foreach ($parents as $key) {
803
    if (array_key_exists($key, $parent_values)) {
804
      $parent_values = &$parent_values[$key];
805
    }
806
  }
807
  switch ($parent_values[$rid]['source_type']) {
808
    case 'conditional_start':
809
      unset($parent_values[_webform_conditional_find_end($parent_values, $rid)]);
810
      break;
811

    
812
    case 'conditional_end':
813
      unset($parent_values[_webform_conditional_find_start($parent_values, $rid)]);
814
      break;
815
  }
816
  // Remove this rule or action from the list of conditionals.
817
  unset($parent_values[$rid]);
818

    
819
  $form_state['rebuild'] = TRUE;
820
}
821

    
822
/**
823
 * Helper. Delete any subconditionals which contain no rules.
824
 *
825
 * @param array $conditional
826
 *   Conditional array containing the rules.
827
 *
828
 * @return array
829
 *   Array of deleted subconditionals. Empty array if none were deleted.
830
 */
831
function webform_delete_empty_subconditionals(array &$conditional) {
832
  $deleted = array();
833
  do {
834
    $empty_deleted = FALSE;
835
    $open_rid = NULL;
836
    foreach ($conditional['rules'] as $rid => $rule) {
837
      switch ($rule['source_type']) {
838
        case 'conditional_start':
839
          $open_rid = $rid;
840
          break;
841

    
842
        case 'conditional_end':
843
          if ($open_rid) {
844
            // A conditional_start rule was immediately followed by a
845
            // conditional_end rule. Delete them both. Repeat the check in case
846
            // the parent is now empty.
847
            $deleted[$open_rid] = $open_rid;
848
            $deleted[$rid] = $rid;
849
            unset($conditional['rules'][$open_rid], $conditional['rules'][$rid]);
850
            $open_rid = NULL;
851
            $empty_deleted = TRUE;
852
          }
853
          break;
854

    
855
        default:
856
          $open_rid = NULL;
857
      }
858
    }
859
  } while ($empty_deleted);
860
  return $deleted;
861
}
862

    
863
/**
864
 * AJAX callback to render out adding a new condition.
865
 */
866
function webform_conditional_element_ajax($form, $form_state) {
867
  $button = $form_state['clicked_button'];
868
  $parents = $button['#parents'];
869

    
870
  // Trim down the parents to go back up to the level of this elements wrapper.
871
  // The button name (add/remove).
872
  array_pop($parents);
873
  // The rule ID.
874
  array_pop($parents);
875
  // The "rules" grouping.
876
  array_pop($parents);
877

    
878
  $element = $form;
879
  foreach ($parents as $key) {
880
    if (!isset($element[$key])) {
881
      // The entire conditional has been removed.
882
      return '';
883
    }
884
    $element = $element[$key];
885
  }
886

    
887
  return drupal_render($element['conditional']);
888
}
889

    
890
/**
891
 * Theme the form for a conditional action.
892
 */
893
function theme_webform_conditional($variables) {
894
  $element = $variables['element'];
895

    
896
  $output = '';
897
  $output .= '<div class="webform-conditional">';
898
  $output .= '<span class="webform-conditional-if">' . t('If') . '</span>';
899

    
900
  foreach (element_children($element['rules']) as $rid) {
901
    $rule = &$element['rules'][$rid];
902
    switch ($rule['source_type']['#value']) {
903
      case 'conditional_start':
904
        $source_phrase = '<div class="webform-subconditional">' . t('(') . '</div>';
905
        break;
906

    
907
      case 'conditional_end':
908
        $source_phrase = '<div class="webform-subconditional">' . t(')') . '</div>';
909
        break;
910

    
911
      default:
912
        // Hide labels.
913
        $rule['source']['#title_display'] = 'invisible';
914
        $rule['operator']['#title_display'] = 'invisible';
915
        $rule['value']['#title_display'] = 'invisible';
916

    
917
        $source = '<div class="webform-conditional-source">' . drupal_render($rule['source']) . '</div>';
918
        $operator = '<div class="webform-conditional-operator">' . drupal_render($rule['operator']) . '</div>';
919
        $value = '<div class="webform-conditional-value">' . drupal_render($rule['value']) . '</div>';
920

    
921
        $source_phrase = t('!source !operator !value', array(
922
          '!source' => $source,
923
          '!operator' => $operator,
924
          '!value' => $value,
925
        ));
926
    }
927

    
928
    $output .= '<div class="webform-conditional-rule">';
929
    // Can't use theme('indentation') here because it causes the draghandle to
930
    // be located after the last indentation div.
931
    $output .= str_repeat('<div class="webform-indentation">&nbsp;</div>', $rule['#level']);
932
    $output .= drupal_render($rule['source_type']);
933
    $output .= '<div class="webform-container-inline webform-conditional-condition">';
934
    $output .= $source_phrase;
935
    $output .= '</div>';
936

    
937
    if (isset($rule['andor'])) {
938
      $rule['andor']['#title_display'] = 'invisible';
939
      $output .= '<div class="webform-conditional-andor webform-container-inline">';
940
      $output .= drupal_render($rule['andor']);
941
      $output .= '</div>';
942
    }
943

    
944
    if (isset($rule['add']) || isset($rule['remove'])) {
945
      $output .= '<span class="webform-conditional-operations webform-container-inline">';
946
      $output .= drupal_render($rule['add_subconditional']);
947
      $output .= drupal_render($rule['add']);
948
      $output .= drupal_render($rule['remove']);
949
      $output .= '</span>';
950
    }
951

    
952
    $output .= '</div>';
953
  }
954

    
955
  // Hide labels.
956
  foreach (element_children($element['actions']) as $aid) {
957
    // Hide labels.
958
    $element['actions'][$aid]['target']['#title_display'] = 'invisible';
959
    $element['actions'][$aid]['invert']['#title_display'] = 'invisible';
960
    $element['actions'][$aid]['action']['#title_display'] = 'invisible';
961
    $element['actions'][$aid]['argument']['#title_display'] = 'invisible';
962

    
963
    $target = '<div class="webform-conditional-target">' . drupal_render($element['actions'][$aid]['target']) . '</div>';
964
    $invert = '<div class="webform-conditional-invert">' . drupal_render($element['actions'][$aid]['invert']) . '</div>';
965
    $action = '<div class="webform-conditional-action">' . drupal_render($element['actions'][$aid]['action']) . '</div>';
966
    $argument = '<div class="webform-conditional-argument">' . drupal_render($element['actions'][$aid]['argument']) . '</div>';
967

    
968
    $target_phrase = t('then !target !invert !action !argument', array(
969
      '!target' => $target,
970
      '!invert' => $invert,
971
      '!action' => $action,
972
      '!argument' => $argument,
973
    ));
974

    
975
    $output .= '<div class="webform-conditional-action">';
976
    $output .= '<div class="webform-container-inline webform-conditional-condition">';
977
    $output .= $target_phrase;
978
    $output .= '</div>';
979

    
980
    if (isset($element['actions'][$aid]['add']) || isset($element['actions'][$aid]['remove'])) {
981
      $output .= '<span class="webform-conditional-operations webform-container-inline">';
982
      $output .= drupal_render($element['actions'][$aid]['add']);
983
      $output .= drupal_render($element['actions'][$aid]['remove']);
984
      $output .= '</span>';
985
    }
986

    
987
    $output .= '</div>';
988
  }
989

    
990
  $output .= '</div>';
991

    
992
  return $output;
993
}
994

    
995
/**
996
 * Return a list of all Webform conditional operators.
997
 */
998
function webform_conditional_operators() {
999
  static $operators;
1000

    
1001
  if (!isset($operators)) {
1002
    $operators = module_invoke_all('webform_conditional_operator_info');
1003
    drupal_alter('webform_conditional_operators', $operators);
1004
  }
1005

    
1006
  return $operators;
1007
}
1008

    
1009
/**
1010
 * Return a nested list of all available operators, suitable for a select list.
1011
 */
1012
function webform_conditional_operators_list() {
1013
  $options = array();
1014
  $operators = webform_conditional_operators();
1015

    
1016
  foreach ($operators as $data_type => $type_operators) {
1017
    $options[$data_type] = array();
1018
    foreach ($type_operators as $operator => $operator_info) {
1019
      $options[$data_type][$operator] = $operator_info['label'];
1020
    }
1021
  }
1022

    
1023
  return $options;
1024
}
1025

    
1026
/**
1027
 * Implements hook_webform_conditional_operator_info().
1028
 *
1029
 * Called from webform.module's webform_webform_conditional_operator_info().
1030
 */
1031
function _webform_conditional_operator_info() {
1032
  // General operators:
1033
  $operators['string']['equal'] = array(
1034
    'label' => t('is'),
1035
    'comparison callback' => 'webform_conditional_operator_string_equal',
1036
    'js comparison callback' => 'conditionalOperatorStringEqual',
1037
    // A form callback is not needed here, since we can use the default,
1038
    // non-JavaScript textfield for all text and numeric fields.
1039
    // @code
1040
    // 'form callback' => 'webform_conditional_operator_text',
1041
    // @endcode
1042
  );
1043
  $operators['string']['not_equal'] = array(
1044
    'label' => t('is not'),
1045
    'comparison callback' => 'webform_conditional_operator_string_not_equal',
1046
    'js comparison callback' => 'conditionalOperatorStringNotEqual',
1047
  );
1048
  $operators['string']['contains'] = array(
1049
    'label' => t('contains'),
1050
    'comparison callback' => 'webform_conditional_operator_string_contains',
1051
    'js comparison callback' => 'conditionalOperatorStringContains',
1052
  );
1053
  $operators['string']['does_not_contain'] = array(
1054
    'label' => t('does not contain'),
1055
    'comparison callback' => 'webform_conditional_operator_string_does_not_contain',
1056
    'js comparison callback' => 'conditionalOperatorStringDoesNotContain',
1057
  );
1058
  $operators['string']['begins_with'] = array(
1059
    'label' => t('begins with'),
1060
    'comparison callback' => 'webform_conditional_operator_string_begins_with',
1061
    'js comparison callback' => 'conditionalOperatorStringBeginsWith',
1062
  );
1063
  $operators['string']['ends_with'] = array(
1064
    'label' => t('ends with'),
1065
    'comparison callback' => 'webform_conditional_operator_string_ends_with',
1066
    'js comparison callback' => 'conditionalOperatorStringEndsWith',
1067
  );
1068
  $operators['string']['empty'] = array(
1069
    'label' => t('is blank'),
1070
    'comparison callback' => 'webform_conditional_operator_string_empty',
1071
    'js comparison callback' => 'conditionalOperatorStringEmpty',
1072
    // No value form at all.
1073
    'form callback' => FALSE,
1074
  );
1075
  $operators['string']['not_empty'] = array(
1076
    'label' => t('is not blank'),
1077
    'comparison callback' => 'webform_conditional_operator_string_not_empty',
1078
    'js comparison callback' => 'conditionalOperatorStringNotEmpty',
1079
    // No value form at all.
1080
    'form callback' => FALSE,
1081
  );
1082

    
1083
  // Numeric operators.
1084
  $operators['numeric']['equal'] = array(
1085
    'label' => t('is equal to'),
1086
    'comparison callback' => 'webform_conditional_operator_numeric_equal',
1087
    'js comparison callback' => 'conditionalOperatorNumericEqual',
1088
  );
1089
  $operators['numeric']['not_equal'] = array(
1090
    'label' => t('is not equal to'),
1091
    'comparison callback' => 'webform_conditional_operator_numeric_not_equal',
1092
    'js comparison callback' => 'conditionalOperatorNumericNotEqual',
1093
  );
1094
  $operators['numeric']['less_than'] = array(
1095
    'label' => t('is less than'),
1096
    'comparison callback' => 'webform_conditional_operator_numeric_less_than',
1097
    'js comparison callback' => 'conditionalOperatorNumericLessThan',
1098
  );
1099
  $operators['numeric']['less_than_equal'] = array(
1100
    'label' => t('is less than or equal'),
1101
    'comparison callback' => 'webform_conditional_operator_numeric_less_than_equal',
1102
    'js comparison callback' => 'conditionalOperatorNumericLessThanEqual',
1103
  );
1104
  $operators['numeric']['greater_than'] = array(
1105
    'label' => t('is greater than'),
1106
    'comparison callback' => 'webform_conditional_operator_numeric_greater_than',
1107
    'js comparison callback' => 'conditionalOperatorNumericGreaterThan',
1108
  );
1109
  $operators['numeric']['greater_than_equal'] = array(
1110
    'label' => t('is greater than or equal'),
1111
    'comparison callback' => 'webform_conditional_operator_numeric_greater_than_equal',
1112
    'js comparison callback' => 'conditionalOperatorNumericGreaterThanEqual',
1113
  );
1114
  $operators['numeric']['empty'] = array(
1115
    'label' => t('is blank'),
1116
    'comparison callback' => 'webform_conditional_operator_string_empty',
1117
    'js comparison callback' => 'conditionalOperatorStringEmpty',
1118
    // No value form at all.
1119
    'form callback' => FALSE,
1120
  );
1121
  $operators['numeric']['not_empty'] = array(
1122
    'label' => t('is not blank'),
1123
    'comparison callback' => 'webform_conditional_operator_string_not_empty',
1124
    'js comparison callback' => 'conditionalOperatorStringNotEmpty',
1125
    // No value form at all.
1126
    'form callback' => FALSE,
1127
  );
1128

    
1129
  // Select operators.
1130
  $operators['select']['equal'] = array(
1131
    'label' => t('is'),
1132
    'comparison callback' => 'webform_conditional_operator_string_equal',
1133
    'js comparison callback' => 'conditionalOperatorStringEqual',
1134
    'form callback' => 'webform_conditional_form_select',
1135
  );
1136
  $operators['select']['not_equal'] = array(
1137
    'label' => t('is not'),
1138
    'comparison callback' => 'webform_conditional_operator_string_not_equal',
1139
    'js comparison callback' => 'conditionalOperatorStringNotEqual',
1140
    'form callback' => 'webform_conditional_form_select',
1141
  );
1142
  $operators['select']['less_than'] = array(
1143
    'label' => t('is before'),
1144
    'comparison callback' => 'webform_conditional_operator_select_less_than',
1145
    'js comparison callback' => 'conditionalOperatorSelectLessThan',
1146
    'form callback' => 'webform_conditional_form_select',
1147
  );
1148
  $operators['select']['less_than_equal'] = array(
1149
    'label' => t('is or is before'),
1150
    'comparison callback' => 'webform_conditional_operator_select_less_than_equal',
1151
    'js comparison callback' => 'conditionalOperatorSelectLessThanEqual',
1152
    'form callback' => 'webform_conditional_form_select',
1153
  );
1154
  $operators['select']['greater_than'] = array(
1155
    'label' => t('is after'),
1156
    'comparison callback' => 'webform_conditional_operator_select_greater_than',
1157
    'js comparison callback' => 'conditionalOperatorSelectGreaterThan',
1158
    'form callback' => 'webform_conditional_form_select',
1159
  );
1160
  $operators['select']['greater_than_equal'] = array(
1161
    'label' => t('is or is after'),
1162
    'comparison callback' => 'webform_conditional_operator_select_greater_than_equal',
1163
    'js comparison callback' => 'conditionalOperatorSelectGreaterThanEqual',
1164
    'form callback' => 'webform_conditional_form_select',
1165
  );
1166
  $operators['select']['empty'] = array(
1167
    'label' => t('is empty'),
1168
    'comparison callback' => 'webform_conditional_operator_string_empty',
1169
    'js comparison callback' => 'conditionalOperatorStringEmpty',
1170
    // No value form at all.
1171
    'form callback' => FALSE,
1172
  );
1173
  $operators['select']['not_empty'] = array(
1174
    'label' => t('is not empty'),
1175
    'comparison callback' => 'webform_conditional_operator_string_not_empty',
1176
    'js comparison callback' => 'conditionalOperatorStringNotEmpty',
1177
    // No value form at all.
1178
    'form callback' => FALSE,
1179
  );
1180

    
1181
  // Date operators:
1182
  $operators['date']['equal'] = array(
1183
    'label' => t('is on'),
1184
    'comparison callback' => 'webform_conditional_operator_datetime_equal',
1185
    'comparison prepare js' => 'webform_conditional_prepare_date_js',
1186
    'js comparison callback' => 'conditionalOperatorDateEqual',
1187
    'form callback' => 'webform_conditional_form_date',
1188
  );
1189
  $operators['date']['not_equal'] = array(
1190
    'label' => t('is not on'),
1191
    'comparison callback' => 'webform_conditional_operator_datetime_not_equal',
1192
    'comparison prepare js' => 'webform_conditional_prepare_date_js',
1193
    'js comparison callback' => 'conditionalOperatorDateNotEqual',
1194
    'form callback' => 'webform_conditional_form_date',
1195
  );
1196
  $operators['date']['before'] = array(
1197
    'label' => t('is before'),
1198
    'comparison callback' => 'webform_conditional_operator_datetime_before',
1199
    'comparison prepare js' => 'webform_conditional_prepare_date_js',
1200
    'js comparison callback' => 'conditionalOperatorDateBefore',
1201
    'form callback' => 'webform_conditional_form_date',
1202
  );
1203
  $operators['date']['before_equal'] = array(
1204
    'label' => t('is on or before'),
1205
    'comparison callback' => 'webform_conditional_operator_datetime_before_equal',
1206
    'comparison prepare js' => 'webform_conditional_prepare_date_js',
1207
    'js comparison callback' => 'conditionalOperatorDateBeforeEqual',
1208
    'form callback' => 'webform_conditional_form_date',
1209
  );
1210
  $operators['date']['after'] = array(
1211
    'label' => t('is after'),
1212
    'comparison callback' => 'webform_conditional_operator_datetime_after',
1213
    'comparison prepare js' => 'webform_conditional_prepare_date_js',
1214
    'js comparison callback' => 'conditionalOperatorDateAfter',
1215
    'form callback' => 'webform_conditional_form_date',
1216
  );
1217
  $operators['date']['after_equal'] = array(
1218
    'label' => t('is on or after'),
1219
    'comparison callback' => 'webform_conditional_operator_datetime_after_equal',
1220
    'comparison prepare js' => 'webform_conditional_prepare_date_js',
1221
    'js comparison callback' => 'conditionalOperatorDateAfterEqual',
1222
    'form callback' => 'webform_conditional_form_date',
1223
  );
1224

    
1225
  // Time operators:
1226
  $operators['time']['equal'] = array(
1227
    'label' => t('is at'),
1228
    'comparison callback' => 'webform_conditional_operator_datetime_equal',
1229
    'comparison prepare js' => 'webform_conditional_prepare_time_js',
1230
    'js comparison callback' => 'conditionalOperatorTimeEqual',
1231
    'form callback' => 'webform_conditional_form_time',
1232
  );
1233
  $operators['time']['not_equal'] = array(
1234
    'label' => t('is not at'),
1235
    'comparison callback' => 'webform_conditional_operator_datetime_not_equal',
1236
    'comparison prepare js' => 'webform_conditional_prepare_time_js',
1237
    'js comparison callback' => 'conditionalOperatorTimeNotEqual',
1238
    'form callback' => 'webform_conditional_form_time',
1239
  );
1240
  $operators['time']['before'] = array(
1241
    'label' => t('is before'),
1242
    'comparison callback' => 'webform_conditional_operator_datetime_before',
1243
    'comparison prepare js' => 'webform_conditional_prepare_time_js',
1244
    'js comparison callback' => 'conditionalOperatorTimeBefore',
1245
    'form callback' => 'webform_conditional_form_time',
1246
  );
1247
  $operators['time']['before_equal'] = array(
1248
    'label' => t('is at or before'),
1249
    'comparison callback' => 'webform_conditional_operator_datetime_before_equal',
1250
    'comparison prepare js' => 'webform_conditional_prepare_time_js',
1251
    'js comparison callback' => 'conditionalOperatorTimeBeforeEqual',
1252
    'form callback' => 'webform_conditional_form_time',
1253
  );
1254
  $operators['time']['after'] = array(
1255
    'label' => t('is after'),
1256
    'comparison callback' => 'webform_conditional_operator_datetime_after',
1257
    'comparison prepare js' => 'webform_conditional_prepare_time_js',
1258
    'js comparison callback' => 'conditionalOperatorTimeAfter',
1259
    'form callback' => 'webform_conditional_form_time',
1260
  );
1261
  $operators['time']['after_equal'] = array(
1262
    'label' => t('is at or after'),
1263
    'comparison callback' => 'webform_conditional_operator_datetime_after_equal',
1264
    'comparison prepare js' => 'webform_conditional_prepare_time_js',
1265
    'js comparison callback' => 'conditionalOperatorTimeAfterEqual',
1266
    'form callback' => 'webform_conditional_form_time',
1267
  );
1268

    
1269
  return $operators;
1270
}
1271

    
1272
/**
1273
 * Form callback for select-type conditional fields.
1274
 *
1275
 * Unlike other built-in conditional value forms, the form callback for select
1276
 * types provides an array of forms, keyed by the $cid, which is the "source"
1277
 * for the condition.
1278
 */
1279
function webform_conditional_form_select($node) {
1280
  static $count = 0;
1281
  $forms = array();
1282
  webform_component_include('select');
1283
  foreach ($node->webform['components'] as $cid => $component) {
1284
    if (webform_component_property($component['type'], 'conditional_type') == 'select') {
1285
      // @todo: Use a pluggable mechanism for retrieving select list values.
1286
      $options = _webform_select_options($component);
1287
      $element = array(
1288
        '#type' => 'select',
1289
        '#multiple' => FALSE,
1290
        '#size' => NULL,
1291
        '#attributes' => array(),
1292
        '#id' => NULL,
1293
        '#name' => 'webform-conditional-select-' . $cid . '-' . $count,
1294
        '#options' => $options,
1295
        '#parents' => array(),
1296
      );
1297
      $forms[$cid] = drupal_render($element);
1298
    }
1299
  }
1300
  $count++;
1301
  return $forms;
1302
}
1303

    
1304
/**
1305
 * Form callback for date conditional fields.
1306
 */
1307
function webform_conditional_form_date($node) {
1308
  static $count = 0;
1309
  $element = array(
1310
    '#title' => NULL,
1311
    '#title_display' => 'invisible',
1312
    '#size' => 24,
1313
    '#attributes' => array('placeholder' => t('@format or valid date', array('@format' => webform_date_format('short')))),
1314
    '#type' => 'textfield',
1315
    '#name' => 'webform-conditional-date-' . $count++,
1316
  );
1317
  return drupal_render($element);
1318
}
1319

    
1320
/**
1321
 * Form callback for time conditional fields.
1322
 */
1323
function webform_conditional_form_time($node) {
1324
  static $count = 0;
1325
  $element = array(
1326
    '#title' => NULL,
1327
    '#title_display' => 'invisible',
1328
    '#size' => 24,
1329
    '#attributes' => array('placeholder' => t('HH:MMam or valid time')),
1330
    '#type' => 'textfield',
1331
    '#name' => 'webform-conditional-time-' . $count++,
1332
  );
1333
  return drupal_render($element);
1334
}
1335

    
1336
/**
1337
 * Load a conditional setting from the database.
1338
 */
1339
function webform_conditional_load($rgid, $nid) {
1340
  $node = node_load($nid);
1341

    
1342
  $conditional = isset($node->webform['conditionals'][$rgid]) ? $node->webform['conditionals'][$rgid] : FALSE;
1343

    
1344
  return $conditional;
1345
}
1346

    
1347
/**
1348
 * Insert a conditional rule group into the database.
1349
 */
1350
function webform_conditional_insert($conditional) {
1351
  $transaction = db_transaction();
1352
  drupal_write_record('webform_conditional', $conditional);
1353
  foreach ($conditional['rules'] as $rid => $rule) {
1354
    $rule['nid'] = $conditional['nid'];
1355
    $rule['rgid'] = $conditional['rgid'];
1356
    $rule['rid'] = $rid;
1357
    drupal_write_record('webform_conditional_rules', $rule);
1358
  }
1359
  foreach ($conditional['actions'] as $aid => $action) {
1360
    $action['nid'] = $conditional['nid'];
1361
    $action['rgid'] = $conditional['rgid'];
1362
    $action['aid'] = $aid;
1363
    drupal_write_record('webform_conditional_actions', $action);
1364
  }
1365
}
1366

    
1367
/**
1368
 * Update a conditional setting in the database.
1369
 */
1370
function webform_conditional_update($node, $conditional) {
1371
  $transaction = db_transaction();
1372
  webform_conditional_delete($node, $conditional);
1373
  webform_conditional_insert($conditional);
1374
}
1375

    
1376
/**
1377
 * Delete a conditional rule group.
1378
 */
1379
function webform_conditional_delete($node, $conditional) {
1380
  $transaction = db_transaction();
1381
  db_delete('webform_conditional')
1382
    ->condition('nid', $node->nid)
1383
    ->condition('rgid', $conditional['rgid'])
1384
    ->execute();
1385
  db_delete('webform_conditional_rules')
1386
    ->condition('nid', $node->nid)
1387
    ->condition('rgid', $conditional['rgid'])
1388
    ->execute();
1389
  db_delete('webform_conditional_actions')
1390
    ->condition('nid', $node->nid)
1391
    ->condition('rgid', $conditional['rgid'])
1392
    ->execute();
1393
}
1394

    
1395
/**
1396
 * Loop through all the conditional settings and add needed JavaScript settings.
1397
 *
1398
 * We do a bit of optimization for JavaScript before adding to the page as
1399
 * settings. We remove unnecessary data structures and provide a "source map"
1400
 * so that JavaScript can quickly determine if it needs to check rules when a
1401
 * field on the page has been modified.
1402
 *
1403
 * @param object $node
1404
 *   The loaded node object, containing the webform.
1405
 * @param array $submission_data
1406
 *   The cid-indexed array of existing submission values to be included for
1407
 *   sources outside of the current page.
1408
 * @param int $page_num
1409
 *   The number of the page for which javascript settings should be generated.
1410
 *
1411
 * @return array
1412
 *   Array of settings to be send to the browser as javascript settings.
1413
 */
1414
function webform_conditional_prepare_javascript($node, array $submission_data, $page_num) {
1415
  $settings = array(
1416
    'ruleGroups' => array(),
1417
    'sourceMap' => array(),
1418
    'values' => array(),
1419
  );
1420
  $operators = webform_conditional_operators();
1421
  $conditionals = $node->webform['conditionals'];
1422
  $components = $node->webform['components'];
1423
  $topological_order = webform_get_conditional_sorter($node)->getOrder();
1424
  foreach ($topological_order[$page_num] as $conditional_spec) {
1425
    $conditional = $conditionals[$conditional_spec['rgid']];
1426
    $rgid_key = 'rgid_' . $conditional['rgid'];
1427
    // Assemble the main conditional group settings.
1428
    $settings['ruleGroups'][$rgid_key] = array(
1429
      'andor' => $conditional['andor'],
1430
    );
1431
    foreach ($conditional['actions'] as $action) {
1432
      if ($action['target_type'] == 'component') {
1433
        $target_component = $components[$action['target']];
1434
        $target_parents = webform_component_parent_keys($node, $target_component);
1435
        $aid_key = 'aid_' . $action['aid'];
1436
        $action_settings = array(
1437
          'target' => 'webform-component--' . str_replace('_', '-', implode('--', $target_parents)),
1438
          'invert' => (int) $action['invert'],
1439
          'action' => $action['action'],
1440
          'argument' => $components[$action['target']]['type'] == 'markup' ? filter_xss_admin($action['argument']) : $action['argument'],
1441
        );
1442
        $settings['ruleGroups'][$rgid_key]['actions'][$aid_key] = $action_settings;
1443
      }
1444
    }
1445
    // Add on the list of rules to the conditional group.
1446
    foreach ($conditional['rules'] as $rule) {
1447
      $rid_key = 'rid_' . $rule['rid'];
1448
      switch ($rule['source_type']) {
1449
        case 'component':
1450
          $source_component = $components[$rule['source']];
1451
          $source_parents = webform_component_parent_keys($node, $source_component);
1452
          $source_id = 'webform-component--' . str_replace('_', '-', implode('--', $source_parents));
1453

    
1454
          // If this source has a value set, add that as a setting. NULL or
1455
          // array(NULL) should be sent as an empty array to simplify the
1456
          // jQuery.
1457
          if (isset($submission_data[$source_component['cid']])) {
1458
            $source_value = $submission_data[$source_component['cid']];
1459
            $source_value = is_array($source_value) ? $source_value : array($source_value);
1460
            $settings['values'][$source_id] = $source_value === array(NULL) ? array() : $source_value;
1461
          }
1462

    
1463
          $conditional_type = webform_component_property($source_component['type'], 'conditional_type');
1464
          $operator_info = $operators[$conditional_type][$rule['operator']];
1465
          $rule_settings = array(
1466
            'source_type' => $rule['source_type'],
1467
            'source' => $source_id,
1468
            'value' => $rule['value'],
1469
            'callback' => $operator_info['js comparison callback'],
1470
          );
1471
          if (isset($operator_info['comparison prepare js'])) {
1472
            $callback = $operator_info['comparison prepare js'];
1473
            $rule_settings['value'] = $callback($rule['value']);
1474
          }
1475
          $settings['ruleGroups'][$rgid_key]['rules'][$rid_key] = $rule_settings;
1476
          $settings['sourceMap'][$source_id][$rgid_key] = $rgid_key;
1477
          break;
1478

    
1479
        case 'conditional_start':
1480
          $settings['ruleGroups'][$rgid_key]['rules'][$rid_key] = array(
1481
            'source_type' => $rule['source_type'],
1482
            'andor' => $rule['operator'],
1483
          );
1484
          break;
1485

    
1486
        case 'conditional_end':
1487
          $settings['ruleGroups'][$rgid_key]['rules'][$rid_key] = array(
1488
            'source_type' => $rule['source_type'],
1489
          );
1490
          break;
1491
      }
1492
    }
1493
  }
1494

    
1495
  return $settings;
1496
}
1497

    
1498
/**
1499
 * Determine whether a component type is capable of a given conditional action.
1500
 */
1501
function webform_conditional_action_able($component_type, $action) {
1502
  switch ($action) {
1503
    case 'show':
1504
      return TRUE;
1505

    
1506
    case 'require':
1507
      return webform_component_feature($component_type, 'required');
1508

    
1509
    default:
1510
      return webform_component_feature($component_type, "conditional_action_$action");
1511
  }
1512
}
1513

    
1514
/**
1515
 * Prepare a conditional value for adding as a JavaScript setting.
1516
 */
1517
function webform_conditional_prepare_date_js($rule_value) {
1518
  // Convert the time/date string to a UTC timestamp for comparison. Note that
1519
  // this means comparisons against immediate times (such as "now") may be
1520
  // slightly stale by the time the comparison executes. Timestamps are in
1521
  // milliseconds, as to match JavaScript's Date.toString() method.
1522
  $date = webform_strtodate('c', $rule_value, 'UTC');
1523
  return webform_strtotime($date);
1524
}
1525

    
1526
/**
1527
 * Prepare a conditional value for adding as a JavaScript setting.
1528
 */
1529
function webform_conditional_prepare_time_js($rule_value) {
1530
  $date = webform_conditional_prepare_date_js($rule_value);
1531
  $today = webform_strtodate('c', 'today', 'UTC');
1532
  $today = webform_strtotime($today);
1533
  return $date - $today;
1534
}
1535

    
1536
/**
1537
 * Conditional callback for string comparisons.
1538
 */
1539
function webform_conditional_operator_string_equal($input_values, $rule_value) {
1540
  foreach ($input_values as $value) {
1541
    // Checkbox values come in as 0 integers for unchecked boxes.
1542
    $value = ($value === 0) ? '' : $value;
1543
    if (strcasecmp($value, $rule_value) === 0) {
1544
      return TRUE;
1545
    }
1546
  }
1547
  return FALSE;
1548
}
1549

    
1550
/**
1551
 * Conditional callback for string comparisons.
1552
 */
1553
function webform_conditional_operator_string_not_equal($input_values, $rule_value) {
1554
  return !webform_conditional_operator_string_equal($input_values, $rule_value);
1555
}
1556

    
1557
/**
1558
 * Conditional callback for string comparisons.
1559
 */
1560
function webform_conditional_operator_string_contains($input_values, $rule_value) {
1561
  foreach ($input_values as $value) {
1562
    if (stripos($value, $rule_value) !== FALSE) {
1563
      return TRUE;
1564
    }
1565
  }
1566
  return FALSE;
1567
}
1568

    
1569
/**
1570
 * Conditional callback for string comparisons.
1571
 */
1572
function webform_conditional_operator_string_does_not_contain($input_values, $rule_value) {
1573
  return !webform_conditional_operator_string_contains($input_values, $rule_value);
1574
}
1575

    
1576
/**
1577
 * Conditional callback for string comparisons.
1578
 */
1579
function webform_conditional_operator_string_begins_with($input_values, $rule_value) {
1580
  foreach ($input_values as $value) {
1581
    if (stripos($value, $rule_value) === 0) {
1582
      return TRUE;
1583
    }
1584
  }
1585
  return FALSE;
1586
}
1587

    
1588
/**
1589
 * Conditional callback for string comparisons.
1590
 */
1591
function webform_conditional_operator_string_ends_with($input_values, $rule_value) {
1592
  foreach ($input_values as $value) {
1593
    if (strripos($value, $rule_value) === strlen($value) - strlen($rule_value)) {
1594
      return TRUE;
1595
    }
1596
  }
1597
  return FALSE;
1598
}
1599

    
1600
/**
1601
 * Conditional callback for checking for empty fields.
1602
 */
1603
function webform_conditional_operator_string_empty($input_values, $rule_value) {
1604
  $empty = TRUE;
1605
  foreach ($input_values as $value) {
1606
    if ($value !== '' && $value !== NULL && $value !== 0) {
1607
      $empty = FALSE;
1608
      break;
1609
    }
1610
  }
1611
  return $empty;
1612
}
1613

    
1614
/**
1615
 * Conditional callback for checking for empty fields.
1616
 */
1617
function webform_conditional_operator_string_not_empty($input_values, $rule_value) {
1618
  return !webform_conditional_operator_string_empty($input_values, $rule_value);
1619
}
1620

    
1621
/**
1622
 * Conditional callback for select comparisons.
1623
 */
1624
function webform_conditional_operator_select_less_than($input_values, $rule_value, $component) {
1625
  return empty($input_values) ? FALSE : webform_compare_select($input_values[0], $rule_value, _webform_select_options($component, TRUE)) < 0;
1626
}
1627

    
1628
/**
1629
 * Conditional callback for select comparisons.
1630
 */
1631
function webform_conditional_operator_select_less_than_equal($input_values, $rule_value, $component) {
1632
  $comparison = empty($input_values) ? NULL : webform_compare_select($input_values[0], $rule_value, _webform_select_options($component, TRUE));
1633
  return $comparison < 0 || $comparison === 0;
1634
}
1635

    
1636
/**
1637
 * Conditional callback for select comparisons.
1638
 */
1639
function webform_conditional_operator_select_greater_than($input_values, $rule_value, $component) {
1640
  return empty($input_values) ? FALSE : webform_compare_select($input_values[0], $rule_value, _webform_select_options($component, TRUE)) > 0;
1641
}
1642

    
1643
/**
1644
 * Conditional callback for select comparisons.
1645
 */
1646
function webform_conditional_operator_select_greater_than_equal($input_values, $rule_value, $component) {
1647
  $comparison = empty($input_values) ? NULL : webform_compare_select($input_values[0], $rule_value, _webform_select_options($component, TRUE));
1648
  return $comparison > 0 || $comparison === 0;
1649
}
1650

    
1651
/**
1652
 * Conditional callback for numeric comparisons.
1653
 */
1654
function webform_conditional_operator_numeric_equal($input_values, $rule_value) {
1655
  return empty($input_values) ? FALSE : webform_compare_floats($input_values[0], $rule_value) === 0;
1656
}
1657

    
1658
/**
1659
 * Conditional callback for numeric comparisons.
1660
 */
1661
function webform_conditional_operator_numeric_not_equal($input_values, $rule_value) {
1662
  return !webform_conditional_operator_numeric_equal($input_values, $rule_value);
1663
}
1664

    
1665
/**
1666
 * Conditional callback for numeric comparisons.
1667
 */
1668
function webform_conditional_operator_numeric_less_than($input_values, $rule_value) {
1669
  return empty($input_values) ? FALSE : webform_compare_floats($input_values[0], $rule_value) < 0;
1670
}
1671

    
1672
/**
1673
 * Conditional callback for numeric comparisons.
1674
 */
1675
function webform_conditional_operator_numeric_less_than_equal($input_values, $rule_value) {
1676
  $comparison = empty($input_values) ? NULL : webform_compare_floats($input_values[0], $rule_value);
1677
  return $comparison < 0 || $comparison === 0;
1678
}
1679

    
1680
/**
1681
 * Conditional callback for numeric comparisons.
1682
 */
1683
function webform_conditional_operator_numeric_greater_than($input_values, $rule_value) {
1684
  return empty($input_values) ? FALSE : webform_compare_floats($input_values[0], $rule_value) > 0;
1685
}
1686

    
1687
/**
1688
 * Conditional callback for numeric comparisons.
1689
 */
1690
function webform_conditional_operator_numeric_greater_than_equal($input_values, $rule_value) {
1691
  $comparison = empty($input_values) ? NULL : webform_compare_floats($input_values[0], $rule_value);
1692
  return $comparison > 0 || $comparison === 0;
1693
}
1694

    
1695
/**
1696
 * Conditional callback for date and time comparisons.
1697
 */
1698
function webform_conditional_operator_datetime_equal($input_values, $rule_value) {
1699
  $input_values = webform_conditional_value_datetime($input_values);
1700
  return empty($input_values) ? FALSE : webform_strtotime($input_values[0]) === webform_strtotime($rule_value);
1701
}
1702

    
1703
/**
1704
 * Conditional callback for date and time comparisons.
1705
 */
1706
function webform_conditional_operator_datetime_not_equal($input_values, $rule_value) {
1707
  return !webform_conditional_operator_datetime_equal($input_values, $rule_value);
1708
}
1709

    
1710
/**
1711
 * Conditional callback for date and time comparisons.
1712
 */
1713
function webform_conditional_operator_datetime_after($input_values, $rule_value) {
1714
  $input_values = webform_conditional_value_datetime($input_values);
1715
  return empty($input_values) ? FALSE : webform_strtotime($input_values[0]) > webform_strtotime($rule_value);
1716
}
1717

    
1718
/**
1719
 * Conditional callback for date and time comparisons.
1720
 */
1721
function webform_conditional_operator_datetime_after_equal($input_values, $rule_value) {
1722
  return webform_conditional_operator_datetime_after($input_values, $rule_value) ||
1723
    webform_conditional_operator_datetime_equal($input_values, $rule_value);
1724
}
1725

    
1726
/**
1727
 * Conditional callback for date and time comparisons.
1728
 */
1729
function webform_conditional_operator_datetime_before($input_values, $rule_value) {
1730
  $input_values = webform_conditional_value_datetime($input_values);
1731
  return empty($input_values) ? FALSE : webform_strtotime($input_values[0]) < webform_strtotime($rule_value);
1732
}
1733

    
1734
/**
1735
 * Conditional callback for date and time comparisons.
1736
 */
1737
function webform_conditional_operator_datetime_before_equal($input_values, $rule_value) {
1738
  return webform_conditional_operator_datetime_before($input_values, $rule_value) ||
1739
    webform_conditional_operator_datetime_equal($input_values, $rule_value);
1740
}
1741

    
1742
/**
1743
 * Utility function to convert incoming time and dates into strings.
1744
 */
1745
function webform_conditional_value_datetime($input_values) {
1746
  // Convert times into a string.
1747
  $input_values = isset($input_values['hour']) ? array(webform_date_string(webform_time_convert($input_values, '24-hour'), 'time')) : $input_values;
1748
  // Convert dates into a string.
1749
  $input_values = isset($input_values['month']) ? array(webform_date_string($input_values, 'date')) : $input_values;
1750
  return $input_values;
1751
}
1752

    
1753
/**
1754
 * Utility function to compare values of a select component.
1755
 *
1756
 * @param string $a
1757
 *   First select option key to compare.
1758
 * @param string $b
1759
 *   Second select option key to compare.
1760
 * @param array $options
1761
 *   Associative array where the $a and $b are within the keys.
1762
 *
1763
 * @return int|null
1764
 *   Based upon position of $a and $b in $options:
1765
 *   -N if $a above (<) $b
1766
 *   0 if $a = $b
1767
 *   +N if $a is below (>) $b
1768
 */
1769
function webform_compare_select($a, $b, array $options) {
1770
  // Select keys that are integer-like strings are numeric indices in PHP.
1771
  // Convert the array keys to an array of strings.
1772
  $options_array = array_map(function ($i) {
1773
    return (string) $i;
1774
  }, array_keys($options));
1775
  $a_position = array_search($a, $options_array, TRUE);
1776
  $b_position = array_search($b, $options_array, TRUE);
1777
  return ($a_position === FALSE || $b_position === FALSE) ? NULL : $a_position - $b_position;
1778
}