Projet

Général

Profil

Paste
Télécharger (34 ko) Statistiques
| Branche: | Révision:

root / drupal7 / sites / all / modules / rules / ui / ui.forms.inc @ 950416da

1
<?php
2

    
3
/**
4
 * @file
5
 * Rules User Interface forms.
6
 */
7

    
8
/**
9
 * Ajax callback for reloading the whole form.
10
 */
11
function rules_ui_form_ajax_reload_form($form, $form_state) {
12
  return $form;
13
}
14

    
15
/**
16
 * Defines #ajax properties.
17
 */
18
function rules_ui_form_default_ajax($effect = 'slide') {
19
  return array(
20
    'callback' => 'rules_ui_form_ajax_reload_form',
21
    'wrapper' => 'rules-form-wrapper',
22
    'effect' => $effect,
23
    'speed' => 'fast',
24
  );
25
}
26

    
27
/**
28
 * Submit handler for switching the parameter input mode.
29
 */
30
function rules_ui_parameter_replace_submit($form, &$form_state) {
31
  if (isset($form_state['triggering_element'])) {
32
    $name = $form_state['triggering_element']['#parameter'];
33
    $form_state['parameter_mode'][$name] = $form_state['parameter_mode'][$name] == 'selector' ? 'input' : 'selector';
34
  }
35
  $form_state['rebuild'] = TRUE;
36
}
37

    
38
/**
39
 * General form submit handler, that rebuilds the form.
40
 */
41
function rules_form_submit_rebuild($form, &$form_state) {
42
  $form_state['rebuild'] = TRUE;
43
}
44

    
45
/**
46
 * Edit a rules configuration.
47
 */
48
function rules_ui_form_edit_rules_config($form, &$form_state, $rules_config, $base_path) {
49
  RulesPluginUI::$basePath = $base_path;
50
  $form_state += array('rules_element' => $rules_config);
51
  // Add the rule configuration's form.
52
  $rules_config->form($form, $form_state, array('show settings' => TRUE, 'button' => TRUE));
53
  $form['#validate'] = array('rules_ui_form_rules_config_validate');
54
  return $form;
55
}
56

    
57
/**
58
 * General rules configuration form validation callback.
59
 *
60
 * Also populates the rules configuration with the form values.
61
 */
62
function rules_ui_form_rules_config_validate($form, &$form_state) {
63
  $form_state['rules_element']->form_validate($form, $form_state);
64
}
65

    
66
/**
67
 * Edit a rules configuration form submit callback.
68
 */
69
function rules_ui_form_edit_rules_config_submit($form, &$form_state) {
70
  $form_state['rules_element']->form_submit($form, $form_state);
71
  drupal_set_message(t('Your changes have been saved.'));
72
  if (empty($form_state['redirect'])) {
73
    $form_state['redirect'] = RulesPluginUI::defaultRedirect($form_state['rules_element']);
74
  }
75
}
76

    
77
/**
78
 * Clone a rules configuration form.
79
 */
80
function rules_ui_form_clone_rules_config($form, &$form_state, $rules_config, $base_path) {
81
  RulesPluginUI::$basePath = $base_path;
82
  $rules_config = clone $rules_config;
83
  $rules_config->id = NULL;
84
  $rules_config->name = '';
85
  $rules_config->label .= ' (' . t('cloned') . ')';
86
  $rules_config->status = ENTITY_CUSTOM;
87

    
88
  $form['#validate'][] = 'rules_ui_form_rules_config_validate';
89
  $form['#submit'][] = 'rules_ui_form_edit_rules_config_submit';
90
  $form_state += array('rules_element' => $rules_config, 'op' => 'clone');
91

    
92
  // Add the rule configuration's form.
93
  $rules_config->form($form, $form_state, array('show settings' => TRUE, 'button' => TRUE, 'init' => TRUE));
94

    
95
  // Open the settings fieldset so altering the name is easier.
96
  $form['settings']['#collapsed'] = FALSE;
97
  return $form;
98
}
99

    
100
/**
101
 * A simple form just showing a textarea with the export.
102
 */
103
function rules_ui_form_export_rules_config($form, &$form_state, $rules_config, $base_path) {
104
  $form['export'] = array(
105
    '#type' => 'textarea',
106
    '#title' => t('Export'),
107
    '#description' => t('For importing copy the content of the text area and paste it into the import page.'),
108
    '#rows' => 25,
109
    '#default_value' => $rules_config->export(),
110
  );
111
  return $form;
112
}
113

    
114
/**
115
 * Configuration form to directly execute a rules configuration.
116
 */
