Projet

Général

Profil

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

root / drupal7 / sites / all / modules / webform_validation / webform_validation.module @ 1f623f01

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

    
85
/**
86
 * Implements hook_form_alter().
87
 */
88
function webform_validation_form_alter(&$form, &$form_state, $form_id) {
89
  if (strpos($form_id, 'webform_client_form_') !== FALSE) {
90
    $form['#validate'][] = 'webform_validation_validate';
91
  }
92
}
93

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

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

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

    
130
  // Filter out rules that don't apply to this step in the multistep form
131
  if ($values && $page_count && $page_count > 1) {
132
    $current_page_components = webform_validation_get_field_keys($form_state['values']['submitted'], $node);
133
    if ($rules) {
134
       // filter out rules that don't belong in the current step
135
      foreach ($rules as $ruleid => $rule) {
136
        // get all the component formkeys for this specific validation rule
137
        $rule_formkeys = webform_validation_rule_get_formkeys($rule);
138
        $rule_applies_to_current_page = FALSE;
139
        if (!empty($rule_formkeys)) {
140
          foreach ($rule_formkeys as $formkey) {
141
            if (in_array($formkey, $current_page_components)) {
142
              // this rule applies to the current page,
143
              // because one of the rule components is on the page
144
              $rule_applies_to_current_page = TRUE;
145
            }
146
          }
147
        }
148

    
149
        if (!$rule_applies_to_current_page) {
150
          unset($rules[$ruleid]);
151
        }
152
      }
153
    }
154
  }
155

    
156
  // Webform 7.x-3.x does not define WEBFORM_CONDITIONAL_INCLUDE. Define if needed.
157
  if (!defined('WebformConditionals::componentShown') && !defined('WEBFORM_CONDITIONAL_INCLUDE')) {
158
    define('WEBFORM_CONDITIONAL_INCLUDE', 1);
159
  }
160

    
161
  if ($rules) {
162
    $component_definitions = webform_validation_prefix_keys($node->webform['components']);
163
    $sorter = webform_get_conditional_sorter($node);
164
    // If the form was retrieved from the form cache, the conditionals may not
165
    // have been executed yet.
166
    if (!$sorter->isExecuted()) {
167
      $sorter->executeConditionals(array(), 0);
168
    }
169
    // Remove hidden components.
170
    foreach ($component_definitions as $key => $component) {
171
      if (defined('WebformConditionals::componentShown')) {
172
        if ($sorter->componentVisibility($component['cid'], $component['page_num']) !== WebformConditionals::componentShown) {
173
          unset($flat_values[$key]);
174
        }
175
      }
176
      else {
177
        // Old conditionals system removed in Webform 7.x-4.8.
178
        // In Webform 7.x-3.x, _webform_client_form_rule_check() returns boolean.
179
        // Cast to int so that the function behaves as it does in 7.x-4.x.
180
        if (isset($flat_values[$key]) && (int) _webform_client_form_rule_check($node, $component, 0, $form_state['values']['submitted']) !== WEBFORM_CONDITIONAL_INCLUDE) {
181
          unset($flat_values[$key]);
182
        }
183
      }
184
    }
185
    foreach ($rules as $rule) {
186
      // create a list of components that need validation against this rule (component id => user submitted value)
187
      $items = array();
188
      foreach ($rule['components'] as $cid => $component) {
189
        if (array_key_exists($cid, $flat_values)) {
190
          $items[$cid] = $flat_values[$cid];
191
        }
192
      }
193
      // prefix array keys to avoid reindexing by the module_invoke_all function call
194
      $items = webform_validation_prefix_keys($items);
195
      $rule['sid'] = $sid;
196
      // have the submitted values validated
197
      $errors = module_invoke_all("webform_validation_validate", $rule['validator'], $items, $component_definitions, $rule);
198
      if ($errors) {
199
        $errors = webform_validation_unprefix_keys($errors);
200
        $components = webform_validation_unprefix_keys($component_definitions);
201
        foreach ($errors as $item_key => $error) {
202
          // Do not set error message if an identical message has already been set.
203
          if (in_array($error, $static_error_messages, TRUE)) {
204
            continue;
205
          }
206
          $static_error_messages[] = $error;
207

    
208
          // build the proper form element error key, taking into account hierarchy
209
          $error_key = 'submitted][' . webform_validation_parent_tree($item_key, $components) . $components[$item_key]['form_key'];
210
          if (is_array($error)) {
211
            foreach ($error as $sub_item_key => $sub_error) {
212
              form_set_error($error_key . '][' . $sub_item_key, $sub_error);
213
            }
214
          }
215
          else {
216
            // @ignore security_form_set_error. filter_xss() is run in _webform_validation_i18n_error_message().
217
            form_set_error($error_key, $error);
218
          }
219
        }
220
      }
221
    }
222
  }
223
}
224

    
225
/**
226
 * Recursive helper function to get all field keys (including fields in fieldsets)
227
 */
