Project

General

Profile

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

root / drupal7 / sites / all / modules / webform_validation / webform_validation.module @ 76bdcd04

1
<?php
2

    
3
/**
4
 * @file
5
 * Add validation rules to webforms.
6
 */
7

    
8
include_once 'webform_validation.validators.inc';
9
include_once 'webform_validation.rules.inc';
10

    
11
/**
12
 * Implements hook_menu().
13
 */
14
function webform_validation_menu() {
15
  $items = array();
16

    
17
  $items['node/%webform_menu/webform/validation'] = array(
18
    'title' => 'Form validation',
19
    'page callback' => 'webform_validation_manage',
20
    'page arguments' => array(1),
21
    'access callback' => 'node_access',
22
    'access arguments' => array('update', 1),
23
    'file' => 'webform_validation.admin.inc',
24
    'weight' => 3,
25
    'type' => MENU_LOCAL_TASK,
26
  );
27

    
28
  $items['node/%webform_menu/webform/validation/add/%'] = array(
29
    'title' => 'Add validation',
30
    'page callback' => 'drupal_get_form',
31
    'page arguments' => array('webform_validation_manage_rule', 1, 'add', 5),
32
    'access callback' => 'node_access',
33
    'access arguments' => array('update', 1),
34
    'file' => 'webform_validation.admin.inc',
35
    'type' => MENU_CALLBACK,
36
  );
37

    
38
  $items['node/%webform_menu/webform/validation/edit/%/%webform_validation_rule'] = array(
39
    'title' => 'Edit rule',
40
    'page callback' => 'drupal_get_form',
41
    'page arguments' => array('webform_validation_manage_rule', 1, 'edit', 5, 6),
42
    'access callback' => 'node_access',
43
    'access arguments' => array('update', 1),
44
    'file' => 'webform_validation.admin.inc',
45
    'type' => MENU_CALLBACK,
46
  );
47

    
48
  $items['node/%webform_menu/webform/validation/delete/%webform_validation_rule'] = array(
49
    'title' => 'Delete rule',
50
    'page callback' => 'drupal_get_form',
51
    'page arguments' => array('webform_validation_delete_rule', 5),
52
    'access callback' => 'node_access',
53
    'access arguments' => array('update', 1),
54
    'file' => 'webform_validation.admin.inc',
55
    'type' => MENU_CALLBACK,
56
  );
57

    
58
  return $items;
59
}
60

    
61
/**
62
 * Loads validation rule from menu parameter.
63
 */
64
function webform_validation_rule_load($ruleid) {
65
  return webform_validation_get_rule($ruleid);
66
}
67

    
68
/**
69
 * Implements hook_theme().
70
 */
71
function webform_validation_theme() {
72
  return array(
73
    'webform_validation_manage_add_rule' => array(
74
      'variables' => array(
75
        'nid' => NULL,
76
      ),
77
    ),
78
    'webform_validation_manage_overview_form' => array(
79
      'render element' => 'form',
80
    ),
81
  );
82
}
83

    
84
/**
85
 * Implements hook_form_BASE_FORM_ID_alter().
86
 */
87
function webform_validation_form_webform_client_form_alter(&$form, &$form_state, $form_id) {
88
  $form['#validate'][] = 'webform_validation_validate';
89
}
90

    
91
/**
92
 * Implements hook_i18n_string_info().
93
 */
94
function webform_validation_i18n_string_info() {
95
  $groups = array();
96
  $groups['webform_validation'] = array(
97
    'title' => t('Webform Validation'),
98
    'description' => t('Translatable strings for webform validation translation'),
99
    // This group doesn't have strings with format.
100
    'format' => FALSE,
101
    // This group cannot list all strings.
102
    'list' => FALSE,
103
    'refresh callback' => 'webform_validation_i18n_string_refresh',
104
  );
105
  return $groups;
106
}
107

    
108
/**
109
 * Webform validation handler to validate against the given rules.
110
 */