117
function rules_ui_form_execute_rules_config($form, &$form_state, $rules_config, $base_path) {
118
  // Only components can be executed.
119
  if (!($rules_config instanceof RulesTriggerableInterface)) {
120
    RulesPluginUI::$basePath = $base_path;
121
    // Create either the appropriate action or condition element.
122
    $element = rules_plugin_factory($rules_config instanceof RulesActionInterface ? 'action' : 'condition', 'component_' . $rules_config->name);
123
    $form['exec_help'] = array(
124
      '#prefix' => '<p>',
125
      '#markup' => t('This form allows you to manually trigger the execution of the @plugin "%label". If this component requires any parameters, input the suiting execution arguments below.', array('@plugin' => $rules_config->plugin(), '%label' => $rules_config->label())),
126
      '#suffix' => '</p>',
127
    );
128
    $element->form($form, $form_state);
129

    
130
    // For conditions hide the option to negate them.
131
    if (isset($form['negate'])) {
132
      $form['negate']['#access'] = FALSE;
133
    }
134
    $form['submit'] = array(
135
      '#type' => 'submit',
136
      '#value' => t('Execute'),
137
      '#weight' => 20,
138
    );
139
    // Re-use the validation callback, which will also populate the action with
140
    // the configuration settings in the form.
141
    $form['#validate'] = array('rules_ui_form_rules_config_validate');
142
    return $form;
143
  }
144
  drupal_not_found();
145
  exit;
146
}
147

    
148
/**
149
 * Submit callback for directly executing a component.
150
 */
151
function rules_ui_form_execute_rules_config_submit($form, &$form_state) {
152
  $element = $form_state['rules_element'];
153
  $result = $element->execute();
154
  if ($element instanceof RulesActionInterface) {
155
    drupal_set_message(t('Component %label has been executed.', array('%label' => $element->label())));
156
  }
157
  else {
158
    drupal_set_message(t('Component %label evaluated to %result.', array('%label' => $element->label(), '%result' => $result ? 'true' : 'false')));
159
  }
160
}
161

    
162
/**
163
 * Gets the confirmation question for valid operations, or else FALSE.
164
 */
165
function rules_ui_confirm_operations($op, $rules_config) {
166
  $vars = array('%plugin' => $rules_config->plugin(), '%label' => $rules_config->label());
167

    
168
  switch ($op) {
169
    case 'enable':
170
      return array(
171
        t('Are you sure you want to enable the %plugin %label?', $vars),
172
        '',
173
      );
174

    
175
    case 'disable':
176
      return array(
177
        t('Are you sure you want to disable the %plugin %label?', $vars),
178
        '',
179
      );
180

    
181
    case 'revert':
182
      return array(
183
        t('Are you sure you want to revert the %plugin %label?', $vars),
184
        t('This action cannot be undone.'),
185
      );
186

    
187
    case 'delete':
188
      return array(
189
        t('Are you sure you want to delete the %plugin %label?', $vars),
190
        t('This action cannot be undone.'),
191
      );
192

    
193
    default:
194
      return FALSE;
195
  }
196
}
197

    
198
/**
199
 * Confirmation form for applying the operation to the config.
200
 */
201
function rules_ui_form_rules_config_confirm_op($form, &$form_state, $rules_config, $op, $base_path) {
202
  if (list($confirm_question, $description) = rules_ui_confirm_operations($op, $rules_config)) {
203
    RulesPluginUI::$basePath = $base_path;
204
    $form_state += array('rules_config' => $rules_config, 'op' => $op);
205
    return confirm_form($form, $confirm_question, $base_path, $description, t('Confirm'), t('Cancel'));
206
  }
207
  else {
208
    drupal_not_found();
209
    exit;
210
  }
211
}
212

    
213
/**
214
 * Applies the operation and returns the message to show to the user.
215
 *
216
 * The operation is also logged to the watchdog. Note that the string is
217
 * defined two times so that the translation extractor can find it.
218
 */
219
function rules_ui_confirm_operation_apply($op, $rules_config) {
220
  $vars = array('%plugin' => $rules_config->plugin(), '%label' => $rules_config->label());
221
  $edit_link = l(t('edit'), RulesPluginUI::path($rules_config->name));
222

    
223
  switch ($op) {
224
    case 'enable':
225
      $rules_config->active = TRUE;
226
      $rules_config->save();
227
      watchdog('rules', 'Enabled %plugin %label.', $vars, WATCHDOG_NOTICE, $edit_link);
228
      return t('Enabled %plugin %label.', $vars);
229

    
230
    case 'disable':
231
      $rules_config->active = FALSE;
232
      $rules_config->save();
233
      watchdog('rules', 'Disabled %plugin %label.', $vars, WATCHDOG_NOTICE, $edit_link);
234
      return t('Disabled %plugin %label.', $vars);
235

    
236
    case 'revert':
237
      $rules_config->delete();
238
      watchdog('rules', 'Reverted %plugin %label to the defaults.', $vars, WATCHDOG_NOTICE, $edit_link);
239
      return t('Reverted %plugin %label to the defaults.', $vars);
240

    
241
    case 'delete':
242
      $rules_config->delete();
243
      watchdog('rules', 'Deleted %plugin %label.', $vars);
244
      return t('Deleted %plugin %label.', $vars);
245
  }
246
}
247

    
248
/**
249
 * Rule config deletion form submit callback.
250
 */
251
function rules_ui_form_rules_config_confirm_op_submit($form, &$form_state) {
252
  if ($form_state['values']['confirm']) {
253
    $msg = rules_ui_confirm_operation_apply($form_state['op'], $form_state['rules_config']);
254
    drupal_set_message($msg);
255
  }
256
}
257

    
258
/**
259
 * Add a new element a rules configuration.
260
 */
