Projet

Général

Profil

Paste
Télécharger (14,8 ko) Statistiques
| Branche: | Révision:

root / drupal7 / sites / all / modules / webform_validation / webform_validation.module @ a2baadd1

1
<?php
2

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

    
8
include_once DRUPAL_ROOT . '/' . drupal_get_path('module', 'webform_validation') . '/' . 'webform_validation.validators.inc';
9
include_once DRUPAL_ROOT . '/' . drupal_get_path('module', 'webform_validation') . '/' . '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
  $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
    $current_page_components = webform_validation_get_field_keys($form_state['values']['submitted'], $node);
132
    if ($rules) {
133
       // filter out rules that don't belong in the current step
134
      foreach ($rules as $ruleid => $rule) {
135
        // get all the component formkeys for this specific validation rule
136
        $rule_formkeys = webform_validation_rule_get_formkeys($rule);
137
        $rule_applies_to_current_page = FALSE;
138
        if (!empty($rule_formkeys)) {
139
          foreach ($rule_formkeys as $formkey) {
140
            if (in_array($formkey, $current_page_components)) {
141
              // this rule applies to the current page,
142
              // because one of the rule components is on the page
143
              $rule_applies_to_current_page = TRUE;
144
            }
145
          }
146
        }
147

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

    
155
  if ($rules) {
156
    foreach ($rules as $rule) {
157
      // create a list of components that need validation against this rule (component id => user submitted value)
158
      $items = array();
159
      foreach ($rule['components'] as $cid => $component) {
160
        if (array_key_exists($cid, $flat_values)) {
161
          $items[$cid] = $flat_values[$cid];
162
        }
163
      }
164
      // prefix array keys to avoid reindexing by the module_invoke_all function call
165
      $items = webform_validation_prefix_keys($items);
166
      $component_definitions = webform_validation_prefix_keys($node->webform['components']);
167
      $rule['sid'] = $sid;
168
      // have the submitted values validated
169
      $errors = module_invoke_all("webform_validation_validate", $rule['validator'], $items, $component_definitions, $rule);
170
      if ($errors) {
171
        $errors = webform_validation_unprefix_keys($errors);
172
        $components = webform_validation_unprefix_keys($component_definitions);
173
        foreach ($errors as $item_key => $error) {
174
          // build the proper form element error key, taking into account hierarchy
175
          $error_key = 'submitted][' . webform_validation_parent_tree($item_key, $components) . $components[$item_key]['form_key'];
176
          if (is_array($error)) {
177
            foreach ($error as $sub_item_key => $sub_error) {
178
              form_set_error($error_key . '][' . $sub_item_key, $sub_error);
179
            }
180
          }
181
          else {
182
            // @ignore security_form_set_error. filter_xss() is run in _webform_validation_i18n_error_message().
183
            form_set_error($error_key, $error);
184
          }
185
        }
186
      }
187
    }
188
  }
189
}
190

    
191
/**
192
 * Recursive helper function to get all field keys (including fields in fieldsets)
193
 */
194
function webform_validation_get_field_keys($submitted, $node) {
195
  static $fields = array();
196
  foreach (element_children($submitted) as $child) {
197
    if (is_array($submitted[$child]) && element_children($submitted[$child])) {
198
      // only keep searching recursively if it's a fieldset
199
      $group_components = _webform_validation_get_group_types();
200
      if (in_array(_webform_validation_get_component_type($node, $child), $group_components)) {
201
        webform_validation_get_field_keys($submitted[$child], $node);
202
      }
203
      else {
204
        $fields[$child] = $child;
205
      }
206

    
207
    }
208
    else {
209
      $fields[$child] = $child;
210
    }
211
  }
212
  return $fields;
213
}
214

    
215
/**
216
 * Recursively add the parents for the element, to be used as first argument to form_set_error
217
 */
218
function webform_validation_parent_tree($cid, $components) {
219
  $output = '';
220
  if ($pid = $components[$cid]['pid']) {
221
    $output .= webform_validation_parent_tree($pid, $components);
222
    $output .= $components[$pid]['form_key'] . '][';
223
  }
224
  return $output;
225
}
226

    
227
/**
228
 * Get an array of formkeys for all components that have been assigned to a rule
229
 */
230
function webform_validation_rule_get_formkeys($rule) {
231
  $formkeys = array();
232
  if (isset($rule['components'])) {
233
    foreach ($rule['components'] as $cid => $component) {
234
      $formkeys[] = $component['form_key'];
235
    }
236
  }
237
  return $formkeys;
238
}
239

    
240
/**
241
 * Prefix numeric array keys to avoid them being reindexed by module_invoke_all
242
 */
243
function webform_validation_prefix_keys($arr) {
244
  $ret = array();
245
  foreach ($arr as $k => $v) {
246
    $ret['item_' . $k] = $v;
247
  }
248
  return $ret;
249
}
250

    
251
/**
252
 * Undo prefixing numeric array keys to avoid them being reindexed by module_invoke_all
253
 */
254
function webform_validation_unprefix_keys($arr) {
255
  $ret = array();
256
  foreach ($arr as $k => $v) {
257
    $new_key = str_replace('item_', '', $k);
258
    $ret[$new_key] = $v;
259
  }
260
  return $ret;
261
}
262
/**
263
 * Theme the 'add rule' list
264
 */
265
function theme_webform_validation_manage_add_rule($variables) {
266
  $nid = $variables['nid'];
267
  $output = '';
268
  $validators = webform_validation_get_validators();
269

    
270
  if ($validators) {
271
    $results = db_query('SELECT DISTINCT type FROM {webform_component} WHERE nid = :nid', array('nid' => $nid));
272
    $types = array();
273
    while ($item = $results->fetch()) {
274
      $types[] = $item->type;
275
    }
276

    
277
    $output = '<h3>' . t('Add a validation rule') . '</h3>';
278
    $output .= '<dl>';
279
    foreach ($validators as $validator_key => $validator_info) {
280
      $url = 'node/' . $nid . '/webform/validation/add/' . $validator_key;
281
      if (array_intersect($types, $validator_info['component_types'])) {
282
        $title = l($validator_info['name'], $url, array('query' => drupal_get_destination()));
283
        $component_list_postfix = '';
284
      }
285
      else {
286
        $title = $validator_info['name'];
287
        $component_list_postfix = '; none present in this form';
288
      }
289
      $item = '<dt>' . $title . '</dt>';
290
      $item .= '<dd>';
291
      $item .= $validator_info['description'];
292
      $item .= ' Works with: ' . implode(', ', $validator_info['component_types']) . $component_list_postfix . '.</dd>';
293
      $output .= $item;
294
    }
295
    $output .= '</dl>';
296
  }
297
  return $output;
298
}
299

    
300
/**
301
 * Implements hook_webform_validation().
302
 */
303
function webform_validation_webform_validation($type, $op, $data) {
304
  if ($type == 'rule' && in_array($op, array('add', 'edit'))) {
305
    if (module_exists('i18n') && isset($data['error_message'])) {
306
      i18n_string_update('webform_validation:error_message:' . $data['ruleid'] . ':message', $data['error_message']);
307
    }
308
  }
309
}
310

    
311
/**
312
 * Implements hook_node_insert().
313
 */
314
function webform_validation_node_insert($node) {
315
  if (module_exists('clone')) {
316
    if (in_array($node->type, webform_variable_get('webform_node_types'))) {
317
      webform_validation_node_clone($node);
318
    }
319
  }
320
}
321

    
322
/**
323
 * Implements hook_node_delete().
324
 */
325
function webform_validation_node_delete($node) {
326
  $rules = webform_validation_get_node_rules($node->nid);
327
  if ($rules) {
328
    foreach (array_keys($rules) as $ruleid) {
329
      webform_dynamic_delete_rule($ruleid);
330
    }
331
  }
332
}
333

    
334
/**
335
 * Adds support for node_clone module
336
 */
337
function webform_validation_node_clone($node) {
338
  if (isset($node->clone_from_original_nid)) {
339
    $original_nid = $node->clone_from_original_nid;
340
    // Get existing rules for original node
341
    $rules = webform_validation_get_node_rules($original_nid);
342
    if ($rules) {
343
      foreach ($rules as $orig_ruleid => $rule) {
344
        unset($rule['ruleid']);
345
        $rule['action'] = 'add';
346
        $rule['nid'] = $node->nid; // attach existing rules to new node
347
        $rule['rule_components'] = $rule['components'];
348
        webform_validation_rule_save($rule);
349
      }
350
    }
351
  }
352
}
353

    
354
/**
355
 * Save a validation rule. Data comes from the admin form or nodeapi function in
356
 * case of node clone.
357
 *
358
 * @param array $values
359
 *   An associative array containing:
360
 *   - action: "add" or "edit".
361
 *   - ruleid: ID of the rule to edit. Do not set for "add".
362
 *   - nid: Node ID of the Webform.
363
 *   - validator: Machine name of the validator used by this validation rule.
364
 *   - rulename: Human-readable name for this validation rule.
365
 *   - rule_components: An array in which the keys and the values are the cid's
366
 *     of the Webform components that this rule applies to.
367
 *
368
 * @return int
369
 *   The $ruleid of the rule added or edited.
370
 */
371
function webform_validation_rule_save($values) {
372
  if ($values['action'] === 'add') {
373
    $primary_keys = array();
374
  }
375
  elseif ($values['action'] === 'edit') {
376
    $primary_keys = array('ruleid');
377
  }
378
  else {
379
    return FALSE;
380
  }
381

    
382
  drupal_write_record('webform_validation_rule', $values, $primary_keys);
383

    
384
  // Delete existing component records for this ruleid.
385
  if ($values['action'] === 'edit') {
386
    db_delete('webform_validation_rule_components')
387
      ->condition('ruleid', $values['ruleid'])
388
      ->execute();
389
  }
390

    
391
  $components = array_filter($values['rule_components']);
392
  if ($values['ruleid'] && $components) {
393
    webform_validation_save_rule_components($values['ruleid'], $components);
394
    module_invoke_all('webform_validation', 'rule', $values['action'], $values);
395
  }
396

    
397
  return $values['ruleid'];
398
}
399

    
400
/**
401
 * Save components attached to a specific rule.
402
 *
403
 * @param int $ruleid
404
 *   The ruleid of the rule being saved.
405
 * @param array $components
406
 *   An array in which the keys are the cid's of the components attached to the rule.
407
 * @return array
408
 *   An array of the return statuses for each query keyed by cid.
409
 */
410
function webform_validation_save_rule_components($ruleid, $components) {
411
  $return_status = array();
412
  foreach ($components as $cid => $component) {
413
    $return_status[$cid] = db_merge('webform_validation_rule_components')
414
      ->key(array(
415
        'ruleid' => $ruleid,
416
        'cid' => $cid,
417
      ))
418
      ->fields(array(
419
        'ruleid' => $ruleid,
420
        'cid' => $cid,
421
      ))
422
      ->execute();
423
  }
424
  return $return_status;
425
}
426

    
427
/**
428
 * Given a webform node, get the component type based on a given component key
429
 */
430
function _webform_validation_get_component_type($node, $component_key) {
431
  if ($node->webform['components']) {
432
    foreach ($node->webform['components'] as $component) {
433
      if ($component['form_key'] == $component_key) {
434
        return $component['type'];
435
      }
436
    }
437
  }
438
  return FALSE;
439
}
440

    
441
/**
442
 * Get all webform components that are defined as a group
443
 */
444
function _webform_validation_get_group_types() {
445
  $types = array();
446
  foreach (webform_components() as $name => $component) {
447
    if (isset($component['features']['group']) && $component['features']['group']) {
448
      $types[] = $name;
449
    }
450
  }
451
  return $types;
452
}
453

    
454
/**
455
 * Implements hook_webform_validator_alter().
456
 */
457
function webform_validation_webform_validator_alter(&$validators) {
458
  // Add support for the Select (or Other) module
459
  if (module_exists('select_or_other')) {
460
    // if this module exists, all select components can now except user input.
461
    // Thus we provide those components the same rules as a textfield
462
    if ($validators) {
463
      foreach ($validators as $validator_name => $validator_info) {
464
        if (in_array('textfield', $validator_info['component_types'])) {
465
          $validators[$validator_name]['component_types'][] = 'select';
466
        }
467
        $validators[$validator_name]['component_types'] = array_unique($validators[$validator_name]['component_types']);
468
      }
469
    }
470
  }
471
}