111
function webform_validation_validate($form, &$form_state) {
112
  $static_error_messages = &drupal_static(__FUNCTION__, array());
113
  $page_count = 1;
114
  $nid = $form_state['values']['details']['nid'];
115
  $node = node_load($nid);
116
  $values = isset($form_state['values']['submitted']) ? $form_state['values']['submitted'] : NULL;
117
  $flat_values = _webform_client_form_submit_flatten($node, $values);
118
  $rules = webform_validation_get_node_rules($nid);
119
  $sid = empty($form_state['values']['details']['sid']) ? 0 : $form_state['values']['details']['sid'];
120

    
121
  // Get number of pages for this webform.
122
  if (isset($form_state['webform']['page_count'])) {
123
    $page_count = $form_state['webform']['page_count'];
124
  }
125
  elseif (isset($form_state['storage']['page_count'])) {
126
    $page_count = $form_state['storage']['page_count'];
127
  }
128

    
129
  // Filter out rules that don't apply to this step in the multistep form.
130
  if ($values && $page_count && $page_count > 1) {
131
    $validators = webform_validation_get_validators();
132
    foreach ($rules as $ruleid => $rule) {
133
      // Skip the rule if it does not have any components on the current page.
134
      if (!array_intersect_key($flat_values, $rule['components'])) {
135
        unset($rules[$ruleid]);
136
      }
137
      // For validators that require at least 2 components, skip the rule if any
138
      // of the components are on a page past the current page.
139
      elseif (isset($validators[$rule['validator']]['min_components']) && $validators[$rule['validator']]['min_components'] > 1) {
140
        foreach (array_keys($rule['components']) as $cid) {
141
          if ($node->webform['components'][$cid]['page_num'] > $form_state['webform']['page_num']) {
142
            unset($rules[$ruleid]);
143
            break;
144
          }
145
        }
146
      }
147
    }
148
  }
149

    
150
  if ($rules) {
151
    // Remove hidden components.
152
    if (defined('WebformConditionals::componentShown')) {
153
      // New conditionals system.
154
      $sorter = webform_get_conditional_sorter($node);
155
      // If the form was retrieved from the form cache, the conditionals may not
156
      // have been executed yet.
157
      if (!$sorter->isExecuted()) {
158
        $sorter->executeConditionals(array(), 0);
159
      }
160
      foreach ($node->webform['components'] as $key => $component) {
161
        if ($sorter->componentVisibility($component['cid'], $component['page_num']) !== WebformConditionals::componentShown) {
162
          unset($flat_values[$key]);
163
        }
164
      }
165
    }
166
    else {
167
      // Old conditionals system removed in Webform 7.x-4.8.
168
      // Webform 7.x-3.x does not define WEBFORM_CONDITIONAL_INCLUDE.
169
      // Define if needed.
170
      if (!defined('WEBFORM_CONDITIONAL_INCLUDE')) {
171
        define('WEBFORM_CONDITIONAL_INCLUDE', 1);
172
      }
173
      foreach ($node->webform['components'] as $key => $component) {
174
        // In Webform 7.x-3.x, _webform_client_form_rule_check() returns
175
        // boolean.
176
        // Cast to int so that the function behaves as it does in 7.x-4.x.
177
        if (isset($flat_values[$key]) && (int) _webform_client_form_rule_check($node, $component, 0, $form_state['values']['submitted']) !== WEBFORM_CONDITIONAL_INCLUDE) {
178
          unset($flat_values[$key]);
179
        }
180
      }
181
    }
182

    
183
    foreach ($rules as $rule) {
184
      // Create a list of components that need validation against this rule
185
      // (component id => user submitted value).
186
      $items = array();
187
      foreach ($rule['components'] as $cid => $component) {
188
        if (array_key_exists($cid, $flat_values)) {
189
          $items[$cid] = $flat_values[$cid];
190
        }
191
      }
192
      $rule['sid'] = $sid;
193
      // Have the submitted values validated.
194
      $errors = module_invoke_all("webform_validation_validate", $rule['validator'], webform_validation_prefix_keys($items), webform_validation_prefix_keys($node->webform['components']), $rule);
195
      if ($errors) {
196
        $errors = webform_validation_unprefix_keys($errors);
197
        // Create hook_webform_validation_validate_alter(). Allow other modules
198
        // to alter error messages.
199
        $context = array(
200
          'validator_name' => $rule['validator'],
201
          'items' => $items,
202
          'components' => $node->webform['components'],
203
          'rule' => $rule,
204
        );
205
        drupal_alter('webform_validation_validate', $errors, $context);
206

    
207
        foreach ($errors as $item_key => $error) {
208
          // Do not set error message if an identical message has already been
209
          // set.
210
          if (in_array($error, $static_error_messages, TRUE)) {
211
            continue;
212
          }
213
          $static_error_messages[] = $error;
214

    
215
          // Build the proper form element error key, taking into account
216
          // hierarchy.
217
          $error_key = 'submitted][' . webform_validation_parent_tree($item_key, $node->webform['components']) . $node->webform['components'][$item_key]['form_key'];
218
          if (is_array($error)) {
219
            foreach ($error as $sub_item_key => $sub_error) {
220
              form_set_error($error_key . '][' . $sub_item_key, $sub_error);
221
            }
222
          }
223
          else {
224
            // filter_xss() is run in _webform_validation_i18n_error_message().
225
            // @ignore security_form_set_error.
226
            form_set_error($error_key, $error);
227
          }
228
        }
229
      }
230
    }
231
  }
232
}
233

    
234
/**
235
 * Helper function to get all field keys (including fields in fieldsets).
236
 *
237
 * @deprecated No longer used and will be removed in 7.x-2.x.
238
 */