261
function rules_ui_add_element($form, &$form_state, $rules_config, $plugin_name, RulesContainerPlugin $parent, $base_path) {
262
  $cache = rules_get_cache();
263
  if (!isset($cache['plugin_info'][$plugin_name]['class'])) {
264
    drupal_not_found();
265
    exit;
266
  }
267
  RulesPluginUI::$basePath = $base_path;
268
  $plugin_is_abstract = in_array('RulesAbstractPlugin', class_parents($cache['plugin_info'][$plugin_name]['class']));
269
  // In the first step create the element and in the second step show its edit
270
  // form.
271
  if ($plugin_is_abstract && !isset($form_state['rules_element'])) {
272
    RulesPluginUI::formDefaults($form, $form_state);
273
    $form_state += array('parent_element' => $parent, 'plugin' => $plugin_name);
274

    
275
    $form['element_name'] = array(
276
      '#type' => 'select',
277
      '#title' => t('Select the %element to add', array('%element' => $plugin_name)),
278
      '#options' => RulesPluginUI::getOptions($plugin_name),
279
      '#ajax' => rules_ui_form_default_ajax() + array(
280
        'trigger_as' => array('name' => 'continue'),
281
      ),
282
    );
283
    $form['continue'] = array(
284
      '#type' => 'submit',
285
      '#name' => 'continue',
286
      '#value' => t('Continue'),
287
      '#ajax' => rules_ui_form_default_ajax(),
288
    );
289
  }
290
  elseif (!$plugin_is_abstract) {
291
    // Create the initial, empty element.
292
    $element = rules_plugin_factory($plugin_name);
293
    // Always add the new element at the bottom, thus set an appropriate weight.
294
    $iterator = $parent->getIterator();
295
    if ($sibling = end($iterator)) {
296
      $element->weight = $sibling->weight + 1;
297
    }
298
    $element->setParent($parent);
299
    $form_state['rules_element'] = $element;
300
  }
301

    
302
  if (isset($form_state['rules_element'])) {
303
    $form_state['rules_element']->form($form, $form_state, array('button' => TRUE, 'init' => TRUE));
304
    $form['#validate'][] = 'rules_ui_edit_element_validate';
305
    $form['#submit'][] = 'rules_ui_edit_element_submit';
306
  }
307
  return $form;
308
}
309

    
310
/**
311
 * Add element submit callback.
312
 *
313
 * Used for "abstract plugins" to create the initial element object with the
314
 * given implementation name and rebuild the form.
315
 */
316
function rules_ui_add_element_submit($form, &$form_state) {
317
  $element = rules_plugin_factory($form_state['plugin'], $form_state['values']['element_name']);
318

    
319
  // Always add the new element at the bottom, thus set an appropriate weight.
320
  $iterator = $form_state['parent_element']->getIterator();
321
  if ($sibling = end($iterator)) {
322
    $element->weight = $sibling->weight + 1;
323
  }
324
  // Clear the element settings so they won't be processed on serialization as
325
  // there is nothing to be processed yet.
326
  $element->settings = array();
327
  $element->setParent($form_state['parent_element']);
328

    
329
  $form_state['rules_element'] = $element;
330
  $form_state['rebuild'] = TRUE;
331
}
332

    
333
/**
334
 * Delete elements.
335
 */
336
function rules_ui_delete_element($form, &$form_state, $rules_config, $rules_element, $base_path) {
337
  RulesPluginUI::$basePath = $base_path;
338

    
339
  if (empty($form_state['rules_config'])) {
340
    // Before modifying the rules config we have to clone it, so any
341
    // modifications won't appear in the static cache of the loading controller.
342
    $rules_config = clone $rules_config;
343
    // Also get the element from the cloned config.
344
    $rules_element = $rules_config->elementMap()->lookup($rules_element->elementId());
345

    
346
    $form_state['rules_config'] = $rules_config;
347
    $form_state['rules_element'] = $rules_element;
348
    $form_state['element_parent'] = $rules_element->parentElement();
349
  }
350

    
351
  // Try deleting the element and warn the user if something breaks, but
352
  // save the parent for determining the right redirect target on submit.
353
  $removed_plugin = $form_state['rules_element']->plugin();
354
  $rules_element->delete();
355

    
356
  if (empty($rules_config->dirty) && empty($form_state['input'])) {
357
    try {
358
      $rules_config->integrityCheck();
359
    }
360
    catch (RulesIntegrityException $e) {
361
      $args = array(
362
        '@plugin' => $e->element->plugin(),
363
        '%label' => $e->element->label(),
364
        '@removed-plugin' => $removed_plugin,
365
        '!url' => url(RulesPluginUI::path($form_state['rules_config']->name, 'edit', $e->element)),
366
      );
367
      drupal_set_message(t('Deleting this @removed-plugin would break your configuration as some of its provided variables are utilized by the @plugin <a href="!url">%label</a>.', $args), 'warning');
368
    }
369
  }
370

    
371
  $confirm_question = t('Are you sure you want to delete the %element_plugin %element_name?', array(
372
    '%element_plugin' => $rules_element->plugin(),
373
    '%element_name' => $rules_element->label(),
374
  ));
375
  return confirm_form($form, $confirm_question, RulesPluginUI::path($rules_config->name), t('This action cannot be undone.'), t('Delete'), t('Cancel'));
376
}
377

    
378
/**
379
 * Rule config deletion form submit callback.
380
 */