228
function webform_validation_get_field_keys($submitted, $node) {
229
  static $fields = array();
230
  foreach (element_children($submitted) as $child) {
231
    if (is_array($submitted[$child]) && element_children($submitted[$child])) {
232
      // only keep searching recursively if it's a fieldset
233
      $group_components = _webform_validation_get_group_types();
234
      if (in_array(_webform_validation_get_component_type($node, $child), $group_components)) {
235
        webform_validation_get_field_keys($submitted[$child], $node);
236
      }
237
      else {
238
        $fields[$child] = $child;
239
      }
240

    
241
    }
242
    else {
243
      $fields[$child] = $child;
244
    }
245
  }
246
  return $fields;
247
}
248

    
249
/**
250
 * Recursively add the parents for the element, to be used as first argument to form_set_error
251
 */
252
function webform_validation_parent_tree($cid, $components) {
253
  $output = '';
254
  if ($pid = $components[$cid]['pid']) {
255
    $output .= webform_validation_parent_tree($pid, $components);
256
    $output .= $components[$pid]['form_key'] . '][';
257
  }
258
  return $output;
259
}
260

    
261
/**
262
 * Get an array of formkeys for all components that have been assigned to a rule
263
 */
264
function webform_validation_rule_get_formkeys($rule) {
265
  $formkeys = array();
266
  if (isset($rule['components'])) {
267
    foreach ($rule['components'] as $cid => $component) {
268
      $formkeys[] = $component['form_key'];
269
    }
270
  }
271
  return $formkeys;
272
}
273

    
274
/**
275
 * Prefix numeric array keys to avoid them being reindexed by module_invoke_all
276
 */
277
function webform_validation_prefix_keys($arr) {
278
  $ret = array();
279
  foreach ($arr as $k => $v) {
280
    $ret['item_' . $k] = $v;
281
  }
282
  return $ret;
283
}
284

    
285
/**
286
 * Undo prefixing numeric array keys to avoid them being reindexed by module_invoke_all
287
 */
288
function webform_validation_unprefix_keys($arr) {
289
  $ret = array();
290
  foreach ($arr as $k => $v) {
291
    $new_key = str_replace('item_', '', $k);
292
    $ret[$new_key] = $v;
293
  }
294
  return $ret;
295
}
296
/**
297
 * Theme the 'add rule' list
298
 */
299
function theme_webform_validation_manage_add_rule($variables) {
300
  $nid = $variables['nid'];
301
  $output = '';
302
  $validators = webform_validation_get_validators();
303

    
304
  if ($validators) {
305
    $results = db_query('SELECT DISTINCT type FROM {webform_component} WHERE nid = :nid', array('nid' => $nid));
306
    $types = array();
307
    while ($item = $results->fetch()) {
308
      $types[] = $item->type;
309
    }
310

    
311
    $output = '<h3>' . t('Add a validation rule') . '</h3>';
312
    $output .= '<dl>';
313
    foreach ($validators as $validator_key => $validator_info) {
314
      $url = 'node/' . $nid . '/webform/validation/add/' . $validator_key;
315
      if (array_intersect($types, $validator_info['component_types'])) {
316
        $title = l($validator_info['name'], $url, array('query' => drupal_get_destination()));
317
        $component_list_postfix = '';
318
      }
319
      else {
320
        $title = $validator_info['name'];
321
        $component_list_postfix = '; ' . t('none present in this form');
322
      }
323
      $item = '<dt>' . $title . '</dt>';
324
      $item .= '<dd>';
325
      $item .= $validator_info['description'];
326
      $item .= ' ' . t('Works with: @component_types.', array('@component_types' => implode(', ', $validator_info['component_types']) . $component_list_postfix)) . '</dd>';
327
      $output .= $item;
328
    }
329
    $output .= '</dl>';
330
  }
331
  return $output;
332
}
333

    
334
/**
335
 * Implements hook_webform_validation().
336
 */
337
function webform_validation_webform_validation($type, $op, $data) {
338
  if ($type == 'rule' && in_array($op, array('add', 'edit'))) {
339
    if (module_exists('i18n_string') && isset($data['error_message'])) {
340
      i18n_string_update('webform_validation:error_message:' . $data['ruleid'] . ':message', $data['error_message']);
341
    }
342
  }
343
}
344

    
345
/**
346
 * Implements hook_node_insert().
347
 */
348
function webform_validation_node_insert($node) {
349
  if (module_exists('clone') && in_array($node->type, webform_variable_get('webform_node_types'))) {
350
    webform_validation_node_clone($node);
351
  }
352
}
353

    
354
/**
355
 * Implements hook_node_delete().
356
 */
357
function webform_validation_node_delete($node) {
358
  $rules = webform_validation_get_node_rules($node->nid);
359
  if ($rules) {
360
    foreach (array_keys($rules) as $ruleid) {
361
      webform_dynamic_delete_rule($ruleid);
362
    }
363
  }
364
}
365

    
366
/**
367
 * Adds support for node_clone module
368
 */