239
function webform_validation_get_field_keys($submitted, $node) {
240
  static $fields = array();
241
  foreach (element_children($submitted) as $child) {
242
    if (is_array($submitted[$child]) && element_children($submitted[$child])) {
243
      // Only keep searching recursively if it's a fieldset.
244
      $group_components = _webform_validation_get_group_types();
245
      if (in_array(_webform_validation_get_component_type($node, $child), $group_components)) {
246
        webform_validation_get_field_keys($submitted[$child], $node);
247
      }
248
      else {
249
        $fields[$child] = $child;
250
      }
251

    
252
    }
253
    else {
254
      $fields[$child] = $child;
255
    }
256
  }
257
  return $fields;
258
}
259

    
260
/**
261
 * Recursively add the parents for the element.
262
 *
263
 * These are used as the first argument to form_set_error().
264
 */
265
function webform_validation_parent_tree($cid, $components) {
266
  $output = '';
267
  if ($pid = $components[$cid]['pid']) {
268
    $output .= webform_validation_parent_tree($pid, $components);
269
    $output .= $components[$pid]['form_key'] . '][';
270
  }
271
  return $output;
272
}
273

    
274
/**
275
 * Get array of formkeys for all components that have been assigned to a rule.
276
 *
277
 * @deprecated No longer used and will be removed in 7.x-2.x.
278
 */
279
function webform_validation_rule_get_formkeys($rule) {
280
  $formkeys = array();
281
  if (isset($rule['components'])) {
282
    foreach ($rule['components'] as $cid => $component) {
283
      $formkeys[] = $component['form_key'];
284
    }
285
  }
286
  return $formkeys;
287
}
288

    
289
/**
290
 * Prefix numeric array keys to avoid them being reindexed.
291
 *
292
 * Reindexing done in module_invoke_all().
293
 *
294
 * Opposite of webform_validation_unprefix_keys().
295
 */
296
function webform_validation_prefix_keys($arr) {
297
  $ret = array();
298
  foreach ($arr as $k => $v) {
299
    $ret['item_' . $k] = $v;
300
  }
301
  return $ret;
302
}
303

    
304
/**
305
 * Undo prefixing numeric array keys.
306
 *
307
 * Opposite of webform_validation_prefix_keys().
308
 */