381
function rules_ui_delete_element_submit($form, &$form_state) {
382
  $rules_config = $form_state['rules_config'];
383
  $rules_config->save();
384
  if (empty($form_state['redirect'])) {
385
    $form_state['redirect'] = RulesPluginUI::defaultRedirect($form_state['element_parent']);
386
  }
387
}
388

    
389
/**
390
 * Configure a rule element.
391
 */
392
function rules_ui_edit_element($form, &$form_state, $rules_config, $element, $base_path) {
393
  RulesPluginUI::$basePath = $base_path;
394
  $form_state += array('rules_element' => $element);
395
  $form_state['rules_element']->form($form, $form_state, array('button' => TRUE));
396
  return $form;
397
}
398

    
399
/**
400
 * Validate the element configuration.
401
 */
402
function rules_ui_edit_element_validate($form, &$form_state) {
403
  $form_state['rules_element']->form_validate($form, $form_state);
404
}
405

    
406
/**
407
 * Submit the element configuration.
408
 */
409
function rules_ui_edit_element_submit($form, &$form_state) {
410
  $form_state['rules_element']->form_submit($form, $form_state);
411
  drupal_set_message(t('Your changes have been saved.'));
412
  if (empty($form_state['redirect'])) {
413
    $form_state['redirect'] = RulesPluginUI::defaultRedirect($form_state['rules_element']);
414
  }
415
}
416

    
417
/**
418
 * Form builder for the "add event" page.
419
 */
420
function rules_ui_add_event_page($form, &$form_state, RulesTriggerableInterface $rules_config, $base_path) {
421
  RulesPluginUI::$basePath = $base_path;
422
  RulesPluginUI::formDefaults($form, $form_state);
423
  $form = rules_ui_add_event($form, $form_state, $rules_config, $base_path);
424
  $form['#validate'][] = 'rules_ui_add_event_validate';
425
  return $form;
426
}
427

    
428
/**
429
 * Submit the event configuration.
430
 */
431
function rules_ui_add_event_page_submit($form, &$form_state) {
432
  rules_ui_add_event_apply($form, $form_state);
433
  $rules_config = $form_state['rules_config'];
434

    
435
  // Tell the user if this breaks something, but let him proceed.
436
  if (empty($rules_config->dirty)) {
437
    try {
438
      $rules_config->integrityCheck();
439
    }
440
    catch (RulesIntegrityException $e) {
441
      $warning = TRUE;
442
      drupal_set_message(t('Added the event, but it does not provide all variables utilized.'), 'warning');
443
    }
444
  }
445
  $rules_config->save();
446
  if (!isset($warning)) {
447
    $events = rules_fetch_data('event_info');
448
    $label = $events[$form_state['values']['event']]['label'];
449
    drupal_set_message(t('Added event %event.', array('%event' => $label)));
450
  }
451
}
452

    
453
/**
454
 * Add a new event.
455
 */
456
function rules_ui_add_event($form, &$form_state, RulesReactionRule $rules_config, $base_path) {
457
  $form_state += array('rules_config' => $rules_config);
458
  $events = array_diff_key(rules_fetch_data('event_info'), array_flip($rules_config->events()));
459

    
460
  $form['help'] = array(
461
    '#markup' => t('Select the event to add. However note that all added events need to provide all variables that should be available to your rule.'),
462
  );
463
  $form['event'] = array(
464
    '#type' => 'select',
465
    '#title' => t('React on event'),
466
    '#options' => RulesPluginUI::getOptions('event', $events),
467
    '#description' => t('Whenever the event occurs, rule evaluation is triggered.'),
468
    '#ajax' => rules_ui_form_default_ajax(),
469
    '#required' => TRUE,
470
  );
471
  if (!empty($form_state['values']['event'])) {
472
    $handler = rules_get_event_handler($form_state['values']['event']);
473
    $form['event_settings'] = $handler->buildForm($form_state);
474
  }
475
  else {
476
    $form['event_settings'] = array();
477
  }
478
  $form['submit'] = array(
479
    '#type' => 'submit',
480
    '#value' => t('Add'),
481
  );
482
  $form_state['redirect'] = RulesPluginUI::path($rules_config->name);
483
  return $form;
484
}
485

    
486
/**
487
 * Validation callback for adding an event.
488
 */