369
function webform_validation_node_clone($node) {
370
  if (!in_array($node->type, webform_variable_get('webform_node_types'))) {
371
    return;
372
  }
373
  if (isset($node->clone_from_original_nid)) {
374
    $original_nid = $node->clone_from_original_nid;
375
    // Get existing rules for original node
376
    $rules = webform_validation_get_node_rules($original_nid);
377
    if ($rules) {
378
      foreach ($rules as $orig_ruleid => $rule) {
379
        unset($rule['ruleid']);
380
        $rule['action'] = 'add';
381
        $rule['nid'] = $node->nid; // attach existing rules to new node
382
        $rule['rule_components'] = $rule['components'];
383
        webform_validation_rule_save($rule);
384
      }
385
    }
386
  }
387
}
388

    
389
/**
390
 * Save a validation rule. Data comes from the admin form or nodeapi function in
391
 * case of node clone.
392
 *
393
 * @param array $values
394
 *   An associative array containing:
395
 *   - action: "add" or "edit".
396
 *   - ruleid: ID of the rule to edit. Do not set for "add".
397
 *   - nid: Node ID of the Webform.
398
 *   - validator: Machine name of the validator used by this validation rule.
399
 *   - rulename: Human-readable name for this validation rule.
400
 *   - rule_components: An array in which the keys and the values are the cid's
401
 *     of the Webform components that this rule applies to.
402
 *
403
 * @return int
404
 *   The $ruleid of the rule added or edited.
405
 */
406
function webform_validation_rule_save($values) {
407
  if ($values['action'] === 'add') {
408
    $primary_keys = array();
409
  }
410
  elseif ($values['action'] === 'edit') {
411
    $primary_keys = array('ruleid');
412
  }
413
  else {
414
    return FALSE;
415
  }
416

    
417
  drupal_write_record('webform_validation_rule', $values, $primary_keys);
418

    
419
  // Delete existing component records for this ruleid.
420
  if ($values['action'] === 'edit') {
421
    db_delete('webform_validation_rule_components')
422
      ->condition('ruleid', $values['ruleid'])
423
      ->execute();
424
  }
425

    
426
  $components = array_filter($values['rule_components']);
427
  if ($values['ruleid'] && $components) {
428
    webform_validation_save_rule_components($values['ruleid'], $components);
429
    module_invoke_all('webform_validation', 'rule', $values['action'], $values);
430
  }
431

    
432
  return $values['ruleid'];
433
}
434

    
435
/**
436
 * Save components attached to a specific rule.
437
 *
438
 * @param int $ruleid
439
 *   The ruleid of the rule being saved.
440
 * @param array $components
441
 *   An array in which the keys are the cid's of the components attached to the rule.
442
 * @return array
443
 *   An array of the return statuses for each query keyed by cid.
444
 */
445
function webform_validation_save_rule_components($ruleid, $components) {
446
  $return_status = array();
447
  foreach ($components as $cid => $component) {
448
    $return_status[$cid] = db_merge('webform_validation_rule_components')
449
      ->key(array(
450
        'ruleid' => $ruleid,
451
        'cid' => $cid,
452
      ))
453
      ->fields(array(
454
        'ruleid' => $ruleid,
455
        'cid' => $cid,
456
      ))
457
      ->execute();
458
  }
459
  return $return_status;
460
}
461

    
462
/**
463
 * Given a webform node, get the component type based on a given component key
464
 */
465
function _webform_validation_get_component_type($node, $component_key) {
466
  if ($node->webform['components']) {
467
    foreach ($node->webform['components'] as $component) {
468
      if ($component['form_key'] == $component_key) {
469
        return $component['type'];
470
      }
471
    }
472
  }
473
  return FALSE;
474
}
475

    
476
/**
477
 * Get all webform components that are defined as a group
478
 */
479
function _webform_validation_get_group_types() {
480
  $types = array();
481
  foreach (webform_components() as $name => $component) {
482
    if (isset($component['features']['group']) && $component['features']['group']) {
483
      $types[] = $name;
484
    }
485
  }
486
  return $types;
487
}
488

    
489
/**
490
 * Implements hook_webform_validator_alter().
491
 */
492
function webform_validation_webform_validator_alter(&$validators) {
493
  // Add support for the Select (or Other) module
494
  if (module_exists('select_or_other')) {
495
    // if this module exists, all select components can now except user input.
496
    // Thus we provide those components the same rules as a textfield
497
    if ($validators) {
498
      foreach ($validators as $validator_name => $validator_info) {
499
        if (in_array('textfield', $validator_info['component_types'])) {
500
          $validators[$validator_name]['component_types'][] = 'select';
501
        }
502
        $validators[$validator_name]['component_types'] = array_unique($validators[$validator_name]['component_types']);
503
      }
504
    }
505
  }
506
}