309
function webform_validation_unprefix_keys($arr) {
310
  $ret = array();
311
  foreach ($arr as $k => $v) {
312
    $new_key = str_replace('item_', '', $k);
313
    $ret[$new_key] = $v;
314
  }
315
  return $ret;
316
}
317

    
318
/**
319
 * Theme the 'add rule' list.
320
 */
321
function theme_webform_validation_manage_add_rule($variables) {
322
  $nid = $variables['nid'];
323
  $output = '';
324
  $validators = webform_validation_get_validators();
325

    
326
  if ($validators) {
327
    $results = db_query('SELECT DISTINCT type FROM {webform_component} WHERE nid = :nid', array('nid' => $nid));
328
    $types = array();
329
    while ($item = $results->fetch()) {
330
      $types[] = $item->type;
331
    }
332

    
333
    $output = '<h3>' . t('Add a validation rule') . '</h3>';
334
    $output .= '<dl>';
335
    foreach ($validators as $validator_key => $validator_info) {
336
      $validator_types = webform_validation_valid_component_types($validator_key);
337
      $title = $validator_info['name'];
338
      if (array_intersect($types, $validator_types)) {
339
        $url = 'node/' . $nid . '/webform/validation/add/' . $validator_key;
340
        $title = l($title, $url, array('query' => drupal_get_destination()));
341
        $component_list_postfix = '';
342
      }
343
      else {
344
        $component_list_postfix = '; ' . t('none present in this form');
345
      }
346
      $item = '<dt>' . $title . '</dt>';
347
      $item .= '<dd>';
348
      $item .= $validator_info['description'];
349
      $item .= ' ' . t('Works with: @component_types.', array('@component_types' => implode(', ', $validator_types) . $component_list_postfix)) . '</dd>';
350
      $output .= $item;
351
    }
352
    $output .= '</dl>';
353
  }
354
  return $output;
355
}
356

    
357
/**
358
 * Implements hook_webform_validation().
359
 */
360
function webform_validation_webform_validation($type, $op, $data) {
361
  if ($type == 'rule' && in_array($op, array('add', 'edit'))) {
362
    if (module_exists('i18n_string') && isset($data['error_message'])) {
363
      i18n_string_update('webform_validation:error_message:' . $data['ruleid'] . ':message', $data['error_message']);
364
    }
365
  }
366
}
367

    
368
/**
369
 * Implements hook_node_insert().
370
 */
371
function webform_validation_node_insert($node) {
372
  if (module_exists('clone') && in_array($node->type, webform_variable_get('webform_node_types'))) {
373
    webform_validation_node_clone($node);
374
  }
375
}
376

    
377
/**
378
 * Implements hook_node_delete().
379
 */
380
function webform_validation_node_delete($node) {
381
  $rules = webform_validation_get_node_rules($node->nid);
382
  if ($rules) {
383
    foreach (array_keys($rules) as $ruleid) {
384
      webform_dynamic_delete_rule($ruleid);
385
    }
386
  }
387
}
388

    
389
/**
390
 * Adds support for node_clone module.
391
 */
392
function webform_validation_node_clone($node) {
393
  if (!in_array($node->type, webform_variable_get('webform_node_types'))) {
394
    return;
395
  }
396
  if (isset($node->clone_from_original_nid)) {
397
    $original_nid = $node->clone_from_original_nid;
398
    // Get existing rules for original node.
399
    $rules = webform_validation_get_node_rules($original_nid);
400
    if ($rules) {
401
      foreach ($rules as $orig_ruleid => $rule) {
402
        unset($rule['ruleid']);
403
        $rule['action'] = 'add';
404
        // Attach existing rules to new node.
405
        $rule['nid'] = $node->nid;
406
        $rule['rule_components'] = $rule['components'];
407
        webform_validation_rule_save($rule);
408
      }
409
    }
410
  }
411
}
412

    
413
/**
414
 * Save a validation rule.
415
 *
416
 * Data comes from the admin form or nodeapi function in case of node clone.
417
 *
418
 * @param array $values
419
 *   An associative array containing:
420
 *   - action: "add" or "edit".
421
 *   - ruleid: ID of the rule to edit. Do not set for "add".
422
 *   - nid: Node ID of the Webform.
423
 *   - validator: Machine name of the validator used by this validation rule.
424
 *   - rulename: Human-readable name for this validation rule.
425
 *   - rule_components: An array in which the keys and the values are the cid's
426
 *     of the Webform components that this rule applies to.
427
 *
428
 * @return int
429
 *   The $ruleid of the rule added or edited.
430
 */