489
function rules_ui_add_event_validate($form, $form_state) {
490
  $handler = rules_get_event_handler($form_state['values']['event']);
491
  $handler->extractFormValues($form['event_settings'], $form_state);
492
  try {
493
    $handler->validate();
494
  }
495
  catch (RulesIntegrityException $e) {
496
    form_set_error(implode('][', $e->keys), $e->getMessage());
497
  }
498
}
499

    
500
/**
501
 * Submit callback that just adds the selected event.
502
 *
503
 * @see rules_admin_add_reaction_rule()
504
 */
505
function rules_ui_add_event_apply($form, &$form_state) {
506
  $handler = rules_get_event_handler($form_state['values']['event']);
507
  $handler->extractFormValues($form['event_settings'], $form_state);
508
  $form_state['rules_config']->event($form_state['values']['event'], $handler->getSettings());
509
}
510

    
511
/**
512
 * Form to remove an event from a rule.
513
 */
514
function rules_ui_remove_event($form, &$form_state, $rules_config, $event, $base_path) {
515
  RulesPluginUI::$basePath = $base_path;
516
  $form_state += array('rules_config' => $rules_config, 'rules_event' => $event);
517
  $event_info = rules_get_event_info($event);
518
  $form_state['event_label'] = $event_info['label'];
519
  $confirm_question = t('Are you sure you want to remove the event?');
520
  return confirm_form($form, $confirm_question, RulesPluginUI::path($rules_config->name), t('You are about to remove the event %event.', array('%event' => $form_state['event_label'])), t('Remove'), t('Cancel'));
521
}
522

    
523
/**
524
 * Submit the event configuration.
525
 */
526
function rules_ui_remove_event_submit($form, &$form_state) {
527
  $rules_config = $form_state['rules_config'];
528
  $rules_config->removeEvent($form_state['rules_event']);
529
  // Tell the user if this breaks something, but let him proceed.
530
  if (empty($rules_config->dirty)) {
531
    try {
532
      $rules_config->integrityCheck();
533
    }
534
    catch (RulesIntegrityException $e) {
535
      $warning = TRUE;
536
      drupal_set_message(t('Removed the event, but it had provided some variables which are now missing.'), 'warning');
537
    }
538
  }
539
  $rules_config->save();
540
  if (!isset($warning)) {
541
    drupal_set_message(t('Event %event has been removed.', array('%event' => $form_state['event_label'])));
542
  }
543
  $form_state['redirect'] = RulesPluginUI::path($rules_config->name);
544
}
545

    
546
/**
547
 * Import form for rule configurations.
548
 */
549
function rules_ui_import_form($form, &$form_state, $base_path) {
550
  RulesPluginUI::$basePath = $base_path;
551
  RulesPluginUI::formDefaults($form, $form_state);
552
  $form['import'] = array(
553
    '#type' => 'textarea',
554
    '#title' => t('Import'),
555
    '#description' => t('Paste an exported Rules configuration here.'),
556
    '#rows' => 20,
557
  );
558
  $form['overwrite'] = array(
559
    '#title' => t('Overwrite'),
560
    '#type' => 'checkbox',
561
    '#description' => t('If checked, any existing configuration with the same identifier will be replaced by the import.'),
562
    '#default_value' => FALSE,
563
  );
564
  $form['submit'] = array(
565
    '#type' => 'submit',
566
    '#value' => t('Import'),
567
  );
568
  return $form;
569
}
570

    
571
/**
572
 * Validation callback for the import form.
573
 */
574
function rules_ui_import_form_validate($form, &$form_state) {
575
  if ($rules_config = rules_import($form_state['values']['import'], $error_msg)) {
576
    // Store the successfully imported entity in $form_state.
577
    $form_state['rules_config'] = $rules_config;
578
    if (!$form_state['values']['overwrite']) {
579
      // Check for existing entities with the same identifier.
580
      if (rules_config_load($rules_config->name)) {
581
        $vars = array('@entity' => t('Rules configuration'), '%label' => $rules_config->label());
582
        form_set_error('import', t('Import of @entity %label failed, a @entity with the same machine name already exists. Check the overwrite option to replace it.', $vars));
583
      }
584
    }
585
    try {
586
      $rules_config->integrityCheck();
587
    }
588
    catch (RulesIntegrityException $e) {
589
      form_set_error('import', t('Integrity check for the imported configuration failed. Error message: %message.', array('%message' => $e->getMessage())));
590
    }
591
    if (!user_access('bypass rules access') && !$rules_config->access()) {
592
      form_set_error('import', t('You have insufficient access permissions for importing this Rules configuration.'));
593
    }
594
  }
595
  else {
596
    form_set_error('import', t('Import failed.'));
597
    if ($error_msg) {
598
      drupal_set_message($error_msg, 'error');
599
    }
600
  }
601
}
602

    
603
/**
604
 * Submit callback for the import form.
605
 */
606
function rules_ui_import_form_submit($form, &$form_state) {
607
  $rules_config = $form_state['rules_config'];
608

    
609
  if ($existing_config = rules_config_load($rules_config->name)) {
610
    // Copy DB id and remove the new indicator to overwrite the existing record.
611
    $rules_config->id = $existing_config->id;
612
    unset($rules_config->is_new);
613
  }
614
  $rules_config->save();
615
  $vars = array('@entity' => t('Rules configuration'), '%label' => $rules_config->label());
616
  watchdog('rules_config', 'Imported @entity %label.', $vars);
617
  drupal_set_message(t('Imported @entity %label.', $vars));
618
  $form_state['redirect'] = RulesPluginUI::$basePath;
619
}
620

    
621
/**
622
 * FAPI process callback for the data selection widget.
623
 *
624
 * This finalises the auto completion callback path by appending the form build
625
 * id.
626
 */
627
function rules_data_selection_process($element, &$form_state, $form) {
628
  $element['#autocomplete_path'] .= '/' . $form['#build_id'];
629
  $form_state['cache'] = TRUE;
630
  return $element;
631
}
632

    
633
/**
634
 * Autocomplete data selection results.
635
 */
636
function rules_ui_form_data_selection_auto_completion($parameter, $form_build_id, $string = '') {
637
  // Get the form and its state from the cache to get the currently edited
638
  // or created element.
639
  $form_state = form_state_defaults();
640
  $form = form_get_cache($form_build_id, $form_state);
641
  if (!isset($form_state['rules_element'])) {
642
    return;
643
  }
644
  $element = $form_state['rules_element'];
645

    
646
  $params = $element->pluginParameterInfo();
647
  $matches = array();
648
  if (isset($params[$parameter])) {
649
    $parts = explode(':', $string);
650
    // Remove the last part as it might be unfinished.
651
    $last_part = array_pop($parts);
652
    $selector = implode(':', $parts);
653

    
654
    // Start with the partly given selector or from scratch.
655
    $result = array();
656
    if ($selector && $wrapper = $element->applyDataSelector($selector)) {
657
      $result = RulesData::matchingDataSelector($wrapper, $params[$parameter], $selector . ':', 0);
658
    }
659
    elseif (!$selector) {
660
      $result = RulesData::matchingDataSelector($element->availableVariables(), $params[$parameter], '', 0);
661
    }
662

    
663
    foreach ($result as $selector => $info) {
664
      // If we have an uncomplete last part, take it into account now.
665
      $attributes = array();
666
      if (!$last_part || strpos($selector, $string) === 0) {
667
        $attributes['class'][] = 'rules-dsac-item';
668
        $attributes['title'] = isset($info['description']) ? strip_tags($info['description']) : '';
669
        if ($selector[strlen($selector) - 1] == ':') {
670
          $attributes['class'][] = 'rules-dsac-group';
671
          $text = check_plain($selector) . '... (' . check_plain($info['label']) . ')';
672
        }
673
        else {
674
          $text = check_plain($selector) . ' (' . check_plain($info['label']) . ')';
675
        }
676
        $matches[$selector] = "<div" . drupal_attributes($attributes) . ">$text</div>";
677
      }
678
    }
679
  }
680
  drupal_json_output($matches);
681
}
682

    
683
/**
684
 * FAPI validation of an integer element.
685
 *
686
 * Copy of the core Drupal private function _element_validate_integer().
687
 */
688
function rules_ui_element_integer_validate($element, &$form_state) {
689
  $value = $element['#value'];
690
  if (isset($value) && $value !== '' && (!is_numeric($value) || intval($value) != $value)) {
691
    form_error($element, t('%name must be an integer value.', array('%name' => isset($element['#title']) ? $element['#title'] : t('Element'))));
692
  }
693
}
694

    
695
/**
696
 * FAPI validation of a decimal element.
697
 *
698
 * Improved version of the private function _element_validate_number().
699
 */
700
function rules_ui_element_decimal_validate($element, &$form_state) {
701
  // Substitute the decimal separator ",".
702
  $value = strtr($element['#value'], ',', '.');
703
  if ($value != '' && !is_numeric($value)) {
704
    form_error($element, t('%name must be a number.', array('%name' => $element['#title'])));
705
  }
706
  elseif ($value != $element['#value']) {
707
    form_set_value($element, $value, $form_state);
708
  }
709
}
710

    
711
/**
712
 * FAPI callback to validate an IP address.
713
 */
714
function rules_ui_element_ip_address_validate($element, &$form_state) {
715
  $value = $element['#value'];
716
  if ($value != '' && !filter_var($value, FILTER_VALIDATE_IP)) {
717
    form_error($element, t('%name is not a valid IP address.', array('%name' => $element['#title'])));
718
  }
719
}
720

    
721
/**
722
 * FAPI validation of a date element.
723
 *
724
 * Makes sure the specified date format is correct and converts date values
725
 * specify a fixed (= non relative) date to a timestamp. Relative dates are
726
 * handled by the date input evaluator.
727
 */
728
function rules_ui_element_date_validate($element, &$form_state) {
729
  $value = $element['#value'];
730
  if ($value == '' || (is_numeric($value) && intval($value) == $value)) {
731
    // The value is a timestamp.
732
    return;
733
  }
734
  elseif (is_string($value) && RulesDateInputEvaluator::gmstrtotime($value) === FALSE) {
735
    form_error($element, t('Wrong date format. Specify the date in the format %format.', array('%format' => gmdate('Y-m-d H:i:s', time() + 86400))));
736
  }
737
  elseif (is_string($value) && RulesDateInputEvaluator::isFixedDateString($value)) {
738
    // As the date string specifies a fixed format, we can convert it now.
739
    $value = RulesDateInputEvaluator::gmstrtotime($value);
740
    form_set_value($element, $value, $form_state);
741
  }
742
}
743

    
744
/**
745
 * FAPI process callback for the duration element type.
746
 */