431
function webform_validation_rule_save(array $values) {
432
  if ($values['action'] === 'add') {
433
    $primary_keys = array();
434
  }
435
  elseif ($values['action'] === 'edit') {
436
    $primary_keys = array('ruleid');
437
  }
438
  else {
439
    return FALSE;
440
  }
441

    
442
  drupal_write_record('webform_validation_rule', $values, $primary_keys);
443

    
444
  // Delete existing component records for this ruleid.
445
  if ($values['action'] === 'edit') {
446
    db_delete('webform_validation_rule_components')
447
      ->condition('ruleid', $values['ruleid'])
448
      ->execute();
449
  }
450

    
451
  $components = array_filter($values['rule_components']);
452
  if ($values['ruleid'] && $components) {
453
    webform_validation_save_rule_components($values['ruleid'], $components);
454
    module_invoke_all('webform_validation', 'rule', $values['action'], $values);
455
  }
456

    
457
  return $values['ruleid'];
458
}
459

    
460
/**
461
 * Save components attached to a specific rule.
462
 *
463
 * @param int $ruleid
464
 *   The ruleid of the rule being saved.
465
 * @param array $components
466
 *   An array in which the keys are the cid's of the components attached to the
467
 *   rule.
468
 *
469
 * @return array
470
 *   An array of the return statuses for each query keyed by cid.
471
 */
472
function webform_validation_save_rule_components($ruleid, array $components) {
473
  $return_status = array();
474
  foreach ($components as $cid => $component) {
475
    $return_status[$cid] = db_merge('webform_validation_rule_components')
476
      ->key(array(
477
        'ruleid' => $ruleid,
478
        'cid' => $cid,
479
      ))
480
      ->fields(array(
481
        'ruleid' => $ruleid,
482
        'cid' => $cid,
483
      ))
484
      ->execute();
485
  }
486
  return $return_status;
487
}
488

    
489
/**
490
 * Given a webform node, get the component type based on a given component key.
491
 */
492
function _webform_validation_get_component_type($node, $component_key) {
493
  if ($node->webform['components']) {
494
    foreach ($node->webform['components'] as $component) {
495
      if ($component['form_key'] == $component_key) {
496
        return $component['type'];
497
      }
498
    }
499
  }
500
  return FALSE;
501
}
502

    
503
/**
504
 * Get all webform components that are defined as a group.
505
 */
506
function _webform_validation_get_group_types() {
507
  $types = array();
508
  foreach (webform_components() as $name => $component) {
509
    if (isset($component['features']['group']) && $component['features']['group']) {
510
      $types[] = $name;
511
    }
512
  }
513
  return $types;
514
}
515

    
516
/**
517
 * Implements hook_webform_validator_alter().
518
 */
519
function webform_validation_webform_validator_alter(&$validators) {
520
  // Add support for the Select (or Other) module.
521
  if (module_exists('select_or_other')) {
522
    // If this module exists, all select components can now except user input.
523
    // Thus we provide those components the same rules as a textfield.
524
    if ($validators) {
525
      foreach ($validators as $validator_name => $validator_info) {
526
        if (in_array('textfield', $validator_info['component_types'])) {
527
          $validators[$validator_name]['component_types'][] = 'select';
528
        }
529
        $validators[$validator_name]['component_types'] = array_unique($validators[$validator_name]['component_types']);
530
      }
531
    }
532
  }
533
}