747
function rules_ui_element_duration_process($element, &$form_state) {
748
  $element['value'] = array(
749
    '#type' => 'textfield',
750
    '#size' => 8,
751
    '#element_validate' => array('rules_ui_element_integer_validate'),
752
    '#default_value' => $element['#default_value'],
753
    '#required' => !empty($element['#required']),
754
  );
755
  $element['multiplier'] = array(
756
    '#type' => 'select',
757
    '#options' => rules_ui_element_duration_multipliers(),
758
    '#default_value' => 1,
759
  );
760

    
761
  // Put the child elements in a container-inline div.
762
  $element['value']['#prefix'] = '<div class="rules-duration container-inline">';
763
  $element['multiplier']['#suffix'] = '</div>';
764

    
765
  // Set an appropriate multiplier.
766
  if (!empty($element['value']['#default_value'])) {
767
    foreach (array_keys(rules_ui_element_duration_multipliers()) as $m) {
768
      if ($element['value']['#default_value'] % $m == 0) {
769
        $element['multiplier']['#default_value'] = $m;
770
      }
771
    }
772
    // Divide value by the multiplier, so the display is correct.
773
    $element['value']['#default_value'] /= $element['multiplier']['#default_value'];
774
  }
775
  return $element;
776
}
777

    
778
/**
779
 * Defines possible duration multiplier.
780
 */
781
function rules_ui_element_duration_multipliers() {
782
  return array(
783
    1 => t('seconds'),
784
    60 => t('minutes'),
785
    3600 => t('hours'),
786
    // Just use approximate numbers for days (might last 23h on DST change),
787
    // months and years.
788
    86400 => t('days'),
789
    86400 * 30 => t('months'),
790
    86400 * 30 * 12 => t('years'),
791
  );
792
}
793

    
794
/**
795
 * Helper function a rules duration form element.
796
 *
797
 * Determines the value for a rules duration form element.
798
 */
799
function rules_ui_element_duration_value($element, $input = FALSE) {
800
  // This runs before child elements are processed, so we cannot calculate the
801
  // value here. But we have to make sure the value is an array, so the form
802
  // API is able to process the children to set their values in the array. Thus
803
  // once the form API has finished processing the element, the value is an
804
  // array containing the child element values. Then finally the after build
805
  // callback converts it back to the numeric value and sets that.
806
  return array();
807
}
808

    
809
/**
810
 * FAPI after build callback for the duration parameter type form.
811
 *
812
 * Fixes up the form value by applying the multiplier.
813
 */
814
function rules_ui_element_duration_after_build($element, &$form_state) {
815
  if ($element['value']['#value'] !== '') {
816
    $element['#value'] = $element['value']['#value'] * $element['multiplier']['#value'];
817
    form_set_value($element, $element['#value'], $form_state);
818
  }
819
  else {
820
    $element['#value'] = NULL;
821
    form_set_value($element, NULL, $form_state);
822
  }
823
  return $element;
824
}
825

    
826
/**
827
 * FAPI after build callback to ensure empty form elements result in no value.
828
 */
829
function rules_ui_element_fix_empty_after_build($element, &$form_state) {
830
  if (isset($element['#value']) && $element['#value'] === '') {
831
    $element['#value'] = NULL;
832
    form_set_value($element, NULL, $form_state);
833
  }
834
  // Work-a-round for the text_format element.
835
  elseif ($element['#type'] == 'text_format' && !isset($element['value']['#value'])) {
836
    form_set_value($element, NULL, $form_state);
837
  }
838
  return $element;
839
}
840

    
841
/**
842
 * FAPI after build callback for specifying a list of values.
843
 *
844
 * Turns the textual value in an array by splitting the text in chunks using the
845
 * delimiter set at $element['#delimiter'].
846
 */
847
function rules_ui_list_textarea_after_build($element, &$form_state) {
848
  $element['#value'] = $element['#value'] ? explode($element['#delimiter'], $element['#value']) : array();
849
  $element['#value'] = array_map('trim', $element['#value']);
850
  form_set_value($element, $element['#value'], $form_state);
851
  return $element;
852
}
853

    
854
/**
855
 * FAPI pre render callback. Turns the value back to a string for rendering.
856
 *
857
 * @see rules_ui_list_textarea_after_build()
858
 */
859
function rules_ui_list_textarea_pre_render($element) {
860
  $element['#value'] = implode($element['#delimiter'], $element['#value']);
861
  return $element;
862
}
863

    
864
/**
865
 * FAPI callback to validate a list of integers.
866
 */
867
function rules_ui_element_integer_list_validate($element, &$form_state) {
868
  foreach ($element['#value'] as $value) {
869
    if ($value !== '' && (!is_numeric($value) || intval($value) != $value)) {
870
      form_error($element, t('Each value must be an integer.'));
871
    }
872
  }
873
}
874

    
875
/**
876
 * FAPI callback to validate a token.
877
 */
878
function rules_ui_element_token_validate($element) {
879
  $value = $element['#value'];
880
  if (isset($value) && $value !== '' && !entity_property_verify_data_type($value, 'token')) {
881
    form_error($element, t('%name may only contain lowercase letters, numbers, and underscores and has to start with a letter.', array('%name' => isset($element['#title']) ? $element['#title'] : t('Element'))));
882
  }
883
}
884

    
885
/**
886
 * FAPI callback to validate a list of tokens.
887
 */
888
function rules_ui_element_token_list_validate($element, &$form_state) {
889
  foreach ($element['#value'] as $value) {
890
    if ($value !== '' && !entity_property_verify_data_type($value, 'token')) {
891
      form_error($element, t('Each value may only contain lowercase letters, numbers, and underscores and has to start with a letter.'));
892
    }
893
  }
894
}
895

    
896
/**
897
 * FAPI callback to validate a machine readable name.
898
 */
899
function rules_ui_element_machine_name_validate($element, &$form_state) {
900
  if ($element['#value'] && !preg_match('!^[a-z0-9_]+$!', $element['#value'])) {
901
    form_error($element, t('Machine-readable names must contain only lowercase letters, numbers, and underscores.'));
902
  }
903
}
904

    
905
/**
906
 * FAPI callback to validate the form for editing variable info.
907
 *
908
 * @see RulesPluginUI::getVariableForm()
909
 */
910
function rules_ui_element_variable_form_validate($elements, &$form_state) {
911
  $names = array();
912
  foreach (element_children($elements['items']) as $item_key) {
913
    $element = &$elements['items'][$item_key];
914
    if ($element['name']['#value'] || $element['type']['#value'] || $element['label']['#value']) {
915
      foreach (array('name' => t('Machine name'), 'label' => t('Label'), 'type' => t('Data type')) as $key => $title) {
916
        if (!$element[$key]['#value']) {
917
          form_error($element[$key], t('!name field is required.', array('!name' => $title)));
918
        }
919
      }
920
      if (isset($names[$element['name']['#value']])) {
921
        form_error($element['name'], t('The machine-readable name %name is already taken.', array('%name' => $element['name']['#value'])));
922
      }
923
      $names[$element['name']['#value']] = TRUE;
924
    }
925
  }
926
}
927

    
928
/**
929
 * Helper to sort elements by their 'weight' key.
930
 */
931
function rules_element_sort_helper($a, $b) {
932
  $a += array('weight' => 0);
933
  $b += array('weight' => 0);
934
  if ($a['weight'] == $b['weight']) {
935
    return 0;
936
  }
937
  return ($a['weight'] < $b['weight']) ? -1 : 1;
938
}
939

    
940
/**
941
 * Form after build handler to set the static base path.
942
 *
943
 * @see RulesPluginUI::formDefaults()
944
 */
945
function rules_form_after_build_restore_base_path($form, &$form_state) {
946
  if (isset($form_state['_rules_base_path'])) {
947
    RulesPluginUI::$basePath = $form_state['_rules_base_path'];
948
  }
949
  return $form;
950
}
951

    
952
/**
953
 * AJAX page callback to load tag suggestions.
954
 *
955
 * Largely copied from taxonomy_autocomplete().
956
 */
957
function rules_autocomplete_tags($tags_typed = '') {
958
  // The user enters a comma-separated list of tags. We only autocomplete the
959
  // last tag.
960
  $tags_typed = drupal_explode_tags($tags_typed);
961
  $tag_last = drupal_strtolower(array_pop($tags_typed));
962

    
963
  $tag_matches = array();
964
  if ($tag_last != '') {
965
    $query = db_select('rules_tags', 'rt');
966
    // Do not select already entered terms.
967
    if (!empty($tags_typed)) {
968
      $query->condition('rt.tag', $tags_typed, 'NOT IN');
969
    }
970
    // Select rows that match by tag name.
971
    $tags_return = $query
972
      ->distinct()
973
      ->fields('rt', array('tag'))
974
      ->condition('rt.tag', '%' . db_like($tag_last) . '%', 'LIKE')
975
      ->groupBy('rt.tag')
976
      ->range(0, 10)
977
      ->execute()
978
      ->fetchCol('rt.tag');
979

    
980
    $prefix = count($tags_typed) ? drupal_implode_tags($tags_typed) . ', ' : '';
981

    
982
    foreach ($tags_return as $name) {
983
      $n = $name;
984
      // Tag names containing commas or quotes must be wrapped in quotes.
985
      if (strpos($name, ',') !== FALSE || strpos($name, '"') !== FALSE) {
986
        $n = '"' . str_replace('"', '""', $name) . '"';
987
      }
988
      $tag_matches[$prefix . $n] = check_plain($name);
989
    }
990
  }
991
  drupal_json_output($tag_matches);
992
}